appflare 0.2.44 → 0.2.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/schema-compiler.ts +7 -7
- package/cli/templates/dashboard/builders/functions/render-page/request-panel.ts +117 -17
- package/cli/templates/dashboard/builders/functions/render-page/scripts.ts +149 -0
- package/cli/utils/handler-discovery.ts +37 -2
- package/dist/cli/index.js +578 -369
- package/dist/cli/index.mjs +578 -369
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
'use strict';var commander=require('commander'),
|
|
2
|
+
'use strict';var commander=require('commander'),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 Te(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 ve(){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
61
61
|
import type {
|
|
62
62
|
AppflareAuth,
|
|
63
63
|
AppflareAuthTokenResolver,
|
|
@@ -166,21 +166,21 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
166
166
|
): Appflare<Options> {
|
|
167
167
|
return new Appflare(options);
|
|
168
168
|
}
|
|
169
|
-
`}function
|
|
170
|
-
`)}function
|
|
169
|
+
`}function ar(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function Re(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 ke(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 J(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)}: ${J(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:`${Re(e.kind)}${Re(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
|
-
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${
|
|
173
|
-
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${
|
|
174
|
-
...params: AppflareRunParams<${
|
|
172
|
+
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
173
|
+
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
174
|
+
...params: AppflareRunParams<${t}>
|
|
175
175
|
) => {
|
|
176
|
-
const { args, options } = resolveRunParams<${
|
|
176
|
+
const { args, options } = resolveRunParams<${t}>(params);
|
|
177
177
|
const mergedOptions = mergeRouteOptions(runtime.options, options);
|
|
178
178
|
const resultOptions: AppflareRouteCallOptions<"return"> = {
|
|
179
179
|
...(mergedOptions ?? {}),
|
|
180
180
|
errorMode: "return",
|
|
181
181
|
};
|
|
182
182
|
const parsed = ${e.schemaConst}.parse(args);
|
|
183
|
-
return requestRoute<${
|
|
183
|
+
return requestRoute<${n}>(runtime.endpoint, {
|
|
184
184
|
route: ${JSON.stringify(e.routePath)},
|
|
185
185
|
method: ${JSON.stringify(a)},
|
|
186
186
|
input: parsed,
|
|
@@ -195,7 +195,7 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
195
195
|
args,
|
|
196
196
|
requestOptions,
|
|
197
197
|
signal,
|
|
198
|
-
}: AppflareQuerySubscribeOptions<${
|
|
198
|
+
}: AppflareQuerySubscribeOptions<${t}, ${n}>): AppflareRealtimeSubscription => {
|
|
199
199
|
const mergedOptions = mergeRouteOptions(runtime.options, requestOptions);
|
|
200
200
|
const parsedArgs = ${e.schemaConst}.parse(normalizeRouteInput(args));
|
|
201
201
|
const requestAuthToken = resolveRealtimeAuthToken(authToken, mergedOptions?.headers);
|
|
@@ -299,8 +299,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
299
299
|
const payload = (message as { payload?: unknown }).payload;
|
|
300
300
|
if (typeof payload === "object" && payload !== null && "data" in payload) {
|
|
301
301
|
onChange(
|
|
302
|
-
(payload as { data: ${
|
|
303
|
-
message as AppflareRealtimeQueryUpdate<${
|
|
302
|
+
(payload as { data: ${n} }).data,
|
|
303
|
+
message as AppflareRealtimeQueryUpdate<${n}>,
|
|
304
304
|
);
|
|
305
305
|
}
|
|
306
306
|
}
|
|
@@ -322,8 +322,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
322
322
|
};
|
|
323
323
|
};
|
|
324
324
|
|
|
325
|
-
const queryKey = (args?: ${
|
|
326
|
-
return ["appflare", "query", ${JSON.stringify(e.routePath)}, (args ?? {}) as ${
|
|
325
|
+
const queryKey = (args?: ${t}): [string, string, string, ${t}] => {
|
|
326
|
+
return ["appflare", "query", ${JSON.stringify(e.routePath)}, (args ?? {}) as ${t}];
|
|
327
327
|
};
|
|
328
328
|
|
|
329
329
|
return {
|
|
@@ -334,18 +334,18 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
334
334
|
};
|
|
335
335
|
};`:`const ${e.alias}Route = (
|
|
336
336
|
runtime: RequestRuntime,
|
|
337
|
-
): AppflareRouteClient<typeof ${e.schemaConst}, ${
|
|
338
|
-
const run: AppflareRouteClient<typeof ${e.schemaConst}, ${
|
|
339
|
-
...params: AppflareRunParams<${
|
|
337
|
+
): AppflareRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
338
|
+
const run: AppflareRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
339
|
+
...params: AppflareRunParams<${t}>
|
|
340
340
|
) => {
|
|
341
|
-
const { args, options } = resolveRunParams<${
|
|
341
|
+
const { args, options } = resolveRunParams<${t}>(params);
|
|
342
342
|
const mergedOptions = mergeRouteOptions(runtime.options, options);
|
|
343
343
|
const resultOptions: AppflareRouteCallOptions<"return"> = {
|
|
344
344
|
...(mergedOptions ?? {}),
|
|
345
345
|
errorMode: "return",
|
|
346
346
|
};
|
|
347
347
|
const parsed = ${e.schemaConst}.parse(args);
|
|
348
|
-
return requestRoute<${
|
|
348
|
+
return requestRoute<${n}>(runtime.endpoint, {
|
|
349
349
|
route: ${JSON.stringify(e.routePath)},
|
|
350
350
|
method: ${JSON.stringify(a)},
|
|
351
351
|
input: parsed,
|
|
@@ -358,15 +358,15 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
358
358
|
schema: ${r},
|
|
359
359
|
run,
|
|
360
360
|
};
|
|
361
|
-
};`}function G(e){let
|
|
362
|
-
`),o=
|
|
363
|
-
export type ${
|
|
361
|
+
};`}function G(e){let t=e.map((l,u)=>ir(l,u)).filter(l=>l!==null),n=t.filter(l=>l.kind==="query"),r=t.filter(l=>l.kind==="mutation"),a=t.map(l=>`import { ${l.exportName} as ${l.alias} } from "${l.importPath}";`).join(`
|
|
362
|
+
`),o=t.map(l=>{let u=`${l.typeBase}Input`,p=`${l.typeBase}Output`,d=`${l.typeBase}Schema`;return `const ${l.schemaConst} = z.object(${l.alias}.definition.args);
|
|
363
|
+
export type ${u} = z.input<typeof ${l.schemaConst}>;
|
|
364
364
|
export type ${p} = Awaited<ReturnType<typeof ${l.alias}.definition.handler>>;
|
|
365
365
|
export const ${d} = ${l.schemaConst};`}).join(`
|
|
366
366
|
|
|
367
|
-
`),i=
|
|
367
|
+
`),i=t.map(l=>sr(l)).join(`
|
|
368
368
|
|
|
369
|
-
`),s=J(
|
|
369
|
+
`),s=J(ke(n)),c=J(ke(r));return `import { z } from "zod";
|
|
370
370
|
import type {
|
|
371
371
|
AppflareErrorMode,
|
|
372
372
|
AppflareRequestError,
|
|
@@ -737,16 +737,16 @@ export function createMutationsClient(
|
|
|
737
737
|
options,
|
|
738
738
|
};
|
|
739
739
|
|
|
740
|
-
return ${
|
|
740
|
+
return ${c} as const;
|
|
741
741
|
}
|
|
742
742
|
|
|
743
743
|
export type QueriesClient = ReturnType<typeof createQueriesClient>;
|
|
744
744
|
export type MutationsClient = ReturnType<typeof createMutationsClient>;
|
|
745
|
-
`}function
|
|
745
|
+
`}function Se(){return `export * from "./types";
|
|
746
746
|
export * from "./appflare";
|
|
747
747
|
export * from "./storage";
|
|
748
748
|
export * from "./handlers";
|
|
749
|
-
`}function
|
|
749
|
+
`}function Ae(){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 Ne(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 $e(e,t){return [{relativePath:"client/index.ts",source:Se()},{relativePath:"client/types.ts",source:Ne(e)},{relativePath:"client/storage.ts",source:Ae()},{relativePath:"client/handlers.ts",source:G(t)},{relativePath:"client/appflare.ts",source:ve()}]}function Ce(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 Fe(){return `
|
|
1138
1138
|
|
|
1139
1139
|
import { getHeaders } from "./server";
|
|
1140
1140
|
export async function resolveSession(
|
|
@@ -1205,7 +1205,7 @@ type R2BucketBinding = {
|
|
|
1205
1205
|
options?: { expiresIn?: number },
|
|
1206
1206
|
) => Promise<URL>;
|
|
1207
1207
|
};
|
|
1208
|
-
`}function
|
|
1208
|
+
`}function Ie(){return `
|
|
1209
1209
|
export function createScheduler(
|
|
1210
1210
|
queue?: SchedulerQueueBinding,
|
|
1211
1211
|
): Scheduler {
|
|
@@ -1234,7 +1234,7 @@ function createContextErrorHelpers() {
|
|
|
1234
1234
|
},
|
|
1235
1235
|
};
|
|
1236
1236
|
}
|
|
1237
|
-
`}function
|
|
1237
|
+
`}function je(){return `
|
|
1238
1238
|
function normalizeStoragePath(path: string): string {
|
|
1239
1239
|
const trimmed = path.trim();
|
|
1240
1240
|
if (trimmed.length === 0) {
|
|
@@ -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 Oe(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 {
|
|
@@ -1488,18 +1488,18 @@ import {
|
|
|
1488
1488
|
|
|
1489
1489
|
${qe()}
|
|
1490
1490
|
|
|
1491
|
-
${Ce()}
|
|
1492
|
-
|
|
1493
1491
|
${Fe()}
|
|
1494
1492
|
|
|
1493
|
+
${Ie()}
|
|
1494
|
+
|
|
1495
1495
|
${Me()}
|
|
1496
1496
|
|
|
1497
|
-
${
|
|
1497
|
+
${je()}
|
|
1498
1498
|
|
|
1499
1499
|
${Ee()}
|
|
1500
1500
|
|
|
1501
1501
|
${Pe(e)}
|
|
1502
|
-
`}function
|
|
1502
|
+
`}function De(){return `
|
|
1503
1503
|
export async function executeOperation<
|
|
1504
1504
|
TShape extends ZodRawShape,
|
|
1505
1505
|
TResult,
|
|
@@ -1538,7 +1538,7 @@ export function handleOperationError(
|
|
|
1538
1538
|
return c.json({ message: (error as Error).message ?? "Unknown error" }, 500);
|
|
1539
1539
|
}
|
|
1540
1540
|
|
|
1541
|
-
`}function
|
|
1541
|
+
`}function Ve(){return `import type { Context } from "hono";
|
|
1542
1542
|
import { ZodError, type ZodRawShape } from "zod";
|
|
1543
1543
|
import {
|
|
1544
1544
|
type AppflareContext,
|
|
@@ -1547,8 +1547,8 @@ import {
|
|
|
1547
1547
|
type WorkerEnv,
|
|
1548
1548
|
} from "./handlers";
|
|
1549
1549
|
|
|
1550
|
-
${
|
|
1551
|
-
`}function
|
|
1550
|
+
${De()}
|
|
1551
|
+
`}function Be(){return `import { betterAuth } from "better-auth";
|
|
1552
1552
|
import { auth } from "./auth.config";
|
|
1553
1553
|
import {
|
|
1554
1554
|
and,
|
|
@@ -1651,7 +1651,7 @@ export async function isStorageAllowed(
|
|
|
1651
1651
|
|
|
1652
1652
|
return false;
|
|
1653
1653
|
}
|
|
1654
|
-
`}function
|
|
1654
|
+
`}function We(){return `type Primitive = string | number | boolean | Date;
|
|
1655
1655
|
type NonNil<T> = Exclude<T, null | undefined>;
|
|
1656
1656
|
type Friendly<T> = T extends Date ? Date | number : T;
|
|
1657
1657
|
type Comparable<T> = Friendly<Extract<NonNil<T>, Primitive>>;
|
|
@@ -1939,7 +1939,7 @@ export type QueryDeleteArgs<TName extends TableName> = {
|
|
|
1939
1939
|
where?: WhereInput<TableModel<TName>, TName>;
|
|
1940
1940
|
limit?: number;
|
|
1941
1941
|
};
|
|
1942
|
-
`}function
|
|
1942
|
+
`}function He(){return `type AggregateWithInput<TName extends TableName> =
|
|
1943
1943
|
QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1944
1944
|
|
|
1945
1945
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -2071,7 +2071,7 @@ export type DbMutationEvent = {
|
|
|
2071
2071
|
export type QueryDbOptions = {
|
|
2072
2072
|
onMutation?: (event: DbMutationEvent) => void;
|
|
2073
2073
|
};
|
|
2074
|
-
`}function
|
|
2074
|
+
`}function Le(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2075
2075
|
return typeof value === "object" && value !== null;
|
|
2076
2076
|
}
|
|
2077
2077
|
|
|
@@ -3450,7 +3450,7 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
3450
3450
|
|
|
3451
3451
|
return [];
|
|
3452
3452
|
}
|
|
3453
|
-
`}function
|
|
3453
|
+
`}function ze(){return `const mergedSchema = {
|
|
3454
3454
|
...authSchema,
|
|
3455
3455
|
...schema,
|
|
3456
3456
|
};
|
|
@@ -3725,9 +3725,9 @@ type TableFindFirstResult<
|
|
|
3725
3725
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3726
3726
|
(typeof mergedSchema)[TName]
|
|
3727
3727
|
>;
|
|
3728
|
-
`}function
|
|
3728
|
+
`}function Ue(){return [ze(),We(),He(),Le()].join(`
|
|
3729
3729
|
|
|
3730
|
-
`)}function
|
|
3730
|
+
`)}function Qe(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3731
3731
|
const withValue = args?.with;
|
|
3732
3732
|
const pathSegments = args?.field
|
|
3733
3733
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -3898,7 +3898,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3898
3898
|
},
|
|
3899
3899
|
}) as AppflareQueryDb;
|
|
3900
3900
|
}
|
|
3901
|
-
`}function
|
|
3901
|
+
`}function _e(){return `export class AppflareHandledError extends Error {
|
|
3902
3902
|
public readonly status: number;
|
|
3903
3903
|
public readonly payload: unknown;
|
|
3904
3904
|
|
|
@@ -3908,7 +3908,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3908
3908
|
this.payload = payload;
|
|
3909
3909
|
}
|
|
3910
3910
|
}
|
|
3911
|
-
`}function
|
|
3911
|
+
`}function Ke(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
3912
3912
|
const where = isRecord(args?.where)
|
|
3913
3913
|
? (args?.where as Record<string, unknown>)
|
|
3914
3914
|
: undefined;
|
|
@@ -4062,7 +4062,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4062
4062
|
);
|
|
4063
4063
|
});
|
|
4064
4064
|
},
|
|
4065
|
-
`}function
|
|
4065
|
+
`}function Je(){return `export function createQueryDb(
|
|
4066
4066
|
$db: AppflareDb,
|
|
4067
4067
|
options?: QueryDbOptions,
|
|
4068
4068
|
): AppflareQueryDb {
|
|
@@ -4104,7 +4104,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4104
4104
|
};
|
|
4105
4105
|
|
|
4106
4106
|
const tableApi = {
|
|
4107
|
-
`}function
|
|
4107
|
+
`}function Ge(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
4108
4108
|
const transaction = ($db as any).transaction;
|
|
4109
4109
|
|
|
4110
4110
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -5059,17 +5059,17 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
5059
5059
|
);
|
|
5060
5060
|
return rows;
|
|
5061
5061
|
},
|
|
5062
|
-
`}function
|
|
5062
|
+
`}function Ze(){return [Je(),Ke(),Ge(),Qe(),_e()].join(`
|
|
5063
5063
|
|
|
5064
|
-
`)}function
|
|
5064
|
+
`)}function Xe(e=[],t=[]){let n=t.map(i=>` ${i.name}?: ${i.tsType} | null;`).join(`
|
|
5065
5065
|
`),a=[e.length>0?[" role: UserRole;"," banned: boolean | null;"," banReason?: string | null | undefined;"," banExpires?: Date | null | undefined;"].join(`
|
|
5066
|
-
`):"",
|
|
5066
|
+
`):"",n].filter(Boolean).join(`
|
|
5067
5067
|
`);return `type AuthSession = typeof auth.$Infer.Session;
|
|
5068
5068
|
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
5069
5069
|
${e.length>0?`export type UserRole = ${e.map(i=>`"${i}"`).join(" | ")};
|
|
5070
5070
|
type User = import("better-auth").User & {
|
|
5071
5071
|
${a}
|
|
5072
|
-
};`:
|
|
5072
|
+
};`:t.length>0?`type User = import("better-auth").User & {
|
|
5073
5073
|
${a}
|
|
5074
5074
|
};`:'type User = import("better-auth").User;'}
|
|
5075
5075
|
type Session = AuthSession['session']
|
|
@@ -5158,7 +5158,7 @@ export type AppflareContext = {
|
|
|
5158
5158
|
storage: AppflareStorage;
|
|
5159
5159
|
error: (status: number, message: string, details?: unknown) => never;
|
|
5160
5160
|
};
|
|
5161
|
-
`}function
|
|
5161
|
+
`}function Ye(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
5162
5162
|
|
|
5163
5163
|
export type SchedulerEnqueueOptions = {
|
|
5164
5164
|
delaySeconds?: number;
|
|
@@ -5290,40 +5290,40 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
5290
5290
|
definition,
|
|
5291
5291
|
};
|
|
5292
5292
|
}
|
|
5293
|
-
`}function
|
|
5293
|
+
`}function et(e=[],t=[]){return [Be(),Ue(),Ze(),Xe(e,t),Ye()].join(`
|
|
5294
5294
|
|
|
5295
|
-
`)}function
|
|
5295
|
+
`)}function tt(e,t=[],n=[]){return `import type { Context } from "hono";
|
|
5296
5296
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5297
5297
|
import { drizzle } from "drizzle-orm/d1";
|
|
5298
5298
|
import { z, type ZodRawShape } from "zod";
|
|
5299
5299
|
import * as authSchema from "./auth.schema";
|
|
5300
5300
|
import * as schema from "${e}";
|
|
5301
5301
|
|
|
5302
|
-
${
|
|
5303
|
-
`}function
|
|
5304
|
-
`)}function
|
|
5305
|
-
`)}function
|
|
5306
|
-
`)}function
|
|
5302
|
+
${et(t,n)}
|
|
5303
|
+
`}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(`
|
|
5304
|
+
`)}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(`
|
|
5305
|
+
`)}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(`
|
|
5306
|
+
`)}function fr(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
5307
5307
|
app.get(
|
|
5308
|
-
"${
|
|
5308
|
+
"${t.routePath}",
|
|
5309
5309
|
sValidator("query", ${r}),
|
|
5310
5310
|
async (c) => {
|
|
5311
5311
|
const ctx = await createExecutionContext(c, options);
|
|
5312
5312
|
try {
|
|
5313
|
-
return await executeOperation(c, ${
|
|
5313
|
+
return await executeOperation(c, ${n}, c.req.valid("query"), ctx);
|
|
5314
5314
|
} catch (error) {
|
|
5315
5315
|
return handleOperationError(c, error, "Invalid query arguments");
|
|
5316
5316
|
}
|
|
5317
5317
|
},
|
|
5318
5318
|
);`}).join(`
|
|
5319
|
-
`)}function
|
|
5319
|
+
`)}function gr(e){return e.filter(({operation:t})=>t.kind==="mutation").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
5320
5320
|
app.post(
|
|
5321
|
-
"${
|
|
5321
|
+
"${t.routePath}",
|
|
5322
5322
|
sValidator("json", ${r}),
|
|
5323
5323
|
async (c) => {
|
|
5324
5324
|
const ctx = await createExecutionContext(c, options);
|
|
5325
5325
|
try {
|
|
5326
|
-
const response = await executeOperation(c, ${
|
|
5326
|
+
const response = await executeOperation(c, ${n}, c.req.valid("json"), ctx);
|
|
5327
5327
|
await publishMutationEvents(c, options, ctx.mutationEvents);
|
|
5328
5328
|
return response;
|
|
5329
5329
|
} catch (error) {
|
|
@@ -5331,26 +5331,26 @@ import * as schema from "${e}";
|
|
|
5331
5331
|
}
|
|
5332
5332
|
},
|
|
5333
5333
|
);`}).join(`
|
|
5334
|
-
`)}function
|
|
5334
|
+
`)}function hr(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`,a=t.handlerName??t.routePath;return `
|
|
5335
5335
|
${JSON.stringify(a)}: {
|
|
5336
|
-
definition: ${
|
|
5336
|
+
definition: ${n}.definition,
|
|
5337
5337
|
schema: ${r},
|
|
5338
5338
|
},`}).join(`
|
|
5339
|
-
`)}function
|
|
5339
|
+
`)}function yr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=`${n}SchedulerSchema`,a=t.taskName??`${t.routePath}`;return `
|
|
5340
5340
|
${JSON.stringify(a)}: {
|
|
5341
|
-
definition: ${
|
|
5341
|
+
definition: ${n}.definition,
|
|
5342
5342
|
schema: ${r},
|
|
5343
5343
|
},`}).join(`
|
|
5344
|
-
`)}function
|
|
5345
|
-
`)}function
|
|
5344
|
+
`)}function br(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`;return ` ${JSON.stringify(r)}: Parameters<typeof ${n}.definition.handler>[1];`}).join(`
|
|
5345
|
+
`)}function wr(e){return e.filter(({operation:t})=>t.kind==="cron").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`,a=t.cronTriggers??[];return `
|
|
5346
5346
|
{
|
|
5347
5347
|
taskName: ${JSON.stringify(r)},
|
|
5348
5348
|
cronTriggers: ${JSON.stringify(a)},
|
|
5349
|
-
definition: ${
|
|
5349
|
+
definition: ${n}.definition,
|
|
5350
5350
|
},`}).join(`
|
|
5351
|
-
`)}function
|
|
5352
|
-
${
|
|
5353
|
-
`)}function
|
|
5351
|
+
`)}function xr(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
5352
|
+
${t}.definition.handler,`).join(`
|
|
5353
|
+
`)}function nt(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 rt=`
|
|
5354
5354
|
function getRealtimeStub(
|
|
5355
5355
|
env: Record<string, unknown>,
|
|
5356
5356
|
options: RegisterHandlersOptions,
|
|
@@ -5424,7 +5424,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
5424
5424
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
5425
5425
|
return url.toString();
|
|
5426
5426
|
}
|
|
5427
|
-
`;var
|
|
5427
|
+
`;var at=`
|
|
5428
5428
|
export class AppflareRealtimeDurableObject {
|
|
5429
5429
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
5430
5430
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -5567,7 +5567,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
5567
5567
|
return new Response("Not found", { status: 404 });
|
|
5568
5568
|
}
|
|
5569
5569
|
}
|
|
5570
|
-
`;var
|
|
5570
|
+
`;var ot=`
|
|
5571
5571
|
async function publishMutationEvents(
|
|
5572
5572
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
5573
5573
|
options: RegisterHandlersOptions,
|
|
@@ -5668,7 +5668,7 @@ async function publishMutationEvents(
|
|
|
5668
5668
|
}
|
|
5669
5669
|
}
|
|
5670
5670
|
}
|
|
5671
|
-
`;var
|
|
5671
|
+
`;var it=`
|
|
5672
5672
|
function registerRealtimeRoutes(
|
|
5673
5673
|
app: Hono<WorkerEnv>,
|
|
5674
5674
|
options: RegisterHandlersOptions,
|
|
@@ -5831,7 +5831,7 @@ function registerRealtimeRoutes(
|
|
|
5831
5831
|
return stub.fetch(c.req.raw);
|
|
5832
5832
|
});
|
|
5833
5833
|
}
|
|
5834
|
-
`;var
|
|
5834
|
+
`;var st=`
|
|
5835
5835
|
type RealtimeSubscription = {
|
|
5836
5836
|
token: string;
|
|
5837
5837
|
signature: string;
|
|
@@ -5860,7 +5860,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5860
5860
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5861
5861
|
? string
|
|
5862
5862
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5863
|
-
`;var
|
|
5863
|
+
`;var lt=`
|
|
5864
5864
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5865
5865
|
return typeof value === "object" && value !== null;
|
|
5866
5866
|
}
|
|
@@ -6369,9 +6369,9 @@ function doesSubscriptionMatchMutation(
|
|
|
6369
6369
|
|
|
6370
6370
|
return false;
|
|
6371
6371
|
}
|
|
6372
|
-
`;var
|
|
6372
|
+
`;var ut=[st,lt,rt,ot,it,at].join(`
|
|
6373
6373
|
|
|
6374
|
-
`);var
|
|
6374
|
+
`);var ct=`
|
|
6375
6375
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
6376
6376
|
if (!value) {
|
|
6377
6377
|
return undefined;
|
|
@@ -6569,7 +6569,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
6569
6569
|
}
|
|
6570
6570
|
});
|
|
6571
6571
|
}
|
|
6572
|
-
`;var
|
|
6572
|
+
`;var dt=`
|
|
6573
6573
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
6574
6574
|
? string
|
|
6575
6575
|
: keyof typeof schedulerHandlers;
|
|
@@ -6624,7 +6624,7 @@ export async function executeScheduledBatch(
|
|
|
6624
6624
|
}
|
|
6625
6625
|
}
|
|
6626
6626
|
}
|
|
6627
|
-
`;var
|
|
6627
|
+
`;var pt=`
|
|
6628
6628
|
export async function executeCronTriggers(
|
|
6629
6629
|
controller: { cron: string },
|
|
6630
6630
|
env: Record<string, unknown>,
|
|
@@ -6649,7 +6649,7 @@ export async function executeCronTriggers(
|
|
|
6649
6649
|
}
|
|
6650
6650
|
}
|
|
6651
6651
|
}
|
|
6652
|
-
`;function
|
|
6652
|
+
`;function mt(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:c,cronEntries:l,storageHandlersEntries:u}=nt(e);return `import { sValidator } from "@hono/standard-validator";
|
|
6653
6653
|
import type { Hono } from "hono";
|
|
6654
6654
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6655
6655
|
import { ZodError, z } from "zod";
|
|
@@ -6666,10 +6666,10 @@ import {
|
|
|
6666
6666
|
} from "./handlers";
|
|
6667
6667
|
import { createExecutionContext, createSchedulerExecutionContext, resolveSession } from "./handlers.context";
|
|
6668
6668
|
import { executeOperation, handleOperationError } from "./handlers.execution";
|
|
6669
|
-
${
|
|
6670
|
-
${
|
|
6669
|
+
${t?`
|
|
6670
|
+
${t}`:""}
|
|
6671
6671
|
|
|
6672
|
-
${
|
|
6672
|
+
${n}
|
|
6673
6673
|
${r}
|
|
6674
6674
|
|
|
6675
6675
|
const realtimeQueryHandlers = {${i||`
|
|
@@ -6680,8 +6680,8 @@ const schedulerHandlers = {${s||`
|
|
|
6680
6680
|
`}
|
|
6681
6681
|
} as const;
|
|
6682
6682
|
|
|
6683
|
-
type GeneratedSchedulerPayloadMap = {${
|
|
6684
|
-
${
|
|
6683
|
+
type GeneratedSchedulerPayloadMap = {${c?`
|
|
6684
|
+
${c}
|
|
6685
6685
|
`:""}};
|
|
6686
6686
|
|
|
6687
6687
|
declare global {
|
|
@@ -6700,15 +6700,15 @@ const cronHandlers: readonly CronHandlerEntry[] = [${l||`
|
|
|
6700
6700
|
`}
|
|
6701
6701
|
];
|
|
6702
6702
|
|
|
6703
|
-
const storageHandlers = [${
|
|
6703
|
+
const storageHandlers = [${u||`
|
|
6704
6704
|
`}
|
|
6705
6705
|
] as const;
|
|
6706
6706
|
|
|
6707
6707
|
setStorageHandlers([...storageHandlers]);
|
|
6708
6708
|
|
|
6709
|
-
${
|
|
6709
|
+
${dt}
|
|
6710
6710
|
|
|
6711
|
-
${
|
|
6711
|
+
${ut}
|
|
6712
6712
|
|
|
6713
6713
|
export function registerGeneratedHandlers(
|
|
6714
6714
|
app: Hono<WorkerEnv>,
|
|
@@ -6721,20 +6721,20 @@ export function registerGeneratedHandlers(
|
|
|
6721
6721
|
`}
|
|
6722
6722
|
}
|
|
6723
6723
|
|
|
6724
|
-
${
|
|
6724
|
+
${ct}
|
|
6725
6725
|
|
|
6726
|
-
${
|
|
6727
|
-
`}function Z(e,n,
|
|
6728
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
6729
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6730
|
-
}`}function
|
|
6726
|
+
${pt}
|
|
6727
|
+
`}function Z(e,t,n,r=[],a=[]){let o=tt(e,r,a),i=Oe(n),s=Ve(),c=mt(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?`,
|
|
6728
|
+
KV: c.env["${e}"] as KVNamespace`:""}function ft(e,t){return `{
|
|
6729
|
+
DATABASE: c.env["${e}"] as D1Database${Tr(t)}
|
|
6730
|
+
}`}function gt(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6731
6731
|
const auth = createAuth(
|
|
6732
|
-
${
|
|
6732
|
+
${ft(t,n)},
|
|
6733
6733
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
6734
6734
|
);
|
|
6735
6735
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6736
6736
|
});
|
|
6737
|
-
`}function
|
|
6737
|
+
`}function vr(){return `export const getHeaders = (headers: Headers) => {
|
|
6738
6738
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6739
6739
|
const headerObject: Record<string, any> = {};
|
|
6740
6740
|
let hasCookie = false;
|
|
@@ -6764,15 +6764,15 @@ ${dt}
|
|
|
6764
6764
|
|
|
6765
6765
|
return headerObject as any as Headers;
|
|
6766
6766
|
};
|
|
6767
|
-
`}function
|
|
6767
|
+
`}function Rr(){return `export const getSanitizedRequest = (req: Request) => {
|
|
6768
6768
|
const newRequest = new Request(req, {
|
|
6769
6769
|
headers: getHeaders(req.headers),
|
|
6770
6770
|
});
|
|
6771
6771
|
return newRequest;
|
|
6772
6772
|
};
|
|
6773
|
-
`}function
|
|
6774
|
-
`+
|
|
6775
|
-
`+
|
|
6773
|
+
`}function ht(){return vr()+`
|
|
6774
|
+
`+Rr()}function yt(e,t,n){return gt(e,t,n)+`
|
|
6775
|
+
`+ht()}function bt(){return `const app = new Hono<WorkerEnv>();
|
|
6776
6776
|
|
|
6777
6777
|
app.use('*', cors({
|
|
6778
6778
|
origin: (origin, c) => {
|
|
@@ -6788,7 +6788,7 @@ app.use('*', cors({
|
|
|
6788
6788
|
},
|
|
6789
6789
|
credentials: true
|
|
6790
6790
|
}));
|
|
6791
|
-
`}function
|
|
6791
|
+
`}function wt(){return `export { AppflareRealtimeDurableObject };
|
|
6792
6792
|
|
|
6793
6793
|
export default {
|
|
6794
6794
|
fetch: app.fetch,
|
|
@@ -6799,64 +6799,64 @@ export default {
|
|
|
6799
6799
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
6800
6800
|
},
|
|
6801
6801
|
};
|
|
6802
|
-
`}function
|
|
6803
|
-
kvBinding: "${
|
|
6802
|
+
`}function xt(e,t,n="APPFLARE_SCHEDULER_QUEUE",r,a="APPFLARE_REALTIME",o="global",i="/realtime/subscribe",s="/realtime/ws",c="appflare.realtime.v1"){let l=t?`
|
|
6803
|
+
kvBinding: "${t}",`:"",u=r?`
|
|
6804
6804
|
r2Binding: "${r}",`:"",p=`
|
|
6805
6805
|
realtimeBinding: "${a}",
|
|
6806
6806
|
realtimeObjectName: "${o}",
|
|
6807
6807
|
realtimeSubscribePath: "${i}",
|
|
6808
6808
|
realtimeWebsocketPath: "${s}",
|
|
6809
|
-
realtimeProtocol: "${
|
|
6809
|
+
realtimeProtocol: "${c}",`;return `const generatedHandlerOptions = {
|
|
6810
6810
|
databaseBinding: "${e}",${l}
|
|
6811
|
-
schedulerBinding: "${
|
|
6811
|
+
schedulerBinding: "${n}",${u}${p}
|
|
6812
6812
|
};
|
|
6813
6813
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6814
6814
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
6815
6815
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
6816
|
-
`}function
|
|
6816
|
+
`}function Tt(){return `import { createAuth } from "./auth.config";
|
|
6817
6817
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
6818
6818
|
import { registerAdminDashboard } from "./admin.routes";
|
|
6819
6819
|
import { Hono } from "hono";
|
|
6820
6820
|
import { cors } from "hono/cors";
|
|
6821
6821
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6822
|
-
`}function
|
|
6822
|
+
`}function vt(){return `type WorkerEnv = {
|
|
6823
6823
|
Bindings: Record<string, unknown>;
|
|
6824
6824
|
};
|
|
6825
|
-
`}function
|
|
6825
|
+
`}function Rt(e,t,n,r,a,o,i,s,c,l){return Tt()+vt()+bt()+xt(t,n,r,a,o,i,s,c,l)+yt(e,t,n)+wt()}function kt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function X(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(kt(o)&&kt(a)){n[r]=X(o,a);continue}n[r]=a;}return n}function kr(e){return Array.from(new Set(e.filter(t=>t.length>0)))}function St(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`,l={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 l;let{scheduler:u,...p}=e.config.wranglerOverrides;return X(l,p)}function Y(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 At(e){return e.tables.map(t=>({exportName:t.exportName,tableName:t.tableName,columns:t.columns.map(n=>n.name)}))}function Nt(e){return `<li data-name="users">
|
|
6826
6826
|
<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">
|
|
6827
6827
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6828
6828
|
<span class="truncate">users</span>
|
|
6829
6829
|
</a>
|
|
6830
6830
|
</li>
|
|
6831
|
-
${e.map(
|
|
6832
|
-
<a href="/admin/table/${
|
|
6831
|
+
${e.map(n=>`<li data-name="${n.tableName}">
|
|
6832
|
+
<a href="/admin/table/${n.exportName}" hx-get="/admin/table/${n.exportName}" 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">
|
|
6833
6833
|
<iconify-icon icon="mdi:table" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6834
|
-
<span class="truncate">${
|
|
6834
|
+
<span class="truncate">${n.tableName}</span>
|
|
6835
6835
|
</a>
|
|
6836
6836
|
</li>`).join(`
|
|
6837
|
-
`)}`}function ee(e,
|
|
6838
|
-
${
|
|
6839
|
-
${
|
|
6840
|
-
${
|
|
6841
|
-
${
|
|
6842
|
-
${
|
|
6843
|
-
${
|
|
6844
|
-
${
|
|
6845
|
-
${
|
|
6846
|
-
${
|
|
6847
|
-
${
|
|
6848
|
-
${
|
|
6849
|
-
${
|
|
6850
|
-
${
|
|
6851
|
-
${
|
|
6852
|
-
${
|
|
6853
|
-
${
|
|
6854
|
-
${
|
|
6855
|
-
${
|
|
6856
|
-
${
|
|
6857
|
-
${
|
|
6858
|
-
${
|
|
6859
|
-
${
|
|
6837
|
+
`)}`}function ee(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+=`
|
|
6838
|
+
${n}<li data-name="${e.name}" class="folder-item">`,i+=`
|
|
6839
|
+
${n} <details class="group/folder" open>`,i+=`
|
|
6840
|
+
${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+=`
|
|
6841
|
+
${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+=`
|
|
6842
|
+
${n} <span class="truncate font-medium">${e.name}</span>`,i+=`
|
|
6843
|
+
${n} </summary>`,i+=`
|
|
6844
|
+
${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+=ee(c,t+2);for(let c of e.handlers){let l=c.kind==="query"?"solar:reorder-linear":"solar:bolt-linear";i+=`
|
|
6845
|
+
${n} <li data-name="${c.exportName}">`,i+=`
|
|
6846
|
+
${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+=`
|
|
6847
|
+
${n} <iconify-icon icon="${l}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
6848
|
+
${n} <span class="truncate">${c.exportName}</span>`,i+=`
|
|
6849
|
+
${n} </a>`,i+=`
|
|
6850
|
+
${n} </li>`;}i+=`
|
|
6851
|
+
${n} </ul>`,i+=`
|
|
6852
|
+
${n} </details>`,i+=`
|
|
6853
|
+
${n}</li>`;}else for(let s of e.handlers){let c=s.kind==="query"?"solar:reorder-linear":"solar:bolt-linear";i+=`
|
|
6854
|
+
${n}<li data-name="${s.exportName}">`,i+=`
|
|
6855
|
+
${n} <a href="/admin/functions${s.routePath}" hx-get="/admin/functions${s.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+=`
|
|
6856
|
+
${n} <iconify-icon icon="${c}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
6857
|
+
${n} <span class="truncate">${s.exportName}</span>`,i+=`
|
|
6858
|
+
${n} </a>`,i+=`
|
|
6859
|
+
${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filter(s=>s.kind==="mutation"),r=Y(t),a=Y(n),o=r.map(s=>ee(s,0)).join(""),i=a.map(s=>ee(s,0)).join("");return `
|
|
6860
6860
|
<div id="pane-functions" class="flex flex-col h-full hidden">
|
|
6861
6861
|
<div class="px-3 pt-5 pb-3">
|
|
6862
6862
|
<p class="text-[10px] font-semibold uppercase tracking-widest opacity-35 mb-3 px-1">Functions</p>
|
|
@@ -6872,15 +6872,15 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
6872
6872
|
</div>
|
|
6873
6873
|
</div>
|
|
6874
6874
|
<nav class="flex-1 overflow-y-auto px-2 pb-4">
|
|
6875
|
-
${
|
|
6875
|
+
${t.length>0?`<p class="text-[9px] font-bold uppercase tracking-wider opacity-25 mt-4 mb-1 px-2">Queries</p>
|
|
6876
6876
|
<ul class="flex flex-col gap-0.5">${o}</ul>`:""}
|
|
6877
|
-
${
|
|
6877
|
+
${n.length>0?`<p class="text-[9px] font-bold uppercase tracking-wider opacity-25 mt-4 mb-1 px-2">Mutations</p>
|
|
6878
6878
|
<ul class="flex flex-col gap-0.5">${i}</ul>`:""}
|
|
6879
6879
|
</nav>
|
|
6880
6880
|
</div>
|
|
6881
|
-
`}function
|
|
6881
|
+
`}function Ct(e){return e.map(t=>`
|
|
6882
6882
|
<a
|
|
6883
|
-
href="/admin/table/${
|
|
6883
|
+
href="/admin/table/${t.exportName}"
|
|
6884
6884
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
6885
6885
|
>
|
|
6886
6886
|
<div class="card-body p-5">
|
|
@@ -6889,42 +6889,42 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
6889
6889
|
<iconify-icon icon="mdi:table" width="20" height="20" class="text-primary"></iconify-icon>
|
|
6890
6890
|
</div>
|
|
6891
6891
|
<div>
|
|
6892
|
-
<h2 class="font-semibold text-sm capitalize group-hover:text-primary transition-colors">${
|
|
6892
|
+
<h2 class="font-semibold text-sm capitalize group-hover:text-primary transition-colors">${t.tableName}</h2>
|
|
6893
6893
|
<p class="text-xs opacity-40 mt-0.5">Manage records</p>
|
|
6894
6894
|
</div>
|
|
6895
6895
|
</div>
|
|
6896
6896
|
</div>
|
|
6897
6897
|
</a>
|
|
6898
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
6899
|
-
try { searchConditions.push(like(tableSchema.${
|
|
6900
|
-
`).join("")}function
|
|
6898
|
+
`.replace(/\n/g,"\\n")).join("")}function Ft(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
6899
|
+
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6900
|
+
`).join("")}function Sr(e){switch(e){case "number":return "mdi:pound";case "boolean":return "mdi:toggle-switch-outline";case "date":return "mdi:calendar";default:return "mdi:format-text"}}function qt(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n),a=r?Sr(r.type):"mdi:format-text";return `
|
|
6901
6901
|
<th>
|
|
6902
6902
|
<a href="#"
|
|
6903
|
-
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${
|
|
6903
|
+
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
6904
6904
|
hx-target="#main-content"
|
|
6905
6905
|
hx-push-url="true"
|
|
6906
6906
|
class="hover:text-primary flex items-center gap-1.5 transition-colors whitespace-nowrap">
|
|
6907
6907
|
<iconify-icon icon="${a}" width="14" height="14" class="opacity-40"></iconify-icon>
|
|
6908
|
-
${
|
|
6909
|
-
<span class="text-[10px] opacity-30">\${sort === '${
|
|
6908
|
+
${n}
|
|
6909
|
+
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6910
6910
|
</a>
|
|
6911
6911
|
</th>
|
|
6912
|
-
`}).join("")}function
|
|
6912
|
+
`}).join("")}function It(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function te(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"?`
|
|
6913
6913
|
<div class="form-control">
|
|
6914
6914
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6915
|
-
<input type="checkbox" name="${
|
|
6916
|
-
<span class="label-text text-sm">${
|
|
6915
|
+
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
6916
|
+
<span class="label-text text-sm">${t}</span>
|
|
6917
6917
|
</label>
|
|
6918
6918
|
</div>
|
|
6919
6919
|
`:`
|
|
6920
6920
|
<div class="form-control">
|
|
6921
6921
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6922
|
-
<input type="checkbox" name="${
|
|
6923
|
-
<span class="label-text text-sm">${
|
|
6922
|
+
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" />
|
|
6923
|
+
<span class="label-text text-sm">${t}</span>
|
|
6924
6924
|
</label>
|
|
6925
6925
|
</div>
|
|
6926
|
-
`;if(
|
|
6927
|
-
const value = (row as any).${
|
|
6926
|
+
`;if(n==="edit"){let i=r.type==="date"?`\${(() => {
|
|
6927
|
+
const value = (row as any).${t};
|
|
6928
6928
|
if (value == null || value === '') return '';
|
|
6929
6929
|
|
|
6930
6930
|
const date =
|
|
@@ -6937,62 +6937,62 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
6937
6937
|
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
6938
6938
|
const day = String(date.getDate()).padStart(2, '0');
|
|
6939
6939
|
return String(year) + '-' + month + '-' + day;
|
|
6940
|
-
})()}`:`\${String((row as any).${
|
|
6940
|
+
})()}`:`\${String((row as any).${t} ?? '')}`;return `
|
|
6941
6941
|
<div class="form-control">
|
|
6942
|
-
<label class="label"><span class="label-text text-sm font-medium">${
|
|
6943
|
-
<input type="${o}" name="${
|
|
6942
|
+
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6943
|
+
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm" value="${i}"${a} />
|
|
6944
6944
|
</div>
|
|
6945
6945
|
`}return `
|
|
6946
6946
|
<div class="form-control">
|
|
6947
|
-
<label class="label"><span class="label-text text-sm font-medium">${
|
|
6948
|
-
<input type="${o}" name="${
|
|
6947
|
+
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6948
|
+
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm"${a} />
|
|
6949
6949
|
</div>
|
|
6950
|
-
`}function ne(e,
|
|
6951
|
-
if (raw_${
|
|
6952
|
-
return c.text('${
|
|
6950
|
+
`}function ne(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n);if(!r)return "";let a=r.optional?"":`
|
|
6951
|
+
if (raw_${n} === '') {
|
|
6952
|
+
return c.text('${n} is required', 400);
|
|
6953
6953
|
}
|
|
6954
6954
|
`;return r.type==="number"?`
|
|
6955
|
-
const raw_${
|
|
6955
|
+
const raw_${n} = getValue(body['${n}']);
|
|
6956
6956
|
${a}
|
|
6957
|
-
if (raw_${
|
|
6958
|
-
const parsed_${
|
|
6959
|
-
if (Number.isNaN(parsed_${
|
|
6960
|
-
return c.text('${
|
|
6957
|
+
if (raw_${n} !== '') {
|
|
6958
|
+
const parsed_${n} = Number(raw_${n});
|
|
6959
|
+
if (Number.isNaN(parsed_${n})) {
|
|
6960
|
+
return c.text('${n} must be a valid number', 400);
|
|
6961
6961
|
}
|
|
6962
|
-
payload.${
|
|
6962
|
+
payload.${n} = parsed_${n};
|
|
6963
6963
|
}
|
|
6964
6964
|
`:r.type==="boolean"?`
|
|
6965
|
-
const raw_${
|
|
6966
|
-
payload.${
|
|
6965
|
+
const raw_${n} = getValue(body['${n}']);
|
|
6966
|
+
payload.${n} = raw_${n} === 'true' || raw_${n} === 'on' || raw_${n} === '1';
|
|
6967
6967
|
`:r.type==="date"?`
|
|
6968
|
-
const raw_${
|
|
6968
|
+
const raw_${n} = getValue(body['${n}']);
|
|
6969
6969
|
${a}
|
|
6970
|
-
if (raw_${
|
|
6971
|
-
if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(raw_${
|
|
6972
|
-
return c.text('${
|
|
6970
|
+
if (raw_${n} !== '') {
|
|
6971
|
+
if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(raw_${n})) {
|
|
6972
|
+
return c.text('${n} must be a valid date (YYYY-MM-DD)', 400);
|
|
6973
6973
|
}
|
|
6974
6974
|
|
|
6975
|
-
const [year_${
|
|
6976
|
-
const parsed_${
|
|
6975
|
+
const [year_${n}, month_${n}, day_${n}] = raw_${n}.split('-').map(Number);
|
|
6976
|
+
const parsed_${n} = new Date(year_${n}, month_${n} - 1, day_${n});
|
|
6977
6977
|
if (
|
|
6978
|
-
Number.isNaN(parsed_${
|
|
6979
|
-
parsed_${
|
|
6980
|
-
parsed_${
|
|
6981
|
-
parsed_${
|
|
6978
|
+
Number.isNaN(parsed_${n}.getTime()) ||
|
|
6979
|
+
parsed_${n}.getFullYear() !== year_${n} ||
|
|
6980
|
+
parsed_${n}.getMonth() !== month_${n} - 1 ||
|
|
6981
|
+
parsed_${n}.getDate() !== day_${n}
|
|
6982
6982
|
) {
|
|
6983
|
-
return c.text('${
|
|
6983
|
+
return c.text('${n} must be a valid date', 400);
|
|
6984
6984
|
}
|
|
6985
6985
|
|
|
6986
|
-
payload.${
|
|
6986
|
+
payload.${n} = parsed_${n};
|
|
6987
6987
|
}
|
|
6988
6988
|
`:`
|
|
6989
|
-
const raw_${
|
|
6989
|
+
const raw_${n} = getValue(body['${n}']);
|
|
6990
6990
|
${a}
|
|
6991
|
-
if (raw_${
|
|
6992
|
-
payload.${
|
|
6991
|
+
if (raw_${n} !== '') {
|
|
6992
|
+
payload.${n} = raw_${n};
|
|
6993
6993
|
}
|
|
6994
6994
|
`}).join(`
|
|
6995
|
-
`)}function Mt(e){return e.columns.find(
|
|
6995
|
+
`)}function Mt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function jt(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function Et(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">
|
|
6996
6996
|
<div class="drawer drawer-end">
|
|
6997
6997
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6998
6998
|
<div class="drawer-content">
|
|
@@ -7013,7 +7013,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7013
7013
|
<button class="btn btn-ghost btn-sm">Cancel</button>
|
|
7014
7014
|
</form>
|
|
7015
7015
|
<form hx-post="/admin/table/${e.exportName}/delete" hx-target="#main-content" hx-swap="outerHTML" class="inline">
|
|
7016
|
-
<input type="hidden" name="${
|
|
7016
|
+
<input type="hidden" name="${n}" value="\${String((row as any).${n} ?? '')}" />
|
|
7017
7017
|
<input type="hidden" name="sort" value="\${sort}" />
|
|
7018
7018
|
<input type="hidden" name="order" value="\${order}" />
|
|
7019
7019
|
<input type="hidden" name="search" value="\${search}" />
|
|
@@ -7034,7 +7034,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7034
7034
|
</label>
|
|
7035
7035
|
</div>
|
|
7036
7036
|
<form hx-post="/admin/table/${e.exportName}/edit" hx-target="#main-content" hx-swap="outerHTML" class="flex flex-col gap-4">
|
|
7037
|
-
<input type="hidden" name="${
|
|
7037
|
+
<input type="hidden" name="${n}" value="\${String((row as any).${n} ?? '')}" />
|
|
7038
7038
|
<input type="hidden" name="sort" value="\${sort}" />
|
|
7039
7039
|
<input type="hidden" name="order" value="\${order}" />
|
|
7040
7040
|
<input type="hidden" name="search" value="\${search}" />
|
|
@@ -7067,18 +7067,18 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7067
7067
|
\` : 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>\`}
|
|
7068
7068
|
</div>
|
|
7069
7069
|
\` : ''}
|
|
7070
|
-
</div>`}function W(e,
|
|
7070
|
+
</div>`}function W(e,t="Search term or filter..."){return `
|
|
7071
7071
|
<div class="form-control w-full md:w-auto relative">
|
|
7072
7072
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
7073
7073
|
<input type="text"
|
|
7074
7074
|
name="search"
|
|
7075
|
-
placeholder="${
|
|
7075
|
+
placeholder="${t}"
|
|
7076
7076
|
value="\${search}"
|
|
7077
7077
|
hx-get="${e}?sort=\${sort}&order=\${order}"
|
|
7078
7078
|
hx-trigger="keyup changed delay:500ms, search"
|
|
7079
7079
|
hx-target="#main-content"
|
|
7080
7080
|
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" />
|
|
7081
|
-
</div>`}function
|
|
7081
|
+
</div>`}function Ot(e,t,n,r,a,o,i,s,c,l){let u=B(`/admin/table/${e.exportName}`),p=W(`/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>',v=r?`
|
|
7082
7082
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
7083
7083
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
7084
7084
|
<div class="text-xs text-base-content/70">
|
|
@@ -7202,7 +7202,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7202
7202
|
const page = parseInt(c.req.query('page') || '1');
|
|
7203
7203
|
const limit = 20;
|
|
7204
7204
|
const offset = (page - 1) * limit;
|
|
7205
|
-
const sort = c.req.query('sort') || '${
|
|
7205
|
+
const sort = c.req.query('sort') || '${t}';
|
|
7206
7206
|
const order = c.req.query('order') || 'desc';
|
|
7207
7207
|
const search = c.req.query('search') || '';
|
|
7208
7208
|
|
|
@@ -7248,7 +7248,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7248
7248
|
<tr class="hover:bg-base-200/30 transition-colors">
|
|
7249
7249
|
${y}
|
|
7250
7250
|
${s}
|
|
7251
|
-
${
|
|
7251
|
+
${c}
|
|
7252
7252
|
</tr>
|
|
7253
7253
|
\`)}
|
|
7254
7254
|
\${data.length === 0 ? html\`
|
|
@@ -7268,7 +7268,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7268
7268
|
</tbody>
|
|
7269
7269
|
</table>
|
|
7270
7270
|
</div>
|
|
7271
|
-
${
|
|
7271
|
+
${u}
|
|
7272
7272
|
</div>
|
|
7273
7273
|
\`;
|
|
7274
7274
|
|
|
@@ -7330,11 +7330,11 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7330
7330
|
title: "${e.tableName} - Admin Dashboard",
|
|
7331
7331
|
children: content
|
|
7332
7332
|
}));
|
|
7333
|
-
});`}function
|
|
7333
|
+
});`}function Dt(e,t,n,r,a,o,i,s){let c=r==="number"?`
|
|
7334
7334
|
const parsedId = Number(rawId);
|
|
7335
|
-
if (Number.isNaN(parsedId)) return c.text('${
|
|
7335
|
+
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
7336
7336
|
idValue = parsedId;
|
|
7337
|
-
`:"",
|
|
7337
|
+
`:"",u=a?`
|
|
7338
7338
|
adminApp.post('/table/${e}/edit', async (c) => {
|
|
7339
7339
|
const db = drizzle(c.env[options.databaseBinding], { schema });
|
|
7340
7340
|
const tableSchema = (schema as any).${e};
|
|
@@ -7342,27 +7342,27 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7342
7342
|
|
|
7343
7343
|
const body = await c.req.parseBody();
|
|
7344
7344
|
const getValue = (value: unknown) => (typeof value === 'string' ? value : '');
|
|
7345
|
-
const rawId = getValue(body['${
|
|
7346
|
-
if (rawId === '') return c.text('${
|
|
7345
|
+
const rawId = getValue(body['${n}']);
|
|
7346
|
+
if (rawId === '') return c.text('${n} is required', 400);
|
|
7347
7347
|
|
|
7348
7348
|
const payload: Record<string, unknown> = {};
|
|
7349
7349
|
|
|
7350
7350
|
${s}
|
|
7351
7351
|
|
|
7352
7352
|
let idValue: unknown = rawId;
|
|
7353
|
-
${
|
|
7353
|
+
${c}
|
|
7354
7354
|
|
|
7355
7355
|
if (Object.keys(payload).length > 0) {
|
|
7356
7356
|
await db
|
|
7357
7357
|
.update(tableSchema)
|
|
7358
7358
|
.set(payload as any)
|
|
7359
|
-
.where(eq(tableSchema.${
|
|
7359
|
+
.where(eq(tableSchema.${n}, idValue as any))
|
|
7360
7360
|
.execute();
|
|
7361
7361
|
}
|
|
7362
7362
|
|
|
7363
7363
|
const query = new URLSearchParams({
|
|
7364
7364
|
page: getValue(body.page) || '1',
|
|
7365
|
-
sort: getValue(body.sort) || '${
|
|
7365
|
+
sort: getValue(body.sort) || '${t}',
|
|
7366
7366
|
order: getValue(body.order) || 'desc',
|
|
7367
7367
|
search: getValue(body.search) || '',
|
|
7368
7368
|
});
|
|
@@ -7376,20 +7376,20 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7376
7376
|
|
|
7377
7377
|
const body = await c.req.parseBody();
|
|
7378
7378
|
const getValue = (value: unknown) => (typeof value === 'string' ? value : '');
|
|
7379
|
-
const rawId = getValue(body['${
|
|
7380
|
-
if (rawId === '') return c.text('${
|
|
7379
|
+
const rawId = getValue(body['${n}']);
|
|
7380
|
+
if (rawId === '') return c.text('${n} is required', 400);
|
|
7381
7381
|
|
|
7382
7382
|
let idValue: unknown = rawId;
|
|
7383
|
-
${
|
|
7383
|
+
${c}
|
|
7384
7384
|
|
|
7385
7385
|
await db
|
|
7386
7386
|
.delete(tableSchema)
|
|
7387
|
-
.where(eq(tableSchema.${
|
|
7387
|
+
.where(eq(tableSchema.${n}, idValue as any))
|
|
7388
7388
|
.execute();
|
|
7389
7389
|
|
|
7390
7390
|
const query = new URLSearchParams({
|
|
7391
7391
|
page: getValue(body.page) || '1',
|
|
7392
|
-
sort: getValue(body.sort) || '${
|
|
7392
|
+
sort: getValue(body.sort) || '${t}',
|
|
7393
7393
|
order: getValue(body.order) || 'desc',
|
|
7394
7394
|
search: getValue(body.search) || '',
|
|
7395
7395
|
});
|
|
@@ -7429,13 +7429,13 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7429
7429
|
|
|
7430
7430
|
await db
|
|
7431
7431
|
.delete(tableSchema)
|
|
7432
|
-
.where(inArray(tableSchema.${
|
|
7432
|
+
.where(inArray(tableSchema.${n}, parsedIds as any))
|
|
7433
7433
|
.execute();
|
|
7434
7434
|
}
|
|
7435
7435
|
|
|
7436
7436
|
const query = new URLSearchParams({
|
|
7437
7437
|
page: getValue(body.page) || '1',
|
|
7438
|
-
sort: getValue(body.sort) || '${
|
|
7438
|
+
sort: getValue(body.sort) || '${t}',
|
|
7439
7439
|
order: getValue(body.order) || 'desc',
|
|
7440
7440
|
search: getValue(body.search) || '',
|
|
7441
7441
|
});
|
|
@@ -7456,22 +7456,22 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7456
7456
|
|
|
7457
7457
|
const query = new URLSearchParams({
|
|
7458
7458
|
page: getValue(body.page) || '1',
|
|
7459
|
-
sort: getValue(body.sort) || '${
|
|
7459
|
+
sort: getValue(body.sort) || '${t}',
|
|
7460
7460
|
order: getValue(body.order) || 'desc',
|
|
7461
7461
|
search: getValue(body.search) || '',
|
|
7462
7462
|
});
|
|
7463
7463
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7464
7464
|
});
|
|
7465
|
-
${
|
|
7466
|
-
`}function re(e){let
|
|
7467
|
-
`+
|
|
7465
|
+
${u}
|
|
7466
|
+
`}function re(e){let t=Mt(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>jt(e,w)),o=r.filter(w=>Et(e,w)),i=Ft(e),s=qt(e,r),c=It(r,t),l=a.map(w=>te(e,w,"create")).join(""),u=o.map(w=>te(e,w,"edit")).join(""),p=ne(e,a),d=ne(e,o),y=n?t:r[0]||"id",v=e.columns.find(w=>w.name===t)?.type,A=Pt(e,n,t,u);return Ot(e,y,t,n,r,i,s,c,A,l)+`
|
|
7467
|
+
`+Dt(e.exportName,y,t,v,n,i,p,d)}function Vt(){return `
|
|
7468
7468
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7469
7469
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
7470
7470
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
7471
7471
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
7472
7472
|
const search = params.search ? params.search : '';
|
|
7473
7473
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
7474
|
-
};`}function
|
|
7474
|
+
};`}function Bt(){return `
|
|
7475
7475
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7476
7476
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7477
7477
|
<div class="modal">
|
|
@@ -7492,7 +7492,7 @@ ${c}
|
|
|
7492
7492
|
</div>
|
|
7493
7493
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
7494
7494
|
</div>
|
|
7495
|
-
\`}`}function
|
|
7495
|
+
\`}`}function Wt(){return `
|
|
7496
7496
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7497
7497
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7498
7498
|
<div class="modal">
|
|
@@ -7513,8 +7513,8 @@ ${c}
|
|
|
7513
7513
|
</div>
|
|
7514
7514
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
7515
7515
|
</div>
|
|
7516
|
-
\`}`}var
|
|
7517
|
-
`),
|
|
7516
|
+
\`}`}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 Ht(){let e=Ar.map($r).join(`
|
|
7517
|
+
`),t=B("/admin/users");return `
|
|
7518
7518
|
const tableHtml = html\`
|
|
7519
7519
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
7520
7520
|
<div class="overflow-x-auto">
|
|
@@ -7582,8 +7582,8 @@ ${c}
|
|
|
7582
7582
|
</div>
|
|
7583
7583
|
</div>
|
|
7584
7584
|
</div>
|
|
7585
|
-
${Vt()}
|
|
7586
7585
|
${Bt()}
|
|
7586
|
+
${Wt()}
|
|
7587
7587
|
</td>
|
|
7588
7588
|
</tr>
|
|
7589
7589
|
\`)}
|
|
@@ -7596,10 +7596,10 @@ ${Bt()}
|
|
|
7596
7596
|
</tbody>
|
|
7597
7597
|
</table>
|
|
7598
7598
|
</div>
|
|
7599
|
-
${
|
|
7599
|
+
${t}
|
|
7600
7600
|
</div>
|
|
7601
7601
|
\`;
|
|
7602
|
-
`}function
|
|
7602
|
+
`}function Lt(){return `
|
|
7603
7603
|
const content = html\`
|
|
7604
7604
|
<div id="main-content">
|
|
7605
7605
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -7615,7 +7615,7 @@ ${Bt()}
|
|
|
7615
7615
|
</div>
|
|
7616
7616
|
\${tableHtml}
|
|
7617
7617
|
</div>
|
|
7618
|
-
\`;`}function
|
|
7618
|
+
\`;`}function zt(){let e=Ht(),t=Lt();return `
|
|
7619
7619
|
adminApp.get('/users', async (c) => {
|
|
7620
7620
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
7621
7621
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7661,7 +7661,7 @@ ${Bt()}
|
|
|
7661
7661
|
|
|
7662
7662
|
${e}
|
|
7663
7663
|
|
|
7664
|
-
${
|
|
7664
|
+
${t}
|
|
7665
7665
|
|
|
7666
7666
|
if (c.req.header('hx-request')) {
|
|
7667
7667
|
return c.html(content);
|
|
@@ -7671,7 +7671,7 @@ ${Bt()}
|
|
|
7671
7671
|
title: "users - Admin Dashboard",
|
|
7672
7672
|
children: content,
|
|
7673
7673
|
}));
|
|
7674
|
-
});`}function
|
|
7674
|
+
});`}function Ut(){return `
|
|
7675
7675
|
adminApp.post('/users/edit', async (c) => {
|
|
7676
7676
|
const session = await requireAdminSession(c);
|
|
7677
7677
|
if (!session) {
|
|
@@ -7815,7 +7815,7 @@ ${Bt()}
|
|
|
7815
7815
|
|
|
7816
7816
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7817
7817
|
});`}function ae(){return `
|
|
7818
|
-
${
|
|
7818
|
+
${Vt()}
|
|
7819
7819
|
|
|
7820
7820
|
const requireAdminSession = async (c: any) => {
|
|
7821
7821
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7826,12 +7826,12 @@ ${Bt()}
|
|
|
7826
7826
|
return session;
|
|
7827
7827
|
};
|
|
7828
7828
|
|
|
7829
|
-
${Lt()}
|
|
7830
|
-
|
|
7831
7829
|
${zt()}
|
|
7832
|
-
|
|
7830
|
+
|
|
7831
|
+
${Ut()}
|
|
7832
|
+
`}function Qt(e){return `${e.tables.map(t=>re(t)).join(`
|
|
7833
7833
|
`)}
|
|
7834
|
-
${ae()}`}function
|
|
7834
|
+
${ae()}`}function _t(e){return `
|
|
7835
7835
|
<div class="flex items-center justify-between">
|
|
7836
7836
|
<div class="flex items-center gap-3">
|
|
7837
7837
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7846,38 +7846,98 @@ ${ae()}`}function Qt(e){return `
|
|
|
7846
7846
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
7847
7847
|
</div>
|
|
7848
7848
|
</div>
|
|
7849
|
-
`}function
|
|
7849
|
+
`}var Cr="input input-xs input-bordered font-mono flex-1 bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-lg border-base-200";function Fr(e){return e.map(t=>{let n=t.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-25 ml-1">${t.type}</span>`:"";if(t.type==="boolean")return `
|
|
7850
|
+
<div class="flex items-center gap-2">
|
|
7851
|
+
<input
|
|
7852
|
+
type="checkbox"
|
|
7853
|
+
data-obj-key="${t.name}"
|
|
7854
|
+
data-obj-field-type="boolean"
|
|
7855
|
+
class="checkbox checkbox-xs checkbox-primary shrink-0"
|
|
7856
|
+
${t.defaultValue==="true"?"checked":""}
|
|
7857
|
+
/>
|
|
7858
|
+
<span class="text-[10px] font-mono opacity-50">${t.name}${n}</span>
|
|
7859
|
+
</div>`;let r=t.type==="number"?"number":t.type==="date"?"datetime-local":"text";return `
|
|
7860
|
+
<div class="flex items-center gap-2">
|
|
7861
|
+
<span class="text-[10px] font-mono opacity-50 w-20 shrink-0 truncate" title="${t.name}">${t.name}${n}</span>
|
|
7862
|
+
<input
|
|
7863
|
+
type="${r}"
|
|
7864
|
+
data-obj-key="${t.name}"
|
|
7865
|
+
data-obj-field-type="${t.type}"
|
|
7866
|
+
placeholder="${t.defaultValue??""}"
|
|
7867
|
+
value="${t.defaultValue??""}"
|
|
7868
|
+
class="${Cr}"
|
|
7869
|
+
/>
|
|
7870
|
+
</div>`}).join(`
|
|
7871
|
+
`)}function qr(e){let t=e.args??[];if(t.length===0)return `
|
|
7850
7872
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
7851
|
-
|
|
7873
|
+
`;let n="input input-sm input-bordered font-mono w-full bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-xl border-base-200";return t.map(r=>{let a=`${r.name}${r.optional?"":" *"}`,o=r.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-40 ml-1">${r.type}</span>`:"",i=r.optional?'<span class="label-text-alt text-[10px] opacity-30 italic">optional</span>':"",s=`
|
|
7874
|
+
<label class="label py-0.5">
|
|
7875
|
+
<span class="label-text text-[11px] font-mono font-semibold">${a}${o}</span>
|
|
7876
|
+
${i}
|
|
7877
|
+
</label>`;if(r.type==="boolean")return `
|
|
7852
7878
|
<div class="flex items-center gap-3 py-1">
|
|
7853
7879
|
<input
|
|
7854
7880
|
type="checkbox"
|
|
7855
|
-
data-arg-key="${
|
|
7881
|
+
data-arg-key="${r.name}"
|
|
7856
7882
|
data-arg-type="boolean"
|
|
7857
7883
|
class="checkbox checkbox-sm checkbox-primary"
|
|
7858
|
-
${
|
|
7884
|
+
${r.defaultValue==="true"?"checked":""}
|
|
7859
7885
|
/>
|
|
7860
|
-
<span class="text-sm font-mono opacity-70">${
|
|
7861
|
-
${
|
|
7862
|
-
</div>
|
|
7863
|
-
|
|
7886
|
+
<span class="text-sm font-mono opacity-70">${r.name}${o}</span>
|
|
7887
|
+
${r.optional?'<span class="text-[10px] opacity-30 italic ml-auto">optional</span>':""}
|
|
7888
|
+
</div>`;if(r.type==="object")return r.fields&&r.fields.length>0?`
|
|
7889
|
+
<div class="form-control">
|
|
7890
|
+
${s}
|
|
7891
|
+
<div
|
|
7892
|
+
data-arg-key="${r.name}"
|
|
7893
|
+
data-arg-type="object"
|
|
7894
|
+
class="border border-base-200 rounded-xl p-3 bg-base-200/20 flex flex-col gap-2"
|
|
7895
|
+
>
|
|
7896
|
+
${Fr(r.fields)}
|
|
7897
|
+
</div>
|
|
7898
|
+
</div>`:`
|
|
7899
|
+
<div class="form-control">
|
|
7900
|
+
${s}
|
|
7901
|
+
<textarea
|
|
7902
|
+
data-arg-key="${r.name}"
|
|
7903
|
+
data-arg-type="object"
|
|
7904
|
+
placeholder="{}"
|
|
7905
|
+
rows="4"
|
|
7906
|
+
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"
|
|
7907
|
+
${r.optional?"":"required"}
|
|
7908
|
+
>${r.defaultValue??""}</textarea>
|
|
7909
|
+
</div>`;if(r.type==="array"){let l=r.itemType??"string",u=JSON.stringify((r.itemFields??[]).map(p=>({name:p.name,type:p.type})));return `
|
|
7910
|
+
<div class="form-control">
|
|
7911
|
+
${s}
|
|
7912
|
+
<div
|
|
7913
|
+
data-arg-key="${r.name}"
|
|
7914
|
+
data-arg-type="array"
|
|
7915
|
+
data-item-type="${l}"
|
|
7916
|
+
data-item-fields='${u}'
|
|
7917
|
+
class="flex flex-col gap-2"
|
|
7918
|
+
></div>
|
|
7919
|
+
<button
|
|
7920
|
+
type="button"
|
|
7921
|
+
onclick="addArrayItem('${r.name}')"
|
|
7922
|
+
class="btn btn-xs btn-ghost gap-1 mt-1 self-start opacity-50 hover:opacity-100"
|
|
7923
|
+
>
|
|
7924
|
+
<iconify-icon icon="solar:add-circle-linear" width="12" height="12"></iconify-icon>
|
|
7925
|
+
Add item
|
|
7926
|
+
</button>
|
|
7927
|
+
</div>`}let c=r.type==="number"?"number":r.type==="date"?"datetime-local":"text";return `
|
|
7864
7928
|
<div class="form-control">
|
|
7865
|
-
|
|
7866
|
-
<span class="label-text text-[11px] font-mono font-semibold">${o}${i}</span>
|
|
7867
|
-
${t.optional?'<span class="label-text-alt text-[10px] opacity-30 italic">optional</span>':""}
|
|
7868
|
-
</label>
|
|
7929
|
+
${s}
|
|
7869
7930
|
<input
|
|
7870
|
-
type="${
|
|
7871
|
-
placeholder="${
|
|
7872
|
-
data-arg-key="${
|
|
7873
|
-
data-arg-type="${
|
|
7874
|
-
value="${
|
|
7875
|
-
class="
|
|
7876
|
-
${
|
|
7931
|
+
type="${c}"
|
|
7932
|
+
placeholder="${r.defaultValue??""}"
|
|
7933
|
+
data-arg-key="${r.name}"
|
|
7934
|
+
data-arg-type="${r.type}"
|
|
7935
|
+
value="${r.defaultValue??""}"
|
|
7936
|
+
class="${n}"
|
|
7937
|
+
${r.optional?"":"required"}
|
|
7877
7938
|
/>
|
|
7878
|
-
</div
|
|
7879
|
-
|
|
7880
|
-
`)}function qr(e){return `
|
|
7939
|
+
</div>`}).join(`
|
|
7940
|
+
`)}function Ir(e){return `
|
|
7881
7941
|
<div class="space-y-4">
|
|
7882
7942
|
<div class="flex items-center justify-between">
|
|
7883
7943
|
<div class="flex flex-col">
|
|
@@ -7890,11 +7950,11 @@ ${ae()}`}function Qt(e){return `
|
|
|
7890
7950
|
</label>
|
|
7891
7951
|
</div>
|
|
7892
7952
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
7893
|
-
${
|
|
7953
|
+
${qr(e)}
|
|
7894
7954
|
</div>
|
|
7895
7955
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7896
7956
|
</div>
|
|
7897
|
-
`}function
|
|
7957
|
+
`}function Mr(){return `
|
|
7898
7958
|
<div class="space-y-4">
|
|
7899
7959
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7900
7960
|
<div class="relative group">
|
|
@@ -7911,7 +7971,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
7911
7971
|
</div>
|
|
7912
7972
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7913
7973
|
</div>
|
|
7914
|
-
`}function
|
|
7974
|
+
`}function jr(){return `
|
|
7915
7975
|
<div class="space-y-4">
|
|
7916
7976
|
<div class="flex items-center justify-between">
|
|
7917
7977
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -7925,7 +7985,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
7925
7985
|
</div>
|
|
7926
7986
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
7927
7987
|
</div>
|
|
7928
|
-
`}function
|
|
7988
|
+
`}function Kt(e){return `
|
|
7929
7989
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
7930
7990
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
7931
7991
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -7946,13 +8006,13 @@ ${ae()}`}function Qt(e){return `
|
|
|
7946
8006
|
<!-- Tab Content -->
|
|
7947
8007
|
<div class="flex-1 overflow-y-auto">
|
|
7948
8008
|
<div id="request-tab-args" class="p-5">
|
|
7949
|
-
${
|
|
8009
|
+
${Ir(e)}
|
|
7950
8010
|
</div>
|
|
7951
8011
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
7952
|
-
${
|
|
8012
|
+
${Mr()}
|
|
7953
8013
|
</div>
|
|
7954
8014
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
7955
|
-
${
|
|
8015
|
+
${jr()}
|
|
7956
8016
|
</div>
|
|
7957
8017
|
</div>
|
|
7958
8018
|
|
|
@@ -7970,7 +8030,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
7970
8030
|
</form>
|
|
7971
8031
|
</div>
|
|
7972
8032
|
</div>
|
|
7973
|
-
`}function
|
|
8033
|
+
`}function Jt(){return `
|
|
7974
8034
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
7975
8035
|
<!-- Panel Header -->
|
|
7976
8036
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -8052,7 +8112,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8052
8112
|
|
|
8053
8113
|
</div>
|
|
8054
8114
|
</div>
|
|
8055
|
-
`}function
|
|
8115
|
+
`}function Gt(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
8056
8116
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
8057
8117
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
8058
8118
|
|
|
@@ -8118,6 +8178,29 @@ ${ae()}`}function Qt(e){return `
|
|
|
8118
8178
|
container.appendChild(row);
|
|
8119
8179
|
};
|
|
8120
8180
|
|
|
8181
|
+
// \u2500\u2500 Field-level value helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
8182
|
+
function getFieldValue(el) {
|
|
8183
|
+
var type = el.getAttribute('data-obj-field-type') || 'string';
|
|
8184
|
+
if (type === 'boolean') return el.checked;
|
|
8185
|
+
if (type === 'number') {
|
|
8186
|
+
var raw = el.value.trim();
|
|
8187
|
+
return raw === '' ? undefined : Number(raw);
|
|
8188
|
+
}
|
|
8189
|
+
var v = el.value.trim();
|
|
8190
|
+
return v === '' ? undefined : v;
|
|
8191
|
+
}
|
|
8192
|
+
|
|
8193
|
+
function collectObjectRow(container) {
|
|
8194
|
+
var obj = {};
|
|
8195
|
+
container.querySelectorAll('[data-obj-key]').forEach(function(f) {
|
|
8196
|
+
var k = f.getAttribute('data-obj-key');
|
|
8197
|
+
if (!k) return;
|
|
8198
|
+
var v = getFieldValue(f);
|
|
8199
|
+
if (v !== undefined) obj[k] = v;
|
|
8200
|
+
});
|
|
8201
|
+
return Object.keys(obj).length ? obj : undefined;
|
|
8202
|
+
}
|
|
8203
|
+
|
|
8121
8204
|
// \u2500\u2500 Collect args from server-rendered inputs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
8122
8205
|
function collectArgs() {
|
|
8123
8206
|
var result = {};
|
|
@@ -8131,6 +8214,36 @@ ${ae()}`}function Qt(e){return `
|
|
|
8131
8214
|
} else if (type === 'number') {
|
|
8132
8215
|
var raw = el.value.trim();
|
|
8133
8216
|
value = raw === '' ? undefined : Number(raw);
|
|
8217
|
+
} else if (type === 'object') {
|
|
8218
|
+
if (el.tagName === 'TEXTAREA') {
|
|
8219
|
+
// Fallback JSON textarea
|
|
8220
|
+
var raw = el.value.trim();
|
|
8221
|
+
if (!raw) return;
|
|
8222
|
+
try { value = JSON.parse(raw); } catch(e) { value = raw; }
|
|
8223
|
+
} else {
|
|
8224
|
+
// Structured field inputs
|
|
8225
|
+
value = collectObjectRow(el);
|
|
8226
|
+
}
|
|
8227
|
+
} else if (type === 'array') {
|
|
8228
|
+
var itemType = el.getAttribute('data-item-type') || 'string';
|
|
8229
|
+
if (itemType === 'object') {
|
|
8230
|
+
var rows = el.querySelectorAll('.array-item-row');
|
|
8231
|
+
var arr = Array.from(rows).map(function(row) {
|
|
8232
|
+
return collectObjectRow(row);
|
|
8233
|
+
}).filter(Boolean);
|
|
8234
|
+
value = arr.length ? arr : undefined;
|
|
8235
|
+
} else {
|
|
8236
|
+
var items = el.querySelectorAll('.array-item-input');
|
|
8237
|
+
var arr = Array.from(items).map(function(inp) {
|
|
8238
|
+
var ft = inp.getAttribute('data-obj-field-type') || 'string';
|
|
8239
|
+
if (ft === 'number') {
|
|
8240
|
+
var raw = inp.value.trim();
|
|
8241
|
+
return raw === '' ? undefined : Number(raw);
|
|
8242
|
+
}
|
|
8243
|
+
return inp.value.trim() || undefined;
|
|
8244
|
+
}).filter(function(v) { return v !== undefined; });
|
|
8245
|
+
value = arr.length ? arr : undefined;
|
|
8246
|
+
}
|
|
8134
8247
|
} else {
|
|
8135
8248
|
value = el.value;
|
|
8136
8249
|
}
|
|
@@ -8141,6 +8254,102 @@ ${ae()}`}function Qt(e){return `
|
|
|
8141
8254
|
return result;
|
|
8142
8255
|
}
|
|
8143
8256
|
|
|
8257
|
+
// \u2500\u2500 Array / object item helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
8258
|
+
function makeFieldInput(field) {
|
|
8259
|
+
if (field.type === 'boolean') {
|
|
8260
|
+
var cb = document.createElement('input');
|
|
8261
|
+
cb.type = 'checkbox';
|
|
8262
|
+
cb.className = 'checkbox checkbox-xs checkbox-primary shrink-0';
|
|
8263
|
+
cb.setAttribute('data-obj-key', field.name);
|
|
8264
|
+
cb.setAttribute('data-obj-field-type', 'boolean');
|
|
8265
|
+
return cb;
|
|
8266
|
+
}
|
|
8267
|
+
var inputType = field.type === 'number' ? 'number'
|
|
8268
|
+
: field.type === 'date' ? 'datetime-local'
|
|
8269
|
+
: 'text';
|
|
8270
|
+
var inp = document.createElement('input');
|
|
8271
|
+
inp.type = inputType;
|
|
8272
|
+
inp.placeholder = field.name;
|
|
8273
|
+
inp.className = 'input input-xs input-bordered font-mono flex-1 bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-lg border-base-200';
|
|
8274
|
+
inp.setAttribute('data-obj-key', field.name);
|
|
8275
|
+
inp.setAttribute('data-obj-field-type', field.type);
|
|
8276
|
+
return inp;
|
|
8277
|
+
}
|
|
8278
|
+
|
|
8279
|
+
window.addArrayItem = function(key) {
|
|
8280
|
+
var container = document.querySelector('[data-arg-key="' + key + '"][data-arg-type="array"]');
|
|
8281
|
+
if (!container) return;
|
|
8282
|
+
var itemType = container.getAttribute('data-item-type') || 'string';
|
|
8283
|
+
|
|
8284
|
+
if (itemType === 'object') {
|
|
8285
|
+
var fieldsJson = container.getAttribute('data-item-fields') || '[]';
|
|
8286
|
+
var itemFields;
|
|
8287
|
+
try { itemFields = JSON.parse(fieldsJson); } catch(e) { itemFields = []; }
|
|
8288
|
+
|
|
8289
|
+
var rowCount = container.querySelectorAll('.array-item-row').length + 1;
|
|
8290
|
+
|
|
8291
|
+
var row = document.createElement('div');
|
|
8292
|
+
row.className = 'array-item-row border border-base-200 rounded-xl p-3 bg-base-200/20 flex flex-col gap-2';
|
|
8293
|
+
|
|
8294
|
+
var header = document.createElement('div');
|
|
8295
|
+
header.className = 'flex items-center justify-between';
|
|
8296
|
+
|
|
8297
|
+
var lbl = document.createElement('span');
|
|
8298
|
+
lbl.className = 'text-[10px] font-mono opacity-30';
|
|
8299
|
+
lbl.textContent = 'Item ' + rowCount;
|
|
8300
|
+
|
|
8301
|
+
var removeBtn = document.createElement('button');
|
|
8302
|
+
removeBtn.type = 'button';
|
|
8303
|
+
removeBtn.className = 'btn btn-xs btn-ghost text-error opacity-40 hover:opacity-100 px-1.5';
|
|
8304
|
+
removeBtn.innerHTML = '<iconify-icon icon="solar:close-circle-linear" width="14" height="14"></iconify-icon>';
|
|
8305
|
+
removeBtn.onclick = function() { row.remove(); };
|
|
8306
|
+
|
|
8307
|
+
header.appendChild(lbl);
|
|
8308
|
+
header.appendChild(removeBtn);
|
|
8309
|
+
row.appendChild(header);
|
|
8310
|
+
|
|
8311
|
+
itemFields.forEach(function(field) {
|
|
8312
|
+
var fieldRow = document.createElement('div');
|
|
8313
|
+
fieldRow.className = 'flex items-center gap-2';
|
|
8314
|
+
|
|
8315
|
+
var fieldLbl = document.createElement('span');
|
|
8316
|
+
fieldLbl.className = 'text-[10px] font-mono opacity-50 w-20 shrink-0 truncate';
|
|
8317
|
+
fieldLbl.title = field.name;
|
|
8318
|
+
fieldLbl.textContent = field.name;
|
|
8319
|
+
|
|
8320
|
+
fieldRow.appendChild(fieldLbl);
|
|
8321
|
+
fieldRow.appendChild(makeFieldInput(field));
|
|
8322
|
+
row.appendChild(fieldRow);
|
|
8323
|
+
});
|
|
8324
|
+
|
|
8325
|
+
container.appendChild(row);
|
|
8326
|
+
} else {
|
|
8327
|
+
var inputType = itemType === 'number' ? 'number'
|
|
8328
|
+
: itemType === 'date' ? 'datetime-local'
|
|
8329
|
+
: 'text';
|
|
8330
|
+
|
|
8331
|
+
var row = document.createElement('div');
|
|
8332
|
+
row.className = 'flex items-center gap-2';
|
|
8333
|
+
|
|
8334
|
+
var inp = document.createElement('input');
|
|
8335
|
+
inp.type = inputType;
|
|
8336
|
+
inp.className = 'array-item-input input input-xs input-bordered font-mono flex-1 bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-lg border-base-200';
|
|
8337
|
+
inp.placeholder = 'value';
|
|
8338
|
+
inp.setAttribute('data-obj-field-type', itemType);
|
|
8339
|
+
|
|
8340
|
+
var removeBtn = document.createElement('button');
|
|
8341
|
+
removeBtn.type = 'button';
|
|
8342
|
+
removeBtn.className = 'btn btn-xs btn-ghost text-error opacity-40 hover:opacity-100 px-1.5';
|
|
8343
|
+
removeBtn.innerHTML = '<iconify-icon icon="solar:close-circle-linear" width="14" height="14"></iconify-icon>';
|
|
8344
|
+
removeBtn.onclick = function() { row.remove(); };
|
|
8345
|
+
|
|
8346
|
+
row.appendChild(inp);
|
|
8347
|
+
row.appendChild(removeBtn);
|
|
8348
|
+
container.appendChild(row);
|
|
8349
|
+
inp.focus();
|
|
8350
|
+
}
|
|
8351
|
+
};
|
|
8352
|
+
|
|
8144
8353
|
function collectHeaders() {
|
|
8145
8354
|
var result = {};
|
|
8146
8355
|
document.querySelectorAll('#headers-rows [data-hdr-key]').forEach(function(keyEl) {
|
|
@@ -8278,9 +8487,9 @@ ${ae()}`}function Qt(e){return `
|
|
|
8278
8487
|
if (indicator) indicator.classList.remove('opacity-0');
|
|
8279
8488
|
showBodyLoading();
|
|
8280
8489
|
|
|
8281
|
-
var isQuery = ${
|
|
8490
|
+
var isQuery = ${t};
|
|
8282
8491
|
var method = isQuery ? 'GET' : 'POST';
|
|
8283
|
-
var pathWithQuery = '${
|
|
8492
|
+
var pathWithQuery = '${n}';
|
|
8284
8493
|
|
|
8285
8494
|
if (isQuery && Object.keys(args).length > 0) {
|
|
8286
8495
|
var params = new URLSearchParams();
|
|
@@ -8350,7 +8559,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8350
8559
|
var _rtToken = null;
|
|
8351
8560
|
var _rtEnabled = false;
|
|
8352
8561
|
var _rtEventCount = 0;
|
|
8353
|
-
var _isRealtimeSupported = ${
|
|
8562
|
+
var _isRealtimeSupported = ${t};
|
|
8354
8563
|
var _realtimeQueryName = '${r}';
|
|
8355
8564
|
var _rtPingInterval = null;
|
|
8356
8565
|
|
|
@@ -8594,21 +8803,21 @@ ${ae()}`}function Qt(e){return `
|
|
|
8594
8803
|
_rtEnabled = false;
|
|
8595
8804
|
});
|
|
8596
8805
|
</script>
|
|
8597
|
-
`}function
|
|
8806
|
+
`}function Zt(e){return `
|
|
8598
8807
|
const content = html\`
|
|
8599
8808
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
8600
|
-
${
|
|
8809
|
+
${_t(e)}
|
|
8601
8810
|
|
|
8602
8811
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
8603
8812
|
<!-- Request Panel -->
|
|
8604
|
-
${
|
|
8813
|
+
${Kt(e)}
|
|
8605
8814
|
|
|
8606
8815
|
<!-- Result Panel -->
|
|
8607
|
-
${
|
|
8816
|
+
${Jt()}
|
|
8608
8817
|
</div>
|
|
8609
8818
|
</div>
|
|
8610
8819
|
|
|
8611
|
-
${
|
|
8820
|
+
${Gt(e)}
|
|
8612
8821
|
\`;
|
|
8613
8822
|
|
|
8614
8823
|
if (c.req.header('hx-request')) {
|
|
@@ -8618,11 +8827,11 @@ ${ae()}`}function Qt(e){return `
|
|
|
8618
8827
|
return c.html(Layout({
|
|
8619
8828
|
title: "${e.exportName} - Functions",
|
|
8620
8829
|
children: content
|
|
8621
|
-
}));`}function
|
|
8622
|
-
adminApp.get('/functions${
|
|
8623
|
-
${
|
|
8830
|
+
}));`}function Xt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
8831
|
+
adminApp.get('/functions${n.routePath}', (c) => {
|
|
8832
|
+
${Zt(n)}
|
|
8624
8833
|
});`).join(`
|
|
8625
|
-
`)}function
|
|
8834
|
+
`)}function Yt(){return `
|
|
8626
8835
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
8627
8836
|
const r2Binding = (options as any).r2Binding;
|
|
8628
8837
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -8691,7 +8900,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8691
8900
|
const parts = prefix.split('/').filter(Boolean);
|
|
8692
8901
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
8693
8902
|
};
|
|
8694
|
-
`}function
|
|
8903
|
+
`}function en(){return `
|
|
8695
8904
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
8696
8905
|
const parts = prefix.split('/').filter(Boolean);
|
|
8697
8906
|
const breadcrumbs: any[] = [];
|
|
@@ -8818,7 +9027,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8818
9027
|
</div>
|
|
8819
9028
|
\`;
|
|
8820
9029
|
};
|
|
8821
|
-
`}function
|
|
9030
|
+
`}function tn(){return `
|
|
8822
9031
|
const handleStorageListRoute = async (c: any) => {
|
|
8823
9032
|
const bucket = getStorageBucket(c);
|
|
8824
9033
|
if (!bucket) {
|
|
@@ -8840,7 +9049,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8840
9049
|
|
|
8841
9050
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8842
9051
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8843
|
-
`}function
|
|
9052
|
+
`}function nn(){return `
|
|
8844
9053
|
adminApp.post('/storage/upload', async (c) => {
|
|
8845
9054
|
const bucket = getStorageBucket(c);
|
|
8846
9055
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8858,7 +9067,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8858
9067
|
|
|
8859
9068
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8860
9069
|
});
|
|
8861
|
-
`}function
|
|
9070
|
+
`}function rn(){return `
|
|
8862
9071
|
adminApp.delete('/storage/delete', async (c) => {
|
|
8863
9072
|
const bucket = getStorageBucket(c);
|
|
8864
9073
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8873,7 +9082,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8873
9082
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
8874
9083
|
return c.html('');
|
|
8875
9084
|
});
|
|
8876
|
-
`}function
|
|
9085
|
+
`}function an(){return `
|
|
8877
9086
|
adminApp.post('/storage/directory', async (c) => {
|
|
8878
9087
|
const bucket = getStorageBucket(c);
|
|
8879
9088
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8899,7 +9108,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8899
9108
|
|
|
8900
9109
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8901
9110
|
});
|
|
8902
|
-
`}function
|
|
9111
|
+
`}function on(){return `
|
|
8903
9112
|
adminApp.get('/storage/download', async (c) => {
|
|
8904
9113
|
const bucket = getStorageBucket(c);
|
|
8905
9114
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8919,7 +9128,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8919
9128
|
|
|
8920
9129
|
return new Response(object.body, { headers });
|
|
8921
9130
|
});
|
|
8922
|
-
`}function
|
|
9131
|
+
`}function sn(){return `
|
|
8923
9132
|
adminApp.get('/storage/preview', async (c) => {
|
|
8924
9133
|
const bucket = getStorageBucket(c);
|
|
8925
9134
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8937,25 +9146,25 @@ ${ae()}`}function Qt(e){return `
|
|
|
8937
9146
|
|
|
8938
9147
|
return new Response(object.body, { headers });
|
|
8939
9148
|
});
|
|
8940
|
-
`}function
|
|
8941
|
-
${an()}
|
|
8942
|
-
|
|
9149
|
+
`}function ln(){return `
|
|
8943
9150
|
${on()}
|
|
8944
9151
|
|
|
8945
|
-
${
|
|
9152
|
+
${sn()}
|
|
8946
9153
|
|
|
8947
9154
|
${nn()}
|
|
8948
9155
|
|
|
8949
9156
|
${rn()}
|
|
8950
9157
|
|
|
8951
|
-
${
|
|
8952
|
-
`}function ln(){return `
|
|
8953
|
-
${Xt()}
|
|
9158
|
+
${an()}
|
|
8954
9159
|
|
|
9160
|
+
${tn()}
|
|
9161
|
+
`}function un(){return `
|
|
8955
9162
|
${Yt()}
|
|
8956
9163
|
|
|
8957
|
-
${
|
|
8958
|
-
|
|
9164
|
+
${en()}
|
|
9165
|
+
|
|
9166
|
+
${ln()}
|
|
9167
|
+
`}function cn(e,t){let n=$t(t);return `
|
|
8959
9168
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
8960
9169
|
return html\`<!DOCTYPE html>
|
|
8961
9170
|
<html lang="en" data-theme="light">
|
|
@@ -9176,7 +9385,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9176
9385
|
</nav>
|
|
9177
9386
|
</div>
|
|
9178
9387
|
|
|
9179
|
-
${
|
|
9388
|
+
${n}
|
|
9180
9389
|
</div>
|
|
9181
9390
|
</div>
|
|
9182
9391
|
\`) : ""}
|
|
@@ -9362,7 +9571,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9362
9571
|
</body>
|
|
9363
9572
|
</html>\`;
|
|
9364
9573
|
}
|
|
9365
|
-
`}function
|
|
9574
|
+
`}function dn(){return `
|
|
9366
9575
|
// Auth Middleware
|
|
9367
9576
|
adminApp.use('*', async (c, next) => {
|
|
9368
9577
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -9421,7 +9630,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9421
9630
|
}
|
|
9422
9631
|
await next();
|
|
9423
9632
|
});
|
|
9424
|
-
`}function
|
|
9633
|
+
`}function pn(e){return `
|
|
9425
9634
|
adminApp.get('/', (c) => {
|
|
9426
9635
|
return c.html(Layout({
|
|
9427
9636
|
title: "Admin Dashboard",
|
|
@@ -9438,7 +9647,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9438
9647
|
\`
|
|
9439
9648
|
}));
|
|
9440
9649
|
});
|
|
9441
|
-
`}function
|
|
9650
|
+
`}function mn(e,t,n){let r=At(t),a=Nt(r),o=Ct(r),i=Qt(t),s=Xt(n),c=un(),l=cn(a,n),u=dn(),p=pn(o);return `import { Hono } from "hono";
|
|
9442
9651
|
import { html, raw } from "hono/html";
|
|
9443
9652
|
import { drizzle } from "drizzle-orm/d1";
|
|
9444
9653
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -9451,7 +9660,7 @@ ${l}
|
|
|
9451
9660
|
export function registerAdminDashboard(app: Hono<any>, options: { databaseBinding: string, r2Binding?: string }) {
|
|
9452
9661
|
const adminApp = new Hono<any>();
|
|
9453
9662
|
|
|
9454
|
-
${
|
|
9663
|
+
${u}
|
|
9455
9664
|
|
|
9456
9665
|
${p}
|
|
9457
9666
|
|
|
@@ -9462,63 +9671,63 @@ ${p}
|
|
|
9462
9671
|
${s}
|
|
9463
9672
|
|
|
9464
9673
|
// Generate storage routes
|
|
9465
|
-
${
|
|
9674
|
+
${c}
|
|
9466
9675
|
|
|
9467
9676
|
app.route('/admin', adminApp);
|
|
9468
9677
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
9469
9678
|
}
|
|
9470
|
-
`}function oe(e){if(typeof e!="object"||e===null)return false;let
|
|
9471
|
-
`}function
|
|
9679
|
+
`}function oe(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 P(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 le(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 Pr(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 Or(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 H(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function fn(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 gn(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 hn(e,t){return `${e}:${t}`}function Dr(e,t,n,r){let a=hn(e,t),o=hn(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 yn(e,t,n){let r=le(e),a=le(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=yn(s.leftTable,s.rightTable,"source"),l=yn(s.rightTable,s.leftTable,"target"),u={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??l:a.sourceField??l,leftSqlName:s.sourceIsLeft?a.sourceSqlName:a.targetSqlName,rightSqlName:s.sourceIsLeft?a.targetSqlName:a.sourceSqlName,onDelete:a.onDelete,onUpdate:a.onUpdate};if(u.leftField===u.rightField)throw new Error(`manyToMany pair '${s.key}' resolves to duplicate junction fields '${u.leftField}'. Set sourceField/targetField explicitly.`);let p=t.get(s.key);p?Br(p,u,s.key):t.set(s.key,u),a.referenceField=o,a.targetReferenceField=i,a.junctionTable=u.junctionTable,a.sourceField=s.sourceIsLeft?u.leftField:u.rightField,a.targetField=s.sourceIsLeft?u.rightField:u.leftField,a.sourceSqlName=s.sourceIsLeft?u.leftSqlName:u.rightSqlName,a.targetSqlName=s.sourceIsLeft?u.rightSqlName:u.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=H(e,n.leftTable,n.leftReferenceField)??"string",a=H(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=Or(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=H(t,o.targetTable,i)??o.fkType??"string";fn(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:gn(`${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??`${le(n)}Id`;a.field=s;let c=H(t,n,i)??a.fkType??"string";fn(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:gn(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},c);}return Wr(t),t}function wn(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??P(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=L(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 Ur(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 Qr(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
9680
|
+
`}function _r(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=ue(i.jsonShape);a.push(`${g(o)}: { shape: ${s} },`);}a.length!==0&&t.push(`${g(n)}: {
|
|
9472
9681
|
${a.map(o=>` ${o}`).join(`
|
|
9473
9682
|
`)}
|
|
9474
|
-
},`);}return
|
|
9683
|
+
},`);}return t.length===0?`export const __appflareJsonColumns = {} as const;
|
|
9475
9684
|
`:`export const __appflareJsonColumns = {
|
|
9476
|
-
${
|
|
9685
|
+
${t.map(n=>` ${n}`).join(`
|
|
9477
9686
|
`)}
|
|
9478
9687
|
} as const;
|
|
9479
|
-
`}function ue(e){return e.kind==="array"?`{ kind: "array", element: ${ue(e.element)} }`:e.kind==="object"?`{ kind: "object", shape: { ${Object.entries(e.shape).map(([
|
|
9480
|
-
targetTable: ${
|
|
9481
|
-
junctionTable: ${
|
|
9482
|
-
sourceField: ${
|
|
9483
|
-
targetField: ${
|
|
9484
|
-
referenceField: ${
|
|
9485
|
-
targetReferenceField: ${
|
|
9486
|
-
},`);a.length!==0&&
|
|
9688
|
+
`}function ue(e){return e.kind==="array"?`{ kind: "array", element: ${ue(e.element)} }`:e.kind==="object"?`{ kind: "object", shape: { ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${ue(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)}: {
|
|
9689
|
+
targetTable: ${g(i.targetTable)},
|
|
9690
|
+
junctionTable: ${g(i.junctionTable)},
|
|
9691
|
+
sourceField: ${g(i.sourceField??"")},
|
|
9692
|
+
targetField: ${g(i.targetField??"")},
|
|
9693
|
+
referenceField: ${g(i.referenceField??"id")},
|
|
9694
|
+
targetReferenceField: ${g(i.targetReferenceField??"id")},
|
|
9695
|
+
},`);a.length!==0&&t.push(`${g(n)}: {
|
|
9487
9696
|
${a.map(o=>` ${o}`).join(`
|
|
9488
9697
|
`)}
|
|
9489
|
-
},`);}return
|
|
9698
|
+
},`);}return t.length===0?`export const __appflareManyToMany = {} as const;
|
|
9490
9699
|
`:`export const __appflareManyToMany = {
|
|
9491
|
-
${
|
|
9700
|
+
${t.map(n=>` ${n}`).join(`
|
|
9492
9701
|
`)}
|
|
9493
9702
|
} as const;
|
|
9494
|
-
`}function
|
|
9703
|
+
`}function Zr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations)){if(i.relation==="one"){a.push(`${g(o)}: {
|
|
9495
9704
|
kind: "one",
|
|
9496
|
-
targetTable: ${
|
|
9497
|
-
sourceField: ${
|
|
9498
|
-
referenceField: ${
|
|
9499
|
-
},`);continue}if(i.relation==="many"){a.push(`${
|
|
9705
|
+
targetTable: ${g(i.targetTable)},
|
|
9706
|
+
sourceField: ${g(i.field??"")},
|
|
9707
|
+
referenceField: ${g(i.referenceField??"id")},
|
|
9708
|
+
},`);continue}if(i.relation==="many"){a.push(`${g(o)}: {
|
|
9500
9709
|
kind: "many",
|
|
9501
|
-
targetTable: ${
|
|
9502
|
-
sourceField: ${
|
|
9503
|
-
referenceField: ${
|
|
9504
|
-
},`);continue}a.push(`${
|
|
9710
|
+
targetTable: ${g(i.targetTable)},
|
|
9711
|
+
sourceField: ${g(i.field??"")},
|
|
9712
|
+
referenceField: ${g(i.referenceField??"id")},
|
|
9713
|
+
},`);continue}a.push(`${g(o)}: {
|
|
9505
9714
|
kind: "manyToMany",
|
|
9506
|
-
targetTable: ${
|
|
9507
|
-
junctionTable: ${
|
|
9508
|
-
sourceField: ${
|
|
9509
|
-
targetField: ${
|
|
9510
|
-
referenceField: ${
|
|
9511
|
-
targetReferenceField: ${
|
|
9512
|
-
},`);}a.length!==0&&
|
|
9715
|
+
targetTable: ${g(i.targetTable)},
|
|
9716
|
+
junctionTable: ${g(i.junctionTable??"")},
|
|
9717
|
+
sourceField: ${g(i.sourceField??"")},
|
|
9718
|
+
targetField: ${g(i.targetField??"")},
|
|
9719
|
+
referenceField: ${g(i.referenceField??"id")},
|
|
9720
|
+
targetReferenceField: ${g(i.targetReferenceField??"id")},
|
|
9721
|
+
},`);}a.length!==0&&t.push(`${g(n)}: {
|
|
9513
9722
|
${a.map(o=>` ${o}`).join(`
|
|
9514
9723
|
`)}
|
|
9515
|
-
},`);}return
|
|
9724
|
+
},`);}return t.length===0?`export const __appflareRelations = {} as const;
|
|
9516
9725
|
`:`export const __appflareRelations = {
|
|
9517
|
-
${
|
|
9726
|
+
${t.map(n=>` ${n}`).join(`
|
|
9518
9727
|
`)}
|
|
9519
9728
|
} as const;
|
|
9520
|
-
`}function
|
|
9521
|
-
${
|
|
9729
|
+
`}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 u of _r(l))n.has(u)||r.add(u);for(let u of Object.values(l.columns))u.references&&!n.has(u.references.table)&&r.add(u.references.table);}let a=new Map;for(let[l,u]of Object.entries(e.tables))for(let[p,d]of Object.entries(u.columns))if(d.type==="enum"&&d.enumValues&&d.enumValues.length>0){let y=d.enumRef??`${l}_${p}`;a.has(y)||a.set(y,{column:d,tableName:l,fieldName:p});}let o=[],i=[];for(let[l,u]of a.entries()){let p=q(l),d=u.column.enumValues.map(y=>`"${y}"`).join(" | ");o.push(`export type ${p} = ${d};`),i.push(`export const ${p}Column = t.customType<{ data: ${p}; dataNotNull: ${p} }>({ dataType: () => "text" });`);}let s=[],c=[];for(let[l,u]of Object.entries(e.tables)){let p=u.sqlName??P(l),d=[],y=[];for(let[b,h]of Object.entries(u.columns)){let T;if(h.type==="enum"&&h.enumValues&&h.enumValues.length>0){let R=h.enumRef??`${l}_${b}`,j=q(R),V=h.sqlName??P(b);T=V!==b?`${j}Column(${g(V)})`:`${j}Column()`,h.isArray&&(T+=".array()");}else T=zr(b,h,t);h.uuidPrimaryKey&&(T+=".$defaultFn(() => crypto.randomUUID())"),h.primaryKey&&(T+=h.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),h.notNull&&(T+=".notNull()"),h.sqlDefault!==void 0&&(T+=`.default(${Pr(h.sqlDefault)})`);let C=Kr(b,h,u);if(C)if(h.references?.onDelete||h.references?.onUpdate){let R=[];h.references.onDelete&&R.push(`onDelete: ${g(h.references.onDelete)}`),h.references.onUpdate&&R.push(`onUpdate: ${g(h.references.onUpdate)}`),T+=`.references(() => ${C.tableName}.${C.fieldName}, { ${R.join(", ")} })`;}else T+=`.references(() => ${C.tableName}.${C.fieldName})`;if(h.unique){let R=typeof h.unique=="object"&&h.unique.name?h.unique.name:`${p}_${P(b)}_unique_idx`;y.push(` t.uniqueIndex(${g(R)}).on(table.${b})`);}if(h.index){let R=typeof h.index=="object"&&h.index.name?h.index.name:`${p}_${P(b)}_idx`;y.push(` t.index(${g(R)}).on(table.${b})`);}d.push(` ${b}: ${T},`);}y.length>0?s.push(`export const ${l} = table(
|
|
9730
|
+
${g(p)},
|
|
9522
9731
|
{
|
|
9523
9732
|
${d.join(`
|
|
9524
9733
|
`)}
|
|
@@ -9527,19 +9736,19 @@ ${d.join(`
|
|
|
9527
9736
|
${y.join(`,
|
|
9528
9737
|
`)}
|
|
9529
9738
|
],
|
|
9530
|
-
);`):s.push(`export const ${l} = table(${
|
|
9739
|
+
);`):s.push(`export const ${l} = table(${g(p)}, {
|
|
9531
9740
|
${d.join(`
|
|
9532
9741
|
`)}
|
|
9533
|
-
});`);let v=Object.entries(
|
|
9742
|
+
});`);let v=Object.entries(u.relations).filter(([,b])=>b.relation==="one"),A=Object.entries(u.relations).filter(([,b])=>b.relation==="many"),w=Object.entries(u.relations).filter(([,b])=>b.relation==="manyToMany");if(v.length===0&&A.length===0&&w.length===0)continue;let M=[];for(let[b,h]of v){let T=Ur(l,u,h);M.push(` ${b}: one(${h.targetTable}, {
|
|
9534
9743
|
fields: [${l}.${T.sourceField}],
|
|
9535
9744
|
references: [${h.targetTable}.${T.targetField}],
|
|
9536
|
-
}),`);}for(let[b,h]of A)
|
|
9537
|
-
${
|
|
9745
|
+
}),`);}for(let[b,h]of A)M.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of w){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);M.push(` ${b}: many(${h.junctionTable}),`);}c.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
9746
|
+
${M.join(`
|
|
9538
9747
|
`)}
|
|
9539
9748
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9540
9749
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
9541
9750
|
import { relations } from "drizzle-orm";
|
|
9542
|
-
${
|
|
9751
|
+
${Qr(r)}
|
|
9543
9752
|
${o.join(`
|
|
9544
9753
|
`)}
|
|
9545
9754
|
${i.join(`
|
|
@@ -9549,30 +9758,30 @@ ${s.join(`
|
|
|
9549
9758
|
|
|
9550
9759
|
`)}
|
|
9551
9760
|
|
|
9552
|
-
${
|
|
9761
|
+
${c.join(`
|
|
9553
9762
|
|
|
9554
9763
|
`)}
|
|
9555
9764
|
|
|
9556
|
-
${
|
|
9765
|
+
${Jr(e)}
|
|
9557
9766
|
|
|
9558
|
-
${
|
|
9767
|
+
${Gr(e)}
|
|
9559
9768
|
|
|
9560
|
-
${
|
|
9561
|
-
`}function ce(e){return e.kind==="array"?`z.array(${ce(e.element)})`:e.kind==="object"?`z.object({ ${Object.entries(e.shape).map(([
|
|
9769
|
+
${Zr(e)}
|
|
9770
|
+
`}function ce(e){return e.kind==="array"?`z.array(${ce(e.element)})`:e.kind==="object"?`z.object({ ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${ce(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 bn(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=ce(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}: ${bn(c,wn(c),O(c))},`),i.push(` ${s}: ${bn(c,O(c),O(c))},`);t.push(`export const ${n}InsertSchema = z.object({
|
|
9562
9771
|
${o.join(`
|
|
9563
9772
|
`)}
|
|
9564
9773
|
});
|
|
9565
|
-
export const ${
|
|
9774
|
+
export const ${n}SelectSchema = z.object({
|
|
9566
9775
|
${i.join(`
|
|
9567
9776
|
`)}
|
|
9568
9777
|
});
|
|
9569
9778
|
|
|
9570
|
-
export type ${a}Insert = z.infer<typeof ${
|
|
9571
|
-
export type ${a}Select = z.infer<typeof ${
|
|
9779
|
+
export type ${a}Insert = z.infer<typeof ${n}InsertSchema>;
|
|
9780
|
+
export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
9572
9781
|
`);}return `import { z } from "zod";
|
|
9573
9782
|
|
|
9574
|
-
${
|
|
9575
|
-
`)}`}function L(e){return e.kind==="array"?`Array<${L(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([
|
|
9783
|
+
${t.join(`
|
|
9784
|
+
`)}`}function L(e){return e.kind==="array"?`Array<${L(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([n,r])=>`${n}: ${L(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?L(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,l]of Object.entries(a.columns)){let u=ea(l),p=O(l)?" | null":"";i.push(` ${c}${O(l)?"?":""}: ${u}${p};`),s.push(` ${c}${wn(l)?"?":""}: ${u}${p};`);}n.push(`export type ${o} = {
|
|
9576
9785
|
${i.join(`
|
|
9577
9786
|
`)}
|
|
9578
9787
|
};
|
|
@@ -9580,30 +9789,30 @@ ${i.join(`
|
|
|
9580
9789
|
export type New${o} = {
|
|
9581
9790
|
${s.join(`
|
|
9582
9791
|
`)}
|
|
9583
|
-
};`);}return `${
|
|
9792
|
+
};`);}return `${t.join(`
|
|
9584
9793
|
`)}
|
|
9585
|
-
${
|
|
9794
|
+
${n.join(`
|
|
9586
9795
|
|
|
9587
9796
|
`)}
|
|
9588
|
-
`}function ea(e,n){if(n){let t=e[n];if(!oe(t))throw new Error(`schemaDsl.exportName '${n}' does not point to a schema() export.`);return t}for(let t of Object.values(e))if(oe(t))return t;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function wn(e){let n=e.config.schemaDsl;if(!n)return;let t=n.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,n.entry),a=path.resolve(e.configDir,n.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,n.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,n.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),u=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),l=ea(u,n.exportName),c=Wr(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=Gr(c,t),d=Yr(c),y=Zr(c);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(c.tables)}}function na(e){return e.replaceAll("\\","/")}function M(e,n){let t=na(path.relative(e,n)).replace(/\.tsx?$/,"");return t.startsWith(".")?t:`./${t}`}var ia=new Set([".ts",".tsx",".mts",".cts"]);async function Rn(e){let n=await promises.readdir(e,{withFileTypes:true}),t=[];for(let r of n){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){t.push(...await Rn(a));continue}r.isFile()&&ia.has(path.extname(r.name))&&t.push(a);}return t}function de(e){return e.replace(/\.[cm]?tsx?$/,"")}function sa(e,n){let t=e,r=false,a,o="unknown";for(;g__namespace.isCallExpression(t);){let i=t.expression;if(!g__namespace.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,t=i.expression;else if(s==="default"){r=true;let u=t.arguments[0];u&&(g__namespace.isStringLiteral(u)||g__namespace.isNumericLiteral(u)?a=u.text:u.kind===g__namespace.SyntaxKind.TrueKeyword?a="true":u.kind===g__namespace.SyntaxKind.FalseKeyword&&(a="false")),t=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else t=i.expression;}return {name:n,type:o,optional:r,defaultValue:a}}function la(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let n=e.properties.find(r=>g__namespace.isPropertyAssignment(r)&&g__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!n||!g__namespace.isObjectLiteralExpression(n.initializer))return [];let t=[];for(let r of n.initializer.properties)!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)||t.push(sa(r.initializer,r.name.text));return t}function ua(e){return g__namespace.isVariableStatement(e)?e.modifiers?.some(n=>n.kind===g__namespace.SyntaxKind.ExportKeyword)??false:false}function kn(e){return g__namespace.isIdentifier(e)?e.text:g__namespace.isParenthesizedExpression(e)?kn(e.expression):null}function ca(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let n=e.properties.find(r=>!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!n||!g__namespace.isPropertyAssignment(n))return [];let t=n.initializer;return g__namespace.isStringLiteral(t)||g__namespace.isNoSubstitutionTemplateLiteral(t)?[t.text.trim()].filter(r=>r.length>0):g__namespace.isArrayLiteralExpression(t)?t.elements.map(r=>g__namespace.isStringLiteral(r)||g__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function da(e,n){let t=g__namespace.createSourceFile(n,e,g__namespace.ScriptTarget.Latest,true,g__namespace.ScriptKind.TS),r=[];for(let a of t.statements)if(ua(a))for(let o of a.declarationList.declarations){if(!g__namespace.isIdentifier(o.name)||!o.initializer||!g__namespace.isCallExpression(o.initializer))continue;let i=kn(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"?ca(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?la(o.initializer.arguments[0]):[]});}return r}function xn(e,n,t){let r=n.replace(/\\/g,"/"),o=de(r).split("/").filter(Boolean);return `/${[e,...o,t].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function pa(e,n){let t=e.replace(/\\/g,"/"),r=`${n}/`,a=t.indexOf(r);return a>=0?t.slice(a+r.length):t===n?"index.ts":t}function Tn(e,n){let t=e.replace(/\\/g,"/"),a=de(t).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,n].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function Sn(e){let n=[],t=await Rn(e.scanDirAbs).catch(()=>[]);for(let a of t){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),u=da(i,a),l=[{kind:"query",kindDirectory:"queries",exports:u.filter(c=>c.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:u.filter(c=>c.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:u.filter(c=>c.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:u.filter(c=>c.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:u.filter(c=>c.kind==="storage")}];for(let c of l){if(c.exports.length===0)continue;let p=pa(s,c.kindDirectory);for(let d of c.exports){let y=c.kind==="query"||c.kind==="mutation"?Tn(p,d.exportName):void 0,v=c.kind==="scheduler"||c.kind==="cron"?Tn(p,d.exportName):void 0,A=c.kind==="query"||c.kind==="mutation"?[...de(p).split("/").filter(Boolean),d.exportName]:void 0,w=c.kind==="query"?xn("queries",p,d.exportName):c.kind==="mutation"?xn("mutations",p,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${v}`;n.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:M(e.outDirAbs,a),clientImportPath:M(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:v,cronTriggers:d.cronTriggers,args:d.args});}}}n.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of n){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 n}function fa(e){let n=[],t="",r=0,a=0,o=0,i=false,s=false,u=false,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){t+=d,l=false;continue}if(d==="\\"){t+=d,l=true;continue}if(!s&&!u&&d==="'"){i=!i,t+=d;continue}if(!i&&!u&&d==='"'){s=!s,t+=d;continue}if(!i&&!s&&d==="`"){u=!u,t+=d;continue}if(i||s||u){t+=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=t.trim();y.length>0&&n.push(y),t="";continue}t+=d;}let c=t.trim();return c.length>0&&n.push(c),n}function ga(e){let n=0,t=0,r=0,a=false,o=false,i=false,s=false;for(let u=0;u<e.length;u+=1){let l=e[u];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==="("){n+=1;continue}if(l===")"){n-=1;continue}if(l==="{"){t+=1;continue}if(l==="}"){t-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&n===0&&t===0&&r===0)return u}}return -1}function ha(e){let n=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(n)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(n)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(n)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(n)?"number":/\.(text|varchar|char)\s*\(/.test(n)?"string":/\.(boolean|bool)\s*\(/.test(n)?"boolean":"unknown"}function ya(e){let n=fa(e),t=[];for(let r of n){let a=ga(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),u=/autoincrement\s*:\s*true/i.test(i),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||u||s;t.push({name:o,expression:i,type:ha(i),optional:p,primaryKey:s,autoIncrement:u});}return t}function ba(e){let n=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,t=[],r=(o,i)=>{let s=0,u=false,l=false,c=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&&!c&&y==="'"){u=!u;continue}if(!u&&!c&&y==='"'){l=!l;continue}if(!u&&!l&&y==="`"){c=!c;continue}if(!(u||l||c)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=n.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",n.lastIndex);if(s===-1){a=n.exec(e);continue}let u=r(e,s);if(u===-1){a=n.exec(e);continue}let l=e.slice(s+1,u);t.push({exportName:o,tableName:i,columns:ya(l)}),a=n.exec(e);}return t}async function Nn(e){let n=await promises.readdir(e,{withFileTypes:true}),t=[];for(let r of n){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){t.push(...await Nn(a));continue}r.isFile()&&r.name==="schema.ts"&&t.push(a);}return t}async function $n(e,n=[]){let t=await Nn(e.scanDirAbs).catch(()=>[]),r=path.resolve(e.configDir,"schema.ts"),a=[...n,...t.length?t:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),u=ba(s);if(u.length>0)return {schemaPath:o,tables:u}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function Ta(e){let n=e.auth.options.plugins;if(!Array.isArray(n))return [];for(let t of n)if(t&&typeof t=="object"){let r=t;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 va(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 Ra(e,n){let t=await Bun.file(e).text(),r=n.map(o=>`"${o}"`).join(" | "),a=t.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
9589
|
-
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
|
|
9590
|
-
`);let
|
|
9591
|
-
`);let
|
|
9592
|
-
`),...Gn
|
|
9593
|
-
`),Bun.write(Kn
|
|
9594
|
-
`);let _=path.relative(o,A).replace(/\\/g,"/"),
|
|
9595
|
-
`),
|
|
9596
|
-
`));function
|
|
9797
|
+
`}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 I(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 Tn(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 vn(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"?vn(p,d.exportName):void 0,v=u.kind==="scheduler"||u.kind==="cron"?vn(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"?Tn("queries",p,d.exportName):u.kind==="mutation"?Tn("mutations",p,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${v}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:I(e.outDirAbs,a),clientImportPath:I(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:v,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":/\.(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 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
|
|
9798
|
+
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 In(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=I(t,a),s=path.resolve(t,"client"),c=I(s,a),l=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()-l).toFixed(0)}ms)
|
|
9799
|
+
`);let u=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",u)),"bin","tsc"),d=path.join(path.dirname(Bun.resolveSync("@better-auth/cli/package.json",u)),"dist","index.mjs"),y=path.resolve(t,"server.ts"),v=path.resolve(t,"client.ts"),A=path.resolve(t,"auth.config.ts"),w=path.resolve(t,"auth.schema.ts"),M=path.resolve(t,"drizzle.config.ts"),b=path.resolve(n,"wrangler.json"),h=await xn(e),T=await Cn(e,h?[h.schemaPath]:[]),C=I(t,T.schemaPath),R=await An(e);process.stdout.write(`\u{1F50D} ${R.length} handler(s) (${(performance.now()-l).toFixed(0)}ms)
|
|
9800
|
+
`);let j=va(r),V=Ra(r),he=Rt(r.auth.basePath,r.database[0].binding,r.kv[0]?.binding,r.scheduler.binding,r.r2[0]?.binding,r.realtime.binding,r.realtime.objectName,r.realtime.subscribePath,r.realtime.websocketPath,r.realtime.protocol),Hn=$e(c,R),Ln=Z(C,R,r.r2[0]?.binding,j,V),zn=Te(i),Un=h?[Sa(o,h.schemaPath),...r.schema.filter(x=>!/(^|\/)schema\.ts$/.test(x))]:r.schema,Qn=Ce(Un),_n=St(e,R),Kn=mn(C,T,R),Jn=path.resolve(t,"admin.routes.ts"),Gn=Ln.map(x=>Bun.write(path.resolve(t,x.relativePath),x.source)),Zn=Hn.map(x=>Bun.write(path.resolve(t,x.relativePath),x.source));await Promise.all([Bun.write(y,he),Bun.write(v,`export * from "./client/index";
|
|
9801
|
+
`),...Zn,...Gn,Bun.write(A,zn),Bun.write(w,""),Bun.write(M,Qn),Bun.write(b,`${JSON.stringify(_n,null,2)}
|
|
9802
|
+
`),Bun.write(Jn,Kn)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-l).toFixed(0)}ms)
|
|
9803
|
+
`);let _=path.relative(o,A).replace(/\\/g,"/"),Xn=_.startsWith(".")?_:`./${_}`,K=path.relative(o,w).replace(/\\/g,"/"),Yn=K.startsWith(".")?K:`./${K}`,ye=await Bun.spawn([process.execPath,d,"generate","--config",Xn,"--output",Yn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(ye!==0)throw new Error(`better-auth generation failed with exit code ${ye}`);process.stdout.write(`\u{1F510} Auth schema (${(performance.now()-l).toFixed(0)}ms)
|
|
9804
|
+
`),j.length>0&&(await ka(w,j),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-l).toFixed(0)}ms)
|
|
9805
|
+
`));function er(x={}){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/*":["./*"]},...x},include:["./*.ts","./client/*.ts"]}}let be=path.resolve(t,"tsconfig.js.json");await Promise.all([Bun.write(be,`${JSON.stringify(er({declaration:true,emitDeclarationOnly:false}),null,2)}
|
|
9597
9806
|
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-l).toFixed(0)}ms)
|
|
9598
|
-
`);async function
|
|
9599
|
-
`);let N=await Bun.spawn([process.execPath,p,"-p",x],{cwd:
|
|
9600
|
-
`);async function
|
|
9601
|
-
`);let
|
|
9602
|
-
`);let
|
|
9807
|
+
`);async function tr(x,$){process.stdout.write(`\u2699\uFE0F ${$}... (${(performance.now()-l).toFixed(0)}ms)
|
|
9808
|
+
`);let N=await Bun.spawn([process.execPath,p,"-p",x],{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(N!==0)throw new Error(`tsc ${$} failed with exit code ${N}`)}await tr(be,"JS files"),process.stdout.write(`\u2705 JS + declarations (${(performance.now()-l).toFixed(0)}ms)
|
|
9809
|
+
`);async function we(x){let $=await promises.readdir(x,{withFileTypes:true});for(let k of $){let N=path.join(x,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith("."))continue;await we(N);}else k.name.endsWith(".ts")&&!k.name.endsWith(".d.ts")&&await promises.rm(N);}}await we(t),process.stdout.write(`\u{1F4E6} Cleaned .ts files (${(performance.now()-l).toFixed(0)}ms)
|
|
9810
|
+
`);let nr=t+"/";async function xe(x){let $=await promises.readdir(x,{withFileTypes:true});for(let k of $){let N=path.join(x,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith(".")||N===t)continue;await xe(N);}else !N.startsWith(nr)&&(k.name.endsWith(".d.ts")||k.name.endsWith(".js"))&&await promises.rm(N);}}await xe(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-l).toFixed(0)}ms)
|
|
9811
|
+
`);let rr=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(rr)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-l).toFixed(0)}ms)
|
|
9603
9812
|
`);let $=await Bun.spawn([process.execPath,p,"--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if($!==0)throw new Error(`TypeScript build failed with exit code ${$}`);process.stdout.write(`\u2705 Build complete (${(performance.now()-l).toFixed(0)}ms)
|
|
9604
|
-
`);}}var Mn=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(),
|
|
9605
|
-
`);return}process.stdout.write(`\u2705 Generated server/client in ${
|
|
9606
|
-
`);}async function
|
|
9607
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
9608
|
-
`),await o();}),process.stdout.write(`\u{1F440} Watching ${
|
|
9609
|
-
`);}async function
|
|
9813
|
+
`);}}var Mn=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(),jn=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),En=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([Mn,zod.z.array(Mn).min(1)]),kv:zod.z.union([jn,zod.z.array(jn)]).optional(),r2:zod.z.union([En,zod.z.array(En)]).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 On(e){return typeof e=="object"&&e!==null}function qa(e){let t=On(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=Pn.safeParse(t);return n.success?n.data:{}}function Ia(e){if(!On(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function Ma(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:Ia(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function D(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=Ma(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 Oa(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 D(e);if(t.build!==void 0&&(n.config.build=t.build),await In(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
9814
|
+
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
9815
|
+
`);}async function Vn(e,t={}){if(await Q(e,{build:t.build}),!t.watch)return;let n=await D(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}
|
|
9816
|
+
`);}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}
|
|
9817
|
+
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
9818
|
+
`);}async function Bn(e,t={}){let n=await D(e),r=Oa(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 l=n.config.database[0].databaseName,u=[i,"wrangler","d1","migrations","apply",l];t.local?u.push("--local"):t.remote?u.push("--remote"):t.preview&&u.push("--preview");let d=await Bun.spawn(u,{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 Wn(e,t={name:"",email:"",password:""}){let n=await D(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(),l=t.name.replace(/'/g,"''"),u=t.email.replace(/'/g,"''"),p=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${l}', '${u}', 1, ${c}, ${c}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${u}', 'credential', '${i}', '${o}', ${c}, ${c});`].join(" "),d=n.config.database[0].databaseName,v=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${p}`];t.local?v.push("--local"):t.remote&&v.push("--remote");let w=await Bun.spawn(v,{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 E=new commander.Command;E.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");E.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});});E.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 Vn(e.config,{watch:e.watch,build:e.build});});E.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 Bn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});E.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 Wn(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 E.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|