appflare 0.2.49 → 0.2.51
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/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'),ja=require('chokidar'),fs=require('fs'),path=require('path'),promises=require('fs/promises'),url=require('url'),f=require('typescript'),zod=require('zod');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;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 ja__default=/*#__PURE__*/_interopDefault(ja);var f__namespace=/*#__PURE__*/_interopNamespace(f);function ve(e){return `import { betterAuth } from "better-auth";
|
|
3
3
|
import { withCloudflare } from "better-auth-cloudflare";
|
|
4
4
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
5
5
|
import { drizzle } from "drizzle-orm/d1";
|
|
@@ -57,7 +57,7 @@ export const createAuth = (
|
|
|
57
57
|
});
|
|
58
58
|
};
|
|
59
59
|
export const auth = createAuth();
|
|
60
|
-
`}function
|
|
60
|
+
`}function Re(){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
61
61
|
import type {
|
|
62
62
|
AppflareAuth,
|
|
63
63
|
AppflareAuthTokenResolver,
|
|
@@ -166,8 +166,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
166
166
|
): Appflare<Options> {
|
|
167
167
|
return new Appflare(options);
|
|
168
168
|
}
|
|
169
|
-
`}function ar(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function
|
|
170
|
-
`)}function ir(e,t){if(e.kind!=="query"&&e.kind!=="mutation")return null;let n=e.clientSegments&&e.clientSegments.length>0?e.clientSegments:e.routePath.replace(/^\//,"").split("/").filter(Boolean).slice(1);if(n.length>=2&&n[n.length-1]===n[n.length-2]&&n.pop(),n.length===0)return null;let r=ar(`op_${t}_${e.kind}_${n.join("_")}`);return {kind:e.kind,routePath:e.routePath,queryName:e.handlerName??n.join("/"),segments:n,importPath:e.clientImportPath,exportName:e.exportName,alias:r,schemaConst:`${r}Schema`,typeBase:`${
|
|
169
|
+
`}function ar(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function ke(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function or(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function Se(e){let t={children:new Map};for(let n of e){let r=t;for(let a of n.segments){let o=r.children.get(a);o||(o={children:new Map},r.children.set(a,o)),r=o;}r.operation=n;}return t}function G(e,t=1){let n=" ".repeat(t),r=" ".repeat(t+1),a=Array.from(e.children.entries()).sort(([i],[s])=>i.localeCompare(s));if(a.length===0)return e.operation?`${e.operation.alias}Route(runtime)`:"{}";let o=["{"];for(let[i,s]of a)o.push(`${r}${or(i)}: ${G(s,t+1)},`);return e.operation&&(o.push(`${r}run: ${e.operation.alias}Route(runtime).run,`),o.push(`${r}schema: ${e.operation.alias}Route(runtime).schema,`),e.operation.kind==="query"&&(o.push(`${r}subscribe: ${e.operation.alias}Route(runtime).subscribe,`),o.push(`${r}queryKey: ${e.operation.alias}Route(runtime).queryKey,`))),o.push(`${n}}`),o.join(`
|
|
170
|
+
`)}function ir(e,t){if(e.kind!=="query"&&e.kind!=="mutation")return null;let n=e.clientSegments&&e.clientSegments.length>0?e.clientSegments:e.routePath.replace(/^\//,"").split("/").filter(Boolean).slice(1);if(n.length>=2&&n[n.length-1]===n[n.length-2]&&n.pop(),n.length===0)return null;let r=ar(`op_${t}_${e.kind}_${n.join("_")}`);return {kind:e.kind,routePath:e.routePath,queryName:e.handlerName??n.join("/"),segments:n,importPath:e.clientImportPath,exportName:e.exportName,alias:r,schemaConst:`${r}Schema`,typeBase:`${ke(e.kind)}${ke(n.join("_"))}`}}function sr(e){let t=`${e.typeBase}Input`,n=`${e.typeBase}Output`,r=`${e.typeBase}Schema`,a=e.kind==="query"?"GET":"POST";return e.kind==="query"?`const ${e.alias}Route = (
|
|
171
171
|
runtime: RequestRuntime,
|
|
172
172
|
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
173
173
|
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
@@ -358,15 +358,15 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
358
358
|
schema: ${r},
|
|
359
359
|
run,
|
|
360
360
|
};
|
|
361
|
-
};`}function
|
|
362
|
-
`),o=t.map(
|
|
363
|
-
export type ${
|
|
364
|
-
export type ${p} = Awaited<ReturnType<typeof ${
|
|
365
|
-
export const ${d} = ${
|
|
361
|
+
};`}function Z(e){let t=e.map((u,l)=>ir(u,l)).filter(u=>u!==null),n=t.filter(u=>u.kind==="query"),r=t.filter(u=>u.kind==="mutation"),a=t.map(u=>`import { ${u.exportName} as ${u.alias} } from "${u.importPath}";`).join(`
|
|
362
|
+
`),o=t.map(u=>{let l=`${u.typeBase}Input`,p=`${u.typeBase}Output`,d=`${u.typeBase}Schema`;return `const ${u.schemaConst} = z.object(${u.alias}.definition.args);
|
|
363
|
+
export type ${l} = z.input<typeof ${u.schemaConst}>;
|
|
364
|
+
export type ${p} = Awaited<ReturnType<typeof ${u.alias}.definition.handler>>;
|
|
365
|
+
export const ${d} = ${u.schemaConst};`}).join(`
|
|
366
366
|
|
|
367
|
-
`),i=t.map(
|
|
367
|
+
`),i=t.map(u=>sr(u)).join(`
|
|
368
368
|
|
|
369
|
-
`),s=
|
|
369
|
+
`),s=G(Se(n)),c=G(Se(r));return `import { z } from "zod";
|
|
370
370
|
import type {
|
|
371
371
|
AppflareErrorMode,
|
|
372
372
|
AppflareRequestError,
|
|
@@ -742,11 +742,11 @@ export function createMutationsClient(
|
|
|
742
742
|
|
|
743
743
|
export type QueriesClient = ReturnType<typeof createQueriesClient>;
|
|
744
744
|
export type MutationsClient = ReturnType<typeof createMutationsClient>;
|
|
745
|
-
`}function
|
|
745
|
+
`}function Ae(){return `export * from "./types";
|
|
746
746
|
export * from "./appflare";
|
|
747
747
|
export * from "./storage";
|
|
748
748
|
export * from "./handlers";
|
|
749
|
-
`}function
|
|
749
|
+
`}function Ne(){return `import type { StorageClient, StorageSignedUrlResponse, StorageListResponse } from "./types";
|
|
750
750
|
|
|
751
751
|
type AuthTokenResolver = (() => string | Promise<string>) | undefined;
|
|
752
752
|
|
|
@@ -938,7 +938,7 @@ export function createStorageClient(
|
|
|
938
938
|
},
|
|
939
939
|
};
|
|
940
940
|
}
|
|
941
|
-
`}function
|
|
941
|
+
`}function $e(e){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
942
942
|
import type appflareConfig from "${e}";
|
|
943
943
|
|
|
944
944
|
export type AppflareConfig = typeof appflareConfig;
|
|
@@ -1122,7 +1122,7 @@ export type RealtimeSubscriptionResponse = {
|
|
|
1122
1122
|
};
|
|
1123
1123
|
};
|
|
1124
1124
|
};
|
|
1125
|
-
`}function
|
|
1125
|
+
`}function Ce(e,t){return [{relativePath:"client/index.ts",source:Ae()},{relativePath:"client/types.ts",source:$e(e)},{relativePath:"client/storage.ts",source:Ne()},{relativePath:"client/handlers.ts",source:Z(t)},{relativePath:"client/appflare.ts",source:Re()}]}function Fe(e){return `import { defineConfig } from "drizzle-kit";
|
|
1126
1126
|
|
|
1127
1127
|
export default defineConfig({
|
|
1128
1128
|
dialect: "sqlite",
|
|
@@ -1134,7 +1134,7 @@ export default defineConfig({
|
|
|
1134
1134
|
token: "token",
|
|
1135
1135
|
},
|
|
1136
1136
|
});
|
|
1137
|
-
`}function
|
|
1137
|
+
`}function qe(){return `
|
|
1138
1138
|
|
|
1139
1139
|
import { getHeaders } from "./server";
|
|
1140
1140
|
export async function resolveSession(
|
|
@@ -1168,7 +1168,7 @@ export async function resolveSession(
|
|
|
1168
1168
|
}
|
|
1169
1169
|
}
|
|
1170
1170
|
|
|
1171
|
-
`}function
|
|
1171
|
+
`}function Me(){return `
|
|
1172
1172
|
type SchedulerQueueBinding = {
|
|
1173
1173
|
send: (body: unknown, options?: SchedulerEnqueueOptions) => Promise<void>;
|
|
1174
1174
|
};
|
|
@@ -1205,7 +1205,7 @@ type R2BucketBinding = {
|
|
|
1205
1205
|
options?: { expiresIn?: number },
|
|
1206
1206
|
) => Promise<URL>;
|
|
1207
1207
|
};
|
|
1208
|
-
`}function
|
|
1208
|
+
`}function Ee(){return `
|
|
1209
1209
|
export function createScheduler(
|
|
1210
1210
|
queue?: SchedulerQueueBinding,
|
|
1211
1211
|
): Scheduler {
|
|
@@ -1226,7 +1226,7 @@ export function createScheduler(
|
|
|
1226
1226
|
},
|
|
1227
1227
|
};
|
|
1228
1228
|
}
|
|
1229
|
-
`}function
|
|
1229
|
+
`}function je(){return `
|
|
1230
1230
|
function createContextErrorHelpers() {
|
|
1231
1231
|
return {
|
|
1232
1232
|
error: (status: number, message: string, details?: unknown) => {
|
|
@@ -1290,7 +1290,7 @@ function buildSignedRequest(
|
|
|
1290
1290
|
headers,
|
|
1291
1291
|
});
|
|
1292
1292
|
}
|
|
1293
|
-
`}function
|
|
1293
|
+
`}function Oe(){return `
|
|
1294
1294
|
function createStorageApi(
|
|
1295
1295
|
ctx: AppflareContext,
|
|
1296
1296
|
bucket: R2BucketBinding | undefined,
|
|
@@ -1467,7 +1467,7 @@ export async function createExecutionContext(
|
|
|
1467
1467
|
ctx.storage = createStorageApi(ctx, storageBucket);
|
|
1468
1468
|
return ctx;
|
|
1469
1469
|
}
|
|
1470
|
-
`}function
|
|
1470
|
+
`}function De(e){return `import type { Context } from "hono";
|
|
1471
1471
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
1472
1472
|
import { createAuth } from "./auth.config";
|
|
1473
1473
|
import {
|
|
@@ -1486,20 +1486,20 @@ import {
|
|
|
1486
1486
|
createQueryDb,
|
|
1487
1487
|
} from "./handlers";
|
|
1488
1488
|
|
|
1489
|
+
${Me()}
|
|
1490
|
+
|
|
1489
1491
|
${qe()}
|
|
1490
1492
|
|
|
1491
|
-
${
|
|
1493
|
+
${Ee()}
|
|
1492
1494
|
|
|
1493
1495
|
${je()}
|
|
1494
1496
|
|
|
1495
|
-
${Me()}
|
|
1496
|
-
|
|
1497
1497
|
${Ie()}
|
|
1498
1498
|
|
|
1499
|
-
${
|
|
1499
|
+
${Oe()}
|
|
1500
1500
|
|
|
1501
1501
|
${Pe(e)}
|
|
1502
|
-
`}function
|
|
1502
|
+
`}function Ve(){return `
|
|
1503
1503
|
export async function executeOperation<
|
|
1504
1504
|
TShape extends ZodRawShape,
|
|
1505
1505
|
TResult,
|
|
@@ -1540,7 +1540,7 @@ export function handleOperationError(
|
|
|
1540
1540
|
return c.json({ message: (error as Error).message ?? "Unknown error" }, 500);
|
|
1541
1541
|
}
|
|
1542
1542
|
|
|
1543
|
-
`}function
|
|
1543
|
+
`}function Be(){return `import type { Context } from "hono";
|
|
1544
1544
|
import { ZodError, type ZodRawShape } from "zod";
|
|
1545
1545
|
import {
|
|
1546
1546
|
type AppflareContext,
|
|
@@ -1549,8 +1549,8 @@ import {
|
|
|
1549
1549
|
type WorkerEnv,
|
|
1550
1550
|
} from "./handlers";
|
|
1551
1551
|
|
|
1552
|
-
${
|
|
1553
|
-
`}function
|
|
1552
|
+
${Ve()}
|
|
1553
|
+
`}function We(){return `import { betterAuth } from "better-auth";
|
|
1554
1554
|
import { auth } from "./auth.config";
|
|
1555
1555
|
import {
|
|
1556
1556
|
and,
|
|
@@ -1655,7 +1655,7 @@ export async function isStorageAllowed(
|
|
|
1655
1655
|
|
|
1656
1656
|
return false;
|
|
1657
1657
|
}
|
|
1658
|
-
`}function
|
|
1658
|
+
`}function He(){return `type Primitive = string | number | boolean | Date;
|
|
1659
1659
|
type NonNil<T> = Exclude<T, null | undefined>;
|
|
1660
1660
|
type Friendly<T> = T extends Date ? Date | number : T;
|
|
1661
1661
|
type Comparable<T> = Friendly<Extract<NonNil<T>, Primitive>>;
|
|
@@ -1943,7 +1943,7 @@ export type QueryDeleteArgs<TName extends TableName> = {
|
|
|
1943
1943
|
where?: WhereInput<TableModel<TName>, TName>;
|
|
1944
1944
|
limit?: number;
|
|
1945
1945
|
};
|
|
1946
|
-
`}function
|
|
1946
|
+
`}function Le(){return `type AggregateWithInput<TName extends TableName> =
|
|
1947
1947
|
QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1948
1948
|
|
|
1949
1949
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -2075,7 +2075,7 @@ export type DbMutationEvent = {
|
|
|
2075
2075
|
export type QueryDbOptions = {
|
|
2076
2076
|
onMutation?: (event: DbMutationEvent) => void;
|
|
2077
2077
|
};
|
|
2078
|
-
`}function
|
|
2078
|
+
`}function ze(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2079
2079
|
return typeof value === "object" && value !== null;
|
|
2080
2080
|
}
|
|
2081
2081
|
|
|
@@ -3454,17 +3454,22 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
3454
3454
|
|
|
3455
3455
|
return [];
|
|
3456
3456
|
}
|
|
3457
|
-
`}function
|
|
3457
|
+
`}function _e(){return `const mergedSchema = {
|
|
3458
3458
|
...authSchema,
|
|
3459
3459
|
...schema,
|
|
3460
3460
|
};
|
|
3461
3461
|
|
|
3462
|
+
const mergedDbSchema = {
|
|
3463
|
+
...authSchema,
|
|
3464
|
+
...schema.__appflareDbSchema,
|
|
3465
|
+
};
|
|
3466
|
+
|
|
3462
3467
|
export const createDb = (database: D1Database) =>
|
|
3463
|
-
drizzle(database, { schema:
|
|
3468
|
+
drizzle(database, { schema: mergedDbSchema });
|
|
3464
3469
|
|
|
3465
3470
|
export type AppflareDb = ReturnType<typeof createDb>;
|
|
3466
3471
|
|
|
3467
|
-
type SchemaRelations = ExtractTablesWithRelations<typeof
|
|
3472
|
+
type SchemaRelations = ExtractTablesWithRelations<typeof mergedDbSchema>;
|
|
3468
3473
|
type TableName = Extract<keyof SchemaRelations, string>;
|
|
3469
3474
|
type TableRelationConfig<TName extends TableName> =
|
|
3470
3475
|
TName extends keyof SchemaRelations ? SchemaRelations[TName] : never;
|
|
@@ -3478,29 +3483,11 @@ type NativeFindManyWith<TName extends TableName> =
|
|
|
3478
3483
|
NonNullable<TableFindManyArgs<TName>> extends { with?: infer TWith }
|
|
3479
3484
|
? TWith
|
|
3480
3485
|
: never;
|
|
3481
|
-
type NormalizeWhereInWith<TWith, TNativeWith> = TWith extends Record<string, unknown>
|
|
3482
|
-
? {
|
|
3483
|
-
[K in keyof TWith]: K extends keyof TNativeWith
|
|
3484
|
-
? TWith[K] extends Record<string, unknown>
|
|
3485
|
-
? Omit<TWith[K], 'where'> & { where?: NonNullable<Extract<TNativeWith[K], Record<string, unknown>>['where']> } & (TWith[K] extends { with: infer TNestedWith }
|
|
3486
|
-
? { with: NormalizeWhereInWith<TNestedWith, TNativeWith[K]> }
|
|
3487
|
-
: {})
|
|
3488
|
-
: TWith[K]
|
|
3489
|
-
: TWith[K];
|
|
3490
|
-
}
|
|
3491
|
-
: TWith;
|
|
3492
|
-
|
|
3493
3486
|
type ResolveNativeFindManyWith<
|
|
3494
3487
|
TName extends TableName,
|
|
3495
3488
|
TArgs extends QueryFindManyArgs<TName> | undefined,
|
|
3496
3489
|
> = TArgs extends { with?: infer TWith }
|
|
3497
|
-
?
|
|
3498
|
-
? [TResolved] extends [never]
|
|
3499
|
-
? TWith extends Record<string, unknown>
|
|
3500
|
-
? NormalizeWhereInWith<TWith, NativeFindManyWith<TName>>
|
|
3501
|
-
: never
|
|
3502
|
-
: TResolved
|
|
3503
|
-
: never
|
|
3490
|
+
? NormalizeNativeWithForTable<TName, TWith>
|
|
3504
3491
|
: never;
|
|
3505
3492
|
type ResolveTableFindManySelection<
|
|
3506
3493
|
TName extends TableName,
|
|
@@ -3512,7 +3499,7 @@ type ResolveTableFindManySelection<
|
|
|
3512
3499
|
? {}
|
|
3513
3500
|
: { with: ResolveNativeFindManyWith<TName, TArgs> });
|
|
3514
3501
|
type TableModel<TName extends TableName> = InferSelectModel<
|
|
3515
|
-
(typeof
|
|
3502
|
+
(typeof mergedDbSchema)[TName]
|
|
3516
3503
|
>;
|
|
3517
3504
|
type ManyToManySchemaMap = typeof schema extends {
|
|
3518
3505
|
__appflareManyToMany: infer TMap extends Record<string, unknown>;
|
|
@@ -3570,6 +3557,148 @@ type RuntimeRelationTargetTable<
|
|
|
3570
3557
|
}
|
|
3571
3558
|
? Extract<TTarget, TableName>
|
|
3572
3559
|
: never;
|
|
3560
|
+
type NativeRelationEntry<
|
|
3561
|
+
TSourceTable extends TableName,
|
|
3562
|
+
TRelationName extends string,
|
|
3563
|
+
> = TRelationName extends keyof NativeFindManyWith<TSourceTable>
|
|
3564
|
+
? NativeFindManyWith<TSourceTable>[TRelationName]
|
|
3565
|
+
: never;
|
|
3566
|
+
type NativeRelationWhere<TEntry> = Extract<
|
|
3567
|
+
TEntry,
|
|
3568
|
+
Record<string, unknown>
|
|
3569
|
+
> extends {
|
|
3570
|
+
where?: infer TWhere;
|
|
3571
|
+
}
|
|
3572
|
+
? TWhere
|
|
3573
|
+
: never;
|
|
3574
|
+
type ManyToManyJunctionTableName<
|
|
3575
|
+
TSourceTable extends TableName,
|
|
3576
|
+
TRelationName extends string,
|
|
3577
|
+
> = TRelationName extends keyof ManyToManySourceTableMap<TSourceTable>
|
|
3578
|
+
? ManyToManySourceTableMap<TSourceTable>[TRelationName] extends {
|
|
3579
|
+
junctionTable: infer TJunctionTable extends string;
|
|
3580
|
+
}
|
|
3581
|
+
? Extract<TJunctionTable, TableName>
|
|
3582
|
+
: never
|
|
3583
|
+
: never;
|
|
3584
|
+
type CleanRelationConfig<TEntry> = Omit<
|
|
3585
|
+
Extract<TEntry, Record<string, unknown>>,
|
|
3586
|
+
"where" | "with" | "_count" | "_avg"
|
|
3587
|
+
>;
|
|
3588
|
+
type NormalizeNativeRelationConfig<
|
|
3589
|
+
TSourceTable extends TableName,
|
|
3590
|
+
TRelationName extends string,
|
|
3591
|
+
TEntry,
|
|
3592
|
+
> = CleanRelationConfig<TEntry> &
|
|
3593
|
+
(Extract<TEntry, Record<string, unknown>> extends { where?: unknown }
|
|
3594
|
+
? {
|
|
3595
|
+
where?: NativeRelationWhere<
|
|
3596
|
+
NativeRelationEntry<TSourceTable, TRelationName>
|
|
3597
|
+
>;
|
|
3598
|
+
}
|
|
3599
|
+
: {}) &
|
|
3600
|
+
(Extract<TEntry, Record<string, unknown>> extends { with?: infer TNestedWith }
|
|
3601
|
+
? RuntimeRelationTargetTable<TSourceTable, TRelationName> extends infer TTargetTable
|
|
3602
|
+
? TTargetTable extends TableName
|
|
3603
|
+
? {
|
|
3604
|
+
with?: NormalizeNativeWithForTable<TTargetTable, TNestedWith>;
|
|
3605
|
+
}
|
|
3606
|
+
: {}
|
|
3607
|
+
: {}
|
|
3608
|
+
: {});
|
|
3609
|
+
type NormalizeManyToManyTargetConfig<
|
|
3610
|
+
TSourceTable extends TableName,
|
|
3611
|
+
TRelationName extends string,
|
|
3612
|
+
TEntry,
|
|
3613
|
+
> = ManyToManyTargetTableName<
|
|
3614
|
+
TSourceTable,
|
|
3615
|
+
TRelationName
|
|
3616
|
+
> extends infer TTargetTable
|
|
3617
|
+
? TTargetTable extends TableName
|
|
3618
|
+
? CleanRelationConfig<TEntry> &
|
|
3619
|
+
(Extract<TEntry, Record<string, unknown>> extends { where?: unknown }
|
|
3620
|
+
? ManyToManyJunctionTableName<
|
|
3621
|
+
TSourceTable,
|
|
3622
|
+
TRelationName
|
|
3623
|
+
> extends infer TJunctionTable
|
|
3624
|
+
? TJunctionTable extends TableName
|
|
3625
|
+
? {
|
|
3626
|
+
where?: NativeRelationWhere<
|
|
3627
|
+
NativeRelationEntry<TJunctionTable, TTargetTable>
|
|
3628
|
+
>;
|
|
3629
|
+
}
|
|
3630
|
+
: {}
|
|
3631
|
+
: {}
|
|
3632
|
+
: {}) &
|
|
3633
|
+
(Extract<TEntry, Record<string, unknown>> extends {
|
|
3634
|
+
with?: infer TNestedWith;
|
|
3635
|
+
}
|
|
3636
|
+
? {
|
|
3637
|
+
with?: NormalizeNativeWithForTable<TTargetTable, TNestedWith>;
|
|
3638
|
+
}
|
|
3639
|
+
: {})
|
|
3640
|
+
: never
|
|
3641
|
+
: never;
|
|
3642
|
+
type NormalizeRelationInputForTable<
|
|
3643
|
+
TSourceTable extends TableName,
|
|
3644
|
+
TRelationName extends string,
|
|
3645
|
+
TEntry,
|
|
3646
|
+
> = [ManyToManyTargetTableName<TSourceTable, TRelationName>] extends [never]
|
|
3647
|
+
? (Extract<TEntry, true> extends never ? never : true) |
|
|
3648
|
+
(Extract<TEntry, Record<string, unknown>> extends infer TConfig
|
|
3649
|
+
? TConfig extends Record<string, unknown>
|
|
3650
|
+
? NormalizeNativeRelationConfig<
|
|
3651
|
+
TSourceTable,
|
|
3652
|
+
TRelationName,
|
|
3653
|
+
TConfig
|
|
3654
|
+
>
|
|
3655
|
+
: never
|
|
3656
|
+
: never)
|
|
3657
|
+
: ManyToManyTargetTableName<
|
|
3658
|
+
TSourceTable,
|
|
3659
|
+
TRelationName
|
|
3660
|
+
> extends infer TTargetTable
|
|
3661
|
+
? TTargetTable extends TableName
|
|
3662
|
+
? (Extract<TEntry, true> extends never
|
|
3663
|
+
? never
|
|
3664
|
+
: {
|
|
3665
|
+
with: {
|
|
3666
|
+
[K in TTargetTable]: true;
|
|
3667
|
+
};
|
|
3668
|
+
}) |
|
|
3669
|
+
(Extract<TEntry, Record<string, unknown>> extends infer TConfig
|
|
3670
|
+
? TConfig extends Record<string, unknown>
|
|
3671
|
+
? CleanRelationConfig<TConfig> & {
|
|
3672
|
+
with: {
|
|
3673
|
+
[K in TTargetTable]: keyof NormalizeManyToManyTargetConfig<
|
|
3674
|
+
TSourceTable,
|
|
3675
|
+
TRelationName,
|
|
3676
|
+
TConfig
|
|
3677
|
+
> extends never
|
|
3678
|
+
? true
|
|
3679
|
+
: NormalizeManyToManyTargetConfig<
|
|
3680
|
+
TSourceTable,
|
|
3681
|
+
TRelationName,
|
|
3682
|
+
TConfig
|
|
3683
|
+
>;
|
|
3684
|
+
};
|
|
3685
|
+
}
|
|
3686
|
+
: never
|
|
3687
|
+
: never)
|
|
3688
|
+
: never
|
|
3689
|
+
: never;
|
|
3690
|
+
type NormalizeNativeWithForTable<
|
|
3691
|
+
TSourceTable extends TableName,
|
|
3692
|
+
TWith,
|
|
3693
|
+
> = TWith extends Record<string, unknown>
|
|
3694
|
+
? {
|
|
3695
|
+
[K in keyof TWith]: NormalizeRelationInputForTable<
|
|
3696
|
+
TSourceTable,
|
|
3697
|
+
Extract<K, string>,
|
|
3698
|
+
TWith[K]
|
|
3699
|
+
>;
|
|
3700
|
+
}
|
|
3701
|
+
: TWith;
|
|
3573
3702
|
|
|
3574
3703
|
type TargetTableForRelation<
|
|
3575
3704
|
TSource extends TableName,
|
|
@@ -3600,6 +3729,48 @@ type ManyToManyRelationRows<
|
|
|
3600
3729
|
>
|
|
3601
3730
|
>
|
|
3602
3731
|
: Array<TableModel<TTargetTable>>;
|
|
3732
|
+
type NativeManyRelationRows<
|
|
3733
|
+
TSourceTable extends TableName,
|
|
3734
|
+
TRelationName extends string,
|
|
3735
|
+
TRelationArgs,
|
|
3736
|
+
> = RuntimeRelationTargetTable<TSourceTable, TRelationName> extends infer TTarget
|
|
3737
|
+
? TTarget extends TableName
|
|
3738
|
+
? TRelationArgs extends true
|
|
3739
|
+
? Array<TableModel<TTarget>>
|
|
3740
|
+
: TRelationArgs extends Record<string, unknown>
|
|
3741
|
+
? Awaited<
|
|
3742
|
+
TableFindManyResult<
|
|
3743
|
+
TTarget,
|
|
3744
|
+
Extract<
|
|
3745
|
+
Omit<TRelationArgs, "_count" | "_avg">,
|
|
3746
|
+
QueryFindManyArgs<TTarget>
|
|
3747
|
+
>
|
|
3748
|
+
>
|
|
3749
|
+
>
|
|
3750
|
+
: Array<TableModel<TTarget>>
|
|
3751
|
+
: never
|
|
3752
|
+
: never;
|
|
3753
|
+
type NativeOneRelationValue<
|
|
3754
|
+
TSourceTable extends TableName,
|
|
3755
|
+
TRelationName extends string,
|
|
3756
|
+
TRelationArgs,
|
|
3757
|
+
> = RuntimeRelationTargetTable<TSourceTable, TRelationName> extends infer TTarget
|
|
3758
|
+
? TTarget extends TableName
|
|
3759
|
+
? TRelationArgs extends true
|
|
3760
|
+
? TableModel<TTarget> | null
|
|
3761
|
+
: TRelationArgs extends Record<string, unknown>
|
|
3762
|
+
? Awaited<
|
|
3763
|
+
TableFindFirstResult<
|
|
3764
|
+
TTarget,
|
|
3765
|
+
Extract<
|
|
3766
|
+
Omit<TRelationArgs, "_count" | "_avg">,
|
|
3767
|
+
QueryFindFirstArgs<TTarget>
|
|
3768
|
+
>
|
|
3769
|
+
>
|
|
3770
|
+
>
|
|
3771
|
+
: TableModel<TTarget> | null
|
|
3772
|
+
: never
|
|
3773
|
+
: never;
|
|
3603
3774
|
type ReplaceManyToManyRelationsInRow<
|
|
3604
3775
|
TSourceTable extends string,
|
|
3605
3776
|
TRow,
|
|
@@ -3610,15 +3781,33 @@ type ReplaceManyToManyRelationsInRow<
|
|
|
3610
3781
|
? TWith extends Record<string, unknown>
|
|
3611
3782
|
? K extends keyof TWith
|
|
3612
3783
|
? [ManyToManyTargetTableName<Extract<TSourceTable, TableName>, K>] extends [never]
|
|
3613
|
-
?
|
|
3614
|
-
|
|
3615
|
-
|
|
3616
|
-
|
|
3617
|
-
|
|
3618
|
-
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3784
|
+
? RuntimeRelationKind<Extract<TSourceTable, TableName>, K> extends "many"
|
|
3785
|
+
? NativeManyRelationRows<
|
|
3786
|
+
Extract<TSourceTable, TableName>,
|
|
3787
|
+
K,
|
|
3788
|
+
TWith[K]
|
|
3789
|
+
>
|
|
3790
|
+
: RuntimeRelationKind<Extract<TSourceTable, TableName>, K> extends "one"
|
|
3791
|
+
? NativeOneRelationValue<
|
|
3792
|
+
Extract<TSourceTable, TableName>,
|
|
3793
|
+
K,
|
|
3794
|
+
TWith[K]
|
|
3795
|
+
>
|
|
3796
|
+
: ReplaceManyToManyRelationsInRow<
|
|
3797
|
+
[RuntimeRelationTargetTable<
|
|
3798
|
+
Extract<TSourceTable, TableName>,
|
|
3799
|
+
K
|
|
3800
|
+
>] extends [never]
|
|
3801
|
+
? K
|
|
3802
|
+
: RuntimeRelationTargetTable<
|
|
3803
|
+
Extract<TSourceTable, TableName>,
|
|
3804
|
+
K
|
|
3805
|
+
>,
|
|
3806
|
+
TRow[K],
|
|
3807
|
+
TWith[K] extends { with: infer TNestedWith }
|
|
3808
|
+
? TNestedWith
|
|
3809
|
+
: undefined
|
|
3810
|
+
>
|
|
3622
3811
|
: ManyToManyRelationRows<
|
|
3623
3812
|
Extract<ManyToManyTargetTableName<Extract<TSourceTable, TableName>, K>, TableName>,
|
|
3624
3813
|
TWith[K]
|
|
@@ -3691,13 +3880,7 @@ type ResolveNativeFindFirstWith<
|
|
|
3691
3880
|
TName extends TableName,
|
|
3692
3881
|
TArgs extends QueryFindFirstArgs<TName> | undefined,
|
|
3693
3882
|
> = TArgs extends { with?: infer TWith }
|
|
3694
|
-
?
|
|
3695
|
-
? [TResolved] extends [never]
|
|
3696
|
-
? TWith extends Record<string, unknown>
|
|
3697
|
-
? NormalizeWhereInWith<TWith, NativeFindFirstWith<TName>>
|
|
3698
|
-
: never
|
|
3699
|
-
: TResolved
|
|
3700
|
-
: never
|
|
3883
|
+
? NormalizeNativeWithForTable<TName, TWith>
|
|
3701
3884
|
: never;
|
|
3702
3885
|
type ResolveTableFindFirstSelection<
|
|
3703
3886
|
TName extends TableName,
|
|
@@ -3727,11 +3910,11 @@ type TableFindFirstResult<
|
|
|
3727
3910
|
>
|
|
3728
3911
|
>;
|
|
3729
3912
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3730
|
-
(typeof
|
|
3913
|
+
(typeof mergedDbSchema)[TName]
|
|
3731
3914
|
>;
|
|
3732
|
-
`}function Ue(){return [
|
|
3915
|
+
`}function Ue(){return [_e(),He(),Le(),ze()].join(`
|
|
3733
3916
|
|
|
3734
|
-
`)}function
|
|
3917
|
+
`)}function Qe(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3735
3918
|
const withValue = args?.with;
|
|
3736
3919
|
const pathSegments = args?.field
|
|
3737
3920
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -3902,7 +4085,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3902
4085
|
},
|
|
3903
4086
|
}) as AppflareQueryDb;
|
|
3904
4087
|
}
|
|
3905
|
-
`}function
|
|
4088
|
+
`}function Ke(){return `export class AppflareHandledError extends Error {
|
|
3906
4089
|
public readonly status: number;
|
|
3907
4090
|
public readonly payload: unknown;
|
|
3908
4091
|
|
|
@@ -3912,7 +4095,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3912
4095
|
this.payload = payload;
|
|
3913
4096
|
}
|
|
3914
4097
|
}
|
|
3915
|
-
`}function
|
|
4098
|
+
`}function Je(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
3916
4099
|
const where = isRecord(args?.where)
|
|
3917
4100
|
? (args?.where as Record<string, unknown>)
|
|
3918
4101
|
: undefined;
|
|
@@ -4066,7 +4249,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4066
4249
|
);
|
|
4067
4250
|
});
|
|
4068
4251
|
},
|
|
4069
|
-
`}function
|
|
4252
|
+
`}function Ge(){return `export function createQueryDb(
|
|
4070
4253
|
$db: AppflareDb,
|
|
4071
4254
|
options?: QueryDbOptions,
|
|
4072
4255
|
): AppflareQueryDb {
|
|
@@ -4108,7 +4291,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4108
4291
|
};
|
|
4109
4292
|
|
|
4110
4293
|
const tableApi = {
|
|
4111
|
-
`}function
|
|
4294
|
+
`}function Ze(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
4112
4295
|
const transaction = ($db as any).transaction;
|
|
4113
4296
|
|
|
4114
4297
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -5063,9 +5246,9 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
5063
5246
|
);
|
|
5064
5247
|
return rows;
|
|
5065
5248
|
},
|
|
5066
|
-
`}function
|
|
5249
|
+
`}function Xe(){return [Ge(),Je(),Ze(),Qe(),Ke()].join(`
|
|
5067
5250
|
|
|
5068
|
-
`)}function
|
|
5251
|
+
`)}function Ye(e=[],t=[]){let n=t.map(i=>` ${i.name}?: ${i.tsType} | null;`).join(`
|
|
5069
5252
|
`),a=[e.length>0?[" role: UserRole;"," banned: boolean | null;"," banReason?: string | null | undefined;"," banExpires?: Date | null | undefined;"].join(`
|
|
5070
5253
|
`):"",n].filter(Boolean).join(`
|
|
5071
5254
|
`);return `type AuthSession = typeof auth.$Infer.Session;
|
|
@@ -5162,7 +5345,7 @@ export type AppflareContext = {
|
|
|
5162
5345
|
storage: AppflareStorage;
|
|
5163
5346
|
error: (status: number, message: string, details?: unknown) => never;
|
|
5164
5347
|
};
|
|
5165
|
-
`}function
|
|
5348
|
+
`}function et(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
5166
5349
|
|
|
5167
5350
|
export type SchedulerEnqueueOptions = {
|
|
5168
5351
|
delaySeconds?: number;
|
|
@@ -5294,16 +5477,16 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
5294
5477
|
definition,
|
|
5295
5478
|
};
|
|
5296
5479
|
}
|
|
5297
|
-
`}function
|
|
5480
|
+
`}function tt(e=[],t=[]){return [We(),Ue(),Xe(),Ye(e,t),et()].join(`
|
|
5298
5481
|
|
|
5299
|
-
`)}function
|
|
5482
|
+
`)}function nt(e,t=[],n=[]){return `import type { Context } from "hono";
|
|
5300
5483
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5301
5484
|
import { drizzle } from "drizzle-orm/d1";
|
|
5302
5485
|
import { z, type ZodRawShape } from "zod";
|
|
5303
5486
|
import * as authSchema from "./auth.schema";
|
|
5304
5487
|
import * as schema from "${e}";
|
|
5305
5488
|
|
|
5306
|
-
${
|
|
5489
|
+
${tt(t,n)}
|
|
5307
5490
|
`}function lr(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function ur(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return lr(`op_${t}_${n}`)}function cr(e){return e.map((t,n)=>({operation:t,index:n,alias:ur(t,n)}))}function dr(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
5308
5491
|
`)}function pr(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
5309
5492
|
`)}function mr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({alias:t})=>`const ${`${t}SchedulerSchema`} = ${t}.definition.args ? z.object(${t}.definition.args) : z.undefined();`).join(`
|
|
@@ -5354,7 +5537,7 @@ import * as schema from "${e}";
|
|
|
5354
5537
|
},`}).join(`
|
|
5355
5538
|
`)}function xr(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
5356
5539
|
${t}.definition.handler,`).join(`
|
|
5357
|
-
`)}function
|
|
5540
|
+
`)}function rt(e){let t=cr(e);return {imports:dr(t),operationSchemas:pr(t),schedulerSchemas:mr(t),queryRoutes:fr(t),mutationRoutes:gr(t),queryRegistryEntries:hr(t),schedulerEntries:yr(t),schedulerPayloadMapEntries:br(t),cronEntries:wr(t),storageHandlersEntries:xr(t)}}var at=`
|
|
5358
5541
|
function getRealtimeStub(
|
|
5359
5542
|
env: Record<string, unknown>,
|
|
5360
5543
|
options: RegisterHandlersOptions,
|
|
@@ -5428,7 +5611,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
5428
5611
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
5429
5612
|
return url.toString();
|
|
5430
5613
|
}
|
|
5431
|
-
`;var
|
|
5614
|
+
`;var ot=`
|
|
5432
5615
|
export class AppflareRealtimeDurableObject {
|
|
5433
5616
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
5434
5617
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -5571,7 +5754,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
5571
5754
|
return new Response("Not found", { status: 404 });
|
|
5572
5755
|
}
|
|
5573
5756
|
}
|
|
5574
|
-
`;var
|
|
5757
|
+
`;var it=`
|
|
5575
5758
|
async function publishMutationEvents(
|
|
5576
5759
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
5577
5760
|
options: RegisterHandlersOptions,
|
|
@@ -5672,7 +5855,7 @@ async function publishMutationEvents(
|
|
|
5672
5855
|
}
|
|
5673
5856
|
}
|
|
5674
5857
|
}
|
|
5675
|
-
`;var
|
|
5858
|
+
`;var st=`
|
|
5676
5859
|
function registerRealtimeRoutes(
|
|
5677
5860
|
app: Hono<WorkerEnv>,
|
|
5678
5861
|
options: RegisterHandlersOptions,
|
|
@@ -5835,7 +6018,7 @@ function registerRealtimeRoutes(
|
|
|
5835
6018
|
return stub.fetch(c.req.raw);
|
|
5836
6019
|
});
|
|
5837
6020
|
}
|
|
5838
|
-
`;var
|
|
6021
|
+
`;var lt=`
|
|
5839
6022
|
type RealtimeSubscription = {
|
|
5840
6023
|
token: string;
|
|
5841
6024
|
signature: string;
|
|
@@ -5864,7 +6047,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5864
6047
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5865
6048
|
? string
|
|
5866
6049
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5867
|
-
`;var
|
|
6050
|
+
`;var ut=`
|
|
5868
6051
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5869
6052
|
return typeof value === "object" && value !== null;
|
|
5870
6053
|
}
|
|
@@ -6373,9 +6556,9 @@ function doesSubscriptionMatchMutation(
|
|
|
6373
6556
|
|
|
6374
6557
|
return false;
|
|
6375
6558
|
}
|
|
6376
|
-
`;var
|
|
6559
|
+
`;var ct=[lt,ut,at,it,st,ot].join(`
|
|
6377
6560
|
|
|
6378
|
-
`);var
|
|
6561
|
+
`);var dt=`
|
|
6379
6562
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
6380
6563
|
if (!value) {
|
|
6381
6564
|
return undefined;
|
|
@@ -6573,7 +6756,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
6573
6756
|
}
|
|
6574
6757
|
});
|
|
6575
6758
|
}
|
|
6576
|
-
`;var
|
|
6759
|
+
`;var pt=`
|
|
6577
6760
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
6578
6761
|
? string
|
|
6579
6762
|
: keyof typeof schedulerHandlers;
|
|
@@ -6637,7 +6820,7 @@ export async function executeScheduledBatch(
|
|
|
6637
6820
|
}
|
|
6638
6821
|
}
|
|
6639
6822
|
}
|
|
6640
|
-
`;var
|
|
6823
|
+
`;var mt=`
|
|
6641
6824
|
export async function executeCronTriggers(
|
|
6642
6825
|
controller: { cron: string },
|
|
6643
6826
|
env: Record<string, unknown>,
|
|
@@ -6671,7 +6854,7 @@ export async function executeCronTriggers(
|
|
|
6671
6854
|
}
|
|
6672
6855
|
}
|
|
6673
6856
|
}
|
|
6674
|
-
`;function
|
|
6857
|
+
`;function ft(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:c,cronEntries:u,storageHandlersEntries:l}=rt(e);return `import { sValidator } from "@hono/standard-validator";
|
|
6675
6858
|
import type { Hono } from "hono";
|
|
6676
6859
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6677
6860
|
import { ZodError, z } from "zod";
|
|
@@ -6718,19 +6901,19 @@ type CronHandlerEntry = {
|
|
|
6718
6901
|
};
|
|
6719
6902
|
};
|
|
6720
6903
|
|
|
6721
|
-
const cronHandlers: readonly CronHandlerEntry[] = [${
|
|
6904
|
+
const cronHandlers: readonly CronHandlerEntry[] = [${u||`
|
|
6722
6905
|
`}
|
|
6723
6906
|
];
|
|
6724
6907
|
|
|
6725
|
-
const storageHandlers = [${
|
|
6908
|
+
const storageHandlers = [${l||`
|
|
6726
6909
|
`}
|
|
6727
6910
|
] as const;
|
|
6728
6911
|
|
|
6729
6912
|
setStorageHandlers([...storageHandlers]);
|
|
6730
6913
|
|
|
6731
|
-
${
|
|
6914
|
+
${pt}
|
|
6732
6915
|
|
|
6733
|
-
${
|
|
6916
|
+
${ct}
|
|
6734
6917
|
|
|
6735
6918
|
export function registerGeneratedHandlers(
|
|
6736
6919
|
app: Hono<WorkerEnv>,
|
|
@@ -6743,20 +6926,20 @@ export function registerGeneratedHandlers(
|
|
|
6743
6926
|
`}
|
|
6744
6927
|
}
|
|
6745
6928
|
|
|
6746
|
-
${
|
|
6929
|
+
${dt}
|
|
6747
6930
|
|
|
6748
|
-
${
|
|
6749
|
-
`}function
|
|
6750
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
6751
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6752
|
-
}`}function
|
|
6931
|
+
${mt}
|
|
6932
|
+
`}function X(e,t,n,r=[],a=[]){let o=nt(e,r,a),i=De(n),s=Be(),c=ft(t);return [{relativePath:"handlers.ts",source:o},{relativePath:"handlers.context.ts",source:i},{relativePath:"handlers.execution.ts",source:s},{relativePath:"handlers.routes.ts",source:c}]}function Tr(e){return e?`,
|
|
6933
|
+
KV: c.env["${e}"] as KVNamespace`:""}function gt(e,t){return `{
|
|
6934
|
+
DATABASE: c.env["${e}"] as D1Database${Tr(t)}
|
|
6935
|
+
}`}function ht(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6753
6936
|
const auth = createAuth(
|
|
6754
|
-
${
|
|
6937
|
+
${gt(t,n)},
|
|
6755
6938
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
6756
6939
|
);
|
|
6757
6940
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6758
6941
|
});
|
|
6759
|
-
`}function
|
|
6942
|
+
`}function vr(){return `export const getHeaders = (headers: Headers) => {
|
|
6760
6943
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6761
6944
|
const headerObject: Record<string, any> = {};
|
|
6762
6945
|
let hasCookie = false;
|
|
@@ -6792,9 +6975,9 @@ ${pt}
|
|
|
6792
6975
|
});
|
|
6793
6976
|
return newRequest;
|
|
6794
6977
|
};
|
|
6795
|
-
`}function
|
|
6796
|
-
`+Rr()}function
|
|
6797
|
-
`+
|
|
6978
|
+
`}function yt(){return vr()+`
|
|
6979
|
+
`+Rr()}function bt(e,t,n){return ht(e,t,n)+`
|
|
6980
|
+
`+yt()}function wt(){return `const app = new Hono<WorkerEnv>();
|
|
6798
6981
|
|
|
6799
6982
|
app.use('*', cors({
|
|
6800
6983
|
origin: (origin, c) => {
|
|
@@ -6810,7 +6993,7 @@ app.use('*', cors({
|
|
|
6810
6993
|
},
|
|
6811
6994
|
credentials: true
|
|
6812
6995
|
}));
|
|
6813
|
-
`}function
|
|
6996
|
+
`}function xt(){return `export { AppflareRealtimeDurableObject };
|
|
6814
6997
|
|
|
6815
6998
|
export default {
|
|
6816
6999
|
fetch: app.fetch,
|
|
@@ -6821,16 +7004,16 @@ export default {
|
|
|
6821
7004
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
6822
7005
|
},
|
|
6823
7006
|
};
|
|
6824
|
-
`}function
|
|
6825
|
-
kvBinding: "${t}",`:"",
|
|
7007
|
+
`}function Tt(e,t,n="APPFLARE_SCHEDULER_QUEUE",r,a="APPFLARE_REALTIME",o="global",i="/realtime/subscribe",s="/realtime/ws",c="appflare.realtime.v1"){let u=t?`
|
|
7008
|
+
kvBinding: "${t}",`:"",l=r?`
|
|
6826
7009
|
r2Binding: "${r}",`:"",p=`
|
|
6827
7010
|
realtimeBinding: "${a}",
|
|
6828
7011
|
realtimeObjectName: "${o}",
|
|
6829
7012
|
realtimeSubscribePath: "${i}",
|
|
6830
7013
|
realtimeWebsocketPath: "${s}",
|
|
6831
7014
|
realtimeProtocol: "${c}",`;return `const generatedHandlerOptions = {
|
|
6832
|
-
databaseBinding: "${e}",${
|
|
6833
|
-
schedulerBinding: "${n}",${
|
|
7015
|
+
databaseBinding: "${e}",${u}
|
|
7016
|
+
schedulerBinding: "${n}",${l}${p}
|
|
6834
7017
|
};
|
|
6835
7018
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6836
7019
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
@@ -6841,10 +7024,10 @@ import { registerAdminDashboard } from "./admin.routes";
|
|
|
6841
7024
|
import { Hono } from "hono";
|
|
6842
7025
|
import { cors } from "hono/cors";
|
|
6843
7026
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6844
|
-
`}function
|
|
7027
|
+
`}function Rt(){return `type WorkerEnv = {
|
|
6845
7028
|
Bindings: Record<string, unknown>;
|
|
6846
7029
|
};
|
|
6847
|
-
`}function
|
|
7030
|
+
`}function kt(e,t,n,r,a,o,i,s,c,u){return vt()+Rt()+wt()+Tt(t,n,r,a,o,i,s,c,u)+bt(e,t,n)+xt()}function St(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function Y(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(St(o)&&St(a)){n[r]=Y(o,a);continue}n[r]=a;}return n}function kr(e){return Array.from(new Set(e.filter(t=>t.length>0)))}function At(e,t){let n=t.filter(d=>d.kind==="scheduler"||d.kind==="cron"),r=kr(t.filter(d=>d.kind==="cron").flatMap(d=>d.cronTriggers??[])),a=e.config.scheduler.enabled&&n.length>0,o=e.config.realtime.enabled,s=(typeof e.config.wranglerOverrides?.name=="string"?e.config.wranglerOverrides.name:void 0)??"appflare-worker",c=e.config.scheduler.queue??`${s}-scheduler`,u={name:s,main:"./src/index.ts",d1_databases:e.config.database.map(d=>({binding:d.binding,database_name:d.databaseName,database_id:d.databaseId,preview_database_id:d.previewDatabaseId??d.databaseId,...d.migrationsDir?{migrations_dir:d.migrationsDir}:{}})),kv_namespaces:e.config.kv.map(d=>({binding:d.binding,id:d.id,...d.previewId?{preview_id:d.previewId}:{}})),r2_buckets:e.config.r2.map(d=>({binding:d.binding,bucket_name:d.bucketName,...d.previewBucketName?{preview_bucket_name:d.previewBucketName}:{},...d.jurisdiction?{jurisdiction:d.jurisdiction}:{}})),...a?{queues:{producers:[{binding:e.config.scheduler.binding,queue:c}],consumers:[{queue:c}]}}:{},...r.length>0?{triggers:{crons:r}}:{},...o?{durable_objects:{bindings:[{name:e.config.realtime.binding,class_name:e.config.realtime.className}]},migrations:[{tag:"appflare-realtime-v1",new_sqlite_classes:[e.config.realtime.className]}]}:{}};if(!e.config.wranglerOverrides)return u;let{scheduler:l,...p}=e.config.wranglerOverrides;return Y(u,p)}function ee(e){let t={children:[],handlers:[]};for(let n of e){let r=n.clientSegments??[n.exportName],a=t;for(let o=0;o<r.length-1;o++){let i=r[o],s=a.children.find(c=>c.name===i&&c.type==="folder");s||(s={name:i,type:"folder",children:[],handlers:[]},a.children.push(s)),a=s;}a.handlers.push(n);}return t.children}function Nt(e){return e.tables.map(t=>({exportName:t.exportName,tableName:t.tableName,columns:t.columns.map(n=>n.name)}))}function $t(e){return `<li data-name="users">
|
|
6848
7031
|
<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">
|
|
6849
7032
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6850
7033
|
<span class="truncate">users</span>
|
|
@@ -6856,17 +7039,17 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6856
7039
|
<span class="truncate">${n.tableName}</span>
|
|
6857
7040
|
</a>
|
|
6858
7041
|
</li>`).join(`
|
|
6859
|
-
`)}`}function
|
|
7042
|
+
`)}`}function te(e,t){let n=" ".repeat(t),r=e.children.length>0,a=e.handlers.length>0,o=r||a,i="";if(o){`folder-${e.name.replace(/[^a-zA-Z0-9]/g,"-")}-${t}`;i+=`
|
|
6860
7043
|
${n}<li data-name="${e.name}" class="folder-item">`,i+=`
|
|
6861
7044
|
${n} <details class="group/folder" open>`,i+=`
|
|
6862
7045
|
${n} <summary class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full cursor-pointer list-none">`,i+=`
|
|
6863
7046
|
${n} <iconify-icon icon="solar:folder-bold-duotone" width="16" height="16" class="opacity-50 shrink-0 transition-transform group-open/folder:rotate-0"></iconify-icon>`,i+=`
|
|
6864
7047
|
${n} <span class="truncate font-medium">${e.name}</span>`,i+=`
|
|
6865
7048
|
${n} </summary>`,i+=`
|
|
6866
|
-
${n} <ul class="flex flex-col gap-0.5 ml-4 border-l border-base-200 pl-2">`;for(let c of e.children)i+=
|
|
7049
|
+
${n} <ul class="flex flex-col gap-0.5 ml-4 border-l border-base-200 pl-2">`;for(let c of e.children)i+=te(c,t+2);for(let c of e.handlers){let u=c.kind==="query"?"solar:reorder-linear":"solar:bolt-linear";i+=`
|
|
6867
7050
|
${n} <li data-name="${c.exportName}">`,i+=`
|
|
6868
7051
|
${n} <a href="/admin/functions${c.routePath}" hx-get="/admin/functions${c.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">`,i+=`
|
|
6869
|
-
${n} <iconify-icon icon="${
|
|
7052
|
+
${n} <iconify-icon icon="${u}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
6870
7053
|
${n} <span class="truncate">${c.exportName}</span>`,i+=`
|
|
6871
7054
|
${n} </a>`,i+=`
|
|
6872
7055
|
${n} </li>`;}i+=`
|
|
@@ -6878,7 +7061,7 @@ ${n} <a href="/admin/functions${s.routePath}" hx-get="/admin/functions${s.route
|
|
|
6878
7061
|
${n} <iconify-icon icon="${c}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
6879
7062
|
${n} <span class="truncate">${s.exportName}</span>`,i+=`
|
|
6880
7063
|
${n} </a>`,i+=`
|
|
6881
|
-
${n}</li>`;}return i}function
|
|
7064
|
+
${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filter(s=>s.kind==="mutation"),r=ee(t),a=ee(n),o=r.map(s=>te(s,0)).join(""),i=a.map(s=>te(s,0)).join("");return `
|
|
6882
7065
|
<div id="pane-functions" class="flex flex-col h-full hidden">
|
|
6883
7066
|
<div class="px-3 pt-5 pb-3">
|
|
6884
7067
|
<p class="text-[10px] font-semibold uppercase tracking-widest opacity-35 mb-3 px-1">Functions</p>
|
|
@@ -6900,7 +7083,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6900
7083
|
<ul class="flex flex-col gap-0.5">${i}</ul>`:""}
|
|
6901
7084
|
</nav>
|
|
6902
7085
|
</div>
|
|
6903
|
-
`}function
|
|
7086
|
+
`}function Ft(e){return e.map(t=>`
|
|
6904
7087
|
<a
|
|
6905
7088
|
href="/admin/table/${t.exportName}"
|
|
6906
7089
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
@@ -6917,9 +7100,9 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6917
7100
|
</div>
|
|
6918
7101
|
</div>
|
|
6919
7102
|
</a>
|
|
6920
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
7103
|
+
`.replace(/\n/g,"\\n")).join("")}function qt(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
6921
7104
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6922
|
-
`).join("")}function Sr(e){switch(e){case "number":return "mdi:pound";case "boolean":return "mdi:toggle-switch-outline";case "date":return "mdi:calendar";case "json":return "mdi:code-braces";default:return "mdi:format-text"}}function
|
|
7105
|
+
`).join("")}function Sr(e){switch(e){case "number":return "mdi:pound";case "boolean":return "mdi:toggle-switch-outline";case "date":return "mdi:calendar";case "json":return "mdi:code-braces";default:return "mdi:format-text"}}function Mt(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n),a=r?Sr(r.type):"mdi:format-text";return `
|
|
6923
7106
|
<th>
|
|
6924
7107
|
<a href="#"
|
|
6925
7108
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -6931,7 +7114,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6931
7114
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6932
7115
|
</a>
|
|
6933
7116
|
</th>
|
|
6934
|
-
`}).join("")}function
|
|
7117
|
+
`}).join("")}function Et(e,t,n){return t.map(r=>{let a=e.columns.find(o=>o.name===r);return n&&r===n?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${r} ?? '')}" data-copy-value="\${String((row as any).${r} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${r} ?? '')}</button></td>`:a?.type==="json"?`<td>\${raw((() => { const __v = (row as any).${r}; if (__v === null || __v === undefined) return '<span class="opacity-30 text-xs">null</span>'; if (Array.isArray(__v)) { if (__v.length === 0) return '<span class="badge badge-ghost badge-sm font-mono text-xs">[ ]</span>'; return '<div class="flex flex-wrap gap-1 max-w-[200px]">' + __v.slice(0, 3).map((item) => '<span class="badge badge-ghost badge-xs font-mono">' + (typeof item === 'object' && item !== null ? JSON.stringify(item).slice(0, 20) + (JSON.stringify(item).length > 20 ? '\u2026' : '') : String(item ?? '')) + '</span>').join('') + (__v.length > 3 ? '<span class="badge badge-ghost badge-xs opacity-50">+' + (__v.length - 3) + '</span>' : '') + '</div>'; } if (typeof __v === 'object') { const __s = JSON.stringify(__v); return '<span class="badge badge-outline badge-sm font-mono text-[10px]">' + __s.slice(0, 50) + (__s.length > 50 ? '\u2026' : '') + '</span>'; } return String(__v ?? ''); })())}</td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${r} ?? '')}">\${String((row as any).${r} ?? '')}</div></td>`}).join("")}function ne(e,t,n){let r=e.columns.find(i=>i.name===t);if(!r)return "";let a=r.optional?"":" required",o=r.type==="number"?"number":r.type==="date"?"date":"text";if(r.type==="boolean")return n==="edit"?`
|
|
6935
7118
|
<div class="form-control">
|
|
6936
7119
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6937
7120
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6979,7 +7162,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6979
7162
|
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6980
7163
|
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm"${a} />
|
|
6981
7164
|
</div>
|
|
6982
|
-
`}function
|
|
7165
|
+
`}function re(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n);if(!r)return "";let a=r.optional?"":`
|
|
6983
7166
|
if (raw_${n} === '') {
|
|
6984
7167
|
return c.text('${n} is required', 400);
|
|
6985
7168
|
}
|
|
@@ -7034,7 +7217,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7034
7217
|
payload.${n} = raw_${n};
|
|
7035
7218
|
}
|
|
7036
7219
|
`}).join(`
|
|
7037
|
-
`)}function
|
|
7220
|
+
`)}function jt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function It(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function Ot(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function Pt(e,t,n,r){return t?`<td class="text-right">
|
|
7038
7221
|
<div class="drawer drawer-end">
|
|
7039
7222
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
7040
7223
|
<div class="drawer-content">
|
|
@@ -7087,7 +7270,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7087
7270
|
</div>
|
|
7088
7271
|
</div>
|
|
7089
7272
|
</div>
|
|
7090
|
-
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function
|
|
7273
|
+
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function W(e){return `
|
|
7091
7274
|
<div class="flex flex-col sm:flex-row justify-between items-center mt-4 gap-3 py-3 px-1">
|
|
7092
7275
|
<div class="text-xs text-base-content/40">
|
|
7093
7276
|
Total found: <span class="font-medium text-base-content/60">\${total}</span>
|
|
@@ -7109,7 +7292,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7109
7292
|
\` : 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>\`}
|
|
7110
7293
|
</div>
|
|
7111
7294
|
\` : ''}
|
|
7112
|
-
</div>`}function
|
|
7295
|
+
</div>`}function H(e,t="Search term or filter..."){return `
|
|
7113
7296
|
<div class="form-control w-full md:w-auto relative">
|
|
7114
7297
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
7115
7298
|
<input type="text"
|
|
@@ -7120,7 +7303,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7120
7303
|
hx-trigger="keyup changed delay:500ms, search"
|
|
7121
7304
|
hx-target="#main-content"
|
|
7122
7305
|
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" />
|
|
7123
|
-
</div>`}function
|
|
7306
|
+
</div>`}function Dt(e,t,n,r,a,o,i,s,c,u){let l=W(`/admin/table/${e.exportName}`),p=H(`/admin/table/${e.exportName}`,"Search term or filter..."),d=r?`<th class="w-10"><input id="select-all-${e.exportName}" type="checkbox" class="checkbox checkbox-xs" /></th>`:'<th class="w-10"><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></th>',y=r?`<td><input type="checkbox" class="checkbox checkbox-xs row-select-checkbox" value="\${String((row as any).${n} ?? '')}" /></td>`:'<td><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></td>',x=r?`
|
|
7124
7307
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
7125
7308
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
7126
7309
|
<div class="text-xs text-base-content/70">
|
|
@@ -7310,7 +7493,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7310
7493
|
</tbody>
|
|
7311
7494
|
</table>
|
|
7312
7495
|
</div>
|
|
7313
|
-
${
|
|
7496
|
+
${l}
|
|
7314
7497
|
</div>
|
|
7315
7498
|
\`;
|
|
7316
7499
|
|
|
@@ -7339,7 +7522,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7339
7522
|
${p}
|
|
7340
7523
|
</div>
|
|
7341
7524
|
\${tableHtml}
|
|
7342
|
-
${
|
|
7525
|
+
${x}
|
|
7343
7526
|
</div>
|
|
7344
7527
|
<div class="drawer-side z-50">
|
|
7345
7528
|
<label for="create-drawer-${e.exportName}" aria-label="close sidebar" class="drawer-overlay"></label>
|
|
@@ -7355,7 +7538,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7355
7538
|
<input type="hidden" name="order" value="\${order}" />
|
|
7356
7539
|
<input type="hidden" name="search" value="\${search}" />
|
|
7357
7540
|
<input type="hidden" name="page" value="\${page}" />
|
|
7358
|
-
${
|
|
7541
|
+
${u}
|
|
7359
7542
|
<button type="submit" class="btn btn-primary btn-sm mt-2">Create record</button>
|
|
7360
7543
|
</form>
|
|
7361
7544
|
</div>
|
|
@@ -7372,11 +7555,11 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7372
7555
|
title: "${e.tableName} - Admin Dashboard",
|
|
7373
7556
|
children: content
|
|
7374
7557
|
}));
|
|
7375
|
-
});`}function
|
|
7558
|
+
});`}function Vt(e,t,n,r,a,o,i,s){let c=r==="number"?`
|
|
7376
7559
|
const parsedId = Number(rawId);
|
|
7377
7560
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
7378
7561
|
idValue = parsedId;
|
|
7379
|
-
`:"",
|
|
7562
|
+
`:"",l=a?`
|
|
7380
7563
|
adminApp.post('/table/${e}/edit', async (c) => {
|
|
7381
7564
|
const db = drizzle(c.env[options.databaseBinding], { schema });
|
|
7382
7565
|
const tableSchema = (schema as any).${e};
|
|
@@ -7504,16 +7687,16 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7504
7687
|
});
|
|
7505
7688
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7506
7689
|
});
|
|
7507
|
-
${
|
|
7508
|
-
`}function
|
|
7509
|
-
`+
|
|
7690
|
+
${l}
|
|
7691
|
+
`}function ae(e){let t=jt(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>It(e,w)),o=r.filter(w=>Ot(e,w)),i=qt(e),s=Mt(e,r),c=Et(e,r,t),u=a.map(w=>ne(e,w,"create")).join(""),l=o.map(w=>ne(e,w,"edit")).join(""),p=re(e,a),d=re(e,o),y=n?t:r[0]||"id",x=e.columns.find(w=>w.name===t)?.type,N=Pt(e,n,t,l);return Dt(e,y,t,n,r,i,s,c,N,u)+`
|
|
7692
|
+
`+Vt(e.exportName,y,t,x,n,i,p,d)}function Bt(){return `
|
|
7510
7693
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7511
7694
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
7512
7695
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
7513
7696
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
7514
7697
|
const search = params.search ? params.search : '';
|
|
7515
7698
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
7516
|
-
};`}function
|
|
7699
|
+
};`}function Wt(){return `
|
|
7517
7700
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7518
7701
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7519
7702
|
<div class="modal">
|
|
@@ -7534,7 +7717,7 @@ ${u}
|
|
|
7534
7717
|
</div>
|
|
7535
7718
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
7536
7719
|
</div>
|
|
7537
|
-
\`}`}function
|
|
7720
|
+
\`}`}function Ht(){return `
|
|
7538
7721
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7539
7722
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7540
7723
|
<div class="modal">
|
|
@@ -7555,8 +7738,8 @@ ${u}
|
|
|
7555
7738
|
</div>
|
|
7556
7739
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
7557
7740
|
</div>
|
|
7558
|
-
\`}`}var Ar=["id","name","email","role","createdAt","banned"],Nr={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function $r(e){let t=Nr[e]||"mdi:format-text";return `<th><a href="#" hx-get="/admin/users?page=\${page}&search=\${search}&sort=${e}&order=\${sort === '${e}' && order === 'asc' ? 'desc' : 'asc'}" hx-target="#main-content" hx-push-url="true" class="hover:text-primary flex items-center gap-1.5 transition-colors whitespace-nowrap"><iconify-icon icon="${t}" width="14" height="14" class="opacity-40"></iconify-icon>${e} <span class="text-[10px] opacity-30">\${sort === '${e}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span></a></th>`}function
|
|
7559
|
-
`),t=
|
|
7741
|
+
\`}`}var Ar=["id","name","email","role","createdAt","banned"],Nr={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function $r(e){let t=Nr[e]||"mdi:format-text";return `<th><a href="#" hx-get="/admin/users?page=\${page}&search=\${search}&sort=${e}&order=\${sort === '${e}' && order === 'asc' ? 'desc' : 'asc'}" hx-target="#main-content" hx-push-url="true" class="hover:text-primary flex items-center gap-1.5 transition-colors whitespace-nowrap"><iconify-icon icon="${t}" width="14" height="14" class="opacity-40"></iconify-icon>${e} <span class="text-[10px] opacity-30">\${sort === '${e}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span></a></th>`}function Lt(){let e=Ar.map($r).join(`
|
|
7742
|
+
`),t=W("/admin/users");return `
|
|
7560
7743
|
const tableHtml = html\`
|
|
7561
7744
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
7562
7745
|
<div class="overflow-x-auto">
|
|
@@ -7624,8 +7807,8 @@ ${u}
|
|
|
7624
7807
|
</div>
|
|
7625
7808
|
</div>
|
|
7626
7809
|
</div>
|
|
7627
|
-
${Bt()}
|
|
7628
7810
|
${Wt()}
|
|
7811
|
+
${Ht()}
|
|
7629
7812
|
</td>
|
|
7630
7813
|
</tr>
|
|
7631
7814
|
\`)}
|
|
@@ -7641,7 +7824,7 @@ ${Wt()}
|
|
|
7641
7824
|
${t}
|
|
7642
7825
|
</div>
|
|
7643
7826
|
\`;
|
|
7644
|
-
`}function
|
|
7827
|
+
`}function zt(){return `
|
|
7645
7828
|
const content = html\`
|
|
7646
7829
|
<div id="main-content">
|
|
7647
7830
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -7653,11 +7836,11 @@ ${Wt()}
|
|
|
7653
7836
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
7654
7837
|
</button>
|
|
7655
7838
|
</div>
|
|
7656
|
-
${
|
|
7839
|
+
${H("/admin/users","Search users...")}
|
|
7657
7840
|
</div>
|
|
7658
7841
|
\${tableHtml}
|
|
7659
7842
|
</div>
|
|
7660
|
-
\`;`}function
|
|
7843
|
+
\`;`}function _t(){let e=Lt(),t=zt();return `
|
|
7661
7844
|
adminApp.get('/users', async (c) => {
|
|
7662
7845
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
7663
7846
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7856,8 +8039,8 @@ ${Wt()}
|
|
|
7856
8039
|
const resolvedPage = String(Math.min(nextPageCandidate, totalPages));
|
|
7857
8040
|
|
|
7858
8041
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7859
|
-
});`}function
|
|
7860
|
-
${
|
|
8042
|
+
});`}function oe(){return `
|
|
8043
|
+
${Bt()}
|
|
7861
8044
|
|
|
7862
8045
|
const requireAdminSession = async (c: any) => {
|
|
7863
8046
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7868,12 +8051,12 @@ ${Wt()}
|
|
|
7868
8051
|
return session;
|
|
7869
8052
|
};
|
|
7870
8053
|
|
|
7871
|
-
${
|
|
8054
|
+
${_t()}
|
|
7872
8055
|
|
|
7873
8056
|
${Ut()}
|
|
7874
|
-
`}function
|
|
8057
|
+
`}function Qt(e){return `${e.tables.map(t=>ae(t)).join(`
|
|
7875
8058
|
`)}
|
|
7876
|
-
${
|
|
8059
|
+
${oe()}`}function Kt(e){return `
|
|
7877
8060
|
<div class="flex items-center justify-between">
|
|
7878
8061
|
<div class="flex items-center gap-3">
|
|
7879
8062
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7948,14 +8131,14 @@ ${ae()}`}function Qt(e){return `
|
|
|
7948
8131
|
class="textarea textarea-sm textarea-bordered font-mono w-full bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-xl border-base-200 resize-y text-xs"
|
|
7949
8132
|
${r.optional?"":"required"}
|
|
7950
8133
|
>${r.defaultValue??""}</textarea>
|
|
7951
|
-
</div>`;if(r.type==="array"){let
|
|
8134
|
+
</div>`;if(r.type==="array"){let u=r.itemType??"string",l=JSON.stringify((r.itemFields??[]).map(p=>({name:p.name,type:p.type})));return `
|
|
7952
8135
|
<div class="form-control">
|
|
7953
8136
|
${s}
|
|
7954
8137
|
<div
|
|
7955
8138
|
data-arg-key="${r.name}"
|
|
7956
8139
|
data-arg-type="array"
|
|
7957
|
-
data-item-type="${
|
|
7958
|
-
data-item-fields='${
|
|
8140
|
+
data-item-type="${u}"
|
|
8141
|
+
data-item-fields='${l}'
|
|
7959
8142
|
class="flex flex-col gap-2"
|
|
7960
8143
|
></div>
|
|
7961
8144
|
<button
|
|
@@ -7979,7 +8162,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
7979
8162
|
${r.optional?"":"required"}
|
|
7980
8163
|
/>
|
|
7981
8164
|
</div>`}).join(`
|
|
7982
|
-
`)}function
|
|
8165
|
+
`)}function Mr(e){return `
|
|
7983
8166
|
<div class="space-y-4">
|
|
7984
8167
|
<div class="flex items-center justify-between">
|
|
7985
8168
|
<div class="flex flex-col">
|
|
@@ -7996,7 +8179,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
7996
8179
|
</div>
|
|
7997
8180
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7998
8181
|
</div>
|
|
7999
|
-
`}function
|
|
8182
|
+
`}function Er(){return `
|
|
8000
8183
|
<div class="space-y-4">
|
|
8001
8184
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
8002
8185
|
<div class="relative group">
|
|
@@ -8013,7 +8196,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8013
8196
|
</div>
|
|
8014
8197
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
8015
8198
|
</div>
|
|
8016
|
-
`}function
|
|
8199
|
+
`}function jr(){return `
|
|
8017
8200
|
<div class="space-y-4">
|
|
8018
8201
|
<div class="flex items-center justify-between">
|
|
8019
8202
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -8027,7 +8210,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8027
8210
|
</div>
|
|
8028
8211
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
8029
8212
|
</div>
|
|
8030
|
-
`}function
|
|
8213
|
+
`}function Jt(e){return `
|
|
8031
8214
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
8032
8215
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
8033
8216
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -8048,13 +8231,13 @@ ${ae()}`}function Qt(e){return `
|
|
|
8048
8231
|
<!-- Tab Content -->
|
|
8049
8232
|
<div class="flex-1 overflow-y-auto">
|
|
8050
8233
|
<div id="request-tab-args" class="p-5">
|
|
8051
|
-
${
|
|
8234
|
+
${Mr(e)}
|
|
8052
8235
|
</div>
|
|
8053
8236
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
8054
|
-
${
|
|
8237
|
+
${Er()}
|
|
8055
8238
|
</div>
|
|
8056
8239
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
8057
|
-
${
|
|
8240
|
+
${jr()}
|
|
8058
8241
|
</div>
|
|
8059
8242
|
</div>
|
|
8060
8243
|
|
|
@@ -8072,7 +8255,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8072
8255
|
</form>
|
|
8073
8256
|
</div>
|
|
8074
8257
|
</div>
|
|
8075
|
-
`}function
|
|
8258
|
+
`}function Gt(){return `
|
|
8076
8259
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
8077
8260
|
<!-- Panel Header -->
|
|
8078
8261
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -8154,7 +8337,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8154
8337
|
|
|
8155
8338
|
</div>
|
|
8156
8339
|
</div>
|
|
8157
|
-
`}function
|
|
8340
|
+
`}function Zt(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
8158
8341
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
8159
8342
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
8160
8343
|
|
|
@@ -8845,21 +9028,21 @@ ${ae()}`}function Qt(e){return `
|
|
|
8845
9028
|
_rtEnabled = false;
|
|
8846
9029
|
});
|
|
8847
9030
|
</script>
|
|
8848
|
-
`}function
|
|
9031
|
+
`}function Xt(e){return `
|
|
8849
9032
|
const content = html\`
|
|
8850
9033
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
8851
|
-
${
|
|
9034
|
+
${Kt(e)}
|
|
8852
9035
|
|
|
8853
9036
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
8854
9037
|
<!-- Request Panel -->
|
|
8855
|
-
${
|
|
9038
|
+
${Jt(e)}
|
|
8856
9039
|
|
|
8857
9040
|
<!-- Result Panel -->
|
|
8858
|
-
${
|
|
9041
|
+
${Gt()}
|
|
8859
9042
|
</div>
|
|
8860
9043
|
</div>
|
|
8861
9044
|
|
|
8862
|
-
${
|
|
9045
|
+
${Zt(e)}
|
|
8863
9046
|
\`;
|
|
8864
9047
|
|
|
8865
9048
|
if (c.req.header('hx-request')) {
|
|
@@ -8869,11 +9052,11 @@ ${ae()}`}function Qt(e){return `
|
|
|
8869
9052
|
return c.html(Layout({
|
|
8870
9053
|
title: "${e.exportName} - Functions",
|
|
8871
9054
|
children: content
|
|
8872
|
-
}));`}function
|
|
9055
|
+
}));`}function Yt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
8873
9056
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
8874
|
-
${
|
|
9057
|
+
${Xt(n)}
|
|
8875
9058
|
});`).join(`
|
|
8876
|
-
`)}function
|
|
9059
|
+
`)}function en(){return `
|
|
8877
9060
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
8878
9061
|
const r2Binding = (options as any).r2Binding;
|
|
8879
9062
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -8942,7 +9125,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8942
9125
|
const parts = prefix.split('/').filter(Boolean);
|
|
8943
9126
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
8944
9127
|
};
|
|
8945
|
-
`}function
|
|
9128
|
+
`}function tn(){return `
|
|
8946
9129
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
8947
9130
|
const parts = prefix.split('/').filter(Boolean);
|
|
8948
9131
|
const breadcrumbs: any[] = [];
|
|
@@ -9069,7 +9252,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9069
9252
|
</div>
|
|
9070
9253
|
\`;
|
|
9071
9254
|
};
|
|
9072
|
-
`}function
|
|
9255
|
+
`}function nn(){return `
|
|
9073
9256
|
const handleStorageListRoute = async (c: any) => {
|
|
9074
9257
|
const bucket = getStorageBucket(c);
|
|
9075
9258
|
if (!bucket) {
|
|
@@ -9091,7 +9274,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9091
9274
|
|
|
9092
9275
|
adminApp.get('/storage', handleStorageListRoute);
|
|
9093
9276
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
9094
|
-
`}function
|
|
9277
|
+
`}function rn(){return `
|
|
9095
9278
|
adminApp.post('/storage/upload', async (c) => {
|
|
9096
9279
|
const bucket = getStorageBucket(c);
|
|
9097
9280
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9109,7 +9292,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9109
9292
|
|
|
9110
9293
|
return c.redirect(prefixToStoragePath(prefix));
|
|
9111
9294
|
});
|
|
9112
|
-
`}function
|
|
9295
|
+
`}function an(){return `
|
|
9113
9296
|
adminApp.delete('/storage/delete', async (c) => {
|
|
9114
9297
|
const bucket = getStorageBucket(c);
|
|
9115
9298
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9124,7 +9307,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9124
9307
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
9125
9308
|
return c.html('');
|
|
9126
9309
|
});
|
|
9127
|
-
`}function
|
|
9310
|
+
`}function on(){return `
|
|
9128
9311
|
adminApp.post('/storage/directory', async (c) => {
|
|
9129
9312
|
const bucket = getStorageBucket(c);
|
|
9130
9313
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9150,7 +9333,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9150
9333
|
|
|
9151
9334
|
return c.redirect(prefixToStoragePath(prefix));
|
|
9152
9335
|
});
|
|
9153
|
-
`}function
|
|
9336
|
+
`}function sn(){return `
|
|
9154
9337
|
adminApp.get('/storage/download', async (c) => {
|
|
9155
9338
|
const bucket = getStorageBucket(c);
|
|
9156
9339
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9170,7 +9353,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9170
9353
|
|
|
9171
9354
|
return new Response(object.body, { headers });
|
|
9172
9355
|
});
|
|
9173
|
-
`}function
|
|
9356
|
+
`}function ln(){return `
|
|
9174
9357
|
adminApp.get('/storage/preview', async (c) => {
|
|
9175
9358
|
const bucket = getStorageBucket(c);
|
|
9176
9359
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9188,25 +9371,25 @@ ${ae()}`}function Qt(e){return `
|
|
|
9188
9371
|
|
|
9189
9372
|
return new Response(object.body, { headers });
|
|
9190
9373
|
});
|
|
9191
|
-
`}function
|
|
9192
|
-
${on()}
|
|
9193
|
-
|
|
9374
|
+
`}function un(){return `
|
|
9194
9375
|
${sn()}
|
|
9195
9376
|
|
|
9196
|
-
${
|
|
9377
|
+
${ln()}
|
|
9197
9378
|
|
|
9198
9379
|
${rn()}
|
|
9199
9380
|
|
|
9200
9381
|
${an()}
|
|
9201
9382
|
|
|
9202
|
-
${
|
|
9203
|
-
`}function un(){return `
|
|
9204
|
-
${Yt()}
|
|
9383
|
+
${on()}
|
|
9205
9384
|
|
|
9385
|
+
${nn()}
|
|
9386
|
+
`}function cn(){return `
|
|
9206
9387
|
${en()}
|
|
9207
9388
|
|
|
9208
|
-
${
|
|
9209
|
-
|
|
9389
|
+
${tn()}
|
|
9390
|
+
|
|
9391
|
+
${un()}
|
|
9392
|
+
`}function dn(e,t){let n=Ct(t);return `
|
|
9210
9393
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
9211
9394
|
return html\`<!DOCTYPE html>
|
|
9212
9395
|
<html lang="en" data-theme="light">
|
|
@@ -9613,7 +9796,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9613
9796
|
</body>
|
|
9614
9797
|
</html>\`;
|
|
9615
9798
|
}
|
|
9616
|
-
`}function
|
|
9799
|
+
`}function pn(){return `
|
|
9617
9800
|
// Auth Middleware
|
|
9618
9801
|
adminApp.use('*', async (c, next) => {
|
|
9619
9802
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -9672,7 +9855,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9672
9855
|
}
|
|
9673
9856
|
await next();
|
|
9674
9857
|
});
|
|
9675
|
-
`}function
|
|
9858
|
+
`}function mn(e){return `
|
|
9676
9859
|
adminApp.get('/', (c) => {
|
|
9677
9860
|
return c.html(Layout({
|
|
9678
9861
|
title: "Admin Dashboard",
|
|
@@ -9689,7 +9872,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9689
9872
|
\`
|
|
9690
9873
|
}));
|
|
9691
9874
|
});
|
|
9692
|
-
`}function
|
|
9875
|
+
`}function fn(e,t,n){let r=Nt(t),a=$t(r),o=Ft(r),i=Qt(t),s=Yt(n),c=cn(),u=dn(a,n),l=pn(),p=mn(o);return `import { Hono } from "hono";
|
|
9693
9876
|
import { html, raw } from "hono/html";
|
|
9694
9877
|
import { drizzle } from "drizzle-orm/d1";
|
|
9695
9878
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -9697,12 +9880,12 @@ import { createAuth } from "./auth.config";
|
|
|
9697
9880
|
import * as schema from "${e}";
|
|
9698
9881
|
import { users } from "./auth.schema";
|
|
9699
9882
|
|
|
9700
|
-
${
|
|
9883
|
+
${u}
|
|
9701
9884
|
|
|
9702
9885
|
export function registerAdminDashboard(app: Hono<any>, options: { databaseBinding: string, r2Binding?: string }) {
|
|
9703
9886
|
const adminApp = new Hono<any>();
|
|
9704
9887
|
|
|
9705
|
-
${
|
|
9888
|
+
${l}
|
|
9706
9889
|
|
|
9707
9890
|
${p}
|
|
9708
9891
|
|
|
@@ -9718,8 +9901,8 @@ ${p}
|
|
|
9718
9901
|
app.route('/admin', adminApp);
|
|
9719
9902
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
9720
9903
|
}
|
|
9721
|
-
`}function
|
|
9722
|
-
`}function Qr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function Kr(e,t,n){if(t.references)return {tableName:t.references.table,fieldName:t.references.column};let r=Object.values(n.relations).find(a=>a.relation==="one"&&a.field===e);if(r)return {tableName:r.targetTable,fieldName:r.referenceField??"id"}}function Jr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.columns)){if(i.type!=="json"||!i.jsonShape)continue;let s=
|
|
9904
|
+
`}function ie(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"&&(typeof t.enums=="object"||t.enums===void 0)}function I(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function q(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function ue(e){return e.endsWith("ies")?`${e.slice(0,-3)}y`:e.endsWith("ses")?e.slice(0,-2):e.endsWith("s")&&e.length>1?e.slice(0,-1):e}function g(e){return JSON.stringify(e)}function Or(e){if(typeof e=="string")return g(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return "null";if(e instanceof Date)return g(e.toISOString());if(typeof e=="object"&&e!==null)return JSON.stringify(e);throw new Error(`Unsupported SQL default value '${String(e)}'. Use string, number, boolean, null, Date, array, or object.`)}function Pr(e){return {kind:"schema",tables:Object.fromEntries(Object.entries(e.tables).map(([t,n])=>[t,{kind:"table",sqlName:n.sqlName,columns:Object.fromEntries(Object.entries(n.columns).map(([r,a])=>[r,{...a}])),relations:Object.fromEntries(Object.entries(n.relations).map(([r,a])=>[r,{...a}]))}])),enums:Object.fromEntries(Object.entries(e.enums??{}).map(([t,n])=>[t,{...n}]))}}function L(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function gn(e,t,n,r,a,o,i){let s=t.columns[n];if(s){if(s.references&&(s.references.table!==r||s.references.column!==a))throw new Error(`Inferred relation '${e}.${n}' conflicts with explicit references(${s.references.table}.${s.references.column}).`);t.columns[n]={...s,notNull:s.notNull??(s.nullable===true?false:o.notNull),nullable:s.nullable??(o.notNull===false?true:void 0),references:{table:r,column:a,onDelete:s.references?.onDelete??o.onDelete,onUpdate:s.references?.onUpdate??o.onUpdate}};return}t.columns[n]={kind:"column",type:o.fkType??i,sqlName:o.sqlName,notNull:o.notNull??true,nullable:o.notNull===false?true:void 0,references:{table:r,column:a,onDelete:o.onDelete,onUpdate:o.onUpdate}};}function hn(e,t,n){if(t.notNull===true&&t.nullable===true)throw new Error(`Invalid nullable configuration on '${e}': cannot set both notNull and nullable to true.`);return t.notNull===true?true:t.nullable===true||t.notNull===false?false:n}function yn(e,t){return `${e}:${t}`}function Dr(e,t,n,r){let a=yn(e,t),o=yn(n,r);return a<=o?{key:`${a}|${o}`,leftTable:e,leftReferenceField:t,rightTable:n,rightReferenceField:r,sourceIsLeft:true}:{key:`${o}|${a}`,leftTable:n,leftReferenceField:r,rightTable:e,rightReferenceField:t,sourceIsLeft:false}}function Vr(e,t){return `${e}${q(t)}Links`}function bn(e,t,n){let r=ue(e),a=ue(t);return r===a?`${n}${q(r)}Id`:`${r}Id`}function Br(e,t,n){if(e.junctionTable!==t.junctionTable)throw new Error(`manyToMany pair '${n}' has conflicting junctionTable values ('${e.junctionTable}' vs '${t.junctionTable}').`);if(e.leftField!==t.leftField)throw new Error(`manyToMany pair '${n}' has conflicting left field values ('${e.leftField}' vs '${t.leftField}').`);if(e.rightField!==t.rightField)throw new Error(`manyToMany pair '${n}' has conflicting right field values ('${e.rightField}' vs '${t.rightField}').`);if(e.leftSqlName!==t.leftSqlName)throw new Error(`manyToMany pair '${n}' has conflicting left sql name values ('${e.leftSqlName}' vs '${t.leftSqlName}').`);if(e.rightSqlName!==t.rightSqlName)throw new Error(`manyToMany pair '${n}' has conflicting right sql name values ('${e.rightSqlName}' vs '${t.rightSqlName}').`);if(e.onDelete!==t.onDelete)throw new Error(`manyToMany pair '${n}' has conflicting onDelete values ('${e.onDelete}' vs '${t.onDelete}').`);if(e.onUpdate!==t.onUpdate)throw new Error(`manyToMany pair '${n}' has conflicting onUpdate values ('${e.onUpdate}' vs '${t.onUpdate}').`);return e}function Wr(e){let t=new Map;for(let[n,r]of Object.entries(e.tables))for(let a of Object.values(r.relations)){if(a.relation!=="manyToMany")continue;let o=a.referenceField??"id",i=a.targetReferenceField??"id",s=Dr(n,o,a.targetTable,i),c=bn(s.leftTable,s.rightTable,"source"),u=bn(s.rightTable,s.leftTable,"target"),l={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??Vr(s.leftTable,s.rightTable),leftField:s.sourceIsLeft?a.sourceField??c:a.targetField??c,rightField:s.sourceIsLeft?a.targetField??u:a.sourceField??u,leftSqlName:s.sourceIsLeft?a.sourceSqlName:a.targetSqlName,rightSqlName:s.sourceIsLeft?a.targetSqlName:a.sourceSqlName,onDelete:a.onDelete,onUpdate:a.onUpdate};if(l.leftField===l.rightField)throw new Error(`manyToMany pair '${s.key}' resolves to duplicate junction fields '${l.leftField}'. Set sourceField/targetField explicitly.`);let p=t.get(s.key);p?Br(p,l,s.key):t.set(s.key,l),a.referenceField=o,a.targetReferenceField=i,a.junctionTable=l.junctionTable,a.sourceField=s.sourceIsLeft?l.leftField:l.rightField,a.targetField=s.sourceIsLeft?l.rightField:l.leftField,a.sourceSqlName=s.sourceIsLeft?l.leftSqlName:l.rightSqlName,a.targetSqlName=s.sourceIsLeft?l.rightSqlName:l.leftSqlName;}for(let n of t.values()){if(n.junctionTable in e.tables)throw new Error(`manyToMany auto junction table '${n.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`);let r=L(e,n.leftTable,n.leftReferenceField)??"string",a=L(e,n.rightTable,n.rightReferenceField)??"string";e.tables[n.junctionTable]={kind:"table",columns:{[n.leftField]:{kind:"column",type:r,sqlName:n.leftSqlName,notNull:true,nullable:false,references:{table:n.leftTable,column:n.leftReferenceField,onDelete:n.onDelete,onUpdate:n.onUpdate},index:true},[n.rightField]:{kind:"column",type:a,sqlName:n.rightSqlName,notNull:true,nullable:false,references:{table:n.rightTable,column:n.rightReferenceField,onDelete:n.onDelete,onUpdate:n.onUpdate},index:true}},relations:{[n.leftTable]:{kind:"relation",relation:"one",targetTable:n.leftTable,field:n.leftField,referenceField:n.leftReferenceField},[n.rightTable]:{kind:"relation",relation:"one",targetTable:n.rightTable,field:n.rightField,referenceField:n.rightReferenceField}}};}}function Hr(e){for(let[t,n]of Object.entries(e.tables)){for(let[r,a]of Object.entries(n.columns))if(a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${t}.${r}': cannot set both notNull and nullable to true.`);for(let[r,a]of Object.entries(n.relations))if(a.relation!=="manyToMany"&&a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${t}.${r}': cannot set both notNull and nullable to true.`)}}function Lr(e){Hr(e);let t=Pr(e);for(let[n,r]of Object.entries(t.tables))for(let[a,o]of Object.entries(r.relations)){if(o.relation!=="one")continue;let i=o.referenceField??"id",s=o.field??`${a}Id`;o.field=s;let c=L(t,o.targetTable,i)??o.fkType??"string";gn(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:hn(`${n}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},c);}for(let[n,r]of Object.entries(t.tables))for(let a of Object.values(r.relations)){if(a.relation!=="many")continue;let o=t.tables[a.targetTable];if(!o)continue;let i=a.referenceField??"id",s=a.field??`${ue(n)}Id`;a.field=s;let c=L(t,n,i)??a.fkType??"string";gn(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:hn(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},c);}return Wr(t),t}function xn(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function O(e){return e.notNull!==true}function zr(e,t,n){let r=t.sqlName??I(e),a=r!==e;if(t.type==="int")return a?`t.int(${g(r)})`:"t.int()";if(t.type==="string")return t.length!==void 0?a?`t.text(${g(r)}, { length: ${t.length} })`:`t.text({ length: ${t.length} })`:a?`t.text(${g(r)})`:"t.text()";if(t.type==="boolean")return a?`t.int(${g(r)}, { mode: "boolean" })`:'t.int({ mode: "boolean" })';if(t.type==="date")return a?`t.int(${g(r)}, { mode: "timestamp_ms" })`:'t.int({ mode: "timestamp_ms" })';if(t.type==="enum"&&t.enumValues&&t.enumValues.length>0)return t.isArray?a?`t.text(${g(r)}).array()`:"t.text().array()":a?`t.text(${g(r)})`:"t.text()";if(t.type==="json"&&t.jsonShape){let o=z(t.jsonShape);return `${a?`t.text(${g(r)}, { mode: "json" })`:'t.text({ mode: "json" })'}.$type<${o}>()`}return n==="camelToSnake"&&a?`t.text(${g(r)})`:"t.text()"}function _r(e,t,n){let r=n.field,a=n.referenceField??"id";if(!r)throw new Error(`Relation on '${e}' targeting '${n.targetTable}' is missing a local field.`);if(!(r in t.columns))throw new Error(`Relation '${e}.${r}' references missing local field '${r}'.`);return {sourceField:r,targetField:a}}function Ur(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
9905
|
+
`}function Qr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function Kr(e,t,n){if(t.references)return {tableName:t.references.table,fieldName:t.references.column};let r=Object.values(n.relations).find(a=>a.relation==="one"&&a.field===e);if(r)return {tableName:r.targetTable,fieldName:r.referenceField??"id"}}function Jr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.columns)){if(i.type!=="json"||!i.jsonShape)continue;let s=ce(i.jsonShape);a.push(`${g(o)}: { shape: ${s} },`);}a.length!==0&&t.push(`${g(n)}: {
|
|
9723
9906
|
${a.map(o=>` ${o}`).join(`
|
|
9724
9907
|
`)}
|
|
9725
9908
|
},`);}return t.length===0?`export const __appflareJsonColumns = {} as const;
|
|
@@ -9727,7 +9910,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9727
9910
|
${t.map(n=>` ${n}`).join(`
|
|
9728
9911
|
`)}
|
|
9729
9912
|
} as const;
|
|
9730
|
-
`}function
|
|
9913
|
+
`}function ce(e){return e.kind==="array"?`{ kind: "array", element: ${ce(e.element)} }`:e.kind==="object"?`{ kind: "object", shape: { ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${ce(r)}`).join(", ")} } }`:`{ kind: ${g(e.kind)} }`}function Gr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations))i.relation==="manyToMany"&&i.junctionTable&&a.push(`${g(o)}: {
|
|
9731
9914
|
targetTable: ${g(i.targetTable)},
|
|
9732
9915
|
junctionTable: ${g(i.junctionTable)},
|
|
9733
9916
|
sourceField: ${g(i.sourceField??"")},
|
|
@@ -9768,29 +9951,29 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9768
9951
|
${t.map(n=>` ${n}`).join(`
|
|
9769
9952
|
`)}
|
|
9770
9953
|
} as const;
|
|
9771
|
-
`}function Xr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let l of Object.values(e.tables)){for(let
|
|
9772
|
-
${g(
|
|
9954
|
+
`}function Xr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let l of Object.values(e.tables)){for(let p of Qr(l))n.has(p)||r.add(p);for(let p of Object.values(l.columns))p.references&&!n.has(p.references.table)&&r.add(p.references.table);}let a=new Map;for(let[l,p]of Object.entries(e.tables))for(let[d,y]of Object.entries(p.columns))if(y.type==="enum"&&y.enumValues&&y.enumValues.length>0){let x=y.enumRef??`${l}_${d}`;a.has(x)||a.set(x,{column:y,tableName:l,fieldName:d});}let o=[],i=[];for(let[l,p]of a.entries()){let d=q(l),y=p.column.enumValues.map(x=>`"${x}"`).join(" | ");o.push(`export type ${d} = ${y};`),i.push(`export const ${d}Column = t.customType<{ data: ${d}; dataNotNull: ${d} }>({ dataType: () => "text" });`);}let s=[],c=[],u=[];for(let[l,p]of Object.entries(e.tables)){let d=p.sqlName??I(l),y=[],x=[];u.push(` ${l},`);for(let[b,h]of Object.entries(p.columns)){let v;if(h.type==="enum"&&h.enumValues&&h.enumValues.length>0){let k=h.enumRef??`${l}_${b}`,V=q(k),B=h.sqlName??I(b);v=B!==b?`${V}Column(${g(B)})`:`${V}Column()`,h.isArray&&(v+=".array()");}else v=zr(b,h,t);h.uuidPrimaryKey&&(v+=".$defaultFn(() => crypto.randomUUID())"),h.primaryKey&&(v+=h.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),h.notNull&&(v+=".notNull()"),h.sqlDefault!==void 0&&(v+=`.default(${Or(h.sqlDefault)})`);let A=Kr(b,h,p);if(A)if(h.references?.onDelete||h.references?.onUpdate){let k=[];h.references.onDelete&&k.push(`onDelete: ${g(h.references.onDelete)}`),h.references.onUpdate&&k.push(`onUpdate: ${g(h.references.onUpdate)}`),v+=`.references((): AnySQLiteColumn => ${A.tableName}.${A.fieldName}, { ${k.join(", ")} })`;}else v+=`.references((): AnySQLiteColumn => ${A.tableName}.${A.fieldName})`;if(h.unique){let k=typeof h.unique=="object"&&h.unique.name?h.unique.name:`${d}_${I(b)}_unique_idx`;x.push(` t.uniqueIndex(${g(k)}).on(table.${b})`);}if(h.index){let k=typeof h.index=="object"&&h.index.name?h.index.name:`${d}_${I(b)}_idx`;x.push(` t.index(${g(k)}).on(table.${b})`);}y.push(` ${b}: ${v},`);}x.length>0?s.push(`export const ${l} = table(
|
|
9955
|
+
${g(d)},
|
|
9773
9956
|
{
|
|
9774
|
-
${
|
|
9957
|
+
${y.join(`
|
|
9775
9958
|
`)}
|
|
9776
9959
|
},
|
|
9777
9960
|
(table) => [
|
|
9778
|
-
${
|
|
9961
|
+
${x.join(`,
|
|
9779
9962
|
`)}
|
|
9780
9963
|
],
|
|
9781
|
-
);`):s.push(`export const ${l} = table(${g(
|
|
9782
|
-
${
|
|
9964
|
+
);`):s.push(`export const ${l} = table(${g(d)}, {
|
|
9965
|
+
${y.join(`
|
|
9783
9966
|
`)}
|
|
9784
|
-
});`);let
|
|
9967
|
+
});`);let N=Object.entries(p.relations).filter(([,b])=>b.relation==="one"),w=Object.entries(p.relations).filter(([,b])=>b.relation==="many"),D=Object.entries(p.relations).filter(([,b])=>b.relation==="manyToMany");if(N.length===0&&w.length===0&&D.length===0)continue;let E=[];for(let[b,h]of N){let v=_r(l,p,h);E.push(` ${b}: one(${h.targetTable}, {
|
|
9785
9968
|
fields: [${l}.${v.sourceField}],
|
|
9786
9969
|
references: [${h.targetTable}.${v.targetField}],
|
|
9787
|
-
}),`);}for(let[b,h]of
|
|
9788
|
-
${
|
|
9970
|
+
}),`);}for(let[b,h]of w)E.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of D){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);E.push(` ${b}: many(${h.junctionTable}),`);}c.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
9971
|
+
${E.join(`
|
|
9789
9972
|
`)}
|
|
9790
|
-
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9791
|
-
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
9973
|
+
}));`),u.push(` ${l}Relations,`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9974
|
+
import { sqliteTable as table, type AnySQLiteColumn } from "drizzle-orm/sqlite-core";
|
|
9792
9975
|
import { relations } from "drizzle-orm";
|
|
9793
|
-
${
|
|
9976
|
+
${Ur(r)}
|
|
9794
9977
|
${o.join(`
|
|
9795
9978
|
`)}
|
|
9796
9979
|
${i.join(`
|
|
@@ -9804,12 +9987,17 @@ ${c.join(`
|
|
|
9804
9987
|
|
|
9805
9988
|
`)}
|
|
9806
9989
|
|
|
9990
|
+
export const __appflareDbSchema = {
|
|
9991
|
+
${u.join(`
|
|
9992
|
+
`)}
|
|
9993
|
+
} as const;
|
|
9994
|
+
|
|
9807
9995
|
${Jr(e)}
|
|
9808
9996
|
|
|
9809
9997
|
${Gr(e)}
|
|
9810
9998
|
|
|
9811
9999
|
${Zr(e)}
|
|
9812
|
-
`}function
|
|
10000
|
+
`}function de(e){return e.kind==="array"?`z.array(${de(e.element)})`:e.kind==="object"?`z.object({ ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${de(r)}`).join(", ")} })`:e.kind==="string"?"z.string()":e.kind==="number"?"z.number()":e.kind==="boolean"?"z.boolean()":e.kind==="date"?"z.date()":"z.unknown()"}function wn(e,t,n){let r="z.unknown()";if(e.type==="int")r="z.number().int()";else if(e.type==="string")r="z.string()",e.length!==void 0&&(r+=`.max(${e.length})`);else if(e.type==="boolean")r="z.boolean()";else if(e.type==="date")r="z.date()";else if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0){let o=`z.enum([${e.enumValues.map(i=>`"${i}"`).join(", ")}])`;r=e.isArray?`z.array(${o})`:o;}else e.type==="json"&&e.jsonShape&&(r=de(e.jsonShape));return t&&(r+=".optional()"),n&&(r+=".nullable()"),r}function Yr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=q(n),o=[],i=[];for(let[s,c]of Object.entries(r.columns))o.push(` ${s}: ${wn(c,xn(c),O(c))},`),i.push(` ${s}: ${wn(c,O(c),O(c))},`);t.push(`export const ${n}InsertSchema = z.object({
|
|
9813
10001
|
${o.join(`
|
|
9814
10002
|
`)}
|
|
9815
10003
|
});
|
|
@@ -9823,7 +10011,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
9823
10011
|
`);}return `import { z } from "zod";
|
|
9824
10012
|
|
|
9825
10013
|
${t.join(`
|
|
9826
|
-
`)}`}function
|
|
10014
|
+
`)}`}function z(e){return e.kind==="array"?`Array<${z(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([n,r])=>`${n}: ${z(r)}`).join("; ")} }`:e.kind==="string"?"string":e.kind==="number"?"number":e.kind==="boolean"?"boolean":e.kind==="date"?"Date":"unknown"}function ea(e){if(e.type==="int")return "number";if(e.type==="string")return "string";if(e.type==="boolean")return "boolean";if(e.type==="date")return "Date";if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0){let t=e.enumValues.map(n=>`"${n}"`).join(" | ");return e.isArray?`Array<${t}>`:t}return e.type==="json"&&e.jsonShape?z(e.jsonShape):"unknown"}function ta(e){let t=[];for(let[r,a]of Object.entries(e.enums??{})){let o=q(r),i=a.values.map(s=>`"${s}"`).join(" | ");t.push(`export type ${o} = ${i};`);}let n=[];for(let[r,a]of Object.entries(e.tables)){let o=q(r),i=[],s=[];for(let[c,u]of Object.entries(a.columns)){let l=ea(u),p=O(u)?" | null":"";i.push(` ${c}${O(u)?"?":""}: ${l}${p};`),s.push(` ${c}${xn(u)?"?":""}: ${l}${p};`);}n.push(`export type ${o} = {
|
|
9827
10015
|
${i.join(`
|
|
9828
10016
|
`)}
|
|
9829
10017
|
};
|
|
@@ -9836,25 +10024,25 @@ ${s.join(`
|
|
|
9836
10024
|
${n.join(`
|
|
9837
10025
|
|
|
9838
10026
|
`)}
|
|
9839
|
-
`}function na(e,t){if(t){let n=e[t];if(!oe(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(oe(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function xn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),l=na(c,t.exportName),u=Lr(l);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 p=Xr(u,n),d=ta(u),y=Yr(u);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(u.tables)}}function aa(e){return e.replaceAll("\\","/")}function j(e,t){let n=aa(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var la=new Set([".ts",".tsx",".mts",".cts"]);async function kn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await kn(a));continue}r.isFile()&&la.has(path.extname(r.name))&&n.push(a);}return n}function pe(e){return e.replace(/\.[cm]?tsx?$/,"")}function de(e,t){let n=e,r=false,a,o="unknown",i,s,c;for(;f__namespace.isCallExpression(n);){let l=n.expression;if(!f__namespace.isPropertyAccessExpression(l))break;let u=l.name.text;if(u==="optional"||u==="nullable")r=true,n=l.expression;else if(u==="default"){r=true;let p=n.arguments[0];p&&(f__namespace.isStringLiteral(p)||f__namespace.isNumericLiteral(p)?a=p.text:p.kind===f__namespace.SyntaxKind.TrueKeyword?a="true":p.kind===f__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=l.expression;}else if(u==="string"||u==="uuid"||u==="email"||u==="url"){o="string";break}else if(u==="number"||u==="int"||u==="float"){o="number";break}else if(u==="boolean"){o="boolean";break}else if(u==="date"){o="date";break}else if(u==="object"){o="object";let p=n.arguments[0];if(p&&f__namespace.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f__namespace.isPropertyAssignment(d)&&f__namespace.isIdentifier(d.name)&&i.push(de(d.initializer,d.name.text));}break}else if(u==="array"){o="array";let p=n.arguments[0];if(p){let d=de(p,"");s=d.type==="array"?"unknown":d.type,d.type==="object"&&(c=d.fields);}break}else n=l.expression;}return {name:t,type:o,optional:r,defaultValue:a,fields:i,itemType:s,itemFields:c}}function ua(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f__namespace.isPropertyAssignment(r)&&f__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)||n.push(de(r.initializer,r.name.text));return n}function ca(e){return f__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f__namespace.SyntaxKind.ExportKeyword)??false:false}function Sn(e){return f__namespace.isIdentifier(e)?e.text:f__namespace.isParenthesizedExpression(e)?Sn(e.expression):null}function da(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return f__namespace.isStringLiteral(n)||f__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>f__namespace.isStringLiteral(r)||f__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function pa(e,t){let n=f__namespace.createSourceFile(t,e,f__namespace.ScriptTarget.Latest,true,f__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(ca(a))for(let o of a.declarationList.declarations){if(!f__namespace.isIdentifier(o.name)||!o.initializer||!f__namespace.isCallExpression(o.initializer))continue;let i=Sn(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"?da(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ua(o.initializer.arguments[0]):[]});}return r}function vn(e,t,n){let r=t.replace(/\\/g,"/"),o=pe(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function ma(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function Tn(e,t){let n=e.replace(/\\/g,"/"),a=pe(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function An(e){let t=[],n=await kn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),c=pa(i,a),l=[{kind:"query",kindDirectory:"queries",exports:c.filter(u=>u.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(u=>u.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(u=>u.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(u=>u.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(u=>u.kind==="storage")}];for(let u of l){if(u.exports.length===0)continue;let p=ma(s,u.kindDirectory);for(let d of u.exports){let y=u.kind==="query"||u.kind==="mutation"?Tn(p,d.exportName):void 0,T=u.kind==="scheduler"||u.kind==="cron"?Tn(p,d.exportName):void 0,A=u.kind==="query"||u.kind==="mutation"?[...pe(p).split("/").filter(Boolean),d.exportName]:void 0,w=u.kind==="query"?vn("queries",p,d.exportName):u.kind==="mutation"?vn("mutations",p,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${T}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:j(e.outDirAbs,a),clientImportPath:j(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:T,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function ga(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){n+=d,l=false;continue}if(d==="\\"){n+=d,l=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let u=n.trim();return u.length>0&&t.push(u),t}function ha(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let c=0;c<e.length;c+=1){let l=e[c];if(s){s=false;continue}if(l==="\\"){s=true;continue}if(!o&&!i&&l==="'"){a=!a;continue}if(!a&&!i&&l==='"'){o=!o;continue}if(!a&&!o&&l==="`"){i=!i;continue}if(!(a||o||i)){if(l==="("){t+=1;continue}if(l===")"){t-=1;continue}if(l==="{"){n+=1;continue}if(l==="}"){n-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&t===0&&n===0&&r===0)return c}}return -1}function ya(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/mode\s*:\s*["'`]json["'`]/.test(t)||/\.json\s*\(/.test(t)?"json":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ba(e){let t=ga(e),n=[];for(let r of t){let a=ha(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),c=/autoincrement\s*:\s*true/i.test(i),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||c||s;n.push({name:o,expression:i,type:ya(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function wa(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,l=false,u=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!l&&!u&&y==="'"){c=!c;continue}if(!c&&!u&&y==='"'){l=!l;continue}if(!c&&!l&&y==="`"){u=!u;continue}if(!(c||l||u)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let l=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ba(l)}),a=t.exec(e);}return n}async function $n(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await $n(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function Cn(e,t=[]){let n=await $n(e.scanDirAbs).catch(()=>[]),r=path.resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),c=wa(s);if(c.length>0)return {schemaPath:o,tables:c}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function Ta(e){let t=e.auth.options.plugins;if(!Array.isArray(t))return [];for(let n of t)if(n&&typeof n=="object"){let r=n;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function Ra(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function ka(e,t){let n=await Bun.file(e).text(),r=t.map(o=>`"${o}"`).join(" | "),a=n.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
9840
|
-
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function Sa(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function
|
|
9841
|
-
`);let
|
|
9842
|
-
`);let
|
|
9843
|
-
`),...Zn,...Gn,Bun.write(
|
|
9844
|
-
`),Bun.write(Jn,Kn)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-
|
|
9845
|
-
`);let
|
|
9846
|
-
`),
|
|
9847
|
-
`));function er(
|
|
9848
|
-
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-
|
|
9849
|
-
`);async function tr(
|
|
9850
|
-
`);let
|
|
9851
|
-
`);async function
|
|
9852
|
-
`);let nr=t+"/";async function
|
|
9853
|
-
`);let rr=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(rr)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-
|
|
9854
|
-
`);let
|
|
9855
|
-
`);}}var
|
|
10027
|
+
`}function na(e,t){if(t){let n=e[t];if(!ie(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(ie(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function Tn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),u=na(c,t.exportName),l=Lr(u);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(i),{recursive:true})]);let p=Xr(l,n),d=ta(l),y=Yr(l);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(l.tables)}}function aa(e){return e.replaceAll("\\","/")}function M(e,t){let n=aa(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var la=new Set([".ts",".tsx",".mts",".cts"]);async function Sn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await Sn(a));continue}r.isFile()&&la.has(path.extname(r.name))&&n.push(a);}return n}function me(e){return e.replace(/\.[cm]?tsx?$/,"")}function pe(e,t){let n=e,r=false,a,o="unknown",i,s,c;for(;f__namespace.isCallExpression(n);){let u=n.expression;if(!f__namespace.isPropertyAccessExpression(u))break;let l=u.name.text;if(l==="optional"||l==="nullable")r=true,n=u.expression;else if(l==="default"){r=true;let p=n.arguments[0];p&&(f__namespace.isStringLiteral(p)||f__namespace.isNumericLiteral(p)?a=p.text:p.kind===f__namespace.SyntaxKind.TrueKeyword?a="true":p.kind===f__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=u.expression;}else if(l==="string"||l==="uuid"||l==="email"||l==="url"){o="string";break}else if(l==="number"||l==="int"||l==="float"){o="number";break}else if(l==="boolean"){o="boolean";break}else if(l==="date"){o="date";break}else if(l==="object"){o="object";let p=n.arguments[0];if(p&&f__namespace.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f__namespace.isPropertyAssignment(d)&&f__namespace.isIdentifier(d.name)&&i.push(pe(d.initializer,d.name.text));}break}else if(l==="array"){o="array";let p=n.arguments[0];if(p){let d=pe(p,"");s=d.type==="array"?"unknown":d.type,d.type==="object"&&(c=d.fields);}break}else n=u.expression;}return {name:t,type:o,optional:r,defaultValue:a,fields:i,itemType:s,itemFields:c}}function ua(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f__namespace.isPropertyAssignment(r)&&f__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)||n.push(pe(r.initializer,r.name.text));return n}function ca(e){return f__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f__namespace.SyntaxKind.ExportKeyword)??false:false}function An(e){return f__namespace.isIdentifier(e)?e.text:f__namespace.isParenthesizedExpression(e)?An(e.expression):null}function da(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return f__namespace.isStringLiteral(n)||f__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>f__namespace.isStringLiteral(r)||f__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function pa(e,t){let n=f__namespace.createSourceFile(t,e,f__namespace.ScriptTarget.Latest,true,f__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(ca(a))for(let o of a.declarationList.declarations){if(!f__namespace.isIdentifier(o.name)||!o.initializer||!f__namespace.isCallExpression(o.initializer))continue;let i=An(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?da(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ua(o.initializer.arguments[0]):[]});}return r}function vn(e,t,n){let r=t.replace(/\\/g,"/"),o=me(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function ma(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function Rn(e,t){let n=e.replace(/\\/g,"/"),a=me(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function Nn(e){let t=[],n=await Sn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),c=pa(i,a),u=[{kind:"query",kindDirectory:"queries",exports:c.filter(l=>l.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(l=>l.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(l=>l.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(l=>l.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(l=>l.kind==="storage")}];for(let l of u){if(l.exports.length===0)continue;let p=ma(s,l.kindDirectory);for(let d of l.exports){let y=l.kind==="query"||l.kind==="mutation"?Rn(p,d.exportName):void 0,x=l.kind==="scheduler"||l.kind==="cron"?Rn(p,d.exportName):void 0,N=l.kind==="query"||l.kind==="mutation"?[...me(p).split("/").filter(Boolean),d.exportName]:void 0,w=l.kind==="query"?vn("queries",p,d.exportName):l.kind==="mutation"?vn("mutations",p,d.exportName):l.kind==="storage"?`/storage/managers/${d.exportName}`:`/${l.kindDirectory}/${x}`;t.push({kind:l.kind,exportName:d.exportName,filePath:a,importPath:M(e.outDirAbs,a),clientImportPath:M(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:N,taskName:x,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function ga(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,u=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let l=n.trim();return l.length>0&&t.push(l),t}function ha(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let c=0;c<e.length;c+=1){let u=e[c];if(s){s=false;continue}if(u==="\\"){s=true;continue}if(!o&&!i&&u==="'"){a=!a;continue}if(!a&&!i&&u==='"'){o=!o;continue}if(!a&&!o&&u==="`"){i=!i;continue}if(!(a||o||i)){if(u==="("){t+=1;continue}if(u===")"){t-=1;continue}if(u==="{"){n+=1;continue}if(u==="}"){n-=1;continue}if(u==="["){r+=1;continue}if(u==="]"){r-=1;continue}if(u===":"&&t===0&&n===0&&r===0)return c}}return -1}function ya(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/mode\s*:\s*["'`]json["'`]/.test(t)||/\.json\s*\(/.test(t)?"json":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ba(e){let t=ga(e),n=[];for(let r of t){let a=ha(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),c=/autoincrement\s*:\s*true/i.test(i),u=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||u||c||s;n.push({name:o,expression:i,type:ya(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function wa(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,u=false,l=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!u&&!l&&y==="'"){c=!c;continue}if(!c&&!l&&y==='"'){u=!u;continue}if(!c&&!u&&y==="`"){l=!l;continue}if(!(c||u||l)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let u=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ba(u)}),a=t.exec(e);}return n}async function Cn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await Cn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function Fn(e,t=[]){let n=await Cn(e.scanDirAbs).catch(()=>[]),r=path.resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),c=wa(s);if(c.length>0)return {schemaPath:o,tables:c}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function va(e){let t=e.auth.options.plugins;if(!Array.isArray(t))return [];for(let n of t)if(n&&typeof n=="object"){let r=n;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function Ra(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function ka(e,t){let n=await Bun.file(e).text(),r=t.map(o=>`"${o}"`).join(" | "),a=n.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
10028
|
+
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function Sa(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function En(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=M(t,a),s=path.resolve(t,"client"),c=M(s,a),u=performance.now();await Promise.all([promises.mkdir(t,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]),process.stdout.write(`\u{1F4C1} Directories (${(performance.now()-u).toFixed(0)}ms)
|
|
10029
|
+
`);let l=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),p=path.join(path.dirname(Bun.resolveSync("typescript/package.json",l)),"bin","tsc"),d=path.join(path.dirname(Bun.resolveSync("@better-auth/cli/package.json",l)),"dist","index.mjs"),y=path.resolve(t,"server.ts"),x=path.resolve(t,"client.ts"),N=path.resolve(t,"auth.config.ts"),w=path.resolve(t,"auth.schema.ts"),D=path.resolve(t,"drizzle.config.ts"),E=path.resolve(n,"wrangler.json"),b=await Tn(e),h=await Fn(e,b?[b.schemaPath]:[]),v=M(t,h.schemaPath),A=await Nn(e);process.stdout.write(`\u{1F50D} ${A.length} handler(s) (${(performance.now()-u).toFixed(0)}ms)
|
|
10030
|
+
`);let k=va(r),V=Ra(r),B=kt(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),ye=Ce(c,A),Ln=X(v,A,r.r2[0]?.binding,k,V),zn=ve(i),_n=b?[Sa(o,b.schemaPath),...r.schema.filter(T=>!/(^|\/)schema\.ts$/.test(T))]:r.schema,Un=Fe(_n),Qn=At(e,A),Kn=fn(v,h,A),Jn=path.resolve(t,"admin.routes.ts"),Gn=Ln.map(T=>Bun.write(path.resolve(t,T.relativePath),T.source)),Zn=ye.map(T=>Bun.write(path.resolve(t,T.relativePath),T.source));await Promise.all([Bun.write(y,B),Bun.write(x,`export * from "./client/index";
|
|
10031
|
+
`),...Zn,...Gn,Bun.write(N,zn),Bun.write(w,""),Bun.write(D,Un),Bun.write(E,`${JSON.stringify(Qn,null,2)}
|
|
10032
|
+
`),Bun.write(Jn,Kn)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-u).toFixed(0)}ms)
|
|
10033
|
+
`);let K=path.relative(o,N).replace(/\\/g,"/"),Xn=K.startsWith(".")?K:`./${K}`,J=path.relative(o,w).replace(/\\/g,"/"),Yn=J.startsWith(".")?J:`./${J}`,be=await Bun.spawn([process.execPath,d,"generate","--config",Xn,"--output",Yn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(be!==0)throw new Error(`better-auth generation failed with exit code ${be}`);process.stdout.write(`\u{1F510} Auth schema (${(performance.now()-u).toFixed(0)}ms)
|
|
10034
|
+
`),k.length>0&&(await ka(w,k),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-u).toFixed(0)}ms)
|
|
10035
|
+
`));function er(T={}){return {compilerOptions:{lib:["es2024"],types:["@types/node","@cloudflare/workers-types/2023-07-01"],module:"es2022",target:"es2024",moduleResolution:"bundler",strictNullChecks:true,skipLibCheck:true,declaration:true,emitDeclarationOnly:true,noCheck:true,jsx:"react-jsx",paths:{"_generated/*":["./*"]},...T},include:["./*.ts","./client/*.ts"]}}let we=path.resolve(t,"tsconfig.js.json");await Promise.all([Bun.write(we,`${JSON.stringify(er({declaration:true,emitDeclarationOnly:false}),null,2)}
|
|
10036
|
+
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-u).toFixed(0)}ms)
|
|
10037
|
+
`);async function tr(T,C){process.stdout.write(`\u2699\uFE0F ${C}... (${(performance.now()-u).toFixed(0)}ms)
|
|
10038
|
+
`);let $=await Bun.spawn([process.execPath,p,"-p",T],{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if($!==0)throw new Error(`tsc ${C} failed with exit code ${$}`)}await tr(we,"JS files"),process.stdout.write(`\u2705 JS + declarations (${(performance.now()-u).toFixed(0)}ms)
|
|
10039
|
+
`);async function xe(T){let C=await promises.readdir(T,{withFileTypes:true});for(let R of C){let $=path.join(T,R.name);if(R.isDirectory()){if(R.name==="node_modules"||R.name.startsWith("."))continue;await xe($);}else R.name.endsWith(".ts")&&!R.name.endsWith(".d.ts")&&await promises.rm($);}}await xe(t),process.stdout.write(`\u{1F4E6} Cleaned .ts files (${(performance.now()-u).toFixed(0)}ms)
|
|
10040
|
+
`);let nr=t+"/";async function Te(T){let C=await promises.readdir(T,{withFileTypes:true});for(let R of C){let $=path.join(T,R.name);if(R.isDirectory()){if(R.name==="node_modules"||R.name.startsWith(".")||$===t)continue;await Te($);}else !$.startsWith(nr)&&(R.name.endsWith(".d.ts")||R.name.endsWith(".js"))&&await promises.rm($);}}await Te(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-u).toFixed(0)}ms)
|
|
10041
|
+
`);let rr=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(rr)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-u).toFixed(0)}ms)
|
|
10042
|
+
`);let C=await Bun.spawn([process.execPath,p,"--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(C!==0)throw new Error(`TypeScript build failed with exit code ${C}`);process.stdout.write(`\u2705 Build complete (${(performance.now()-u).toFixed(0)}ms)
|
|
10043
|
+
`);}}var jn=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(),In=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),On=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(),Pn=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),queue:zod.z.string().min(1).optional()}).strict(),Ca=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(),Fa=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([jn,zod.z.array(jn).min(1)]),kv:zod.z.union([In,zod.z.array(In)]).optional(),r2:zod.z.union([On,zod.z.array(On)]).optional(),auth:zod.z.object({enabled:zod.z.boolean(),basePath:zod.z.string().min(1),options:zod.z.custom(e=>typeof e=="object"&&e!==null),clientOptions:zod.z.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:Pn.optional(),realtime:Ca.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),build:zod.z.boolean().optional()}).strict();function Dn(e){return typeof e=="object"&&e!==null}function qa(e){let t=Dn(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=Pn.safeParse(t);return n.success?n.data:{}}function Ma(e){if(!Dn(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function Ea(e){let n={...qa(e)??{},...e.scheduler??{}},r=e.realtime??{};return {...e,database:Array.isArray(e.database)?e.database:[e.database],kv:e.kv?Array.isArray(e.kv)?e.kv:[e.kv]:[],r2:e.r2?Array.isArray(e.r2)?e.r2:[e.r2]:[],scheduler:{enabled:n.enabled??true,binding:n.binding??"APPFLARE_SCHEDULER_QUEUE",queue:n.queue},realtime:{enabled:r.enabled??true,binding:r.binding??"APPFLARE_REALTIME",className:r.className??"AppflareRealtimeDurableObject",objectName:r.objectName??"global",subscribePath:r.subscribePath??"/realtime/subscribe",websocketPath:r.websocketPath??"/realtime/ws",protocol:r.protocol??"appflare.realtime.v1"},wranglerOverrides:Ma(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function P(e){let t=path.isAbsolute(e??"")?e:path.resolve(process.cwd(),e??"appflare.config.ts"),n=path.dirname(t),o=(await import(url.pathToFileURL(t).href)).default,i=Fa.parse(o),s=Ea(i);return {configPath:t,configDir:n,scanDirAbs:path.resolve(n,s.scanDir),outDirAbs:path.resolve(n,s.outDir),wranglerOutDirAbs:path.resolve(n,s.wranglerOutDir),config:s}}function Pa(e){let t=e;for(;;){if(fs.existsSync(path.resolve(t,"package.json")))return t;let n=path.dirname(t);if(n===t)return e;t=n;}}async function Q(e,t={}){let n=await P(e);if(t.build!==void 0&&(n.config.build=t.build),await En(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
9856
10044
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
9857
|
-
`);}async function
|
|
9858
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
10045
|
+
`);}async function Bn(e,t={}){if(await Q(e,{build:t.build}),!t.watch)return;let n=await P(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await Q(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
10046
|
+
`);}finally{r=false,a&&(a=false,await o());}};ja__default.default.watch(n.scanDirAbs,{ignoreInitial:true,ignored:s=>s.includes("/_generated/")||s.includes("/dist/")||s.includes("/out/")||s.includes("/node_modules/")||s.endsWith(".d.ts")}).on("all",async(s,c)=>{process.stdout.write(`\u{1F504} Change detected: ${c}
|
|
9859
10047
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
9860
|
-
`);}async function
|
|
10048
|
+
`);}async function Wn(e,t={}){let n=await P(e),r=Pa(process.cwd());if([!!t.local,!!t.remote,!!t.preview].filter(Boolean).length>1)throw new Error("Only one of --local, --remote, or --preview can be set.");let o=path.resolve(n.outDirAbs,"drizzle.config.js"),i=process.platform==="win32"?"npx.cmd":"npx",c=await Bun.spawn([i,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(c!==0)throw new Error(`drizzle-kit generate failed with exit code ${c}`);let u=n.config.database[0].databaseName,l=[i,"wrangler","d1","migrations","apply",u];t.local?l.push("--local"):t.remote?l.push("--remote"):t.preview&&l.push("--preview");let d=await Bun.spawn(l,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(d!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${d}`)}async function Hn(e,t={name:"",email:"",password:""}){let n=await P(e);if([!!t.local,!!t.remote].filter(Boolean).length>1)throw new Error("Only one of --local or --remote can be set.");let{hashPassword:a}=await import('better-auth/crypto'),o=await a(t.password),i=crypto.randomUUID(),s=crypto.randomUUID(),c=Date.now(),u=t.name.replace(/'/g,"''"),l=t.email.replace(/'/g,"''"),p=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${u}', '${l}', 1, ${c}, ${c}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${l}', 'credential', '${i}', '${o}', ${c}, ${c});`].join(" "),d=n.config.database[0].databaseName,x=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${p}`];t.local?x.push("--local"):t.remote&&x.push("--remote");let w=await Bun.spawn(x,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(w!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${w}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var j=new commander.Command;j.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");j.command("build").description("Generate server.ts, client.ts, auth.config.js, drizzle.config.js, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--no-build","Skip TypeScript build step").action(async e=>{await Q(e.config,{build:e.build});});j.command("dev").description("Run generator in development mode").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("-w, --watch","Watch scanDir and regenerate on changes",false).option("--no-build","Skip TypeScript build step").action(async e=>{await Bn(e.config,{watch:e.watch,build:e.build});});j.command("migrate").description("Generate drizzle migration files from outDir/auth.schema.ts and apply them to the configured D1 database").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute commands/files against a local DB for use with wrangler dev",false).option("--remote","Execute commands/files against a remote DB for use with wrangler dev --remote",false).option("--preview","Execute commands/files against a preview D1 DB",false).action(async e=>{await Wn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});j.command("add-admin").description("Add an admin user to the database").requiredOption("-n, --name <name>","Admin's display name").requiredOption("-e, --email <email>","Admin's email address").requiredOption("-p, --password <password>","Admin's password").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute command against a local DB for use with wrangler dev",false).option("--remote","Execute command against a remote DB for use with wrangler dev --remote",false).action(async e=>{await Hn(e.config,{name:e.name,email:e.email,password:e.password,local:e.local,remote:e.remote});});(async()=>{process.versions.bun||(console.error("Appflare CLI must be run with Bun."),process.exit(1)),await j.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|