appflare 0.2.45 → 0.2.47
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/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/templates/handlers/generators/registration/modules/cron.ts +9 -0
- package/cli/templates/handlers/generators/registration/modules/scheduler.ts +9 -0
- package/cli/utils/handler-discovery.ts +37 -2
- package/dist/cli/index.js +600 -373
- package/dist/cli/index.mjs +600 -373
- package/dist/react/index.js +1 -1
- package/dist/react/index.mjs +1 -1
- package/package.json +1 -1
- package/react/use-infinite-query.ts +1 -1
- package/react/use-query.ts +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 ${
|
|
364
|
-
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
|
+
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 Me(){return `
|
|
1209
1209
|
export function createScheduler(
|
|
1210
1210
|
queue?: SchedulerQueueBinding,
|
|
1211
1211
|
): Scheduler {
|
|
@@ -1226,7 +1226,7 @@ export function createScheduler(
|
|
|
1226
1226
|
},
|
|
1227
1227
|
};
|
|
1228
1228
|
}
|
|
1229
|
-
`}function
|
|
1229
|
+
`}function Ie(){return `
|
|
1230
1230
|
function createContextErrorHelpers() {
|
|
1231
1231
|
return {
|
|
1232
1232
|
error: (status: number, message: string, details?: unknown) => {
|
|
@@ -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
|
|
|
1495
1493
|
${Me()}
|
|
1496
1494
|
|
|
1497
1495
|
${Ie()}
|
|
1498
1496
|
|
|
1497
|
+
${je()}
|
|
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;
|
|
@@ -6614,6 +6614,15 @@ export async function executeScheduledBatch(
|
|
|
6614
6614
|
const payloadValue = body.payload === null ? undefined : body.payload;
|
|
6615
6615
|
const parsed = operation.schema.parse(payloadValue);
|
|
6616
6616
|
await operation.definition.handler(ctx, parsed);
|
|
6617
|
+
|
|
6618
|
+
if (typeof publishMutationEvents === "function") {
|
|
6619
|
+
await publishMutationEvents(
|
|
6620
|
+
{ req: { raw: new Request("http://localhost") }, env },
|
|
6621
|
+
options,
|
|
6622
|
+
ctx.mutationEvents,
|
|
6623
|
+
);
|
|
6624
|
+
}
|
|
6625
|
+
ctx.mutationEvents.length = 0;
|
|
6617
6626
|
} catch (error) {
|
|
6618
6627
|
if (error instanceof ZodError) {
|
|
6619
6628
|
console.error("Invalid scheduler payload", task, error.issues);
|
|
@@ -6624,7 +6633,7 @@ export async function executeScheduledBatch(
|
|
|
6624
6633
|
}
|
|
6625
6634
|
}
|
|
6626
6635
|
}
|
|
6627
|
-
`;var
|
|
6636
|
+
`;var pt=`
|
|
6628
6637
|
export async function executeCronTriggers(
|
|
6629
6638
|
controller: { cron: string },
|
|
6630
6639
|
env: Record<string, unknown>,
|
|
@@ -6644,12 +6653,21 @@ export async function executeCronTriggers(
|
|
|
6644
6653
|
|
|
6645
6654
|
try {
|
|
6646
6655
|
await cronEntry.definition.handler(ctx);
|
|
6656
|
+
|
|
6657
|
+
if (typeof publishMutationEvents === "function") {
|
|
6658
|
+
await publishMutationEvents(
|
|
6659
|
+
{ req: { raw: new Request("http://localhost") }, env },
|
|
6660
|
+
options,
|
|
6661
|
+
ctx.mutationEvents,
|
|
6662
|
+
);
|
|
6663
|
+
}
|
|
6664
|
+
ctx.mutationEvents.length = 0;
|
|
6647
6665
|
} catch (error) {
|
|
6648
6666
|
console.error("Cron task failed", cronEntry.taskName, error);
|
|
6649
6667
|
}
|
|
6650
6668
|
}
|
|
6651
6669
|
}
|
|
6652
|
-
`;function
|
|
6670
|
+
`;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
6671
|
import type { Hono } from "hono";
|
|
6654
6672
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6655
6673
|
import { ZodError, z } from "zod";
|
|
@@ -6666,10 +6684,10 @@ import {
|
|
|
6666
6684
|
} from "./handlers";
|
|
6667
6685
|
import { createExecutionContext, createSchedulerExecutionContext, resolveSession } from "./handlers.context";
|
|
6668
6686
|
import { executeOperation, handleOperationError } from "./handlers.execution";
|
|
6669
|
-
${
|
|
6670
|
-
${
|
|
6687
|
+
${t?`
|
|
6688
|
+
${t}`:""}
|
|
6671
6689
|
|
|
6672
|
-
${
|
|
6690
|
+
${n}
|
|
6673
6691
|
${r}
|
|
6674
6692
|
|
|
6675
6693
|
const realtimeQueryHandlers = {${i||`
|
|
@@ -6680,8 +6698,8 @@ const schedulerHandlers = {${s||`
|
|
|
6680
6698
|
`}
|
|
6681
6699
|
} as const;
|
|
6682
6700
|
|
|
6683
|
-
type GeneratedSchedulerPayloadMap = {${
|
|
6684
|
-
${
|
|
6701
|
+
type GeneratedSchedulerPayloadMap = {${c?`
|
|
6702
|
+
${c}
|
|
6685
6703
|
`:""}};
|
|
6686
6704
|
|
|
6687
6705
|
declare global {
|
|
@@ -6700,15 +6718,15 @@ const cronHandlers: readonly CronHandlerEntry[] = [${l||`
|
|
|
6700
6718
|
`}
|
|
6701
6719
|
];
|
|
6702
6720
|
|
|
6703
|
-
const storageHandlers = [${
|
|
6721
|
+
const storageHandlers = [${u||`
|
|
6704
6722
|
`}
|
|
6705
6723
|
] as const;
|
|
6706
6724
|
|
|
6707
6725
|
setStorageHandlers([...storageHandlers]);
|
|
6708
6726
|
|
|
6709
|
-
${
|
|
6727
|
+
${dt}
|
|
6710
6728
|
|
|
6711
|
-
${
|
|
6729
|
+
${ut}
|
|
6712
6730
|
|
|
6713
6731
|
export function registerGeneratedHandlers(
|
|
6714
6732
|
app: Hono<WorkerEnv>,
|
|
@@ -6721,20 +6739,20 @@ export function registerGeneratedHandlers(
|
|
|
6721
6739
|
`}
|
|
6722
6740
|
}
|
|
6723
6741
|
|
|
6724
|
-
${
|
|
6742
|
+
${ct}
|
|
6725
6743
|
|
|
6726
|
-
${
|
|
6727
|
-
`}function Z(e,n,
|
|
6728
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
6729
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6730
|
-
}`}function
|
|
6744
|
+
${pt}
|
|
6745
|
+
`}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?`,
|
|
6746
|
+
KV: c.env["${e}"] as KVNamespace`:""}function ft(e,t){return `{
|
|
6747
|
+
DATABASE: c.env["${e}"] as D1Database${Tr(t)}
|
|
6748
|
+
}`}function gt(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6731
6749
|
const auth = createAuth(
|
|
6732
|
-
${
|
|
6750
|
+
${ft(t,n)},
|
|
6733
6751
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
6734
6752
|
);
|
|
6735
6753
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6736
6754
|
});
|
|
6737
|
-
`}function
|
|
6755
|
+
`}function vr(){return `export const getHeaders = (headers: Headers) => {
|
|
6738
6756
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6739
6757
|
const headerObject: Record<string, any> = {};
|
|
6740
6758
|
let hasCookie = false;
|
|
@@ -6764,15 +6782,15 @@ ${dt}
|
|
|
6764
6782
|
|
|
6765
6783
|
return headerObject as any as Headers;
|
|
6766
6784
|
};
|
|
6767
|
-
`}function
|
|
6785
|
+
`}function Rr(){return `export const getSanitizedRequest = (req: Request) => {
|
|
6768
6786
|
const newRequest = new Request(req, {
|
|
6769
6787
|
headers: getHeaders(req.headers),
|
|
6770
6788
|
});
|
|
6771
6789
|
return newRequest;
|
|
6772
6790
|
};
|
|
6773
|
-
`}function
|
|
6774
|
-
`+
|
|
6775
|
-
`+
|
|
6791
|
+
`}function ht(){return vr()+`
|
|
6792
|
+
`+Rr()}function yt(e,t,n){return gt(e,t,n)+`
|
|
6793
|
+
`+ht()}function bt(){return `const app = new Hono<WorkerEnv>();
|
|
6776
6794
|
|
|
6777
6795
|
app.use('*', cors({
|
|
6778
6796
|
origin: (origin, c) => {
|
|
@@ -6788,7 +6806,7 @@ app.use('*', cors({
|
|
|
6788
6806
|
},
|
|
6789
6807
|
credentials: true
|
|
6790
6808
|
}));
|
|
6791
|
-
`}function
|
|
6809
|
+
`}function wt(){return `export { AppflareRealtimeDurableObject };
|
|
6792
6810
|
|
|
6793
6811
|
export default {
|
|
6794
6812
|
fetch: app.fetch,
|
|
@@ -6799,64 +6817,64 @@ export default {
|
|
|
6799
6817
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
6800
6818
|
},
|
|
6801
6819
|
};
|
|
6802
|
-
`}function
|
|
6803
|
-
kvBinding: "${
|
|
6804
|
-
r2Binding: "${r}",`:"",
|
|
6820
|
+
`}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?`
|
|
6821
|
+
kvBinding: "${t}",`:"",u=r?`
|
|
6822
|
+
r2Binding: "${r}",`:"",p=`
|
|
6805
6823
|
realtimeBinding: "${a}",
|
|
6806
6824
|
realtimeObjectName: "${o}",
|
|
6807
6825
|
realtimeSubscribePath: "${i}",
|
|
6808
6826
|
realtimeWebsocketPath: "${s}",
|
|
6809
|
-
realtimeProtocol: "${
|
|
6827
|
+
realtimeProtocol: "${c}",`;return `const generatedHandlerOptions = {
|
|
6810
6828
|
databaseBinding: "${e}",${l}
|
|
6811
|
-
schedulerBinding: "${
|
|
6829
|
+
schedulerBinding: "${n}",${u}${p}
|
|
6812
6830
|
};
|
|
6813
6831
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6814
6832
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
6815
6833
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
6816
|
-
`}function
|
|
6834
|
+
`}function Tt(){return `import { createAuth } from "./auth.config";
|
|
6817
6835
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
6818
6836
|
import { registerAdminDashboard } from "./admin.routes";
|
|
6819
6837
|
import { Hono } from "hono";
|
|
6820
6838
|
import { cors } from "hono/cors";
|
|
6821
6839
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6822
|
-
`}function
|
|
6840
|
+
`}function vt(){return `type WorkerEnv = {
|
|
6823
6841
|
Bindings: Record<string, unknown>;
|
|
6824
6842
|
};
|
|
6825
|
-
`}function
|
|
6843
|
+
`}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
6844
|
<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
6845
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6828
6846
|
<span class="truncate">users</span>
|
|
6829
6847
|
</a>
|
|
6830
6848
|
</li>
|
|
6831
|
-
${e.map(
|
|
6832
|
-
<a href="/admin/table/${
|
|
6849
|
+
${e.map(n=>`<li data-name="${n.tableName}">
|
|
6850
|
+
<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
6851
|
<iconify-icon icon="mdi:table" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6834
|
-
<span class="truncate">${
|
|
6852
|
+
<span class="truncate">${n.tableName}</span>
|
|
6835
6853
|
</a>
|
|
6836
6854
|
</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
|
-
${
|
|
6855
|
+
`)}`}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+=`
|
|
6856
|
+
${n}<li data-name="${e.name}" class="folder-item">`,i+=`
|
|
6857
|
+
${n} <details class="group/folder" open>`,i+=`
|
|
6858
|
+
${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+=`
|
|
6859
|
+
${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+=`
|
|
6860
|
+
${n} <span class="truncate font-medium">${e.name}</span>`,i+=`
|
|
6861
|
+
${n} </summary>`,i+=`
|
|
6862
|
+
${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+=`
|
|
6863
|
+
${n} <li data-name="${c.exportName}">`,i+=`
|
|
6864
|
+
${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+=`
|
|
6865
|
+
${n} <iconify-icon icon="${l}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
6866
|
+
${n} <span class="truncate">${c.exportName}</span>`,i+=`
|
|
6867
|
+
${n} </a>`,i+=`
|
|
6868
|
+
${n} </li>`;}i+=`
|
|
6869
|
+
${n} </ul>`,i+=`
|
|
6870
|
+
${n} </details>`,i+=`
|
|
6871
|
+
${n}</li>`;}else for(let s of e.handlers){let c=s.kind==="query"?"solar:reorder-linear":"solar:bolt-linear";i+=`
|
|
6872
|
+
${n}<li data-name="${s.exportName}">`,i+=`
|
|
6873
|
+
${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+=`
|
|
6874
|
+
${n} <iconify-icon icon="${c}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
6875
|
+
${n} <span class="truncate">${s.exportName}</span>`,i+=`
|
|
6876
|
+
${n} </a>`,i+=`
|
|
6877
|
+
${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
6878
|
<div id="pane-functions" class="flex flex-col h-full hidden">
|
|
6861
6879
|
<div class="px-3 pt-5 pb-3">
|
|
6862
6880
|
<p class="text-[10px] font-semibold uppercase tracking-widest opacity-35 mb-3 px-1">Functions</p>
|
|
@@ -6872,15 +6890,15 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
6872
6890
|
</div>
|
|
6873
6891
|
</div>
|
|
6874
6892
|
<nav class="flex-1 overflow-y-auto px-2 pb-4">
|
|
6875
|
-
${
|
|
6893
|
+
${t.length>0?`<p class="text-[9px] font-bold uppercase tracking-wider opacity-25 mt-4 mb-1 px-2">Queries</p>
|
|
6876
6894
|
<ul class="flex flex-col gap-0.5">${o}</ul>`:""}
|
|
6877
|
-
${
|
|
6895
|
+
${n.length>0?`<p class="text-[9px] font-bold uppercase tracking-wider opacity-25 mt-4 mb-1 px-2">Mutations</p>
|
|
6878
6896
|
<ul class="flex flex-col gap-0.5">${i}</ul>`:""}
|
|
6879
6897
|
</nav>
|
|
6880
6898
|
</div>
|
|
6881
|
-
`}function
|
|
6899
|
+
`}function Ct(e){return e.map(t=>`
|
|
6882
6900
|
<a
|
|
6883
|
-
href="/admin/table/${
|
|
6901
|
+
href="/admin/table/${t.exportName}"
|
|
6884
6902
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
6885
6903
|
>
|
|
6886
6904
|
<div class="card-body p-5">
|
|
@@ -6889,42 +6907,42 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
6889
6907
|
<iconify-icon icon="mdi:table" width="20" height="20" class="text-primary"></iconify-icon>
|
|
6890
6908
|
</div>
|
|
6891
6909
|
<div>
|
|
6892
|
-
<h2 class="font-semibold text-sm capitalize group-hover:text-primary transition-colors">${
|
|
6910
|
+
<h2 class="font-semibold text-sm capitalize group-hover:text-primary transition-colors">${t.tableName}</h2>
|
|
6893
6911
|
<p class="text-xs opacity-40 mt-0.5">Manage records</p>
|
|
6894
6912
|
</div>
|
|
6895
6913
|
</div>
|
|
6896
6914
|
</div>
|
|
6897
6915
|
</a>
|
|
6898
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
6899
|
-
try { searchConditions.push(like(tableSchema.${
|
|
6900
|
-
`).join("")}function
|
|
6916
|
+
`.replace(/\n/g,"\\n")).join("")}function Ft(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
6917
|
+
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6918
|
+
`).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
6919
|
<th>
|
|
6902
6920
|
<a href="#"
|
|
6903
|
-
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${
|
|
6921
|
+
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
6904
6922
|
hx-target="#main-content"
|
|
6905
6923
|
hx-push-url="true"
|
|
6906
6924
|
class="hover:text-primary flex items-center gap-1.5 transition-colors whitespace-nowrap">
|
|
6907
6925
|
<iconify-icon icon="${a}" width="14" height="14" class="opacity-40"></iconify-icon>
|
|
6908
|
-
${
|
|
6909
|
-
<span class="text-[10px] opacity-30">\${sort === '${
|
|
6926
|
+
${n}
|
|
6927
|
+
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6910
6928
|
</a>
|
|
6911
6929
|
</th>
|
|
6912
|
-
`}).join("")}function
|
|
6930
|
+
`}).join("")}function Mt(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function 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
6931
|
<div class="form-control">
|
|
6914
6932
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6915
|
-
<input type="checkbox" name="${
|
|
6916
|
-
<span class="label-text text-sm">${
|
|
6933
|
+
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
6934
|
+
<span class="label-text text-sm">${t}</span>
|
|
6917
6935
|
</label>
|
|
6918
6936
|
</div>
|
|
6919
6937
|
`:`
|
|
6920
6938
|
<div class="form-control">
|
|
6921
6939
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6922
|
-
<input type="checkbox" name="${
|
|
6923
|
-
<span class="label-text text-sm">${
|
|
6940
|
+
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" />
|
|
6941
|
+
<span class="label-text text-sm">${t}</span>
|
|
6924
6942
|
</label>
|
|
6925
6943
|
</div>
|
|
6926
|
-
`;if(
|
|
6927
|
-
const value = (row as any).${
|
|
6944
|
+
`;if(n==="edit"){let i=r.type==="date"?`\${(() => {
|
|
6945
|
+
const value = (row as any).${t};
|
|
6928
6946
|
if (value == null || value === '') return '';
|
|
6929
6947
|
|
|
6930
6948
|
const date =
|
|
@@ -6937,62 +6955,62 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
6937
6955
|
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
6938
6956
|
const day = String(date.getDate()).padStart(2, '0');
|
|
6939
6957
|
return String(year) + '-' + month + '-' + day;
|
|
6940
|
-
})()}`:`\${String((row as any).${
|
|
6958
|
+
})()}`:`\${String((row as any).${t} ?? '')}`;return `
|
|
6941
6959
|
<div class="form-control">
|
|
6942
|
-
<label class="label"><span class="label-text text-sm font-medium">${
|
|
6943
|
-
<input type="${o}" name="${
|
|
6960
|
+
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6961
|
+
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm" value="${i}"${a} />
|
|
6944
6962
|
</div>
|
|
6945
6963
|
`}return `
|
|
6946
6964
|
<div class="form-control">
|
|
6947
|
-
<label class="label"><span class="label-text text-sm font-medium">${
|
|
6948
|
-
<input type="${o}" name="${
|
|
6965
|
+
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6966
|
+
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm"${a} />
|
|
6949
6967
|
</div>
|
|
6950
|
-
`}function ne(e,
|
|
6951
|
-
if (raw_${
|
|
6952
|
-
return c.text('${
|
|
6968
|
+
`}function ne(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n);if(!r)return "";let a=r.optional?"":`
|
|
6969
|
+
if (raw_${n} === '') {
|
|
6970
|
+
return c.text('${n} is required', 400);
|
|
6953
6971
|
}
|
|
6954
6972
|
`;return r.type==="number"?`
|
|
6955
|
-
const raw_${
|
|
6973
|
+
const raw_${n} = getValue(body['${n}']);
|
|
6956
6974
|
${a}
|
|
6957
|
-
if (raw_${
|
|
6958
|
-
const parsed_${
|
|
6959
|
-
if (Number.isNaN(parsed_${
|
|
6960
|
-
return c.text('${
|
|
6975
|
+
if (raw_${n} !== '') {
|
|
6976
|
+
const parsed_${n} = Number(raw_${n});
|
|
6977
|
+
if (Number.isNaN(parsed_${n})) {
|
|
6978
|
+
return c.text('${n} must be a valid number', 400);
|
|
6961
6979
|
}
|
|
6962
|
-
payload.${
|
|
6980
|
+
payload.${n} = parsed_${n};
|
|
6963
6981
|
}
|
|
6964
6982
|
`:r.type==="boolean"?`
|
|
6965
|
-
const raw_${
|
|
6966
|
-
payload.${
|
|
6983
|
+
const raw_${n} = getValue(body['${n}']);
|
|
6984
|
+
payload.${n} = raw_${n} === 'true' || raw_${n} === 'on' || raw_${n} === '1';
|
|
6967
6985
|
`:r.type==="date"?`
|
|
6968
|
-
const raw_${
|
|
6986
|
+
const raw_${n} = getValue(body['${n}']);
|
|
6969
6987
|
${a}
|
|
6970
|
-
if (raw_${
|
|
6971
|
-
if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(raw_${
|
|
6972
|
-
return c.text('${
|
|
6988
|
+
if (raw_${n} !== '') {
|
|
6989
|
+
if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(raw_${n})) {
|
|
6990
|
+
return c.text('${n} must be a valid date (YYYY-MM-DD)', 400);
|
|
6973
6991
|
}
|
|
6974
6992
|
|
|
6975
|
-
const [year_${
|
|
6976
|
-
const parsed_${
|
|
6993
|
+
const [year_${n}, month_${n}, day_${n}] = raw_${n}.split('-').map(Number);
|
|
6994
|
+
const parsed_${n} = new Date(year_${n}, month_${n} - 1, day_${n});
|
|
6977
6995
|
if (
|
|
6978
|
-
Number.isNaN(parsed_${
|
|
6979
|
-
parsed_${
|
|
6980
|
-
parsed_${
|
|
6981
|
-
parsed_${
|
|
6996
|
+
Number.isNaN(parsed_${n}.getTime()) ||
|
|
6997
|
+
parsed_${n}.getFullYear() !== year_${n} ||
|
|
6998
|
+
parsed_${n}.getMonth() !== month_${n} - 1 ||
|
|
6999
|
+
parsed_${n}.getDate() !== day_${n}
|
|
6982
7000
|
) {
|
|
6983
|
-
return c.text('${
|
|
7001
|
+
return c.text('${n} must be a valid date', 400);
|
|
6984
7002
|
}
|
|
6985
7003
|
|
|
6986
|
-
payload.${
|
|
7004
|
+
payload.${n} = parsed_${n};
|
|
6987
7005
|
}
|
|
6988
7006
|
`:`
|
|
6989
|
-
const raw_${
|
|
7007
|
+
const raw_${n} = getValue(body['${n}']);
|
|
6990
7008
|
${a}
|
|
6991
|
-
if (raw_${
|
|
6992
|
-
payload.${
|
|
7009
|
+
if (raw_${n} !== '') {
|
|
7010
|
+
payload.${n} = raw_${n};
|
|
6993
7011
|
}
|
|
6994
7012
|
`}).join(`
|
|
6995
|
-
`)}function
|
|
7013
|
+
`)}function It(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
7014
|
<div class="drawer drawer-end">
|
|
6997
7015
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6998
7016
|
<div class="drawer-content">
|
|
@@ -7013,7 +7031,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7013
7031
|
<button class="btn btn-ghost btn-sm">Cancel</button>
|
|
7014
7032
|
</form>
|
|
7015
7033
|
<form hx-post="/admin/table/${e.exportName}/delete" hx-target="#main-content" hx-swap="outerHTML" class="inline">
|
|
7016
|
-
<input type="hidden" name="${
|
|
7034
|
+
<input type="hidden" name="${n}" value="\${String((row as any).${n} ?? '')}" />
|
|
7017
7035
|
<input type="hidden" name="sort" value="\${sort}" />
|
|
7018
7036
|
<input type="hidden" name="order" value="\${order}" />
|
|
7019
7037
|
<input type="hidden" name="search" value="\${search}" />
|
|
@@ -7034,7 +7052,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7034
7052
|
</label>
|
|
7035
7053
|
</div>
|
|
7036
7054
|
<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="${
|
|
7055
|
+
<input type="hidden" name="${n}" value="\${String((row as any).${n} ?? '')}" />
|
|
7038
7056
|
<input type="hidden" name="sort" value="\${sort}" />
|
|
7039
7057
|
<input type="hidden" name="order" value="\${order}" />
|
|
7040
7058
|
<input type="hidden" name="search" value="\${search}" />
|
|
@@ -7067,18 +7085,18 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7067
7085
|
\` : 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
7086
|
</div>
|
|
7069
7087
|
\` : ''}
|
|
7070
|
-
</div>`}function W(e,
|
|
7088
|
+
</div>`}function W(e,t="Search term or filter..."){return `
|
|
7071
7089
|
<div class="form-control w-full md:w-auto relative">
|
|
7072
7090
|
<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
7091
|
<input type="text"
|
|
7074
7092
|
name="search"
|
|
7075
|
-
placeholder="${
|
|
7093
|
+
placeholder="${t}"
|
|
7076
7094
|
value="\${search}"
|
|
7077
7095
|
hx-get="${e}?sort=\${sort}&order=\${order}"
|
|
7078
7096
|
hx-trigger="keyup changed delay:500ms, search"
|
|
7079
7097
|
hx-target="#main-content"
|
|
7080
7098
|
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
|
|
7099
|
+
</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
7100
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
7083
7101
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
7084
7102
|
<div class="text-xs text-base-content/70">
|
|
@@ -7202,7 +7220,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7202
7220
|
const page = parseInt(c.req.query('page') || '1');
|
|
7203
7221
|
const limit = 20;
|
|
7204
7222
|
const offset = (page - 1) * limit;
|
|
7205
|
-
const sort = c.req.query('sort') || '${
|
|
7223
|
+
const sort = c.req.query('sort') || '${t}';
|
|
7206
7224
|
const order = c.req.query('order') || 'desc';
|
|
7207
7225
|
const search = c.req.query('search') || '';
|
|
7208
7226
|
|
|
@@ -7248,7 +7266,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7248
7266
|
<tr class="hover:bg-base-200/30 transition-colors">
|
|
7249
7267
|
${y}
|
|
7250
7268
|
${s}
|
|
7251
|
-
${
|
|
7269
|
+
${c}
|
|
7252
7270
|
</tr>
|
|
7253
7271
|
\`)}
|
|
7254
7272
|
\${data.length === 0 ? html\`
|
|
@@ -7268,7 +7286,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7268
7286
|
</tbody>
|
|
7269
7287
|
</table>
|
|
7270
7288
|
</div>
|
|
7271
|
-
${
|
|
7289
|
+
${u}
|
|
7272
7290
|
</div>
|
|
7273
7291
|
\`;
|
|
7274
7292
|
|
|
@@ -7294,7 +7312,7 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7294
7312
|
</div>
|
|
7295
7313
|
</div>
|
|
7296
7314
|
<div class="mb-4">
|
|
7297
|
-
${
|
|
7315
|
+
${p}
|
|
7298
7316
|
</div>
|
|
7299
7317
|
\${tableHtml}
|
|
7300
7318
|
${v}
|
|
@@ -7330,11 +7348,11 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7330
7348
|
title: "${e.tableName} - Admin Dashboard",
|
|
7331
7349
|
children: content
|
|
7332
7350
|
}));
|
|
7333
|
-
});`}function
|
|
7351
|
+
});`}function Dt(e,t,n,r,a,o,i,s){let c=r==="number"?`
|
|
7334
7352
|
const parsedId = Number(rawId);
|
|
7335
|
-
if (Number.isNaN(parsedId)) return c.text('${
|
|
7353
|
+
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
7336
7354
|
idValue = parsedId;
|
|
7337
|
-
`:"",
|
|
7355
|
+
`:"",u=a?`
|
|
7338
7356
|
adminApp.post('/table/${e}/edit', async (c) => {
|
|
7339
7357
|
const db = drizzle(c.env[options.databaseBinding], { schema });
|
|
7340
7358
|
const tableSchema = (schema as any).${e};
|
|
@@ -7342,27 +7360,27 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7342
7360
|
|
|
7343
7361
|
const body = await c.req.parseBody();
|
|
7344
7362
|
const getValue = (value: unknown) => (typeof value === 'string' ? value : '');
|
|
7345
|
-
const rawId = getValue(body['${
|
|
7346
|
-
if (rawId === '') return c.text('${
|
|
7363
|
+
const rawId = getValue(body['${n}']);
|
|
7364
|
+
if (rawId === '') return c.text('${n} is required', 400);
|
|
7347
7365
|
|
|
7348
7366
|
const payload: Record<string, unknown> = {};
|
|
7349
7367
|
|
|
7350
7368
|
${s}
|
|
7351
7369
|
|
|
7352
7370
|
let idValue: unknown = rawId;
|
|
7353
|
-
${
|
|
7371
|
+
${c}
|
|
7354
7372
|
|
|
7355
7373
|
if (Object.keys(payload).length > 0) {
|
|
7356
7374
|
await db
|
|
7357
7375
|
.update(tableSchema)
|
|
7358
7376
|
.set(payload as any)
|
|
7359
|
-
.where(eq(tableSchema.${
|
|
7377
|
+
.where(eq(tableSchema.${n}, idValue as any))
|
|
7360
7378
|
.execute();
|
|
7361
7379
|
}
|
|
7362
7380
|
|
|
7363
7381
|
const query = new URLSearchParams({
|
|
7364
7382
|
page: getValue(body.page) || '1',
|
|
7365
|
-
sort: getValue(body.sort) || '${
|
|
7383
|
+
sort: getValue(body.sort) || '${t}',
|
|
7366
7384
|
order: getValue(body.order) || 'desc',
|
|
7367
7385
|
search: getValue(body.search) || '',
|
|
7368
7386
|
});
|
|
@@ -7376,20 +7394,20 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7376
7394
|
|
|
7377
7395
|
const body = await c.req.parseBody();
|
|
7378
7396
|
const getValue = (value: unknown) => (typeof value === 'string' ? value : '');
|
|
7379
|
-
const rawId = getValue(body['${
|
|
7380
|
-
if (rawId === '') return c.text('${
|
|
7397
|
+
const rawId = getValue(body['${n}']);
|
|
7398
|
+
if (rawId === '') return c.text('${n} is required', 400);
|
|
7381
7399
|
|
|
7382
7400
|
let idValue: unknown = rawId;
|
|
7383
|
-
${
|
|
7401
|
+
${c}
|
|
7384
7402
|
|
|
7385
7403
|
await db
|
|
7386
7404
|
.delete(tableSchema)
|
|
7387
|
-
.where(eq(tableSchema.${
|
|
7405
|
+
.where(eq(tableSchema.${n}, idValue as any))
|
|
7388
7406
|
.execute();
|
|
7389
7407
|
|
|
7390
7408
|
const query = new URLSearchParams({
|
|
7391
7409
|
page: getValue(body.page) || '1',
|
|
7392
|
-
sort: getValue(body.sort) || '${
|
|
7410
|
+
sort: getValue(body.sort) || '${t}',
|
|
7393
7411
|
order: getValue(body.order) || 'desc',
|
|
7394
7412
|
search: getValue(body.search) || '',
|
|
7395
7413
|
});
|
|
@@ -7429,13 +7447,13 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7429
7447
|
|
|
7430
7448
|
await db
|
|
7431
7449
|
.delete(tableSchema)
|
|
7432
|
-
.where(inArray(tableSchema.${
|
|
7450
|
+
.where(inArray(tableSchema.${n}, parsedIds as any))
|
|
7433
7451
|
.execute();
|
|
7434
7452
|
}
|
|
7435
7453
|
|
|
7436
7454
|
const query = new URLSearchParams({
|
|
7437
7455
|
page: getValue(body.page) || '1',
|
|
7438
|
-
sort: getValue(body.sort) || '${
|
|
7456
|
+
sort: getValue(body.sort) || '${t}',
|
|
7439
7457
|
order: getValue(body.order) || 'desc',
|
|
7440
7458
|
search: getValue(body.search) || '',
|
|
7441
7459
|
});
|
|
@@ -7456,22 +7474,22 @@ ${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filt
|
|
|
7456
7474
|
|
|
7457
7475
|
const query = new URLSearchParams({
|
|
7458
7476
|
page: getValue(body.page) || '1',
|
|
7459
|
-
sort: getValue(body.sort) || '${
|
|
7477
|
+
sort: getValue(body.sort) || '${t}',
|
|
7460
7478
|
order: getValue(body.order) || 'desc',
|
|
7461
7479
|
search: getValue(body.search) || '',
|
|
7462
7480
|
});
|
|
7463
7481
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7464
7482
|
});
|
|
7465
|
-
${
|
|
7466
|
-
`}function re(e){let
|
|
7467
|
-
`+
|
|
7483
|
+
${u}
|
|
7484
|
+
`}function re(e){let t=It(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=Mt(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)+`
|
|
7485
|
+
`+Dt(e.exportName,y,t,v,n,i,p,d)}function Vt(){return `
|
|
7468
7486
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7469
7487
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
7470
7488
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
7471
7489
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
7472
7490
|
const search = params.search ? params.search : '';
|
|
7473
7491
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
7474
|
-
};`}function
|
|
7492
|
+
};`}function Bt(){return `
|
|
7475
7493
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7476
7494
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7477
7495
|
<div class="modal">
|
|
@@ -7492,7 +7510,7 @@ ${c}
|
|
|
7492
7510
|
</div>
|
|
7493
7511
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
7494
7512
|
</div>
|
|
7495
|
-
\`}`}function
|
|
7513
|
+
\`}`}function Wt(){return `
|
|
7496
7514
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7497
7515
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7498
7516
|
<div class="modal">
|
|
@@ -7513,8 +7531,8 @@ ${c}
|
|
|
7513
7531
|
</div>
|
|
7514
7532
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
7515
7533
|
</div>
|
|
7516
|
-
\`}`}var
|
|
7517
|
-
`),
|
|
7534
|
+
\`}`}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(`
|
|
7535
|
+
`),t=B("/admin/users");return `
|
|
7518
7536
|
const tableHtml = html\`
|
|
7519
7537
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
7520
7538
|
<div class="overflow-x-auto">
|
|
@@ -7582,8 +7600,8 @@ ${c}
|
|
|
7582
7600
|
</div>
|
|
7583
7601
|
</div>
|
|
7584
7602
|
</div>
|
|
7585
|
-
${Vt()}
|
|
7586
7603
|
${Bt()}
|
|
7604
|
+
${Wt()}
|
|
7587
7605
|
</td>
|
|
7588
7606
|
</tr>
|
|
7589
7607
|
\`)}
|
|
@@ -7596,10 +7614,10 @@ ${Bt()}
|
|
|
7596
7614
|
</tbody>
|
|
7597
7615
|
</table>
|
|
7598
7616
|
</div>
|
|
7599
|
-
${
|
|
7617
|
+
${t}
|
|
7600
7618
|
</div>
|
|
7601
7619
|
\`;
|
|
7602
|
-
`}function
|
|
7620
|
+
`}function Lt(){return `
|
|
7603
7621
|
const content = html\`
|
|
7604
7622
|
<div id="main-content">
|
|
7605
7623
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -7615,7 +7633,7 @@ ${Bt()}
|
|
|
7615
7633
|
</div>
|
|
7616
7634
|
\${tableHtml}
|
|
7617
7635
|
</div>
|
|
7618
|
-
\`;`}function
|
|
7636
|
+
\`;`}function zt(){let e=Ht(),t=Lt();return `
|
|
7619
7637
|
adminApp.get('/users', async (c) => {
|
|
7620
7638
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
7621
7639
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7661,7 +7679,7 @@ ${Bt()}
|
|
|
7661
7679
|
|
|
7662
7680
|
${e}
|
|
7663
7681
|
|
|
7664
|
-
${
|
|
7682
|
+
${t}
|
|
7665
7683
|
|
|
7666
7684
|
if (c.req.header('hx-request')) {
|
|
7667
7685
|
return c.html(content);
|
|
@@ -7671,7 +7689,7 @@ ${Bt()}
|
|
|
7671
7689
|
title: "users - Admin Dashboard",
|
|
7672
7690
|
children: content,
|
|
7673
7691
|
}));
|
|
7674
|
-
});`}function
|
|
7692
|
+
});`}function Ut(){return `
|
|
7675
7693
|
adminApp.post('/users/edit', async (c) => {
|
|
7676
7694
|
const session = await requireAdminSession(c);
|
|
7677
7695
|
if (!session) {
|
|
@@ -7815,7 +7833,7 @@ ${Bt()}
|
|
|
7815
7833
|
|
|
7816
7834
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7817
7835
|
});`}function ae(){return `
|
|
7818
|
-
${
|
|
7836
|
+
${Vt()}
|
|
7819
7837
|
|
|
7820
7838
|
const requireAdminSession = async (c: any) => {
|
|
7821
7839
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7826,12 +7844,12 @@ ${Bt()}
|
|
|
7826
7844
|
return session;
|
|
7827
7845
|
};
|
|
7828
7846
|
|
|
7829
|
-
${Lt()}
|
|
7830
|
-
|
|
7831
7847
|
${zt()}
|
|
7832
|
-
|
|
7848
|
+
|
|
7849
|
+
${Ut()}
|
|
7850
|
+
`}function Qt(e){return `${e.tables.map(t=>re(t)).join(`
|
|
7833
7851
|
`)}
|
|
7834
|
-
${ae()}`}function
|
|
7852
|
+
${ae()}`}function _t(e){return `
|
|
7835
7853
|
<div class="flex items-center justify-between">
|
|
7836
7854
|
<div class="flex items-center gap-3">
|
|
7837
7855
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7846,38 +7864,98 @@ ${ae()}`}function Qt(e){return `
|
|
|
7846
7864
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
7847
7865
|
</div>
|
|
7848
7866
|
</div>
|
|
7849
|
-
`}function
|
|
7867
|
+
`}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 `
|
|
7868
|
+
<div class="flex items-center gap-2">
|
|
7869
|
+
<input
|
|
7870
|
+
type="checkbox"
|
|
7871
|
+
data-obj-key="${t.name}"
|
|
7872
|
+
data-obj-field-type="boolean"
|
|
7873
|
+
class="checkbox checkbox-xs checkbox-primary shrink-0"
|
|
7874
|
+
${t.defaultValue==="true"?"checked":""}
|
|
7875
|
+
/>
|
|
7876
|
+
<span class="text-[10px] font-mono opacity-50">${t.name}${n}</span>
|
|
7877
|
+
</div>`;let r=t.type==="number"?"number":t.type==="date"?"datetime-local":"text";return `
|
|
7878
|
+
<div class="flex items-center gap-2">
|
|
7879
|
+
<span class="text-[10px] font-mono opacity-50 w-20 shrink-0 truncate" title="${t.name}">${t.name}${n}</span>
|
|
7880
|
+
<input
|
|
7881
|
+
type="${r}"
|
|
7882
|
+
data-obj-key="${t.name}"
|
|
7883
|
+
data-obj-field-type="${t.type}"
|
|
7884
|
+
placeholder="${t.defaultValue??""}"
|
|
7885
|
+
value="${t.defaultValue??""}"
|
|
7886
|
+
class="${Cr}"
|
|
7887
|
+
/>
|
|
7888
|
+
</div>`}).join(`
|
|
7889
|
+
`)}function qr(e){let t=e.args??[];if(t.length===0)return `
|
|
7850
7890
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
7851
|
-
|
|
7891
|
+
`;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=`
|
|
7892
|
+
<label class="label py-0.5">
|
|
7893
|
+
<span class="label-text text-[11px] font-mono font-semibold">${a}${o}</span>
|
|
7894
|
+
${i}
|
|
7895
|
+
</label>`;if(r.type==="boolean")return `
|
|
7852
7896
|
<div class="flex items-center gap-3 py-1">
|
|
7853
7897
|
<input
|
|
7854
7898
|
type="checkbox"
|
|
7855
|
-
data-arg-key="${
|
|
7899
|
+
data-arg-key="${r.name}"
|
|
7856
7900
|
data-arg-type="boolean"
|
|
7857
7901
|
class="checkbox checkbox-sm checkbox-primary"
|
|
7858
|
-
${
|
|
7902
|
+
${r.defaultValue==="true"?"checked":""}
|
|
7859
7903
|
/>
|
|
7860
|
-
<span class="text-sm font-mono opacity-70">${
|
|
7861
|
-
${
|
|
7862
|
-
</div>
|
|
7863
|
-
|
|
7904
|
+
<span class="text-sm font-mono opacity-70">${r.name}${o}</span>
|
|
7905
|
+
${r.optional?'<span class="text-[10px] opacity-30 italic ml-auto">optional</span>':""}
|
|
7906
|
+
</div>`;if(r.type==="object")return r.fields&&r.fields.length>0?`
|
|
7907
|
+
<div class="form-control">
|
|
7908
|
+
${s}
|
|
7909
|
+
<div
|
|
7910
|
+
data-arg-key="${r.name}"
|
|
7911
|
+
data-arg-type="object"
|
|
7912
|
+
class="border border-base-200 rounded-xl p-3 bg-base-200/20 flex flex-col gap-2"
|
|
7913
|
+
>
|
|
7914
|
+
${Fr(r.fields)}
|
|
7915
|
+
</div>
|
|
7916
|
+
</div>`:`
|
|
7917
|
+
<div class="form-control">
|
|
7918
|
+
${s}
|
|
7919
|
+
<textarea
|
|
7920
|
+
data-arg-key="${r.name}"
|
|
7921
|
+
data-arg-type="object"
|
|
7922
|
+
placeholder="{}"
|
|
7923
|
+
rows="4"
|
|
7924
|
+
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"
|
|
7925
|
+
${r.optional?"":"required"}
|
|
7926
|
+
>${r.defaultValue??""}</textarea>
|
|
7927
|
+
</div>`;if(r.type==="array"){let l=r.itemType??"string",u=JSON.stringify((r.itemFields??[]).map(p=>({name:p.name,type:p.type})));return `
|
|
7928
|
+
<div class="form-control">
|
|
7929
|
+
${s}
|
|
7930
|
+
<div
|
|
7931
|
+
data-arg-key="${r.name}"
|
|
7932
|
+
data-arg-type="array"
|
|
7933
|
+
data-item-type="${l}"
|
|
7934
|
+
data-item-fields='${u}'
|
|
7935
|
+
class="flex flex-col gap-2"
|
|
7936
|
+
></div>
|
|
7937
|
+
<button
|
|
7938
|
+
type="button"
|
|
7939
|
+
onclick="addArrayItem('${r.name}')"
|
|
7940
|
+
class="btn btn-xs btn-ghost gap-1 mt-1 self-start opacity-50 hover:opacity-100"
|
|
7941
|
+
>
|
|
7942
|
+
<iconify-icon icon="solar:add-circle-linear" width="12" height="12"></iconify-icon>
|
|
7943
|
+
Add item
|
|
7944
|
+
</button>
|
|
7945
|
+
</div>`}let c=r.type==="number"?"number":r.type==="date"?"datetime-local":"text";return `
|
|
7864
7946
|
<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>
|
|
7947
|
+
${s}
|
|
7869
7948
|
<input
|
|
7870
|
-
type="${
|
|
7871
|
-
placeholder="${
|
|
7872
|
-
data-arg-key="${
|
|
7873
|
-
data-arg-type="${
|
|
7874
|
-
value="${
|
|
7875
|
-
class="
|
|
7876
|
-
${
|
|
7949
|
+
type="${c}"
|
|
7950
|
+
placeholder="${r.defaultValue??""}"
|
|
7951
|
+
data-arg-key="${r.name}"
|
|
7952
|
+
data-arg-type="${r.type}"
|
|
7953
|
+
value="${r.defaultValue??""}"
|
|
7954
|
+
class="${n}"
|
|
7955
|
+
${r.optional?"":"required"}
|
|
7877
7956
|
/>
|
|
7878
|
-
</div
|
|
7879
|
-
|
|
7880
|
-
`)}function qr(e){return `
|
|
7957
|
+
</div>`}).join(`
|
|
7958
|
+
`)}function Mr(e){return `
|
|
7881
7959
|
<div class="space-y-4">
|
|
7882
7960
|
<div class="flex items-center justify-between">
|
|
7883
7961
|
<div class="flex flex-col">
|
|
@@ -7890,11 +7968,11 @@ ${ae()}`}function Qt(e){return `
|
|
|
7890
7968
|
</label>
|
|
7891
7969
|
</div>
|
|
7892
7970
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
7893
|
-
${
|
|
7971
|
+
${qr(e)}
|
|
7894
7972
|
</div>
|
|
7895
7973
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7896
7974
|
</div>
|
|
7897
|
-
`}function
|
|
7975
|
+
`}function Ir(){return `
|
|
7898
7976
|
<div class="space-y-4">
|
|
7899
7977
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7900
7978
|
<div class="relative group">
|
|
@@ -7911,7 +7989,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
7911
7989
|
</div>
|
|
7912
7990
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7913
7991
|
</div>
|
|
7914
|
-
`}function
|
|
7992
|
+
`}function jr(){return `
|
|
7915
7993
|
<div class="space-y-4">
|
|
7916
7994
|
<div class="flex items-center justify-between">
|
|
7917
7995
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -7925,7 +8003,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
7925
8003
|
</div>
|
|
7926
8004
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
7927
8005
|
</div>
|
|
7928
|
-
`}function
|
|
8006
|
+
`}function Kt(e){return `
|
|
7929
8007
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
7930
8008
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
7931
8009
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -7946,13 +8024,13 @@ ${ae()}`}function Qt(e){return `
|
|
|
7946
8024
|
<!-- Tab Content -->
|
|
7947
8025
|
<div class="flex-1 overflow-y-auto">
|
|
7948
8026
|
<div id="request-tab-args" class="p-5">
|
|
7949
|
-
${
|
|
8027
|
+
${Mr(e)}
|
|
7950
8028
|
</div>
|
|
7951
8029
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
7952
|
-
${
|
|
8030
|
+
${Ir()}
|
|
7953
8031
|
</div>
|
|
7954
8032
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
7955
|
-
${
|
|
8033
|
+
${jr()}
|
|
7956
8034
|
</div>
|
|
7957
8035
|
</div>
|
|
7958
8036
|
|
|
@@ -7970,7 +8048,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
7970
8048
|
</form>
|
|
7971
8049
|
</div>
|
|
7972
8050
|
</div>
|
|
7973
|
-
`}function
|
|
8051
|
+
`}function Jt(){return `
|
|
7974
8052
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
7975
8053
|
<!-- Panel Header -->
|
|
7976
8054
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -8052,7 +8130,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8052
8130
|
|
|
8053
8131
|
</div>
|
|
8054
8132
|
</div>
|
|
8055
|
-
`}function
|
|
8133
|
+
`}function Gt(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
8056
8134
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
8057
8135
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
8058
8136
|
|
|
@@ -8118,6 +8196,29 @@ ${ae()}`}function Qt(e){return `
|
|
|
8118
8196
|
container.appendChild(row);
|
|
8119
8197
|
};
|
|
8120
8198
|
|
|
8199
|
+
// \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
|
|
8200
|
+
function getFieldValue(el) {
|
|
8201
|
+
var type = el.getAttribute('data-obj-field-type') || 'string';
|
|
8202
|
+
if (type === 'boolean') return el.checked;
|
|
8203
|
+
if (type === 'number') {
|
|
8204
|
+
var raw = el.value.trim();
|
|
8205
|
+
return raw === '' ? undefined : Number(raw);
|
|
8206
|
+
}
|
|
8207
|
+
var v = el.value.trim();
|
|
8208
|
+
return v === '' ? undefined : v;
|
|
8209
|
+
}
|
|
8210
|
+
|
|
8211
|
+
function collectObjectRow(container) {
|
|
8212
|
+
var obj = {};
|
|
8213
|
+
container.querySelectorAll('[data-obj-key]').forEach(function(f) {
|
|
8214
|
+
var k = f.getAttribute('data-obj-key');
|
|
8215
|
+
if (!k) return;
|
|
8216
|
+
var v = getFieldValue(f);
|
|
8217
|
+
if (v !== undefined) obj[k] = v;
|
|
8218
|
+
});
|
|
8219
|
+
return Object.keys(obj).length ? obj : undefined;
|
|
8220
|
+
}
|
|
8221
|
+
|
|
8121
8222
|
// \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
8223
|
function collectArgs() {
|
|
8123
8224
|
var result = {};
|
|
@@ -8131,6 +8232,36 @@ ${ae()}`}function Qt(e){return `
|
|
|
8131
8232
|
} else if (type === 'number') {
|
|
8132
8233
|
var raw = el.value.trim();
|
|
8133
8234
|
value = raw === '' ? undefined : Number(raw);
|
|
8235
|
+
} else if (type === 'object') {
|
|
8236
|
+
if (el.tagName === 'TEXTAREA') {
|
|
8237
|
+
// Fallback JSON textarea
|
|
8238
|
+
var raw = el.value.trim();
|
|
8239
|
+
if (!raw) return;
|
|
8240
|
+
try { value = JSON.parse(raw); } catch(e) { value = raw; }
|
|
8241
|
+
} else {
|
|
8242
|
+
// Structured field inputs
|
|
8243
|
+
value = collectObjectRow(el);
|
|
8244
|
+
}
|
|
8245
|
+
} else if (type === 'array') {
|
|
8246
|
+
var itemType = el.getAttribute('data-item-type') || 'string';
|
|
8247
|
+
if (itemType === 'object') {
|
|
8248
|
+
var rows = el.querySelectorAll('.array-item-row');
|
|
8249
|
+
var arr = Array.from(rows).map(function(row) {
|
|
8250
|
+
return collectObjectRow(row);
|
|
8251
|
+
}).filter(Boolean);
|
|
8252
|
+
value = arr.length ? arr : undefined;
|
|
8253
|
+
} else {
|
|
8254
|
+
var items = el.querySelectorAll('.array-item-input');
|
|
8255
|
+
var arr = Array.from(items).map(function(inp) {
|
|
8256
|
+
var ft = inp.getAttribute('data-obj-field-type') || 'string';
|
|
8257
|
+
if (ft === 'number') {
|
|
8258
|
+
var raw = inp.value.trim();
|
|
8259
|
+
return raw === '' ? undefined : Number(raw);
|
|
8260
|
+
}
|
|
8261
|
+
return inp.value.trim() || undefined;
|
|
8262
|
+
}).filter(function(v) { return v !== undefined; });
|
|
8263
|
+
value = arr.length ? arr : undefined;
|
|
8264
|
+
}
|
|
8134
8265
|
} else {
|
|
8135
8266
|
value = el.value;
|
|
8136
8267
|
}
|
|
@@ -8141,6 +8272,102 @@ ${ae()}`}function Qt(e){return `
|
|
|
8141
8272
|
return result;
|
|
8142
8273
|
}
|
|
8143
8274
|
|
|
8275
|
+
// \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
|
|
8276
|
+
function makeFieldInput(field) {
|
|
8277
|
+
if (field.type === 'boolean') {
|
|
8278
|
+
var cb = document.createElement('input');
|
|
8279
|
+
cb.type = 'checkbox';
|
|
8280
|
+
cb.className = 'checkbox checkbox-xs checkbox-primary shrink-0';
|
|
8281
|
+
cb.setAttribute('data-obj-key', field.name);
|
|
8282
|
+
cb.setAttribute('data-obj-field-type', 'boolean');
|
|
8283
|
+
return cb;
|
|
8284
|
+
}
|
|
8285
|
+
var inputType = field.type === 'number' ? 'number'
|
|
8286
|
+
: field.type === 'date' ? 'datetime-local'
|
|
8287
|
+
: 'text';
|
|
8288
|
+
var inp = document.createElement('input');
|
|
8289
|
+
inp.type = inputType;
|
|
8290
|
+
inp.placeholder = field.name;
|
|
8291
|
+
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';
|
|
8292
|
+
inp.setAttribute('data-obj-key', field.name);
|
|
8293
|
+
inp.setAttribute('data-obj-field-type', field.type);
|
|
8294
|
+
return inp;
|
|
8295
|
+
}
|
|
8296
|
+
|
|
8297
|
+
window.addArrayItem = function(key) {
|
|
8298
|
+
var container = document.querySelector('[data-arg-key="' + key + '"][data-arg-type="array"]');
|
|
8299
|
+
if (!container) return;
|
|
8300
|
+
var itemType = container.getAttribute('data-item-type') || 'string';
|
|
8301
|
+
|
|
8302
|
+
if (itemType === 'object') {
|
|
8303
|
+
var fieldsJson = container.getAttribute('data-item-fields') || '[]';
|
|
8304
|
+
var itemFields;
|
|
8305
|
+
try { itemFields = JSON.parse(fieldsJson); } catch(e) { itemFields = []; }
|
|
8306
|
+
|
|
8307
|
+
var rowCount = container.querySelectorAll('.array-item-row').length + 1;
|
|
8308
|
+
|
|
8309
|
+
var row = document.createElement('div');
|
|
8310
|
+
row.className = 'array-item-row border border-base-200 rounded-xl p-3 bg-base-200/20 flex flex-col gap-2';
|
|
8311
|
+
|
|
8312
|
+
var header = document.createElement('div');
|
|
8313
|
+
header.className = 'flex items-center justify-between';
|
|
8314
|
+
|
|
8315
|
+
var lbl = document.createElement('span');
|
|
8316
|
+
lbl.className = 'text-[10px] font-mono opacity-30';
|
|
8317
|
+
lbl.textContent = 'Item ' + rowCount;
|
|
8318
|
+
|
|
8319
|
+
var removeBtn = document.createElement('button');
|
|
8320
|
+
removeBtn.type = 'button';
|
|
8321
|
+
removeBtn.className = 'btn btn-xs btn-ghost text-error opacity-40 hover:opacity-100 px-1.5';
|
|
8322
|
+
removeBtn.innerHTML = '<iconify-icon icon="solar:close-circle-linear" width="14" height="14"></iconify-icon>';
|
|
8323
|
+
removeBtn.onclick = function() { row.remove(); };
|
|
8324
|
+
|
|
8325
|
+
header.appendChild(lbl);
|
|
8326
|
+
header.appendChild(removeBtn);
|
|
8327
|
+
row.appendChild(header);
|
|
8328
|
+
|
|
8329
|
+
itemFields.forEach(function(field) {
|
|
8330
|
+
var fieldRow = document.createElement('div');
|
|
8331
|
+
fieldRow.className = 'flex items-center gap-2';
|
|
8332
|
+
|
|
8333
|
+
var fieldLbl = document.createElement('span');
|
|
8334
|
+
fieldLbl.className = 'text-[10px] font-mono opacity-50 w-20 shrink-0 truncate';
|
|
8335
|
+
fieldLbl.title = field.name;
|
|
8336
|
+
fieldLbl.textContent = field.name;
|
|
8337
|
+
|
|
8338
|
+
fieldRow.appendChild(fieldLbl);
|
|
8339
|
+
fieldRow.appendChild(makeFieldInput(field));
|
|
8340
|
+
row.appendChild(fieldRow);
|
|
8341
|
+
});
|
|
8342
|
+
|
|
8343
|
+
container.appendChild(row);
|
|
8344
|
+
} else {
|
|
8345
|
+
var inputType = itemType === 'number' ? 'number'
|
|
8346
|
+
: itemType === 'date' ? 'datetime-local'
|
|
8347
|
+
: 'text';
|
|
8348
|
+
|
|
8349
|
+
var row = document.createElement('div');
|
|
8350
|
+
row.className = 'flex items-center gap-2';
|
|
8351
|
+
|
|
8352
|
+
var inp = document.createElement('input');
|
|
8353
|
+
inp.type = inputType;
|
|
8354
|
+
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';
|
|
8355
|
+
inp.placeholder = 'value';
|
|
8356
|
+
inp.setAttribute('data-obj-field-type', itemType);
|
|
8357
|
+
|
|
8358
|
+
var removeBtn = document.createElement('button');
|
|
8359
|
+
removeBtn.type = 'button';
|
|
8360
|
+
removeBtn.className = 'btn btn-xs btn-ghost text-error opacity-40 hover:opacity-100 px-1.5';
|
|
8361
|
+
removeBtn.innerHTML = '<iconify-icon icon="solar:close-circle-linear" width="14" height="14"></iconify-icon>';
|
|
8362
|
+
removeBtn.onclick = function() { row.remove(); };
|
|
8363
|
+
|
|
8364
|
+
row.appendChild(inp);
|
|
8365
|
+
row.appendChild(removeBtn);
|
|
8366
|
+
container.appendChild(row);
|
|
8367
|
+
inp.focus();
|
|
8368
|
+
}
|
|
8369
|
+
};
|
|
8370
|
+
|
|
8144
8371
|
function collectHeaders() {
|
|
8145
8372
|
var result = {};
|
|
8146
8373
|
document.querySelectorAll('#headers-rows [data-hdr-key]').forEach(function(keyEl) {
|
|
@@ -8278,9 +8505,9 @@ ${ae()}`}function Qt(e){return `
|
|
|
8278
8505
|
if (indicator) indicator.classList.remove('opacity-0');
|
|
8279
8506
|
showBodyLoading();
|
|
8280
8507
|
|
|
8281
|
-
var isQuery = ${
|
|
8508
|
+
var isQuery = ${t};
|
|
8282
8509
|
var method = isQuery ? 'GET' : 'POST';
|
|
8283
|
-
var pathWithQuery = '${
|
|
8510
|
+
var pathWithQuery = '${n}';
|
|
8284
8511
|
|
|
8285
8512
|
if (isQuery && Object.keys(args).length > 0) {
|
|
8286
8513
|
var params = new URLSearchParams();
|
|
@@ -8350,7 +8577,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8350
8577
|
var _rtToken = null;
|
|
8351
8578
|
var _rtEnabled = false;
|
|
8352
8579
|
var _rtEventCount = 0;
|
|
8353
|
-
var _isRealtimeSupported = ${
|
|
8580
|
+
var _isRealtimeSupported = ${t};
|
|
8354
8581
|
var _realtimeQueryName = '${r}';
|
|
8355
8582
|
var _rtPingInterval = null;
|
|
8356
8583
|
|
|
@@ -8594,21 +8821,21 @@ ${ae()}`}function Qt(e){return `
|
|
|
8594
8821
|
_rtEnabled = false;
|
|
8595
8822
|
});
|
|
8596
8823
|
</script>
|
|
8597
|
-
`}function
|
|
8824
|
+
`}function Zt(e){return `
|
|
8598
8825
|
const content = html\`
|
|
8599
8826
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
8600
|
-
${
|
|
8827
|
+
${_t(e)}
|
|
8601
8828
|
|
|
8602
8829
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
8603
8830
|
<!-- Request Panel -->
|
|
8604
|
-
${
|
|
8831
|
+
${Kt(e)}
|
|
8605
8832
|
|
|
8606
8833
|
<!-- Result Panel -->
|
|
8607
|
-
${
|
|
8834
|
+
${Jt()}
|
|
8608
8835
|
</div>
|
|
8609
8836
|
</div>
|
|
8610
8837
|
|
|
8611
|
-
${
|
|
8838
|
+
${Gt(e)}
|
|
8612
8839
|
\`;
|
|
8613
8840
|
|
|
8614
8841
|
if (c.req.header('hx-request')) {
|
|
@@ -8618,11 +8845,11 @@ ${ae()}`}function Qt(e){return `
|
|
|
8618
8845
|
return c.html(Layout({
|
|
8619
8846
|
title: "${e.exportName} - Functions",
|
|
8620
8847
|
children: content
|
|
8621
|
-
}));`}function
|
|
8622
|
-
adminApp.get('/functions${
|
|
8623
|
-
${
|
|
8848
|
+
}));`}function Xt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
8849
|
+
adminApp.get('/functions${n.routePath}', (c) => {
|
|
8850
|
+
${Zt(n)}
|
|
8624
8851
|
});`).join(`
|
|
8625
|
-
`)}function
|
|
8852
|
+
`)}function Yt(){return `
|
|
8626
8853
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
8627
8854
|
const r2Binding = (options as any).r2Binding;
|
|
8628
8855
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -8691,7 +8918,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8691
8918
|
const parts = prefix.split('/').filter(Boolean);
|
|
8692
8919
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
8693
8920
|
};
|
|
8694
|
-
`}function
|
|
8921
|
+
`}function en(){return `
|
|
8695
8922
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
8696
8923
|
const parts = prefix.split('/').filter(Boolean);
|
|
8697
8924
|
const breadcrumbs: any[] = [];
|
|
@@ -8818,7 +9045,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8818
9045
|
</div>
|
|
8819
9046
|
\`;
|
|
8820
9047
|
};
|
|
8821
|
-
`}function
|
|
9048
|
+
`}function tn(){return `
|
|
8822
9049
|
const handleStorageListRoute = async (c: any) => {
|
|
8823
9050
|
const bucket = getStorageBucket(c);
|
|
8824
9051
|
if (!bucket) {
|
|
@@ -8840,7 +9067,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8840
9067
|
|
|
8841
9068
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8842
9069
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8843
|
-
`}function
|
|
9070
|
+
`}function nn(){return `
|
|
8844
9071
|
adminApp.post('/storage/upload', async (c) => {
|
|
8845
9072
|
const bucket = getStorageBucket(c);
|
|
8846
9073
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8858,7 +9085,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8858
9085
|
|
|
8859
9086
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8860
9087
|
});
|
|
8861
|
-
`}function
|
|
9088
|
+
`}function rn(){return `
|
|
8862
9089
|
adminApp.delete('/storage/delete', async (c) => {
|
|
8863
9090
|
const bucket = getStorageBucket(c);
|
|
8864
9091
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8873,7 +9100,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8873
9100
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
8874
9101
|
return c.html('');
|
|
8875
9102
|
});
|
|
8876
|
-
`}function
|
|
9103
|
+
`}function an(){return `
|
|
8877
9104
|
adminApp.post('/storage/directory', async (c) => {
|
|
8878
9105
|
const bucket = getStorageBucket(c);
|
|
8879
9106
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8899,7 +9126,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8899
9126
|
|
|
8900
9127
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8901
9128
|
});
|
|
8902
|
-
`}function
|
|
9129
|
+
`}function on(){return `
|
|
8903
9130
|
adminApp.get('/storage/download', async (c) => {
|
|
8904
9131
|
const bucket = getStorageBucket(c);
|
|
8905
9132
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8919,7 +9146,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8919
9146
|
|
|
8920
9147
|
return new Response(object.body, { headers });
|
|
8921
9148
|
});
|
|
8922
|
-
`}function
|
|
9149
|
+
`}function sn(){return `
|
|
8923
9150
|
adminApp.get('/storage/preview', async (c) => {
|
|
8924
9151
|
const bucket = getStorageBucket(c);
|
|
8925
9152
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8937,25 +9164,25 @@ ${ae()}`}function Qt(e){return `
|
|
|
8937
9164
|
|
|
8938
9165
|
return new Response(object.body, { headers });
|
|
8939
9166
|
});
|
|
8940
|
-
`}function
|
|
8941
|
-
${an()}
|
|
8942
|
-
|
|
9167
|
+
`}function ln(){return `
|
|
8943
9168
|
${on()}
|
|
8944
9169
|
|
|
8945
|
-
${
|
|
9170
|
+
${sn()}
|
|
8946
9171
|
|
|
8947
9172
|
${nn()}
|
|
8948
9173
|
|
|
8949
9174
|
${rn()}
|
|
8950
9175
|
|
|
8951
|
-
${
|
|
8952
|
-
`}function ln(){return `
|
|
8953
|
-
${Xt()}
|
|
9176
|
+
${an()}
|
|
8954
9177
|
|
|
9178
|
+
${tn()}
|
|
9179
|
+
`}function un(){return `
|
|
8955
9180
|
${Yt()}
|
|
8956
9181
|
|
|
8957
|
-
${
|
|
8958
|
-
|
|
9182
|
+
${en()}
|
|
9183
|
+
|
|
9184
|
+
${ln()}
|
|
9185
|
+
`}function cn(e,t){let n=$t(t);return `
|
|
8959
9186
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
8960
9187
|
return html\`<!DOCTYPE html>
|
|
8961
9188
|
<html lang="en" data-theme="light">
|
|
@@ -9176,7 +9403,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9176
9403
|
</nav>
|
|
9177
9404
|
</div>
|
|
9178
9405
|
|
|
9179
|
-
${
|
|
9406
|
+
${n}
|
|
9180
9407
|
</div>
|
|
9181
9408
|
</div>
|
|
9182
9409
|
\`) : ""}
|
|
@@ -9362,7 +9589,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9362
9589
|
</body>
|
|
9363
9590
|
</html>\`;
|
|
9364
9591
|
}
|
|
9365
|
-
`}function
|
|
9592
|
+
`}function dn(){return `
|
|
9366
9593
|
// Auth Middleware
|
|
9367
9594
|
adminApp.use('*', async (c, next) => {
|
|
9368
9595
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -9421,7 +9648,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9421
9648
|
}
|
|
9422
9649
|
await next();
|
|
9423
9650
|
});
|
|
9424
|
-
`}function
|
|
9651
|
+
`}function pn(e){return `
|
|
9425
9652
|
adminApp.get('/', (c) => {
|
|
9426
9653
|
return c.html(Layout({
|
|
9427
9654
|
title: "Admin Dashboard",
|
|
@@ -9438,7 +9665,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9438
9665
|
\`
|
|
9439
9666
|
}));
|
|
9440
9667
|
});
|
|
9441
|
-
`}function
|
|
9668
|
+
`}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
9669
|
import { html, raw } from "hono/html";
|
|
9443
9670
|
import { drizzle } from "drizzle-orm/d1";
|
|
9444
9671
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -9451,9 +9678,9 @@ ${l}
|
|
|
9451
9678
|
export function registerAdminDashboard(app: Hono<any>, options: { databaseBinding: string, r2Binding?: string }) {
|
|
9452
9679
|
const adminApp = new Hono<any>();
|
|
9453
9680
|
|
|
9454
|
-
${
|
|
9681
|
+
${u}
|
|
9455
9682
|
|
|
9456
|
-
${
|
|
9683
|
+
${p}
|
|
9457
9684
|
|
|
9458
9685
|
// Generate table routes
|
|
9459
9686
|
${i}
|
|
@@ -9462,63 +9689,63 @@ ${m}
|
|
|
9462
9689
|
${s}
|
|
9463
9690
|
|
|
9464
9691
|
// Generate storage routes
|
|
9465
|
-
${
|
|
9692
|
+
${c}
|
|
9466
9693
|
|
|
9467
9694
|
app.route('/admin', adminApp);
|
|
9468
9695
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
9469
9696
|
}
|
|
9470
|
-
`}function oe(e){if(typeof e!="object"||e===null)return false;let
|
|
9471
|
-
`}function
|
|
9697
|
+
`}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";
|
|
9698
|
+
`}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
9699
|
${a.map(o=>` ${o}`).join(`
|
|
9473
9700
|
`)}
|
|
9474
|
-
},`);}return
|
|
9701
|
+
},`);}return t.length===0?`export const __appflareJsonColumns = {} as const;
|
|
9475
9702
|
`:`export const __appflareJsonColumns = {
|
|
9476
|
-
${
|
|
9703
|
+
${t.map(n=>` ${n}`).join(`
|
|
9477
9704
|
`)}
|
|
9478
9705
|
} 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&&
|
|
9706
|
+
`}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)}: {
|
|
9707
|
+
targetTable: ${g(i.targetTable)},
|
|
9708
|
+
junctionTable: ${g(i.junctionTable)},
|
|
9709
|
+
sourceField: ${g(i.sourceField??"")},
|
|
9710
|
+
targetField: ${g(i.targetField??"")},
|
|
9711
|
+
referenceField: ${g(i.referenceField??"id")},
|
|
9712
|
+
targetReferenceField: ${g(i.targetReferenceField??"id")},
|
|
9713
|
+
},`);a.length!==0&&t.push(`${g(n)}: {
|
|
9487
9714
|
${a.map(o=>` ${o}`).join(`
|
|
9488
9715
|
`)}
|
|
9489
|
-
},`);}return
|
|
9716
|
+
},`);}return t.length===0?`export const __appflareManyToMany = {} as const;
|
|
9490
9717
|
`:`export const __appflareManyToMany = {
|
|
9491
|
-
${
|
|
9718
|
+
${t.map(n=>` ${n}`).join(`
|
|
9492
9719
|
`)}
|
|
9493
9720
|
} as const;
|
|
9494
|
-
`}function
|
|
9721
|
+
`}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
9722
|
kind: "one",
|
|
9496
|
-
targetTable: ${
|
|
9497
|
-
sourceField: ${
|
|
9498
|
-
referenceField: ${
|
|
9499
|
-
},`);continue}if(i.relation==="many"){a.push(`${
|
|
9723
|
+
targetTable: ${g(i.targetTable)},
|
|
9724
|
+
sourceField: ${g(i.field??"")},
|
|
9725
|
+
referenceField: ${g(i.referenceField??"id")},
|
|
9726
|
+
},`);continue}if(i.relation==="many"){a.push(`${g(o)}: {
|
|
9500
9727
|
kind: "many",
|
|
9501
|
-
targetTable: ${
|
|
9502
|
-
sourceField: ${
|
|
9503
|
-
referenceField: ${
|
|
9504
|
-
},`);continue}a.push(`${
|
|
9728
|
+
targetTable: ${g(i.targetTable)},
|
|
9729
|
+
sourceField: ${g(i.field??"")},
|
|
9730
|
+
referenceField: ${g(i.referenceField??"id")},
|
|
9731
|
+
},`);continue}a.push(`${g(o)}: {
|
|
9505
9732
|
kind: "manyToMany",
|
|
9506
|
-
targetTable: ${
|
|
9507
|
-
junctionTable: ${
|
|
9508
|
-
sourceField: ${
|
|
9509
|
-
targetField: ${
|
|
9510
|
-
referenceField: ${
|
|
9511
|
-
targetReferenceField: ${
|
|
9512
|
-
},`);}a.length!==0&&
|
|
9733
|
+
targetTable: ${g(i.targetTable)},
|
|
9734
|
+
junctionTable: ${g(i.junctionTable??"")},
|
|
9735
|
+
sourceField: ${g(i.sourceField??"")},
|
|
9736
|
+
targetField: ${g(i.targetField??"")},
|
|
9737
|
+
referenceField: ${g(i.referenceField??"id")},
|
|
9738
|
+
targetReferenceField: ${g(i.targetReferenceField??"id")},
|
|
9739
|
+
},`);}a.length!==0&&t.push(`${g(n)}: {
|
|
9513
9740
|
${a.map(o=>` ${o}`).join(`
|
|
9514
9741
|
`)}
|
|
9515
|
-
},`);}return
|
|
9742
|
+
},`);}return t.length===0?`export const __appflareRelations = {} as const;
|
|
9516
9743
|
`:`export const __appflareRelations = {
|
|
9517
|
-
${
|
|
9744
|
+
${t.map(n=>` ${n}`).join(`
|
|
9518
9745
|
`)}
|
|
9519
9746
|
} as const;
|
|
9520
|
-
`}function
|
|
9521
|
-
${
|
|
9747
|
+
`}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(
|
|
9748
|
+
${g(p)},
|
|
9522
9749
|
{
|
|
9523
9750
|
${d.join(`
|
|
9524
9751
|
`)}
|
|
@@ -9527,19 +9754,19 @@ ${d.join(`
|
|
|
9527
9754
|
${y.join(`,
|
|
9528
9755
|
`)}
|
|
9529
9756
|
],
|
|
9530
|
-
);`):s.push(`export const ${l} = table(${
|
|
9757
|
+
);`):s.push(`export const ${l} = table(${g(p)}, {
|
|
9531
9758
|
${d.join(`
|
|
9532
9759
|
`)}
|
|
9533
|
-
});`);let v=Object.entries(
|
|
9760
|
+
});`);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 I=[];for(let[b,h]of v){let T=Ur(l,u,h);I.push(` ${b}: one(${h.targetTable}, {
|
|
9534
9761
|
fields: [${l}.${T.sourceField}],
|
|
9535
9762
|
references: [${h.targetTable}.${T.targetField}],
|
|
9536
|
-
}),`);}for(let[b,h]of A)I.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.`);I.push(` ${b}: many(${h.junctionTable}),`);}
|
|
9763
|
+
}),`);}for(let[b,h]of A)I.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.`);I.push(` ${b}: many(${h.junctionTable}),`);}c.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
9537
9764
|
${I.join(`
|
|
9538
9765
|
`)}
|
|
9539
9766
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9540
9767
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
9541
9768
|
import { relations } from "drizzle-orm";
|
|
9542
|
-
${
|
|
9769
|
+
${Qr(r)}
|
|
9543
9770
|
${o.join(`
|
|
9544
9771
|
`)}
|
|
9545
9772
|
${i.join(`
|
|
@@ -9549,30 +9776,30 @@ ${s.join(`
|
|
|
9549
9776
|
|
|
9550
9777
|
`)}
|
|
9551
9778
|
|
|
9552
|
-
${
|
|
9779
|
+
${c.join(`
|
|
9553
9780
|
|
|
9554
9781
|
`)}
|
|
9555
9782
|
|
|
9556
|
-
${
|
|
9783
|
+
${Jr(e)}
|
|
9557
9784
|
|
|
9558
|
-
${
|
|
9785
|
+
${Gr(e)}
|
|
9559
9786
|
|
|
9560
|
-
${
|
|
9561
|
-
`}function ce(e){return e.kind==="array"?`z.array(${ce(e.element)})`:e.kind==="object"?`z.object({ ${Object.entries(e.shape).map(([
|
|
9787
|
+
${Zr(e)}
|
|
9788
|
+
`}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
9789
|
${o.join(`
|
|
9563
9790
|
`)}
|
|
9564
9791
|
});
|
|
9565
|
-
export const ${
|
|
9792
|
+
export const ${n}SelectSchema = z.object({
|
|
9566
9793
|
${i.join(`
|
|
9567
9794
|
`)}
|
|
9568
9795
|
});
|
|
9569
9796
|
|
|
9570
|
-
export type ${a}Insert = z.infer<typeof ${
|
|
9571
|
-
export type ${a}Select = z.infer<typeof ${
|
|
9797
|
+
export type ${a}Insert = z.infer<typeof ${n}InsertSchema>;
|
|
9798
|
+
export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
9572
9799
|
`);}return `import { z } from "zod";
|
|
9573
9800
|
|
|
9574
|
-
${
|
|
9575
|
-
`)}`}function L(e){return e.kind==="array"?`Array<${L(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([
|
|
9801
|
+
${t.join(`
|
|
9802
|
+
`)}`}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
9803
|
${i.join(`
|
|
9577
9804
|
`)}
|
|
9578
9805
|
};
|
|
@@ -9580,30 +9807,30 @@ ${i.join(`
|
|
|
9580
9807
|
export type New${o} = {
|
|
9581
9808
|
${s.join(`
|
|
9582
9809
|
`)}
|
|
9583
|
-
};`);}return `${
|
|
9810
|
+
};`);}return `${t.join(`
|
|
9584
9811
|
`)}
|
|
9585
|
-
${
|
|
9812
|
+
${n.join(`
|
|
9586
9813
|
|
|
9587
9814
|
`)}
|
|
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 m=Gr(c,t),d=Yr(c),y=Zr(c);return await Promise.all([Bun.write(a,m),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 m=pa(s,c.kindDirectory);for(let d of c.exports){let y=c.kind==="query"||c.kind==="mutation"?Tn(m,d.exportName):void 0,v=c.kind==="scheduler"||c.kind==="cron"?Tn(m,d.exportName):void 0,A=c.kind==="query"||c.kind==="mutation"?[...de(m).split("/").filter(Boolean),d.exportName]:void 0,w=c.kind==="query"?xn("queries",m,d.exportName):c.kind==="mutation"?xn("mutations",m,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 m=0;m<e.length;m+=1){let d=e[m];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),m=!/\.notnull\s*\(/i.test(i)||l||u||s;t.push({name:o,expression:i,type:ha(i),optional:m,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,m=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(m){m=false;continue}if(y==="\\"){m=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
|
|
9815
|
+
`}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 M(e,t){let n=aa(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var la=new Set([".ts",".tsx",".mts",".cts"]);async function 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: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});}}}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
|
|
9816
|
+
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 Mn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=M(t,a),s=path.resolve(t,"client"),c=M(s,a),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)
|
|
9817
|
+
`);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"),I=path.resolve(t,"drizzle.config.ts"),b=path.resolve(n,"wrangler.json"),h=await xn(e),T=await Cn(e,h?[h.schemaPath]:[]),C=M(t,T.schemaPath),R=await An(e);process.stdout.write(`\u{1F50D} ${R.length} handler(s) (${(performance.now()-l).toFixed(0)}ms)
|
|
9818
|
+
`);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";
|
|
9819
|
+
`),...Zn,...Gn,Bun.write(A,zn),Bun.write(w,""),Bun.write(I,Qn),Bun.write(b,`${JSON.stringify(_n,null,2)}
|
|
9820
|
+
`),Bun.write(Jn,Kn)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-l).toFixed(0)}ms)
|
|
9821
|
+
`);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)
|
|
9822
|
+
`),j.length>0&&(await ka(w,j),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-l).toFixed(0)}ms)
|
|
9823
|
+
`));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
9824
|
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-l).toFixed(0)}ms)
|
|
9598
|
-
`);async function
|
|
9599
|
-
`);let N=await Bun.spawn([process.execPath,
|
|
9600
|
-
`);async function
|
|
9601
|
-
`);let
|
|
9602
|
-
`);let
|
|
9603
|
-
`);let $=await Bun.spawn([process.execPath,
|
|
9604
|
-
`);}}var
|
|
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
|
|
9825
|
+
`);async function tr(x,$){process.stdout.write(`\u2699\uFE0F ${$}... (${(performance.now()-l).toFixed(0)}ms)
|
|
9826
|
+
`);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)
|
|
9827
|
+
`);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)
|
|
9828
|
+
`);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)
|
|
9829
|
+
`);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)
|
|
9830
|
+
`);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)
|
|
9831
|
+
`);}}var In=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([In,zod.z.array(In).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 Ma(e){if(!On(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function Ia(e){let n={...qa(e)??{},...e.scheduler??{}},r=e.realtime??{};return {...e,database:Array.isArray(e.database)?e.database:[e.database],kv:e.kv?Array.isArray(e.kv)?e.kv:[e.kv]:[],r2:e.r2?Array.isArray(e.r2)?e.r2:[e.r2]:[],scheduler:{enabled:n.enabled??true,binding:n.binding??"APPFLARE_SCHEDULER_QUEUE",queue:n.queue},realtime:{enabled:r.enabled??true,binding:r.binding??"APPFLARE_REALTIME",className:r.className??"AppflareRealtimeDurableObject",objectName:r.objectName??"global",subscribePath:r.subscribePath??"/realtime/subscribe",websocketPath:r.websocketPath??"/realtime/ws",protocol:r.protocol??"appflare.realtime.v1"},wranglerOverrides:Ma(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function 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=Ia(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 Mn(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
9832
|
+
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
9833
|
+
`);}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}
|
|
9834
|
+
`);}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}
|
|
9835
|
+
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
9836
|
+
`);}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);});
|