appflare 0.2.14 → 0.2.15
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/schema-compiler.ts +104 -8
- package/cli/templates/dashboard/builders/table-routes/helpers.ts +1 -5
- package/cli/templates/handlers/generators/types/query-definitions/schema-and-table-types.ts +23 -19
- package/cli/utils/schema-discovery.ts +1 -1
- package/dist/cli/index.js +179 -175
- package/dist/cli/index.mjs +179 -175
- package/dist/index.d.mts +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/schema.ts +19 -2
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'),Kr=require('chokidar'),fs=require('fs'),path=require('path'),promises=require('fs/promises'),url=require('url'),m=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 Kr__default=/*#__PURE__*/_interopDefault(Kr);var m__namespace=/*#__PURE__*/_interopNamespace(m);function Z(t){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 Y(){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 qn(t){let e=t.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(e)?`_${e}`:e||"_route"}function X(t){return t.split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Cn(t){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function tt(t){let e={children:new Map};for(let n of t){let r=e;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 e}function F(t,e=1){let n=" ".repeat(e),r=" ".repeat(e+1),a=Array.from(t.children.entries()).sort(([i],[s])=>i.localeCompare(s));if(a.length===0)return t.operation?`${t.operation.alias}Route(runtime)`:"{}";let o=["{"];for(let[i,s]of a)o.push(`${r}${Cn(i)}: ${F(s,e+1)},`);return t.operation&&(o.push(`${r}run: ${t.operation.alias}Route(runtime).run,`),o.push(`${r}schema: ${t.operation.alias}Route(runtime).schema,`),t.operation.kind==="query"&&o.push(`${r}subscribe: ${t.operation.alias}Route(runtime).subscribe,`)),o.push(`${n}}`),o.join(`
|
|
168
|
+
`)}function Pn(t,e){if(t.kind!=="query"&&t.kind!=="mutation")return null;let n=t.clientSegments&&t.clientSegments.length>0?t.clientSegments:t.routePath.replace(/^\//,"").split("/").filter(Boolean).slice(1);if(n.length===0)return null;let r=qn(`op_${e}_${t.kind}_${n.join("_")}`);return {kind:t.kind,routePath:t.routePath,queryName:t.handlerName??n.join("/"),segments:n,importPath:t.clientImportPath,exportName:t.exportName,alias:r,schemaConst:`${r}Schema`,typeBase:`${X(t.kind)}${X(n.join("_"))}`}}function Dn(t){let e=`${t.typeBase}Input`,n=`${t.typeBase}Output`,r=`${t.typeBase}Schema`,a=t.kind==="query"?"GET":"POST";return t.kind==="query"?`const ${t.alias}Route = (
|
|
169
169
|
runtime: RequestRuntime,
|
|
170
170
|
): AppflareQueryRouteClient<typeof ${t.schemaConst}, ${n}> => {
|
|
171
171
|
const run: AppflareQueryRouteClient<typeof ${t.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 M(t){let e=t.map((c,d)=>
|
|
354
|
+
};`}function M(t){let e=t.map((c,d)=>Pn(c,d)).filter(c=>c!==null),n=e.filter(c=>c.kind==="query"),r=e.filter(c=>c.kind==="mutation"),a=e.map(c=>`import { ${c.exportName} as ${c.alias} } from "${c.importPath}";`).join(`
|
|
355
355
|
`),o=e.map(c=>{let d=`${c.typeBase}Input`,g=`${c.typeBase}Output`,u=`${c.typeBase}Schema`;return `const ${c.schemaConst} = z.object(${c.alias}.definition.args);
|
|
356
356
|
export type ${d} = z.input<typeof ${c.schemaConst}>;
|
|
357
357
|
export type ${g} = Awaited<ReturnType<typeof ${c.alias}.definition.handler>>;
|
|
358
358
|
export const ${u} = ${c.schemaConst};`}).join(`
|
|
359
359
|
|
|
360
|
-
`),i=e.map(c=>
|
|
360
|
+
`),i=e.map(c=>Dn(c)).join(`
|
|
361
361
|
|
|
362
|
-
`),s=
|
|
362
|
+
`),s=F(tt(n)),l=F(tt(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 et(){return `export * from "./types";
|
|
740
740
|
export * from "./appflare";
|
|
741
741
|
export * from "./storage";
|
|
742
742
|
export * from "./handlers";
|
|
743
|
-
`}function
|
|
743
|
+
`}function nt(){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 rt(t){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
921
921
|
import type appflareConfig from "${t}";
|
|
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 at(t,e){return [{relativePath:"client/index.ts",source:et()},{relativePath:"client/types.ts",source:rt(t)},{relativePath:"client/storage.ts",source:nt()},{relativePath:"client/handlers.ts",source:M(e)},{relativePath:"client/appflare.ts",source:Y()}]}function ot(t){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 it(){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 st(){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 lt(){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 ct(){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 ut(){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 dt(){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 pt(t){return `
|
|
1357
1357
|
export function createSchedulerExecutionContext(
|
|
1358
1358
|
env: Record<string, unknown>,
|
|
1359
1359
|
options: RegisterHandlersOptions,
|
|
@@ -1430,7 +1430,7 @@ export async function createExecutionContext(
|
|
|
1430
1430
|
ctx.storage = createStorageApi(ctx, storageBucket);
|
|
1431
1431
|
return ctx;
|
|
1432
1432
|
}
|
|
1433
|
-
`}function
|
|
1433
|
+
`}function mt(t){return `import type { Context } from "hono";
|
|
1434
1434
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
1435
1435
|
import { createAuth } from "./auth.config";
|
|
1436
1436
|
import {
|
|
@@ -1449,20 +1449,20 @@ import {
|
|
|
1449
1449
|
createQueryDb,
|
|
1450
1450
|
} from "./handlers";
|
|
1451
1451
|
|
|
1452
|
-
${it()}
|
|
1453
|
-
|
|
1454
|
-
${ot()}
|
|
1455
|
-
|
|
1456
1452
|
${st()}
|
|
1457
1453
|
|
|
1454
|
+
${it()}
|
|
1455
|
+
|
|
1458
1456
|
${lt()}
|
|
1459
1457
|
|
|
1460
1458
|
${ct()}
|
|
1461
1459
|
|
|
1462
1460
|
${ut()}
|
|
1463
1461
|
|
|
1464
|
-
${dt(
|
|
1465
|
-
|
|
1462
|
+
${dt()}
|
|
1463
|
+
|
|
1464
|
+
${pt(t)}
|
|
1465
|
+
`}function gt(){return `
|
|
1466
1466
|
export async function executeOperation(
|
|
1467
1467
|
c: Context<WorkerEnv>,
|
|
1468
1468
|
operation: RegisteredOperation<ZodRawShape, unknown>,
|
|
@@ -1498,7 +1498,7 @@ export function handleOperationError(
|
|
|
1498
1498
|
return c.json({ message: (error as Error).message ?? "Unknown error" }, 500);
|
|
1499
1499
|
}
|
|
1500
1500
|
|
|
1501
|
-
`}function
|
|
1501
|
+
`}function ft(){return `import type { Context } from "hono";
|
|
1502
1502
|
import { ZodError, type ZodRawShape } from "zod";
|
|
1503
1503
|
import {
|
|
1504
1504
|
type AppflareContext,
|
|
@@ -1507,8 +1507,8 @@ import {
|
|
|
1507
1507
|
type WorkerEnv,
|
|
1508
1508
|
} from "./handlers";
|
|
1509
1509
|
|
|
1510
|
-
${
|
|
1511
|
-
`}function
|
|
1510
|
+
${gt()}
|
|
1511
|
+
`}function ht(){return `import { betterAuth } from "better-auth";
|
|
1512
1512
|
import { auth } from "./auth.config";
|
|
1513
1513
|
import {
|
|
1514
1514
|
and,
|
|
@@ -1611,7 +1611,7 @@ export async function isStorageAllowed(
|
|
|
1611
1611
|
|
|
1612
1612
|
return false;
|
|
1613
1613
|
}
|
|
1614
|
-
`}function
|
|
1614
|
+
`}function bt(){return `type Primitive = string | number | boolean | Date;
|
|
1615
1615
|
type NonNil<T> = Exclude<T, null | undefined>;
|
|
1616
1616
|
type Friendly<T> = T extends Date ? Date | number : T;
|
|
1617
1617
|
type Comparable<T> = Friendly<Extract<NonNil<T>, Primitive>>;
|
|
@@ -1776,7 +1776,7 @@ export type QueryDeleteArgs<TName extends TableName> = {
|
|
|
1776
1776
|
where?: WhereInput<TableModel<TName>>;
|
|
1777
1777
|
limit?: number;
|
|
1778
1778
|
};
|
|
1779
|
-
`}function
|
|
1779
|
+
`}function yt(){return `type AggregateWithInput<TName extends TableName> =
|
|
1780
1780
|
QueryWithInput<NativeFindManyWith<TName>>;
|
|
1781
1781
|
|
|
1782
1782
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -1906,7 +1906,7 @@ export type DbMutationEvent = {
|
|
|
1906
1906
|
export type QueryDbOptions = {
|
|
1907
1907
|
onMutation?: (event: DbMutationEvent) => void;
|
|
1908
1908
|
};
|
|
1909
|
-
`}function
|
|
1909
|
+
`}function xt(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
1910
1910
|
return typeof value === "object" && value !== null;
|
|
1911
1911
|
}
|
|
1912
1912
|
|
|
@@ -2589,7 +2589,7 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
2589
2589
|
|
|
2590
2590
|
return [];
|
|
2591
2591
|
}
|
|
2592
|
-
`}function
|
|
2592
|
+
`}function wt(){return `const mergedSchema = {
|
|
2593
2593
|
...authSchema,
|
|
2594
2594
|
...schema,
|
|
2595
2595
|
};
|
|
@@ -2628,20 +2628,25 @@ type ResolveTableFindManySelection<
|
|
|
2628
2628
|
(ResolveNativeFindManyWith<TName, TArgs> extends never
|
|
2629
2629
|
? {}
|
|
2630
2630
|
: { with: ResolveNativeFindManyWith<TName, TArgs> });
|
|
2631
|
+
type TableModel<TName extends TableName> = InferSelectModel<
|
|
2632
|
+
(typeof mergedSchema)[TName]
|
|
2633
|
+
>;
|
|
2631
2634
|
type TableFindManyResult<
|
|
2632
2635
|
TName extends TableName,
|
|
2633
2636
|
TArgs extends QueryFindManyArgs<TName> | undefined =
|
|
2634
2637
|
| QueryFindManyArgs<TName>
|
|
2635
2638
|
| undefined,
|
|
2636
|
-
> =
|
|
2637
|
-
Array<
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2639
|
+
> = TArgs extends undefined
|
|
2640
|
+
? Promise<Array<TableModel<TName>>>
|
|
2641
|
+
: Promise<
|
|
2642
|
+
Array<
|
|
2643
|
+
BuildQueryResult<
|
|
2644
|
+
SchemaRelations,
|
|
2645
|
+
TableRelationConfig<TName>,
|
|
2646
|
+
ResolveTableFindManySelection<TName, TArgs>
|
|
2647
|
+
>
|
|
2648
|
+
>
|
|
2649
|
+
>;
|
|
2645
2650
|
type TableFindFirstArgs<TName extends TableName> = Omit<
|
|
2646
2651
|
TableFindManyArgs<TName>,
|
|
2647
2652
|
"limit"
|
|
@@ -2670,22 +2675,21 @@ type TableFindFirstResult<
|
|
|
2670
2675
|
TArgs extends QueryFindFirstArgs<TName> | undefined =
|
|
2671
2676
|
| QueryFindFirstArgs<TName>
|
|
2672
2677
|
| undefined,
|
|
2673
|
-
> =
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
>;
|
|
2678
|
+
> = TArgs extends undefined
|
|
2679
|
+
? Promise<TableModel<TName> | null>
|
|
2680
|
+
: Promise<
|
|
2681
|
+
BuildQueryResult<
|
|
2682
|
+
SchemaRelations,
|
|
2683
|
+
TableRelationConfig<TName>,
|
|
2684
|
+
ResolveTableFindFirstSelection<TName, TArgs>
|
|
2685
|
+
> | null
|
|
2686
|
+
>;
|
|
2683
2687
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
2684
2688
|
(typeof mergedSchema)[TName]
|
|
2685
2689
|
>;
|
|
2686
|
-
`}function
|
|
2690
|
+
`}function vt(){return [wt(),bt(),yt(),xt()].join(`
|
|
2687
2691
|
|
|
2688
|
-
`)}function
|
|
2692
|
+
`)}function kt(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
2689
2693
|
const withValue = args?.with;
|
|
2690
2694
|
const pathSegments = args?.field
|
|
2691
2695
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -2846,7 +2850,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
2846
2850
|
},
|
|
2847
2851
|
}) as AppflareQueryDb;
|
|
2848
2852
|
}
|
|
2849
|
-
`}function
|
|
2853
|
+
`}function Tt(){return `export class AppflareHandledError extends Error {
|
|
2850
2854
|
public readonly status: number;
|
|
2851
2855
|
public readonly payload: unknown;
|
|
2852
2856
|
|
|
@@ -2856,7 +2860,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
2856
2860
|
this.payload = payload;
|
|
2857
2861
|
}
|
|
2858
2862
|
}
|
|
2859
|
-
`}function
|
|
2863
|
+
`}function St(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
2860
2864
|
const where = isRecord(args?.where)
|
|
2861
2865
|
? (args?.where as Record<string, unknown>)
|
|
2862
2866
|
: undefined;
|
|
@@ -2938,7 +2942,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
2938
2942
|
applyRelationAggregatePlanToResult(result, aggregatePlan),
|
|
2939
2943
|
);
|
|
2940
2944
|
},
|
|
2941
|
-
`}function
|
|
2945
|
+
`}function Rt(){return `export function createQueryDb(
|
|
2942
2946
|
$db: AppflareDb,
|
|
2943
2947
|
options?: QueryDbOptions,
|
|
2944
2948
|
): AppflareQueryDb {
|
|
@@ -2980,7 +2984,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
2980
2984
|
};
|
|
2981
2985
|
|
|
2982
2986
|
const tableApi = {
|
|
2983
|
-
`}function
|
|
2987
|
+
`}function At(){return ` insert: async (args: QueryInsertArgs<TableName>) => {
|
|
2984
2988
|
let insertQuery: any = ($db as any)
|
|
2985
2989
|
.insert(table as any)
|
|
2986
2990
|
.values(args.values as any);
|
|
@@ -3114,9 +3118,9 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3114
3118
|
);
|
|
3115
3119
|
return rows;
|
|
3116
3120
|
},
|
|
3117
|
-
`}function
|
|
3121
|
+
`}function $t(){return [Rt(),St(),At(),kt(),Tt()].join(`
|
|
3118
3122
|
|
|
3119
|
-
`)}function
|
|
3123
|
+
`)}function Nt(){return `type AuthSession = typeof auth.$Infer.Session;
|
|
3120
3124
|
type User = AuthSession['user']
|
|
3121
3125
|
type Session = AuthSession['session']
|
|
3122
3126
|
|
|
@@ -3177,7 +3181,7 @@ export type AppflareContext = {
|
|
|
3177
3181
|
storage: AppflareStorage;
|
|
3178
3182
|
error: (status: number, message: string, details?: unknown) => never;
|
|
3179
3183
|
};
|
|
3180
|
-
`}function
|
|
3184
|
+
`}function qt(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
3181
3185
|
|
|
3182
3186
|
export type SchedulerEnqueueOptions = {
|
|
3183
3187
|
delaySeconds?: number;
|
|
@@ -3309,20 +3313,20 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
3309
3313
|
definition,
|
|
3310
3314
|
};
|
|
3311
3315
|
}
|
|
3312
|
-
`}function
|
|
3316
|
+
`}function Ct(){return [ht(),vt(),$t(),Nt(),qt()].join(`
|
|
3313
3317
|
|
|
3314
|
-
`)}function
|
|
3318
|
+
`)}function Pt(t){return `import type { Context } from "hono";
|
|
3315
3319
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
3316
3320
|
import { drizzle } from "drizzle-orm/d1";
|
|
3317
3321
|
import { z, type ZodRawShape } from "zod";
|
|
3318
3322
|
import * as authSchema from "./auth.schema";
|
|
3319
3323
|
import * as schema from "${t}";
|
|
3320
3324
|
|
|
3321
|
-
${
|
|
3322
|
-
`}function
|
|
3325
|
+
${Ct()}
|
|
3326
|
+
`}function On(t){let e=t.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(e)?`_${e}`:e}function En(t,e){let n=t.routePath.replace(/^\//,"").replace(/\//g,"_");return On(`op_${e}_${n}`)}function In(t){return t.map((e,n)=>({operation:e,index:n,alias:En(e,n)}))}function Fn(t){return t.map(({operation:e,alias:n})=>`import { ${e.exportName} as ${n} } from "${e.importPath}";`).join(`
|
|
3323
3327
|
`)}function Mn(t){return t.filter(({operation:e})=>e.kind==="query"||e.kind==="mutation").map(({alias:e})=>`const ${`${e}Schema`} = z.object(${e}.definition.args);`).join(`
|
|
3324
|
-
`)}function
|
|
3325
|
-
`)}function
|
|
3328
|
+
`)}function jn(t){return t.filter(({operation:e})=>e.kind==="scheduler").map(({alias:e})=>`const ${`${e}SchedulerSchema`} = ${e}.definition.args ? z.object(${e}.definition.args) : z.undefined();`).join(`
|
|
3329
|
+
`)}function Bn(t){return t.filter(({operation:e})=>e.kind==="query").map(({operation:e,alias:n})=>{let r=`${n}Schema`;return `
|
|
3326
3330
|
app.get(
|
|
3327
3331
|
"${e.routePath}",
|
|
3328
3332
|
sValidator("query", ${r}),
|
|
@@ -3335,7 +3339,7 @@ ${qt()}
|
|
|
3335
3339
|
}
|
|
3336
3340
|
},
|
|
3337
3341
|
);`}).join(`
|
|
3338
|
-
`)}function
|
|
3342
|
+
`)}function Hn(t){return t.filter(({operation:e})=>e.kind==="mutation").map(({operation:e,alias:n})=>{let r=`${n}Schema`;return `
|
|
3339
3343
|
app.post(
|
|
3340
3344
|
"${e.routePath}",
|
|
3341
3345
|
sValidator("json", ${r}),
|
|
@@ -3350,26 +3354,26 @@ ${qt()}
|
|
|
3350
3354
|
}
|
|
3351
3355
|
},
|
|
3352
3356
|
);`}).join(`
|
|
3353
|
-
`)}function
|
|
3357
|
+
`)}function Vn(t){return t.filter(({operation:e})=>e.kind==="query").map(({operation:e,alias:n})=>{let r=`${n}Schema`,a=e.handlerName??e.routePath;return `
|
|
3354
3358
|
${JSON.stringify(a)}: {
|
|
3355
3359
|
definition: ${n}.definition,
|
|
3356
3360
|
schema: ${r},
|
|
3357
3361
|
},`}).join(`
|
|
3358
|
-
`)}function
|
|
3362
|
+
`)}function zn(t){return t.filter(({operation:e})=>e.kind==="scheduler").map(({operation:e,alias:n})=>{let r=`${n}SchedulerSchema`,a=e.taskName??`${e.routePath}`;return `
|
|
3359
3363
|
${JSON.stringify(a)}: {
|
|
3360
3364
|
definition: ${n}.definition,
|
|
3361
3365
|
schema: ${r},
|
|
3362
3366
|
},`}).join(`
|
|
3363
|
-
`)}function
|
|
3364
|
-
`)}function
|
|
3367
|
+
`)}function Wn(t){return t.filter(({operation:e})=>e.kind==="scheduler").map(({operation:e,alias:n})=>{let r=e.taskName??`${e.routePath}`;return ` ${JSON.stringify(r)}: Parameters<typeof ${n}.definition.handler>[1];`}).join(`
|
|
3368
|
+
`)}function Ln(t){return t.filter(({operation:e})=>e.kind==="cron").map(({operation:e,alias:n})=>{let r=e.taskName??`${e.routePath}`,a=e.cronTriggers??[];return `
|
|
3365
3369
|
{
|
|
3366
3370
|
taskName: ${JSON.stringify(r)},
|
|
3367
3371
|
cronTriggers: ${JSON.stringify(a)},
|
|
3368
3372
|
definition: ${n}.definition,
|
|
3369
3373
|
},`}).join(`
|
|
3370
|
-
`)}function
|
|
3374
|
+
`)}function Un(t){return t.filter(({operation:e})=>e.kind==="storage").map(({alias:e})=>`
|
|
3371
3375
|
${e}.definition.handler,`).join(`
|
|
3372
|
-
`)}function
|
|
3376
|
+
`)}function Dt(t){let e=In(t);return {imports:Fn(e),operationSchemas:Mn(e),schedulerSchemas:jn(e),queryRoutes:Bn(e),mutationRoutes:Hn(e),queryRegistryEntries:Vn(e),schedulerEntries:zn(e),schedulerPayloadMapEntries:Wn(e),cronEntries:Ln(e),storageHandlersEntries:Un(e)}}var Ot=`
|
|
3373
3377
|
function getRealtimeStub(
|
|
3374
3378
|
env: Record<string, unknown>,
|
|
3375
3379
|
options: RegisterHandlersOptions,
|
|
@@ -3443,7 +3447,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
3443
3447
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
3444
3448
|
return url.toString();
|
|
3445
3449
|
}
|
|
3446
|
-
`;var
|
|
3450
|
+
`;var Et=`
|
|
3447
3451
|
export class AppflareRealtimeDurableObject {
|
|
3448
3452
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
3449
3453
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -3586,7 +3590,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
3586
3590
|
return new Response("Not found", { status: 404 });
|
|
3587
3591
|
}
|
|
3588
3592
|
}
|
|
3589
|
-
`;var
|
|
3593
|
+
`;var It=`
|
|
3590
3594
|
async function publishMutationEvents(
|
|
3591
3595
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
3592
3596
|
options: RegisterHandlersOptions,
|
|
@@ -3687,7 +3691,7 @@ async function publishMutationEvents(
|
|
|
3687
3691
|
}
|
|
3688
3692
|
}
|
|
3689
3693
|
}
|
|
3690
|
-
`;var
|
|
3694
|
+
`;var Ft=`
|
|
3691
3695
|
function registerRealtimeRoutes(
|
|
3692
3696
|
app: Hono<WorkerEnv>,
|
|
3693
3697
|
options: RegisterHandlersOptions,
|
|
@@ -3879,7 +3883,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
3879
3883
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
3880
3884
|
? string
|
|
3881
3885
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
3882
|
-
`;var
|
|
3886
|
+
`;var jt=`
|
|
3883
3887
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
3884
3888
|
return typeof value === "object" && value !== null;
|
|
3885
3889
|
}
|
|
@@ -4394,9 +4398,9 @@ function doesSubscriptionMatchMutation(
|
|
|
4394
4398
|
|
|
4395
4399
|
return false;
|
|
4396
4400
|
}
|
|
4397
|
-
`;var
|
|
4401
|
+
`;var Bt=[Mt,jt,Ot,It,Ft,Et].join(`
|
|
4398
4402
|
|
|
4399
|
-
`);var
|
|
4403
|
+
`);var Ht=`
|
|
4400
4404
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
4401
4405
|
if (!value) {
|
|
4402
4406
|
return undefined;
|
|
@@ -4589,7 +4593,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
4589
4593
|
}
|
|
4590
4594
|
});
|
|
4591
4595
|
}
|
|
4592
|
-
`;var
|
|
4596
|
+
`;var Vt=`
|
|
4593
4597
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
4594
4598
|
? string
|
|
4595
4599
|
: keyof typeof schedulerHandlers;
|
|
@@ -4644,7 +4648,7 @@ export async function executeScheduledBatch(
|
|
|
4644
4648
|
}
|
|
4645
4649
|
}
|
|
4646
4650
|
}
|
|
4647
|
-
`;var
|
|
4651
|
+
`;var zt=`
|
|
4648
4652
|
export async function executeCronTriggers(
|
|
4649
4653
|
controller: { cron: string },
|
|
4650
4654
|
env: Record<string, unknown>,
|
|
@@ -4673,7 +4677,7 @@ export async function executeCronTriggers(
|
|
|
4673
4677
|
}
|
|
4674
4678
|
}
|
|
4675
4679
|
}
|
|
4676
|
-
`;function
|
|
4680
|
+
`;function Wt(t){let{imports:e,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:l,cronEntries:c,storageHandlersEntries:d}=Dt(t);return `import { sValidator } from "@hono/standard-validator";
|
|
4677
4681
|
import type { Hono } from "hono";
|
|
4678
4682
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
4679
4683
|
import { ZodError, z } from "zod";
|
|
@@ -4722,9 +4726,9 @@ const storageHandlers = [${d||`
|
|
|
4722
4726
|
|
|
4723
4727
|
setStorageHandlers([...storageHandlers]);
|
|
4724
4728
|
|
|
4725
|
-
${
|
|
4729
|
+
${Vt}
|
|
4726
4730
|
|
|
4727
|
-
${
|
|
4731
|
+
${Bt}
|
|
4728
4732
|
|
|
4729
4733
|
export function registerGeneratedHandlers(
|
|
4730
4734
|
app: Hono<WorkerEnv>,
|
|
@@ -4737,20 +4741,20 @@ export function registerGeneratedHandlers(
|
|
|
4737
4741
|
`}
|
|
4738
4742
|
}
|
|
4739
4743
|
|
|
4740
|
-
${
|
|
4744
|
+
${Ht}
|
|
4741
4745
|
|
|
4742
|
-
${
|
|
4743
|
-
`}function
|
|
4744
|
-
KV: c.env["${t}"] as KVNamespace`:""}function
|
|
4745
|
-
DATABASE: c.env["${t}"] as D1Database${
|
|
4746
|
-
}`}function
|
|
4746
|
+
${zt}
|
|
4747
|
+
`}function j(t,e,n){let r=Pt(t),a=mt(n),o=ft(),i=Wt(e);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 Qn(t){return t?`,
|
|
4748
|
+
KV: c.env["${t}"] as KVNamespace`:""}function Lt(t,e){return `{
|
|
4749
|
+
DATABASE: c.env["${t}"] as D1Database${Qn(e)}
|
|
4750
|
+
}`}function Ut(t,e,n){return `app.on(["GET", "POST"], "${t}/*", async (c) => {
|
|
4747
4751
|
const auth = createAuth(
|
|
4748
|
-
${
|
|
4752
|
+
${Lt(e,n)},
|
|
4749
4753
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
4750
4754
|
);
|
|
4751
4755
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
4752
4756
|
});
|
|
4753
|
-
`}function
|
|
4757
|
+
`}function _n(){return `export const getHeaders = (headers: Headers) => {
|
|
4754
4758
|
const newHeaders = Object.fromEntries(headers as any);
|
|
4755
4759
|
const headerObject: Record<string, any> = {};
|
|
4756
4760
|
let hasCookie = false;
|
|
@@ -4780,15 +4784,15 @@ ${Vt}
|
|
|
4780
4784
|
|
|
4781
4785
|
return headerObject as any as Headers;
|
|
4782
4786
|
};
|
|
4783
|
-
`}function
|
|
4787
|
+
`}function Kn(){return `export const getSanitizedRequest = (req: Request) => {
|
|
4784
4788
|
const newRequest = new Request(req, {
|
|
4785
4789
|
headers: getHeaders(req.headers),
|
|
4786
4790
|
});
|
|
4787
4791
|
return newRequest;
|
|
4788
4792
|
};
|
|
4789
|
-
`}function
|
|
4790
|
-
`+
|
|
4791
|
-
`+
|
|
4793
|
+
`}function Qt(){return _n()+`
|
|
4794
|
+
`+Kn()}function _t(t,e,n){return Ut(t,e,n)+`
|
|
4795
|
+
`+Qt()}function Kt(){return `const app = new Hono<WorkerEnv>();
|
|
4792
4796
|
|
|
4793
4797
|
app.use('*', cors({
|
|
4794
4798
|
origin: (origin, c) => {
|
|
@@ -4804,7 +4808,7 @@ app.use('*', cors({
|
|
|
4804
4808
|
},
|
|
4805
4809
|
credentials: true
|
|
4806
4810
|
}));
|
|
4807
|
-
`}function
|
|
4811
|
+
`}function Gt(){return `export { AppflareRealtimeDurableObject };
|
|
4808
4812
|
|
|
4809
4813
|
export default {
|
|
4810
4814
|
fetch: app.fetch,
|
|
@@ -4815,7 +4819,7 @@ export default {
|
|
|
4815
4819
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
4816
4820
|
},
|
|
4817
4821
|
};
|
|
4818
|
-
`}function
|
|
4822
|
+
`}function Jt(t,e,n="APPFLARE_SCHEDULER_QUEUE",r,a="APPFLARE_REALTIME",o="global",i="/realtime/subscribe",s="/realtime/ws",l="appflare.realtime.v1"){let c=e?`
|
|
4819
4823
|
kvBinding: "${e}",`:"",d=r?`
|
|
4820
4824
|
r2Binding: "${r}",`:"",g=`
|
|
4821
4825
|
realtimeBinding: "${a}",
|
|
@@ -4829,16 +4833,16 @@ export default {
|
|
|
4829
4833
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
4830
4834
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
4831
4835
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
4832
|
-
`}function
|
|
4836
|
+
`}function Zt(){return `import { createAuth } from "./auth.config";
|
|
4833
4837
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
4834
4838
|
import { registerAdminDashboard } from "./admin.routes";
|
|
4835
4839
|
import { Hono } from "hono";
|
|
4836
4840
|
import { cors } from "hono/cors";
|
|
4837
4841
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
4838
|
-
`}function
|
|
4842
|
+
`}function Yt(){return `type WorkerEnv = {
|
|
4839
4843
|
Bindings: Record<string, unknown>;
|
|
4840
4844
|
};
|
|
4841
|
-
`}function
|
|
4845
|
+
`}function Xt(t,e,n,r,a,o,i,s,l,c){return Zt()+Yt()+Kt()+Jt(e,n,r,a,o,i,s,l,c)+_t(t,e,n)+Gt()}function te(t){return !!t&&typeof t=="object"&&!Array.isArray(t)}function B(t,e){let n={...t};for(let[r,a]of Object.entries(e)){let o=n[r];if(te(o)&&te(a)){n[r]=B(o,a);continue}n[r]=a;}return n}function Gn(t){return Array.from(new Set(t.filter(e=>e.length>0)))}function ee(t,e){let n=e.filter(u=>u.kind==="scheduler"||u.kind==="cron"),r=Gn(e.filter(u=>u.kind==="cron").flatMap(u=>u.cronTriggers??[])),a=t.config.scheduler.enabled&&n.length>0,o=t.config.realtime.enabled,s=(typeof t.config.wranglerOverrides?.name=="string"?t.config.wranglerOverrides.name:void 0)??"appflare-worker",l=t.config.scheduler.queue??`${s}-scheduler`,c={name:s,main:"./src/index.ts",d1_databases:t.config.database.map(u=>({binding:u.binding,database_name:u.databaseName,database_id:u.databaseId,preview_database_id:u.previewDatabaseId??u.databaseId,...u.migrationsDir?{migrations_dir:u.migrationsDir}:{}})),kv_namespaces:t.config.kv.map(u=>({binding:u.binding,id:u.id,...u.previewId?{preview_id:u.previewId}:{}})),r2_buckets:t.config.r2.map(u=>({binding:u.binding,bucket_name:u.bucketName,...u.previewBucketName?{preview_bucket_name:u.previewBucketName}:{},...u.jurisdiction?{jurisdiction:u.jurisdiction}:{}})),...a?{queues:{producers:[{binding:t.config.scheduler.binding,queue:l}],consumers:[{queue:l}]}}:{},...r.length>0?{triggers:{crons:r}}:{},...o?{durable_objects:{bindings:[{name:t.config.realtime.binding,class_name:t.config.realtime.className}]},migrations:[{tag:"appflare-realtime-v1",new_sqlite_classes:[t.config.realtime.className]}]}:{}};if(!t.config.wranglerOverrides)return c;let{scheduler:d,...g}=t.config.wranglerOverrides;return B(c,g)}function ne(t){return t.tables.map(e=>({exportName:e.exportName,tableName:e.tableName,columns:e.columns.map(n=>n.name)}))}function re(t){return `<li data-name="users">
|
|
4842
4846
|
<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">
|
|
4843
4847
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
4844
4848
|
<span class="truncate">users</span>
|
|
@@ -4850,7 +4854,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
4850
4854
|
<span class="truncate">${n.tableName}</span>
|
|
4851
4855
|
</a>
|
|
4852
4856
|
</li>`).join(`
|
|
4853
|
-
`)}`}function
|
|
4857
|
+
`)}`}function ae(t){let e=t.filter(o=>o.kind==="query"),n=t.filter(o=>o.kind==="mutation"),r=e.map(o=>`
|
|
4854
4858
|
<li data-name="${o.exportName}">
|
|
4855
4859
|
<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">
|
|
4856
4860
|
<iconify-icon icon="solar:reorder-linear" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
@@ -4884,7 +4888,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
4884
4888
|
<ul class="flex flex-col gap-0.5">${a}</ul>`:""}
|
|
4885
4889
|
</nav>
|
|
4886
4890
|
</div>
|
|
4887
|
-
`}function
|
|
4891
|
+
`}function oe(t){return t.map(e=>`
|
|
4888
4892
|
<a
|
|
4889
4893
|
href="/admin/table/${e.exportName}"
|
|
4890
4894
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
@@ -4901,9 +4905,9 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
4901
4905
|
</div>
|
|
4902
4906
|
</div>
|
|
4903
4907
|
</a>
|
|
4904
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
4908
|
+
`.replace(/\n/g,"\\n")).join("")}function ie(t){return t.columns.filter(e=>e.type==="string").map(e=>`
|
|
4905
4909
|
try { searchConditions.push(like(tableSchema.${e.name}, \`%\${search}%\`)); } catch (e) {}
|
|
4906
|
-
`).join("")}function
|
|
4910
|
+
`).join("")}function Jn(t){switch(t){case "number":return "mdi:pound";case "boolean":return "mdi:toggle-switch-outline";case "date":return "mdi:calendar";default:return "mdi:format-text"}}function se(t,e){return e.map(n=>{let r=t.columns.find(o=>o.name===n),a=r?Jn(r.type):"mdi:format-text";return `
|
|
4907
4911
|
<th>
|
|
4908
4912
|
<a href="#"
|
|
4909
4913
|
hx-get="/admin/table/${t.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -4915,7 +4919,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
4915
4919
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
4916
4920
|
</a>
|
|
4917
4921
|
</th>
|
|
4918
|
-
`}).join("")}function
|
|
4922
|
+
`}).join("")}function le(t){return t.map(e=>`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${e} ?? '')}">\${String((row as any).${e} ?? '')}</div></td>`).join("")}function H(t,e,n){let r=t.columns.find(i=>i.name===e);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"?`
|
|
4919
4923
|
<div class="form-control">
|
|
4920
4924
|
<label class="label cursor-pointer justify-start gap-3">
|
|
4921
4925
|
<input type="checkbox" name="${e}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${e} ? 'checked' : ''} />
|
|
@@ -4953,7 +4957,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
4953
4957
|
<label class="label"><span class="label-text text-sm font-medium">${e}</span></label>
|
|
4954
4958
|
<input type="${o}" name="${e}" class="input input-bordered w-full text-sm"${a} />
|
|
4955
4959
|
</div>
|
|
4956
|
-
`}function
|
|
4960
|
+
`}function V(t,e){return e.map(n=>{let r=t.columns.find(o=>o.name===n);if(!r)return "";let a=r.optional?"":`
|
|
4957
4961
|
if (raw_${n} === '') {
|
|
4958
4962
|
return c.text('${n} is required', 400);
|
|
4959
4963
|
}
|
|
@@ -4998,7 +5002,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
4998
5002
|
payload.${n} = raw_${n};
|
|
4999
5003
|
}
|
|
5000
5004
|
`}).join(`
|
|
5001
|
-
`)}function
|
|
5005
|
+
`)}function ce(t){return t.columns.find(e=>e.primaryKey)?.name||t.columns[0]?.name||""}function ue(t,e){let n=t.columns.find(r=>r.name===e);return !(!n||n.autoIncrement||n.primaryKey)}function de(t,e){let n=t.columns.find(r=>r.name===e);return !(!n||n.primaryKey||n.autoIncrement)}function pe(t,e,n,r){return e?`<td class="text-right">
|
|
5002
5006
|
<div class="drawer drawer-end">
|
|
5003
5007
|
<input id="edit-drawer-${t.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
5004
5008
|
<div class="drawer-content">
|
|
@@ -5051,7 +5055,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
5051
5055
|
</div>
|
|
5052
5056
|
</div>
|
|
5053
5057
|
</div>
|
|
5054
|
-
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function
|
|
5058
|
+
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function q(t){return `
|
|
5055
5059
|
<div class="flex flex-col sm:flex-row justify-between items-center mt-4 gap-3 py-3 px-1">
|
|
5056
5060
|
<div class="text-xs text-base-content/40">
|
|
5057
5061
|
Total found: <span class="font-medium text-base-content/60">\${total}</span>
|
|
@@ -5073,7 +5077,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
5073
5077
|
\` : html\`<button class="join-item btn btn-sm btn-ghost btn-disabled"><iconify-icon icon="mdi:chevron-right" width="16" height="16"></iconify-icon></button>\`}
|
|
5074
5078
|
</div>
|
|
5075
5079
|
\` : ''}
|
|
5076
|
-
</div>`}function
|
|
5080
|
+
</div>`}function C(t,e="Search term or filter..."){return `
|
|
5077
5081
|
<div class="form-control w-full md:w-auto relative">
|
|
5078
5082
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
5079
5083
|
<input type="text"
|
|
@@ -5084,7 +5088,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
5084
5088
|
hx-trigger="keyup changed delay:500ms, search"
|
|
5085
5089
|
hx-target="#main-content"
|
|
5086
5090
|
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" />
|
|
5087
|
-
</div>`}function
|
|
5091
|
+
</div>`}function me(t,e,n,r,a,o,i,s,l,c){let d=q(`/admin/table/${t.exportName}`),g=C(`/admin/table/${t.exportName}`,"Search term or filter..."),u=r?`<th class="w-10"><input id="select-all-${t.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>',b=r?`
|
|
5088
5092
|
<div id="bulk-delete-bar-${t.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
5089
5093
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
5090
5094
|
<div class="text-xs text-base-content/70">
|
|
@@ -5303,7 +5307,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
5303
5307
|
${g}
|
|
5304
5308
|
</div>
|
|
5305
5309
|
\${tableHtml}
|
|
5306
|
-
${
|
|
5310
|
+
${b}
|
|
5307
5311
|
</div>
|
|
5308
5312
|
<div class="drawer-side z-50">
|
|
5309
5313
|
<label for="create-drawer-${t.exportName}" aria-label="close sidebar" class="drawer-overlay"></label>
|
|
@@ -5336,7 +5340,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
5336
5340
|
title: "${t.tableName} - Admin Dashboard",
|
|
5337
5341
|
children: content
|
|
5338
5342
|
}));
|
|
5339
|
-
});`}function
|
|
5343
|
+
});`}function ge(t,e,n,r,a,o,i,s){let l=r==="number"?`
|
|
5340
5344
|
const parsedId = Number(rawId);
|
|
5341
5345
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
5342
5346
|
idValue = parsedId;
|
|
@@ -5469,15 +5473,15 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
5469
5473
|
return c.redirect('/admin/table/${t}?' + query.toString());
|
|
5470
5474
|
});
|
|
5471
5475
|
${d}
|
|
5472
|
-
`}function
|
|
5473
|
-
`+
|
|
5476
|
+
`}function z(t){let e=ce(t),n=!!e,r=t.columns.map(h=>h.name),a=r.filter(h=>ue(t,h)),o=r.filter(h=>de(t,h)),i=ie(t),s=se(t,r),l=le(r),c=a.map(h=>H(t,h,"create")).join(""),d=o.map(h=>H(t,h,"edit")).join(""),g=V(t,a),u=V(t,o),y=n?e:r[0]||"id",b=t.columns.find(h=>h.name===e)?.type,f=pe(t,n,e,d);return me(t,y,e,n,r,i,s,l,f,c)+`
|
|
5477
|
+
`+ge(t.exportName,y,e,b,n,i,g,u)}function fe(){return `
|
|
5474
5478
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
5475
5479
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
5476
5480
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
5477
5481
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
5478
5482
|
const search = params.search ? params.search : '';
|
|
5479
5483
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
5480
|
-
};`}function
|
|
5484
|
+
};`}function he(){return `
|
|
5481
5485
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
5482
5486
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
5483
5487
|
<div class="modal">
|
|
@@ -5498,7 +5502,7 @@ ${d}
|
|
|
5498
5502
|
</div>
|
|
5499
5503
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
5500
5504
|
</div>
|
|
5501
|
-
\`}`}function
|
|
5505
|
+
\`}`}function be(){return `
|
|
5502
5506
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
5503
5507
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
5504
5508
|
<div class="modal">
|
|
@@ -5519,8 +5523,8 @@ ${d}
|
|
|
5519
5523
|
</div>
|
|
5520
5524
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
5521
5525
|
</div>
|
|
5522
|
-
\`}`}var Zn=["id","name","email","role","createdAt","banned"],Yn={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function Xn(t){let e=Yn[t]||"mdi:format-text";return `<th><a href="#" hx-get="/admin/users?page=\${page}&search=\${search}&sort=${t}&order=\${sort === '${t}' && 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="${e}" width="14" height="14" class="opacity-40"></iconify-icon>${t} <span class="text-[10px] opacity-30">\${sort === '${t}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span></a></th>`}function
|
|
5523
|
-
`),e=
|
|
5526
|
+
\`}`}var Zn=["id","name","email","role","createdAt","banned"],Yn={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function Xn(t){let e=Yn[t]||"mdi:format-text";return `<th><a href="#" hx-get="/admin/users?page=\${page}&search=\${search}&sort=${t}&order=\${sort === '${t}' && 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="${e}" width="14" height="14" class="opacity-40"></iconify-icon>${t} <span class="text-[10px] opacity-30">\${sort === '${t}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span></a></th>`}function ye(){let t=Zn.map(Xn).join(`
|
|
5527
|
+
`),e=q("/admin/users");return `
|
|
5524
5528
|
const tableHtml = html\`
|
|
5525
5529
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
5526
5530
|
<div class="overflow-x-auto">
|
|
@@ -5588,8 +5592,8 @@ ${d}
|
|
|
5588
5592
|
</div>
|
|
5589
5593
|
</div>
|
|
5590
5594
|
</div>
|
|
5591
|
-
${fe()}
|
|
5592
5595
|
${he()}
|
|
5596
|
+
${be()}
|
|
5593
5597
|
</td>
|
|
5594
5598
|
</tr>
|
|
5595
5599
|
\`)}
|
|
@@ -5604,7 +5608,7 @@ ${he()}
|
|
|
5604
5608
|
</div>
|
|
5605
5609
|
${e}
|
|
5606
5610
|
</div>
|
|
5607
|
-
\`;`}function
|
|
5611
|
+
\`;`}function xe(){return `
|
|
5608
5612
|
const content = html\`
|
|
5609
5613
|
<div id="main-content">
|
|
5610
5614
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -5616,11 +5620,11 @@ ${he()}
|
|
|
5616
5620
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
5617
5621
|
</button>
|
|
5618
5622
|
</div>
|
|
5619
|
-
${
|
|
5623
|
+
${C("/admin/users","Search users...")}
|
|
5620
5624
|
</div>
|
|
5621
5625
|
\${tableHtml}
|
|
5622
5626
|
</div>
|
|
5623
|
-
\`;`}function
|
|
5627
|
+
\`;`}function we(){let t=ye(),e=xe();return `
|
|
5624
5628
|
adminApp.get('/users', async (c) => {
|
|
5625
5629
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
5626
5630
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -5676,7 +5680,7 @@ ${he()}
|
|
|
5676
5680
|
title: "users - Admin Dashboard",
|
|
5677
5681
|
children: content,
|
|
5678
5682
|
}));
|
|
5679
|
-
});`}function
|
|
5683
|
+
});`}function ve(){return `
|
|
5680
5684
|
adminApp.post('/users/edit', async (c) => {
|
|
5681
5685
|
const session = await requireAdminSession(c);
|
|
5682
5686
|
if (!session) {
|
|
@@ -5819,8 +5823,8 @@ ${he()}
|
|
|
5819
5823
|
const resolvedPage = String(Math.min(nextPageCandidate, totalPages));
|
|
5820
5824
|
|
|
5821
5825
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
5822
|
-
});`}function
|
|
5823
|
-
${
|
|
5826
|
+
});`}function W(){return `
|
|
5827
|
+
${fe()}
|
|
5824
5828
|
|
|
5825
5829
|
const requireAdminSession = async (c: any) => {
|
|
5826
5830
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -5831,12 +5835,12 @@ ${he()}
|
|
|
5831
5835
|
return session;
|
|
5832
5836
|
};
|
|
5833
5837
|
|
|
5834
|
-
${xe()}
|
|
5835
|
-
|
|
5836
5838
|
${we()}
|
|
5837
|
-
|
|
5839
|
+
|
|
5840
|
+
${ve()}
|
|
5841
|
+
`}function ke(t){return `${t.tables.map(e=>z(e)).join(`
|
|
5838
5842
|
`)}
|
|
5839
|
-
${
|
|
5843
|
+
${W()}`}function Te(t){return `
|
|
5840
5844
|
<div class="flex items-center justify-between">
|
|
5841
5845
|
<div class="flex items-center gap-3">
|
|
5842
5846
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -5930,7 +5934,7 @@ ${z()}`}function ke(t){return `
|
|
|
5930
5934
|
</div>
|
|
5931
5935
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
5932
5936
|
</div>
|
|
5933
|
-
`}function
|
|
5937
|
+
`}function Se(t){return `
|
|
5934
5938
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
5935
5939
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
5936
5940
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -5975,7 +5979,7 @@ ${z()}`}function ke(t){return `
|
|
|
5975
5979
|
</form>
|
|
5976
5980
|
</div>
|
|
5977
5981
|
</div>
|
|
5978
|
-
`}function
|
|
5982
|
+
`}function Re(){return `
|
|
5979
5983
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
5980
5984
|
<!-- Panel Header -->
|
|
5981
5985
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -6057,7 +6061,7 @@ ${z()}`}function ke(t){return `
|
|
|
6057
6061
|
|
|
6058
6062
|
</div>
|
|
6059
6063
|
</div>
|
|
6060
|
-
`}function
|
|
6064
|
+
`}function Ae(t){let e=t.kind==="query",n=t.routePath,r=t.handlerName??t.routePath;return `
|
|
6061
6065
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
6062
6066
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
6063
6067
|
|
|
@@ -6599,21 +6603,21 @@ ${z()}`}function ke(t){return `
|
|
|
6599
6603
|
_rtEnabled = false;
|
|
6600
6604
|
});
|
|
6601
6605
|
</script>
|
|
6602
|
-
`}function
|
|
6606
|
+
`}function $e(t){return `
|
|
6603
6607
|
const content = html\`
|
|
6604
6608
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
6605
|
-
${
|
|
6609
|
+
${Te(t)}
|
|
6606
6610
|
|
|
6607
6611
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
6608
6612
|
<!-- Request Panel -->
|
|
6609
|
-
${
|
|
6613
|
+
${Se(t)}
|
|
6610
6614
|
|
|
6611
6615
|
<!-- Result Panel -->
|
|
6612
|
-
${
|
|
6616
|
+
${Re()}
|
|
6613
6617
|
</div>
|
|
6614
6618
|
</div>
|
|
6615
6619
|
|
|
6616
|
-
${
|
|
6620
|
+
${Ae(t)}
|
|
6617
6621
|
\`;
|
|
6618
6622
|
|
|
6619
6623
|
if (c.req.header('hx-request')) {
|
|
@@ -6623,11 +6627,11 @@ ${z()}`}function ke(t){return `
|
|
|
6623
6627
|
return c.html(Layout({
|
|
6624
6628
|
title: "${t.exportName} - Functions",
|
|
6625
6629
|
children: content
|
|
6626
|
-
}));`}function
|
|
6630
|
+
}));`}function Ne(t){return t.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
6627
6631
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
6628
|
-
${
|
|
6632
|
+
${$e(n)}
|
|
6629
6633
|
});`).join(`
|
|
6630
|
-
`)}function
|
|
6634
|
+
`)}function qe(){return `
|
|
6631
6635
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
6632
6636
|
const r2Binding = (options as any).r2Binding;
|
|
6633
6637
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -6696,7 +6700,7 @@ ${z()}`}function ke(t){return `
|
|
|
6696
6700
|
const parts = prefix.split('/').filter(Boolean);
|
|
6697
6701
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
6698
6702
|
};
|
|
6699
|
-
`}function
|
|
6703
|
+
`}function Ce(){return `
|
|
6700
6704
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
6701
6705
|
const parts = prefix.split('/').filter(Boolean);
|
|
6702
6706
|
const breadcrumbs = [];
|
|
@@ -6823,7 +6827,7 @@ ${z()}`}function ke(t){return `
|
|
|
6823
6827
|
</div>
|
|
6824
6828
|
\`;
|
|
6825
6829
|
};
|
|
6826
|
-
`}function
|
|
6830
|
+
`}function Pe(){return `
|
|
6827
6831
|
const handleStorageListRoute = async (c: any) => {
|
|
6828
6832
|
const bucket = getStorageBucket(c);
|
|
6829
6833
|
if (!bucket) {
|
|
@@ -6845,7 +6849,7 @@ ${z()}`}function ke(t){return `
|
|
|
6845
6849
|
|
|
6846
6850
|
adminApp.get('/storage', handleStorageListRoute);
|
|
6847
6851
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
6848
|
-
`}function
|
|
6852
|
+
`}function De(){return `
|
|
6849
6853
|
adminApp.post('/storage/upload', async (c) => {
|
|
6850
6854
|
const bucket = getStorageBucket(c);
|
|
6851
6855
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -6863,7 +6867,7 @@ ${z()}`}function ke(t){return `
|
|
|
6863
6867
|
|
|
6864
6868
|
return c.redirect(prefixToStoragePath(prefix));
|
|
6865
6869
|
});
|
|
6866
|
-
`}function
|
|
6870
|
+
`}function Oe(){return `
|
|
6867
6871
|
adminApp.delete('/storage/delete', async (c) => {
|
|
6868
6872
|
const bucket = getStorageBucket(c);
|
|
6869
6873
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -6878,7 +6882,7 @@ ${z()}`}function ke(t){return `
|
|
|
6878
6882
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
6879
6883
|
return c.html('');
|
|
6880
6884
|
});
|
|
6881
|
-
`}function
|
|
6885
|
+
`}function Ee(){return `
|
|
6882
6886
|
adminApp.post('/storage/directory', async (c) => {
|
|
6883
6887
|
const bucket = getStorageBucket(c);
|
|
6884
6888
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -6904,7 +6908,7 @@ ${z()}`}function ke(t){return `
|
|
|
6904
6908
|
|
|
6905
6909
|
return c.redirect(prefixToStoragePath(prefix));
|
|
6906
6910
|
});
|
|
6907
|
-
`}function
|
|
6911
|
+
`}function Ie(){return `
|
|
6908
6912
|
adminApp.get('/storage/download', async (c) => {
|
|
6909
6913
|
const bucket = getStorageBucket(c);
|
|
6910
6914
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -6924,7 +6928,7 @@ ${z()}`}function ke(t){return `
|
|
|
6924
6928
|
|
|
6925
6929
|
return new Response(object.body, { headers });
|
|
6926
6930
|
});
|
|
6927
|
-
`}function
|
|
6931
|
+
`}function Fe(){return `
|
|
6928
6932
|
adminApp.get('/storage/preview', async (c) => {
|
|
6929
6933
|
const bucket = getStorageBucket(c);
|
|
6930
6934
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -6943,24 +6947,24 @@ ${z()}`}function ke(t){return `
|
|
|
6943
6947
|
return new Response(object.body, { headers });
|
|
6944
6948
|
});
|
|
6945
6949
|
`}function Me(){return `
|
|
6946
|
-
${Oe()}
|
|
6947
|
-
|
|
6948
6950
|
${Ie()}
|
|
6949
6951
|
|
|
6950
|
-
${
|
|
6951
|
-
|
|
6952
|
-
${Ee()}
|
|
6952
|
+
${Fe()}
|
|
6953
6953
|
|
|
6954
6954
|
${De()}
|
|
6955
6955
|
|
|
6956
|
-
${
|
|
6957
|
-
|
|
6958
|
-
${
|
|
6956
|
+
${Oe()}
|
|
6957
|
+
|
|
6958
|
+
${Ee()}
|
|
6959
6959
|
|
|
6960
|
+
${Pe()}
|
|
6961
|
+
`}function je(){return `
|
|
6960
6962
|
${qe()}
|
|
6961
6963
|
|
|
6964
|
+
${Ce()}
|
|
6965
|
+
|
|
6962
6966
|
${Me()}
|
|
6963
|
-
`}function
|
|
6967
|
+
`}function Be(t,e){let n=ae(e);return `
|
|
6964
6968
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
6965
6969
|
return html\`<!DOCTYPE html>
|
|
6966
6970
|
<html lang="en" data-theme="light">
|
|
@@ -7335,7 +7339,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
7335
7339
|
</body>
|
|
7336
7340
|
</html>\`;
|
|
7337
7341
|
}
|
|
7338
|
-
`}function
|
|
7342
|
+
`}function He(){return `
|
|
7339
7343
|
// Auth Middleware
|
|
7340
7344
|
adminApp.use('*', async (c, next) => {
|
|
7341
7345
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7394,7 +7398,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
7394
7398
|
}
|
|
7395
7399
|
await next();
|
|
7396
7400
|
});
|
|
7397
|
-
`}function
|
|
7401
|
+
`}function Ve(t){return `
|
|
7398
7402
|
adminApp.get('/', (c) => {
|
|
7399
7403
|
return c.html(Layout({
|
|
7400
7404
|
title: "Admin Dashboard",
|
|
@@ -7411,7 +7415,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
7411
7415
|
\`
|
|
7412
7416
|
}));
|
|
7413
7417
|
});
|
|
7414
|
-
`}function
|
|
7418
|
+
`}function ze(t,e,n){let r=ne(e),a=re(r),o=oe(r),i=ke(e),s=Ne(n),l=je(),c=Be(a,n),d=He(),g=Ve(o);return `import { Hono } from "hono";
|
|
7415
7419
|
import { html, raw } from "hono/html";
|
|
7416
7420
|
import { drizzle } from "drizzle-orm/d1";
|
|
7417
7421
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -7440,8 +7444,8 @@ ${g}
|
|
|
7440
7444
|
app.route('/admin', adminApp);
|
|
7441
7445
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
7442
7446
|
}
|
|
7443
|
-
`}function
|
|
7444
|
-
`}function
|
|
7447
|
+
`}function L(t){if(typeof t!="object"||t===null)return false;let e=t;return e.kind==="schema"&&typeof e.tables=="object"}function P(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function _e(t){return t.replace(/[_-]+/g," ").replace(/\s+(.)/g,(e,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(e,n)=>n.toUpperCase())}function ir(t){return t.endsWith("ies")?`${t.slice(0,-3)}y`:t.endsWith("ses")?t.slice(0,-2):t.endsWith("s")&&t.length>1?t.slice(0,-1):t}function x(t){return JSON.stringify(t)}function sr(t){if(typeof t=="string")return x(t);if(typeof t=="number"||typeof t=="boolean")return String(t);if(t===null)return "null";if(t instanceof Date)return x(t.toISOString());throw new Error(`Unsupported SQL default value '${String(t)}'. Use string, number, boolean, null, or Date.`)}function lr(t){return {kind:"schema",tables:Object.fromEntries(Object.entries(t.tables).map(([e,n])=>[e,{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 We(t,e,n){let r=t.tables[e];return r?r.columns[n]?.type:void 0}function Le(t,e,n,r,a,o,i){let s=e.columns[n];if(s){if(s.references&&(s.references.table!==r||s.references.column!==a))throw new Error(`Inferred relation '${t}.${n}' conflicts with explicit references(${s.references.table}.${s.references.column}).`);e.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}e.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 Ue(t,e,n){if(e.notNull===true&&e.nullable===true)throw new Error(`Invalid nullable configuration on '${t}': cannot set both notNull and nullable to true.`);return e.notNull===true?true:e.nullable===true||e.notNull===false?false:n}function cr(t){for(let[e,n]of Object.entries(t.tables)){for(let[r,a]of Object.entries(n.columns))if(a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${e}.${r}': cannot set both notNull and nullable to true.`);for(let[r,a]of Object.entries(n.relations))if(a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${e}.${r}': cannot set both notNull and nullable to true.`)}}function ur(t){cr(t);let e=lr(t);for(let[n,r]of Object.entries(e.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=We(e,o.targetTable,i)??o.fkType??"string";Le(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:Ue(`${n}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},l);}for(let[n,r]of Object.entries(e.tables))for(let a of Object.values(r.relations)){if(a.relation!=="many")continue;let o=e.tables[a.targetTable];if(!o)continue;let i=a.referenceField??"id",s=a.field??`${ir(n)}Id`,l=We(e,n,i)??a.fkType??"string";Le(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:Ue(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},l);}return e}function Ke(t){return t.primaryKey===true||t.notNull!==true||t.autoIncrement===true||t.sqlDefault!==void 0||t.runtimeDefaultFn!==void 0}function $(t){return t.notNull!==true}function dr(t,e,n){let r=e.sqlName??P(t),a=r!==t;return e.type==="int"?a?`t.int(${x(r)})`:"t.int()":e.type==="string"?e.length!==void 0?a?`t.text(${x(r)}, { length: ${e.length} })`:`t.text({ length: ${e.length} })`:a?`t.text(${x(r)})`:"t.text()":e.type==="boolean"?a?`t.int(${x(r)}, { mode: "boolean" })`:'t.int({ mode: "boolean" })':e.type==="date"?a?`t.int(${x(r)}, { mode: "timestamp_ms" })`:'t.int({ mode: "timestamp_ms" })':n==="camelToSnake"&&a?`t.text(${x(r)})`:"t.text()"}function pr(t,e,n){let r=n.field,a=n.referenceField??"id";if(!r)throw new Error(`Relation on '${t}' targeting '${n.targetTable}' is missing a local field.`);if(!(r in e.columns))throw new Error(`Relation '${t}.${r}' references missing local field '${r}'.`);return {sourceField:r,targetField:a}}function mr(t){return t.size===0?"":`import { ${Array.from(t).sort().join(", ")} } from "./auth.schema";
|
|
7448
|
+
`}function gr(t){return Object.values(t.relations).filter(e=>e.relation==="one").map(e=>e.targetTable)}function fr(t,e,n){if(e.references)return {tableName:e.references.table,fieldName:e.references.column};let r=Object.values(n.relations).find(a=>a.relation==="one"&&a.field===t);if(r)return {tableName:r.targetTable,fieldName:r.referenceField??"id"}}function hr(t,e){let n=new Set(Object.keys(t.tables)),r=new Set;for(let i of Object.values(t.tables)){for(let s of gr(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(t.tables)){let l=s.sqlName??P(i),c=[],d=[];for(let[b,f]of Object.entries(s.columns)){let h=dr(b,f,e);f.uuidPrimaryKey&&(h+=".$defaultFn(() => crypto.randomUUID())"),f.primaryKey&&(h+=f.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),f.notNull&&(h+=".notNull()"),f.sqlDefault!==void 0&&(h+=`.default(${sr(f.sqlDefault)})`);let k=fr(b,f,s);if(k)if(f.references?.onDelete||f.references?.onUpdate){let w=[];f.references.onDelete&&w.push(`onDelete: ${x(f.references.onDelete)}`),f.references.onUpdate&&w.push(`onUpdate: ${x(f.references.onUpdate)}`),h+=`.references(() => ${k.tableName}.${k.fieldName}, { ${w.join(", ")} })`;}else h+=`.references(() => ${k.tableName}.${k.fieldName})`;if(f.unique){let w=typeof f.unique=="object"&&f.unique.name?f.unique.name:`${l}_${P(b)}_unique_idx`;d.push(` t.uniqueIndex(${x(w)}).on(table.${b})`);}if(f.index){let w=typeof f.index=="object"&&f.index.name?f.index.name:`${l}_${P(b)}_idx`;d.push(` t.index(${x(w)}).on(table.${b})`);}c.push(` ${b}: ${h},`);}d.length>0?a.push(`export const ${i} = table(
|
|
7445
7449
|
${x(l)},
|
|
7446
7450
|
{
|
|
7447
7451
|
${c.join(`
|
|
@@ -7454,16 +7458,16 @@ ${d.join(`,
|
|
|
7454
7458
|
);`):a.push(`export const ${i} = table(${x(l)}, {
|
|
7455
7459
|
${c.join(`
|
|
7456
7460
|
`)}
|
|
7457
|
-
});`);let g=Object.entries(s.relations).filter(([,
|
|
7458
|
-
fields: [${i}.${
|
|
7459
|
-
references: [${f.targetTable}.${
|
|
7460
|
-
}),`);}for(let[
|
|
7461
|
+
});`);let g=Object.entries(s.relations).filter(([,b])=>b.relation==="one"),u=Object.entries(s.relations).filter(([,b])=>b.relation==="many");if(g.length===0&&u.length===0)continue;let y=[];for(let[b,f]of g){let h=pr(i,s,f);y.push(` ${b}: one(${f.targetTable}, {
|
|
7462
|
+
fields: [${i}.${h.sourceField}],
|
|
7463
|
+
references: [${f.targetTable}.${h.targetField}],
|
|
7464
|
+
}),`);}for(let[b,f]of u)y.push(` ${b}: many(${f.targetTable}),`);o.push(`export const ${i}Relations = relations(${i}, ({ one, many }) => ({
|
|
7461
7465
|
${y.join(`
|
|
7462
7466
|
`)}
|
|
7463
7467
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
7464
7468
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
7465
7469
|
import { relations } from "drizzle-orm";
|
|
7466
|
-
${
|
|
7470
|
+
${mr(r)}
|
|
7467
7471
|
${a.join(`
|
|
7468
7472
|
|
|
7469
7473
|
`)}
|
|
@@ -7471,7 +7475,7 @@ ${a.join(`
|
|
|
7471
7475
|
${o.join(`
|
|
7472
7476
|
|
|
7473
7477
|
`)}
|
|
7474
|
-
`}function
|
|
7478
|
+
`}function Qe(t,e,n){let r="z.unknown()";return t.type==="int"?r="z.number().int()":t.type==="string"?(r="z.string()",t.length!==void 0&&(r+=`.max(${t.length})`)):t.type==="boolean"?r="z.boolean()":t.type==="date"&&(r="z.date()"),e&&(r+=".optional()"),n&&(r+=".nullable()"),r}function br(t){let e=[];for(let[n,r]of Object.entries(t.tables)){let a=_e(n),o=[],i=[];for(let[s,l]of Object.entries(r.columns))o.push(` ${s}: ${Qe(l,Ke(l),$(l))},`),i.push(` ${s}: ${Qe(l,$(l),$(l))},`);e.push(`export const ${n}InsertSchema = z.object({
|
|
7475
7479
|
${o.join(`
|
|
7476
7480
|
`)}
|
|
7477
7481
|
});
|
|
@@ -7485,7 +7489,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
7485
7489
|
`);}return `import { z } from "zod";
|
|
7486
7490
|
|
|
7487
7491
|
${e.join(`
|
|
7488
|
-
`)}`}function
|
|
7492
|
+
`)}`}function yr(t){return t.type==="int"?"number":t.type==="string"?"string":t.type==="boolean"?"boolean":t.type==="date"?"Date":"unknown"}function xr(t){let e=[];for(let[n,r]of Object.entries(t.tables)){let a=_e(n),o=[],i=[];for(let[s,l]of Object.entries(r.columns)){let c=yr(l),d=$(l)?" | null":"";o.push(` ${s}${$(l)?"?":""}: ${c}${d};`),i.push(` ${s}${Ke(l)?"?":""}: ${c}${d};`);}e.push(`export type ${a} = {
|
|
7489
7493
|
${o.join(`
|
|
7490
7494
|
`)}
|
|
7491
7495
|
};
|
|
@@ -7496,11 +7500,11 @@ ${i.join(`
|
|
|
7496
7500
|
};`);}return `${e.join(`
|
|
7497
7501
|
|
|
7498
7502
|
`)}
|
|
7499
|
-
`}function xr(t,e){if(e){let n=t[e];if(!W(n))throw new Error(`schemaDsl.exportName '${e}' does not point to a schema() export.`);return n}for(let n of Object.values(t))if(W(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function Ke(t){let e=t.config.schemaDsl;if(!e)return;let n=e.namingStrategy??"camelToSnake",r=path.resolve(t.configDir,e.entry),a=path.resolve(t.configDir,e.outFile??path.resolve(t.outDirAbs,"schema.compiled.ts")),o=path.resolve(t.configDir,e.typesOutFile??path.resolve(t.outDirAbs,"schema.types.ts")),i=path.resolve(t.configDir,e.zodOutFile??path.resolve(t.outDirAbs,"schema.zod.ts")),l=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),c=xr(l,e.exportName),d=cr(c);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 g=fr(d,n),u=yr(d),y=hr(d);return await Promise.all([Bun.write(a,g),Bun.write(o,u),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(d.tables)}}function vr(t){return t.replaceAll("\\","/")}function S(t,e){let n=vr(path.relative(t,e)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Rr=new Set([".ts",".tsx",".mts",".cts"]);async function Ye(t){let e=await promises.readdir(t,{withFileTypes:true}),n=[];for(let r of e){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(t,r.name);if(r.isDirectory()){n.push(...await Ye(a));continue}r.isFile()&&Rr.has(path.extname(r.name))&&n.push(a);}return n}function Q(t){return t.replace(/\.[cm]?tsx?$/,"")}function Ar(t,e){let n=t,r=false,a,o="unknown";for(;m__namespace.isCallExpression(n);){let i=n.expression;if(!m__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&&(m__namespace.isStringLiteral(l)||m__namespace.isNumericLiteral(l)?a=l.text:l.kind===m__namespace.SyntaxKind.TrueKeyword?a="true":l.kind===m__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:e,type:o,optional:r,defaultValue:a}}function $r(t){if(!t||!m__namespace.isObjectLiteralExpression(t))return [];let e=t.properties.find(r=>m__namespace.isPropertyAssignment(r)&&m__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!e||!m__namespace.isObjectLiteralExpression(e.initializer))return [];let n=[];for(let r of e.initializer.properties)!m__namespace.isPropertyAssignment(r)||!m__namespace.isIdentifier(r.name)||n.push(Ar(r.initializer,r.name.text));return n}function Nr(t){return m__namespace.isVariableStatement(t)?t.modifiers?.some(e=>e.kind===m__namespace.SyntaxKind.ExportKeyword)??false:false}function Xe(t){return m__namespace.isIdentifier(t)?t.text:m__namespace.isParenthesizedExpression(t)?Xe(t.expression):null}function qr(t){if(!t||!m__namespace.isObjectLiteralExpression(t))return [];let e=t.properties.find(r=>!m__namespace.isPropertyAssignment(r)||!m__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!e||!m__namespace.isPropertyAssignment(e))return [];let n=e.initializer;return m__namespace.isStringLiteral(n)||m__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):m__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>m__namespace.isStringLiteral(r)||m__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Cr(t,e){let n=m__namespace.createSourceFile(e,t,m__namespace.ScriptTarget.Latest,true,m__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(Nr(a))for(let o of a.declarationList.declarations){if(!m__namespace.isIdentifier(o.name)||!o.initializer||!m__namespace.isCallExpression(o.initializer))continue;let i=Xe(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"?qr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?$r(o.initializer.arguments[0]):[]});}return r}function Ge(t,e,n){let r=e.replace(/\\/g,"/"),o=Q(r).split("/").filter(Boolean);return `/${[t,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Pr(t,e){let n=t.replace(/\\/g,"/"),r=`${e}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===e?"index.ts":n}function Je(t,e){let n=t.replace(/\\/g,"/"),a=Q(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,e].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function tn(t){let e=[],n=await Ye(t.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(t.scanDirAbs,a),l=Cr(i,a),c=[{kind:"query",kindDirectory:"queries",exports:l.filter(d=>d.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:l.filter(d=>d.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:l.filter(d=>d.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:l.filter(d=>d.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:l.filter(d=>d.kind==="storage")}];for(let d of c){if(d.exports.length===0)continue;let g=Pr(s,d.kindDirectory);for(let u of d.exports){let y=d.kind==="query"||d.kind==="mutation"?Je(g,u.exportName):void 0,h=d.kind==="scheduler"||d.kind==="cron"?Je(g,u.exportName):void 0,f=d.kind==="query"||d.kind==="mutation"?[...Q(g).split("/").filter(Boolean),u.exportName]:void 0,b=d.kind==="query"?Ge("queries",g,u.exportName):d.kind==="mutation"?Ge("mutations",g,u.exportName):d.kind==="storage"?`/storage/managers/${u.exportName}`:`/${d.kindDirectory}/${h}`;e.push({kind:d.kind,exportName:u.exportName,filePath:a,importPath:S(t.outDirAbs,a),clientImportPath:S(path.resolve(t.outDirAbs,"client"),a),routePath:b,handlerName:y,clientSegments:f,taskName:h,cronTriggers:u.cronTriggers,args:u.args});}}}e.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of e){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 e}function Dr(t){let e=[],n="",r=0,a=0,o=0,i=false,s=false,l=false,c=false;for(let g=0;g<t.length;g+=1){let u=t[g];if(c){n+=u,c=false;continue}if(u==="\\"){n+=u,c=true;continue}if(!s&&!l&&u==="'"){i=!i,n+=u;continue}if(!i&&!l&&u==='"'){s=!s,n+=u;continue}if(!i&&!s&&u==="`"){l=!l,n+=u;continue}if(i||s||l){n+=u;continue}if(u==="("?r+=1:u===")"?r-=1:u==="{"?a+=1:u==="}"?a-=1:u==="["?o+=1:u==="]"&&(o-=1),u===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&e.push(y),n="";continue}n+=u;}let d=n.trim();return d.length>0&&e.push(d),e}function Or(t){let e=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let l=0;l<t.length;l+=1){let c=t[l];if(s){s=false;continue}if(c==="\\"){s=true;continue}if(!o&&!i&&c==="'"){a=!a;continue}if(!a&&!i&&c==='"'){o=!o;continue}if(!a&&!o&&c==="`"){i=!i;continue}if(!(a||o||i)){if(c==="("){e+=1;continue}if(c===")"){e-=1;continue}if(c==="{"){n+=1;continue}if(c==="}"){n-=1;continue}if(c==="["){r+=1;continue}if(c==="]"){r-=1;continue}if(c===":"&&e===0&&n===0&&r===0)return l}}return -1}function Ir(t){let e=t.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(e)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(e)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(e)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(e)?"number":/\.(text|varchar|char)\s*\(/.test(e)?"string":/\.(boolean|bool)\s*\(/.test(e)?"boolean":"unknown"}function Mr(t){let e=Dr(t),n=[];for(let r of e){let a=Or(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),c=/\.default\s*\(/i.test(i),g=!/\.notnull\s*\(/i.test(i)||c||l;n.push({name:o,expression:i,type:Ir(i),optional:g,primaryKey:s,autoIncrement:l});}return n}function Fr(t){let e=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,l=false,c=false,d=false,g=false;for(let u=i;u<o.length;u+=1){let y=o[u];if(g){g=false;continue}if(y==="\\"){g=true;continue}if(!c&&!d&&y==="'"){l=!l;continue}if(!l&&!d&&y==='"'){c=!c;continue}if(!l&&!c&&y==="`"){d=!d;continue}if(!(l||c||d)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return u}}return -1},a=e.exec(t);for(;a;){let o=a[1],i=a[2],s=t.indexOf("{",e.lastIndex);if(s===-1){a=e.exec(t);continue}let l=r(t,s);if(l===-1){a=e.exec(t);continue}let c=t.slice(s+1,l);n.push({exportName:o,tableName:i,columns:Mr(c)}),a=e.exec(t);}return n}async function nn(t){let e=await promises.readdir(t,{withFileTypes:true}),n=[];for(let r of e){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(t,r.name);if(r.isDirectory()){n.push(...await nn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function rn(t,e=[]){let n=await nn(t.scanDirAbs).catch(()=>[]),r=path.resolve(t.configDir,"schema.ts"),a=[...e,...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=Fr(s);if(l.length>0)return {schemaPath:o,tables:l}}throw new Error(`Unable to discover schema.ts under scanDir (${t.scanDirAbs}) or fallback (${r}).`)}function jr(t,e){let n=path.relative(t,e).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function an(t){let{outDirAbs:e,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=t,i=S(e,a),s=path.resolve(e,"client"),l=S(s,a);await Promise.all([promises.mkdir(e,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]);let c=path.resolve(e,"server.ts"),d=path.resolve(e,"client.ts"),g=path.resolve(e,"auth.config.ts"),u=path.resolve(e,"auth.schema.ts"),y=path.resolve(e,"drizzle.config.ts"),h=path.resolve(n,"wrangler.json"),f=await Ke(t),b=await rn(t,f?[f.schemaPath]:[]),R=S(e,b.schemaPath),v=await tn(t),fn=Yt(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),hn=rt(l,v),bn=F(R,v,r.r2[0]?.binding),yn=J(i),xn=f?[jr(o,f.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,wn=at(xn),vn=te(t,v),kn=Ve(R,b,v),Tn=path.resolve(e,"admin.routes.ts"),Sn=bn.map(k=>Bun.write(path.resolve(e,k.relativePath),k.source)),Rn=hn.map(k=>Bun.write(path.resolve(e,k.relativePath),k.source));await Promise.all([Bun.write(c,fn),Bun.write(d,`export * from "./client/index";
|
|
7500
|
-
`),...Rn
|
|
7501
|
-
`),Bun.write(Tn
|
|
7503
|
+
`}function wr(t,e){if(e){let n=t[e];if(!L(n))throw new Error(`schemaDsl.exportName '${e}' does not point to a schema() export.`);return n}for(let n of Object.values(t))if(L(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function Ge(t){let e=t.config.schemaDsl;if(!e)return;let n=e.namingStrategy??"camelToSnake",r=path.resolve(t.configDir,e.entry),a=path.resolve(t.configDir,e.outFile??path.resolve(t.outDirAbs,"schema.compiled.ts")),o=path.resolve(t.configDir,e.typesOutFile??path.resolve(t.outDirAbs,"schema.types.ts")),i=path.resolve(t.configDir,e.zodOutFile??path.resolve(t.outDirAbs,"schema.zod.ts")),l=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),c=wr(l,e.exportName),d=ur(c);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 g=hr(d,n),u=xr(d),y=br(d);return await Promise.all([Bun.write(a,g),Bun.write(o,u),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(d.tables)}}function kr(t){return t.replaceAll("\\","/")}function R(t,e){let n=kr(path.relative(t,e)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Ar=new Set([".ts",".tsx",".mts",".cts"]);async function Xe(t){let e=await promises.readdir(t,{withFileTypes:true}),n=[];for(let r of e){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(t,r.name);if(r.isDirectory()){n.push(...await Xe(a));continue}r.isFile()&&Ar.has(path.extname(r.name))&&n.push(a);}return n}function _(t){return t.replace(/\.[cm]?tsx?$/,"")}function $r(t,e){let n=t,r=false,a,o="unknown";for(;m__namespace.isCallExpression(n);){let i=n.expression;if(!m__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&&(m__namespace.isStringLiteral(l)||m__namespace.isNumericLiteral(l)?a=l.text:l.kind===m__namespace.SyntaxKind.TrueKeyword?a="true":l.kind===m__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:e,type:o,optional:r,defaultValue:a}}function Nr(t){if(!t||!m__namespace.isObjectLiteralExpression(t))return [];let e=t.properties.find(r=>m__namespace.isPropertyAssignment(r)&&m__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!e||!m__namespace.isObjectLiteralExpression(e.initializer))return [];let n=[];for(let r of e.initializer.properties)!m__namespace.isPropertyAssignment(r)||!m__namespace.isIdentifier(r.name)||n.push($r(r.initializer,r.name.text));return n}function qr(t){return m__namespace.isVariableStatement(t)?t.modifiers?.some(e=>e.kind===m__namespace.SyntaxKind.ExportKeyword)??false:false}function tn(t){return m__namespace.isIdentifier(t)?t.text:m__namespace.isParenthesizedExpression(t)?tn(t.expression):null}function Cr(t){if(!t||!m__namespace.isObjectLiteralExpression(t))return [];let e=t.properties.find(r=>!m__namespace.isPropertyAssignment(r)||!m__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!e||!m__namespace.isPropertyAssignment(e))return [];let n=e.initializer;return m__namespace.isStringLiteral(n)||m__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):m__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>m__namespace.isStringLiteral(r)||m__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Pr(t,e){let n=m__namespace.createSourceFile(e,t,m__namespace.ScriptTarget.Latest,true,m__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(qr(a))for(let o of a.declarationList.declarations){if(!m__namespace.isIdentifier(o.name)||!o.initializer||!m__namespace.isCallExpression(o.initializer))continue;let i=tn(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"?Cr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?Nr(o.initializer.arguments[0]):[]});}return r}function Je(t,e,n){let r=e.replace(/\\/g,"/"),o=_(r).split("/").filter(Boolean);return `/${[t,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Dr(t,e){let n=t.replace(/\\/g,"/"),r=`${e}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===e?"index.ts":n}function Ze(t,e){let n=t.replace(/\\/g,"/"),a=_(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,e].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function en(t){let e=[],n=await Xe(t.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(t.scanDirAbs,a),l=Pr(i,a),c=[{kind:"query",kindDirectory:"queries",exports:l.filter(d=>d.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:l.filter(d=>d.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:l.filter(d=>d.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:l.filter(d=>d.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:l.filter(d=>d.kind==="storage")}];for(let d of c){if(d.exports.length===0)continue;let g=Dr(s,d.kindDirectory);for(let u of d.exports){let y=d.kind==="query"||d.kind==="mutation"?Ze(g,u.exportName):void 0,b=d.kind==="scheduler"||d.kind==="cron"?Ze(g,u.exportName):void 0,f=d.kind==="query"||d.kind==="mutation"?[..._(g).split("/").filter(Boolean),u.exportName]:void 0,h=d.kind==="query"?Je("queries",g,u.exportName):d.kind==="mutation"?Je("mutations",g,u.exportName):d.kind==="storage"?`/storage/managers/${u.exportName}`:`/${d.kindDirectory}/${b}`;e.push({kind:d.kind,exportName:u.exportName,filePath:a,importPath:R(t.outDirAbs,a),clientImportPath:R(path.resolve(t.outDirAbs,"client"),a),routePath:h,handlerName:y,clientSegments:f,taskName:b,cronTriggers:u.cronTriggers,args:u.args});}}}e.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of e){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 e}function Er(t){let e=[],n="",r=0,a=0,o=0,i=false,s=false,l=false,c=false;for(let g=0;g<t.length;g+=1){let u=t[g];if(c){n+=u,c=false;continue}if(u==="\\"){n+=u,c=true;continue}if(!s&&!l&&u==="'"){i=!i,n+=u;continue}if(!i&&!l&&u==='"'){s=!s,n+=u;continue}if(!i&&!s&&u==="`"){l=!l,n+=u;continue}if(i||s||l){n+=u;continue}if(u==="("?r+=1:u===")"?r-=1:u==="{"?a+=1:u==="}"?a-=1:u==="["?o+=1:u==="]"&&(o-=1),u===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&e.push(y),n="";continue}n+=u;}let d=n.trim();return d.length>0&&e.push(d),e}function Ir(t){let e=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let l=0;l<t.length;l+=1){let c=t[l];if(s){s=false;continue}if(c==="\\"){s=true;continue}if(!o&&!i&&c==="'"){a=!a;continue}if(!a&&!i&&c==='"'){o=!o;continue}if(!a&&!o&&c==="`"){i=!i;continue}if(!(a||o||i)){if(c==="("){e+=1;continue}if(c===")"){e-=1;continue}if(c==="{"){n+=1;continue}if(c==="}"){n-=1;continue}if(c==="["){r+=1;continue}if(c==="]"){r-=1;continue}if(c===":"&&e===0&&n===0&&r===0)return l}}return -1}function Fr(t){let e=t.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(e)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(e)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(e)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(e)?"number":/\.(text|varchar|char)\s*\(/.test(e)?"string":/\.(boolean|bool)\s*\(/.test(e)?"boolean":"unknown"}function Mr(t){let e=Er(t),n=[];for(let r of e){let a=Ir(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),c=/\.default\s*\(/i.test(i),g=!/\.notnull\s*\(/i.test(i)||c||l||s;n.push({name:o,expression:i,type:Fr(i),optional:g,primaryKey:s,autoIncrement:l});}return n}function jr(t){let e=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,l=false,c=false,d=false,g=false;for(let u=i;u<o.length;u+=1){let y=o[u];if(g){g=false;continue}if(y==="\\"){g=true;continue}if(!c&&!d&&y==="'"){l=!l;continue}if(!l&&!d&&y==='"'){c=!c;continue}if(!l&&!c&&y==="`"){d=!d;continue}if(!(l||c||d)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return u}}return -1},a=e.exec(t);for(;a;){let o=a[1],i=a[2],s=t.indexOf("{",e.lastIndex);if(s===-1){a=e.exec(t);continue}let l=r(t,s);if(l===-1){a=e.exec(t);continue}let c=t.slice(s+1,l);n.push({exportName:o,tableName:i,columns:Mr(c)}),a=e.exec(t);}return n}async function rn(t){let e=await promises.readdir(t,{withFileTypes:true}),n=[];for(let r of e){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(t,r.name);if(r.isDirectory()){n.push(...await rn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function an(t,e=[]){let n=await rn(t.scanDirAbs).catch(()=>[]),r=path.resolve(t.configDir,"schema.ts"),a=[...e,...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=jr(s);if(l.length>0)return {schemaPath:o,tables:l}}throw new Error(`Unable to discover schema.ts under scanDir (${t.scanDirAbs}) or fallback (${r}).`)}function Br(t,e){let n=path.relative(t,e).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function on(t){let{outDirAbs:e,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=t,i=R(e,a),s=path.resolve(e,"client"),l=R(s,a);await Promise.all([promises.mkdir(e,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]);let c=path.resolve(e,"server.ts"),d=path.resolve(e,"client.ts"),g=path.resolve(e,"auth.config.ts"),u=path.resolve(e,"auth.schema.ts"),y=path.resolve(e,"drizzle.config.ts"),b=path.resolve(n,"wrangler.json"),f=await Ge(t),h=await an(t,f?[f.schemaPath]:[]),k=R(e,h.schemaPath),w=await en(t),hn=Xt(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),bn=at(l,w),yn=j(k,w,r.r2[0]?.binding),xn=Z(i),wn=f?[Br(o,f.schemaPath),...r.schema.filter(T=>!/(^|\/)schema\.ts$/.test(T))]:r.schema,vn=ot(wn),kn=ee(t,w),Tn=ze(k,h,w),Sn=path.resolve(e,"admin.routes.ts"),Rn=yn.map(T=>Bun.write(path.resolve(e,T.relativePath),T.source)),An=bn.map(T=>Bun.write(path.resolve(e,T.relativePath),T.source));await Promise.all([Bun.write(c,hn),Bun.write(d,`export * from "./client/index";
|
|
7504
|
+
`),...An,...Rn,Bun.write(g,xn),Bun.write(u,""),Bun.write(y,vn),Bun.write(b,`${JSON.stringify(kn,null,2)}
|
|
7505
|
+
`),Bun.write(Sn,Tn)]);let E=path.relative(o,g).replace(/\\/g,"/"),$n=E.startsWith(".")?E:`./${E}`,I=path.relative(o,u).replace(/\\/g,"/"),Nn=I.startsWith(".")?I:`./${I}`,J=await Bun.spawn(["npx","@better-auth/cli","generate","--config",$n,"--output",Nn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(J!==0)throw new Error(`better-auth generation failed with exit code ${J}`)}var sn=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(),ln=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),cn=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(),un=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),queue:zod.z.string().min(1).optional()}).strict(),Wr=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(),Lr=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([sn,zod.z.array(sn).min(1)]),kv:zod.z.union([ln,zod.z.array(ln)]).optional(),r2:zod.z.union([cn,zod.z.array(cn)]).optional(),auth:zod.z.object({enabled:zod.z.boolean(),basePath:zod.z.string().min(1),options:zod.z.custom(t=>typeof t=="object"&&t!==null),clientOptions:zod.z.custom(t=>typeof t=="object"&&t!==null)}).strict(),scheduler:un.optional(),realtime:Wr.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}).strict();function dn(t){return typeof t=="object"&&t!==null}function Ur(t){let e=dn(t.wranglerOverrides)?t.wranglerOverrides.scheduler:void 0,n=un.safeParse(e);return n.success?n.data:{}}function Qr(t){if(!dn(t)||!("scheduler"in t))return t;let{scheduler:e,...n}=t;return n}function _r(t){let n={...Ur(t)??{},...t.scheduler??{}},r=t.realtime??{};return {...t,database:Array.isArray(t.database)?t.database:[t.database],kv:t.kv?Array.isArray(t.kv)?t.kv:[t.kv]:[],r2:t.r2?Array.isArray(t.r2)?t.r2:[t.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:Qr(t.wranglerOverrides),wranglerOutDir:t.wranglerOutDir??t.wranglerOutPath??t.outDir}}async function N(t){let e=path.isAbsolute(t??"")?t:path.resolve(process.cwd(),t??"appflare.config.ts"),n=path.dirname(e),o=(await import(url.pathToFileURL(e).href)).default,i=Lr.parse(o),s=_r(i);return {configPath:e,configDir:n,scanDirAbs:path.resolve(n,s.scanDir),outDirAbs:path.resolve(n,s.outDir),wranglerOutDirAbs:path.resolve(n,s.wranglerOutDir),config:s}}function Zr(t){let e=t;for(;;){if(fs.existsSync(path.resolve(e,"package.json")))return e;let n=path.dirname(e);if(n===e)return t;e=n;}}async function O(t){let e=await N(t);if(await on(e),e.wranglerOutDirAbs===e.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${e.outDirAbs}
|
|
7502
7506
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${e.outDirAbs} and wrangler.json in ${e.wranglerOutDirAbs}
|
|
7503
|
-
`);}async function
|
|
7504
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
7507
|
+
`);}async function mn(t,e=false){if(await O(t),!e)return;let n=await N(t),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await O(t);}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
7508
|
+
`);}finally{r=false,a&&(a=false,await o());}};Kr__default.default.watch(n.scanDirAbs,{ignoreInitial:true}).on("all",async(s,l)=>{process.stdout.write(`\u{1F504} Change detected: ${l}
|
|
7505
7509
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
7506
|
-
`);}async function
|
|
7510
|
+
`);}async function gn(t,e={}){let n=await N(t),r=Zr(process.cwd());if([!!e.local,!!e.remote,!!e.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 c=n.config.database[0].databaseName,d=[i,"wrangler","d1","migrations","apply",c];e.local?d.push("--local"):e.remote?d.push("--remote"):e.preview&&d.push("--preview");let u=await Bun.spawn(d,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(u!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${u}`)}async function fn(t,e={name:"",email:"",password:""}){let n=await N(t);if([!!e.local,!!e.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(e.password),i=crypto.randomUUID(),s=crypto.randomUUID(),l=Date.now(),c=e.name.replace(/'/g,"''"),d=e.email.replace(/'/g,"''"),g=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${c}', '${d}', 1, ${l}, ${l}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${d}', 'credential', '${i}', '${o}', ${l}, ${l});`].join(" "),u=n.config.database[0].databaseName,b=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",u,`--command=${g}`];e.local?b.push("--local"):e.remote&&b.push("--remote");let h=await Bun.spawn(b,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(h!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${h}`);console.log("\u2705 Admin user "+e.email+" created successfully!");}var A=new commander.Command;A.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");A.command("build").description("Generate server.ts, client.ts, auth.config.ts, drizzle.config.ts, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").action(async t=>{await O(t.config);});A.command("dev").description("Run generator in development mode").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("-w, --watch","Watch scanDir and regenerate on changes",false).action(async t=>{await mn(t.config,t.watch);});A.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 t=>{await gn(t.config,{local:t.local,remote:t.remote,preview:t.preview});});A.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 t=>{await fn(t.config,{name:t.name,email:t.email,password:t.password,local:t.local,remote:t.remote});});(async()=>{process.versions.bun||(console.error("Appflare CLI must be run with Bun."),process.exit(1)),await A.parseAsync(process.argv);})().catch(t=>{console.error(t),process.exit(1);});
|