appflare 0.2.48 → 0.2.49
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/Documentation.md +898 -898
- package/cli/commands/index.ts +247 -247
- package/cli/generate.ts +360 -360
- package/cli/index.ts +120 -120
- package/cli/load-config.ts +184 -184
- package/cli/schema-compiler.ts +1366 -1366
- package/cli/templates/auth/README.md +156 -156
- package/cli/templates/auth/config.ts +61 -61
- package/cli/templates/auth/route-config.ts +1 -1
- package/cli/templates/auth/route-handler.ts +1 -1
- package/cli/templates/auth/route-request-utils.ts +5 -5
- package/cli/templates/auth/route.config.ts +18 -18
- package/cli/templates/auth/route.handler.ts +18 -18
- package/cli/templates/auth/route.request-utils.ts +55 -55
- package/cli/templates/auth/route.ts +14 -14
- package/cli/templates/core/README.md +266 -266
- package/cli/templates/core/app-creation.ts +19 -19
- package/cli/templates/core/client/appflare.ts +112 -112
- package/cli/templates/core/client/handlers/index.ts +763 -763
- package/cli/templates/core/client/handlers.ts +1 -1
- package/cli/templates/core/client/index.ts +7 -7
- package/cli/templates/core/client/storage.ts +195 -195
- package/cli/templates/core/client/types.ts +187 -187
- package/cli/templates/core/client-modules/appflare.ts +1 -1
- package/cli/templates/core/client-modules/handlers.ts +1 -1
- package/cli/templates/core/client-modules/index.ts +1 -1
- package/cli/templates/core/client-modules/storage.ts +1 -1
- package/cli/templates/core/client-modules/types.ts +1 -1
- package/cli/templates/core/client.artifacts.ts +39 -39
- package/cli/templates/core/client.ts +4 -4
- package/cli/templates/core/drizzle.ts +15 -15
- package/cli/templates/core/export.ts +14 -14
- package/cli/templates/core/handlers.route.ts +24 -24
- package/cli/templates/core/handlers.ts +1 -1
- package/cli/templates/core/imports.ts +9 -9
- package/cli/templates/core/server.ts +38 -38
- package/cli/templates/core/types.ts +6 -6
- package/cli/templates/core/wrangler.ts +109 -109
- package/cli/templates/dashboard/builders/functions/index.ts +17 -17
- package/cli/templates/dashboard/builders/functions/render-page/header.ts +20 -20
- package/cli/templates/dashboard/builders/functions/render-page/index.ts +33 -33
- package/cli/templates/dashboard/builders/functions/render-page/request-panel.ts +271 -271
- package/cli/templates/dashboard/builders/functions/render-page/result-panel.ts +85 -85
- package/cli/templates/dashboard/builders/functions/render-page/scripts.ts +703 -703
- package/cli/templates/dashboard/builders/functions/tree-builder.ts +47 -47
- package/cli/templates/dashboard/builders/navigation.ts +155 -155
- package/cli/templates/dashboard/builders/storage/index.ts +13 -13
- package/cli/templates/dashboard/builders/storage/routes/create-directory-route.ts +29 -29
- package/cli/templates/dashboard/builders/storage/routes/delete-route.ts +18 -18
- package/cli/templates/dashboard/builders/storage/routes/download-route.ts +23 -23
- package/cli/templates/dashboard/builders/storage/routes/index.ts +22 -22
- package/cli/templates/dashboard/builders/storage/routes/list-route.ts +25 -25
- package/cli/templates/dashboard/builders/storage/routes/preview-route.ts +21 -21
- package/cli/templates/dashboard/builders/storage/routes/upload-route.ts +21 -21
- package/cli/templates/dashboard/builders/storage/runtime/helpers.ts +72 -72
- package/cli/templates/dashboard/builders/storage/runtime/storage-page.ts +130 -130
- package/cli/templates/dashboard/builders/table-routes/common/drawer-panel.ts +27 -27
- package/cli/templates/dashboard/builders/table-routes/common/pagination.ts +30 -30
- package/cli/templates/dashboard/builders/table-routes/common/search-bar.ts +23 -23
- package/cli/templates/dashboard/builders/table-routes/fragments.ts +257 -217
- package/cli/templates/dashboard/builders/table-routes/helpers.ts +45 -45
- package/cli/templates/dashboard/builders/table-routes/index.ts +8 -8
- package/cli/templates/dashboard/builders/table-routes/table/actions-cell.ts +71 -71
- package/cli/templates/dashboard/builders/table-routes/table/get-route.ts +291 -291
- package/cli/templates/dashboard/builders/table-routes/table/index.ts +80 -80
- package/cli/templates/dashboard/builders/table-routes/table/post-routes.ts +163 -163
- package/cli/templates/dashboard/builders/table-routes/table-route.ts +7 -7
- package/cli/templates/dashboard/builders/table-routes/users/get-route.ts +69 -69
- package/cli/templates/dashboard/builders/table-routes/users/html/modals.ts +57 -57
- package/cli/templates/dashboard/builders/table-routes/users/html/page.ts +27 -27
- package/cli/templates/dashboard/builders/table-routes/users/html/table.ts +128 -128
- package/cli/templates/dashboard/builders/table-routes/users/index.ts +32 -32
- package/cli/templates/dashboard/builders/table-routes/users/post-routes.ts +150 -150
- package/cli/templates/dashboard/builders/table-routes/users/redirect.ts +14 -14
- package/cli/templates/dashboard/builders/table-routes/users-route.ts +10 -10
- package/cli/templates/dashboard/components/dashboard-home.ts +23 -23
- package/cli/templates/dashboard/components/layout.ts +420 -420
- package/cli/templates/dashboard/components/login-page.ts +65 -65
- package/cli/templates/dashboard/index.ts +61 -61
- package/cli/templates/dashboard/types.ts +9 -9
- package/cli/templates/handlers/README.md +353 -353
- package/cli/templates/handlers/auth.ts +37 -37
- package/cli/templates/handlers/execution.ts +44 -42
- package/cli/templates/handlers/generators/context/context-creation.ts +101 -101
- package/cli/templates/handlers/generators/context/error-helpers.ts +11 -11
- package/cli/templates/handlers/generators/context/scheduler.ts +24 -24
- package/cli/templates/handlers/generators/context/storage-api.ts +82 -82
- package/cli/templates/handlers/generators/context/storage-helpers.ts +59 -59
- package/cli/templates/handlers/generators/context/types.ts +40 -40
- package/cli/templates/handlers/generators/context.ts +43 -43
- package/cli/templates/handlers/generators/execution.ts +15 -15
- package/cli/templates/handlers/generators/handlers.ts +14 -14
- package/cli/templates/handlers/generators/registration/modules/cron.ts +35 -35
- package/cli/templates/handlers/generators/registration/modules/realtime/auth.ts +75 -75
- package/cli/templates/handlers/generators/registration/modules/realtime/durable-object.ts +144 -144
- package/cli/templates/handlers/generators/registration/modules/realtime/index.ts +14 -14
- package/cli/templates/handlers/generators/registration/modules/realtime/publisher.ts +102 -102
- package/cli/templates/handlers/generators/registration/modules/realtime/routes.ts +164 -164
- package/cli/templates/handlers/generators/registration/modules/realtime/types.ts +30 -30
- package/cli/templates/handlers/generators/registration/modules/realtime/utils.ts +510 -510
- package/cli/templates/handlers/generators/registration/modules/scheduler.ts +65 -65
- package/cli/templates/handlers/generators/registration/modules/storage.ts +199 -199
- package/cli/templates/handlers/generators/registration/sections.ts +210 -210
- package/cli/templates/handlers/generators/types/context.ts +121 -121
- package/cli/templates/handlers/generators/types/core.ts +108 -108
- package/cli/templates/handlers/generators/types/operations.ts +135 -135
- package/cli/templates/handlers/generators/types/query-definitions/filter-and-where-types.ts +291 -291
- package/cli/templates/handlers/generators/types/query-definitions/query-api-types.ts +135 -135
- package/cli/templates/handlers/generators/types/query-definitions/query-helper-functions.ts +1382 -1382
- package/cli/templates/handlers/generators/types/query-definitions/schema-and-table-types.ts +278 -278
- package/cli/templates/handlers/generators/types/query-definitions.ts +13 -13
- package/cli/templates/handlers/generators/types/query-runtime/handled-error.ts +13 -13
- package/cli/templates/handlers/generators/types/query-runtime/runtime-aggregate-and-footer.ts +174 -174
- package/cli/templates/handlers/generators/types/query-runtime/runtime-read.ts +156 -156
- package/cli/templates/handlers/generators/types/query-runtime/runtime-setup.ts +45 -45
- package/cli/templates/handlers/generators/types/query-runtime/runtime-write.ts +958 -958
- package/cli/templates/handlers/generators/types/query-runtime.ts +15 -15
- package/cli/templates/handlers/index.ts +47 -47
- package/cli/templates/handlers/operations.ts +116 -116
- package/cli/templates/handlers/registration.ts +91 -91
- package/cli/templates/handlers/types.ts +17 -17
- package/cli/templates/handlers/utils.ts +48 -48
- package/cli/types.ts +110 -110
- package/cli/utils/handler-discovery.ts +501 -501
- package/cli/utils/json-utils.ts +24 -24
- package/cli/utils/path-utils.ts +19 -19
- package/cli/utils/schema-discovery.ts +402 -399
- package/dist/cli/index.js +77 -55
- package/dist/cli/index.mjs +77 -55
- package/index.ts +18 -18
- package/package.json +58 -58
- package/react/index.ts +5 -5
- package/react/use-infinite-query.ts +255 -255
- package/react/use-mutation.ts +89 -89
- package/react/use-query.ts +210 -210
- package/schema.ts +641 -641
- package/test-better-auth-hash.ts +2 -2
- package/tsconfig.json +6 -6
- package/tsup.config.ts +82 -82
package/dist/cli/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import {Command}from'commander';import
|
|
2
|
+
import {Command}from'commander';import Ia from'chokidar';import {existsSync}from'fs';import {resolve,isAbsolute,dirname,join,relative,extname}from'path';import {mkdir,readdir,rm}from'fs/promises';import {pathToFileURL,fileURLToPath}from'url';import*as f from'typescript';import {z}from'zod';function ve(e){return `import { betterAuth } from "better-auth";
|
|
3
3
|
import { withCloudflare } from "better-auth-cloudflare";
|
|
4
4
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
5
5
|
import { drizzle } from "drizzle-orm/d1";
|
|
@@ -57,7 +57,7 @@ export const createAuth = (
|
|
|
57
57
|
});
|
|
58
58
|
};
|
|
59
59
|
export const auth = createAuth();
|
|
60
|
-
`}function
|
|
60
|
+
`}function Te(){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
61
61
|
import type {
|
|
62
62
|
AppflareAuth,
|
|
63
63
|
AppflareAuthTokenResolver,
|
|
@@ -1122,7 +1122,7 @@ export type RealtimeSubscriptionResponse = {
|
|
|
1122
1122
|
};
|
|
1123
1123
|
};
|
|
1124
1124
|
};
|
|
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:
|
|
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:Te()}]}function Ce(e){return `import { defineConfig } from "drizzle-kit";
|
|
1126
1126
|
|
|
1127
1127
|
export default defineConfig({
|
|
1128
1128
|
dialect: "sqlite",
|
|
@@ -1205,7 +1205,7 @@ type R2BucketBinding = {
|
|
|
1205
1205
|
options?: { expiresIn?: number },
|
|
1206
1206
|
) => Promise<URL>;
|
|
1207
1207
|
};
|
|
1208
|
-
`}function
|
|
1208
|
+
`}function je(){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 Me(){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 Ie(){return `
|
|
1238
1238
|
function normalizeStoragePath(path: string): string {
|
|
1239
1239
|
const trimmed = path.trim();
|
|
1240
1240
|
if (trimmed.length === 0) {
|
|
@@ -1490,12 +1490,12 @@ ${qe()}
|
|
|
1490
1490
|
|
|
1491
1491
|
${Fe()}
|
|
1492
1492
|
|
|
1493
|
+
${je()}
|
|
1494
|
+
|
|
1493
1495
|
${Me()}
|
|
1494
1496
|
|
|
1495
1497
|
${Ie()}
|
|
1496
1498
|
|
|
1497
|
-
${je()}
|
|
1498
|
-
|
|
1499
1499
|
${Ee()}
|
|
1500
1500
|
|
|
1501
1501
|
${Pe(e)}
|
|
@@ -1527,6 +1527,8 @@ export function handleOperationError(
|
|
|
1527
1527
|
error: unknown,
|
|
1528
1528
|
validationMessage: string,
|
|
1529
1529
|
): Response {
|
|
1530
|
+
console.log(error);
|
|
1531
|
+
|
|
1530
1532
|
if (error instanceof AppflareHandledError) {
|
|
1531
1533
|
return c.json(error.payload, error.status as any);
|
|
1532
1534
|
}
|
|
@@ -3729,7 +3731,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3729
3731
|
>;
|
|
3730
3732
|
`}function Ue(){return [ze(),We(),He(),Le()].join(`
|
|
3731
3733
|
|
|
3732
|
-
`)}function
|
|
3734
|
+
`)}function _e(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3733
3735
|
const withValue = args?.with;
|
|
3734
3736
|
const pathSegments = args?.field
|
|
3735
3737
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -3900,7 +3902,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3900
3902
|
},
|
|
3901
3903
|
}) as AppflareQueryDb;
|
|
3902
3904
|
}
|
|
3903
|
-
`}function
|
|
3905
|
+
`}function Qe(){return `export class AppflareHandledError extends Error {
|
|
3904
3906
|
public readonly status: number;
|
|
3905
3907
|
public readonly payload: unknown;
|
|
3906
3908
|
|
|
@@ -5061,7 +5063,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
5061
5063
|
);
|
|
5062
5064
|
return rows;
|
|
5063
5065
|
},
|
|
5064
|
-
`}function Ze(){return [Je(),Ke(),Ge(),
|
|
5066
|
+
`}function Ze(){return [Je(),Ke(),Ge(),_e(),Qe()].join(`
|
|
5065
5067
|
|
|
5066
5068
|
`)}function Xe(e=[],t=[]){let n=t.map(i=>` ${i.name}?: ${i.tsType} | null;`).join(`
|
|
5067
5069
|
`),a=[e.length>0?[" role: UserRole;"," banned: boolean | null;"," banReason?: string | null | undefined;"," banExpires?: Date | null | undefined;"].join(`
|
|
@@ -6744,9 +6746,9 @@ export function registerGeneratedHandlers(
|
|
|
6744
6746
|
${ct}
|
|
6745
6747
|
|
|
6746
6748
|
${pt}
|
|
6747
|
-
`}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
|
|
6749
|
+
`}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 vr(e){return e?`,
|
|
6748
6750
|
KV: c.env["${e}"] as KVNamespace`:""}function ft(e,t){return `{
|
|
6749
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6751
|
+
DATABASE: c.env["${e}"] as D1Database${vr(t)}
|
|
6750
6752
|
}`}function gt(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6751
6753
|
const auth = createAuth(
|
|
6752
6754
|
${ft(t,n)},
|
|
@@ -6754,7 +6756,7 @@ ${pt}
|
|
|
6754
6756
|
);
|
|
6755
6757
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6756
6758
|
});
|
|
6757
|
-
`}function
|
|
6759
|
+
`}function Tr(){return `export const getHeaders = (headers: Headers) => {
|
|
6758
6760
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6759
6761
|
const headerObject: Record<string, any> = {};
|
|
6760
6762
|
let hasCookie = false;
|
|
@@ -6790,7 +6792,7 @@ ${pt}
|
|
|
6790
6792
|
});
|
|
6791
6793
|
return newRequest;
|
|
6792
6794
|
};
|
|
6793
|
-
`}function ht(){return
|
|
6795
|
+
`}function ht(){return Tr()+`
|
|
6794
6796
|
`+Rr()}function yt(e,t,n){return gt(e,t,n)+`
|
|
6795
6797
|
`+ht()}function bt(){return `const app = new Hono<WorkerEnv>();
|
|
6796
6798
|
|
|
@@ -6833,16 +6835,16 @@ export default {
|
|
|
6833
6835
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6834
6836
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
6835
6837
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
6836
|
-
`}function
|
|
6838
|
+
`}function vt(){return `import { createAuth } from "./auth.config";
|
|
6837
6839
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
6838
6840
|
import { registerAdminDashboard } from "./admin.routes";
|
|
6839
6841
|
import { Hono } from "hono";
|
|
6840
6842
|
import { cors } from "hono/cors";
|
|
6841
6843
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6842
|
-
`}function
|
|
6844
|
+
`}function Tt(){return `type WorkerEnv = {
|
|
6843
6845
|
Bindings: Record<string, unknown>;
|
|
6844
6846
|
};
|
|
6845
|
-
`}function Rt(e,t,n,r,a,o,i,s,c,l){return
|
|
6847
|
+
`}function Rt(e,t,n,r,a,o,i,s,c,l){return vt()+Tt()+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">
|
|
6846
6848
|
<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">
|
|
6847
6849
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6848
6850
|
<span class="truncate">users</span>
|
|
@@ -6917,7 +6919,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6917
6919
|
</a>
|
|
6918
6920
|
`.replace(/\n/g,"\\n")).join("")}function Ft(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
6919
6921
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6920
|
-
`).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 `
|
|
6922
|
+
`).join("")}function Sr(e){switch(e){case "number":return "mdi:pound";case "boolean":return "mdi:toggle-switch-outline";case "date":return "mdi:calendar";case "json":return "mdi:code-braces";default:return "mdi:format-text"}}function 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 `
|
|
6921
6923
|
<th>
|
|
6922
6924
|
<a href="#"
|
|
6923
6925
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -6929,7 +6931,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6929
6931
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6930
6932
|
</a>
|
|
6931
6933
|
</th>
|
|
6932
|
-
`}).join("")}function
|
|
6934
|
+
`}).join("")}function jt(e,t,n){return t.map(r=>{let a=e.columns.find(o=>o.name===r);return n&&r===n?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${r} ?? '')}" data-copy-value="\${String((row as any).${r} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${r} ?? '')}</button></td>`:a?.type==="json"?`<td>\${raw((() => { const __v = (row as any).${r}; if (__v === null || __v === undefined) return '<span class="opacity-30 text-xs">null</span>'; if (Array.isArray(__v)) { if (__v.length === 0) return '<span class="badge badge-ghost badge-sm font-mono text-xs">[ ]</span>'; return '<div class="flex flex-wrap gap-1 max-w-[200px]">' + __v.slice(0, 3).map((item) => '<span class="badge badge-ghost badge-xs font-mono">' + (typeof item === 'object' && item !== null ? JSON.stringify(item).slice(0, 20) + (JSON.stringify(item).length > 20 ? '\u2026' : '') : String(item ?? '')) + '</span>').join('') + (__v.length > 3 ? '<span class="badge badge-ghost badge-xs opacity-50">+' + (__v.length - 3) + '</span>' : '') + '</div>'; } if (typeof __v === 'object') { const __s = JSON.stringify(__v); return '<span class="badge badge-outline badge-sm font-mono text-[10px]">' + __s.slice(0, 50) + (__s.length > 50 ? '\u2026' : '') + '</span>'; } return String(__v ?? ''); })())}</td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${r} ?? '')}">\${String((row as any).${r} ?? '')}</div></td>`}).join("")}function 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"?`
|
|
6933
6935
|
<div class="form-control">
|
|
6934
6936
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6935
6937
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6943,6 +6945,16 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6943
6945
|
<span class="label-text text-sm">${t}</span>
|
|
6944
6946
|
</label>
|
|
6945
6947
|
</div>
|
|
6948
|
+
`;if(r.type==="json")return n==="edit"?`
|
|
6949
|
+
<div class="form-control">
|
|
6950
|
+
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6951
|
+
<textarea name="${t}" class="textarea textarea-bordered w-full font-mono text-xs h-32"${a}>\${typeof (row as any).${t} === 'string' ? (row as any).${t} : JSON.stringify((row as any).${t} ?? null, null, 2)}</textarea>
|
|
6952
|
+
</div>
|
|
6953
|
+
`:`
|
|
6954
|
+
<div class="form-control">
|
|
6955
|
+
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6956
|
+
<textarea name="${t}" class="textarea textarea-bordered w-full font-mono text-xs h-32" placeholder="null"${a}></textarea>
|
|
6957
|
+
</div>
|
|
6946
6958
|
`;if(n==="edit"){let i=r.type==="date"?`\${(() => {
|
|
6947
6959
|
const value = (row as any).${t};
|
|
6948
6960
|
if (value == null || value === '') return '';
|
|
@@ -6984,6 +6996,16 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6984
6996
|
`:r.type==="boolean"?`
|
|
6985
6997
|
const raw_${n} = getValue(body['${n}']);
|
|
6986
6998
|
payload.${n} = raw_${n} === 'true' || raw_${n} === 'on' || raw_${n} === '1';
|
|
6999
|
+
`:r.type==="json"?`
|
|
7000
|
+
const raw_${n} = getValue(body['${n}']);
|
|
7001
|
+
${a}
|
|
7002
|
+
if (raw_${n} !== '') {
|
|
7003
|
+
try {
|
|
7004
|
+
payload.${n} = JSON.parse(raw_${n});
|
|
7005
|
+
} catch (e) {
|
|
7006
|
+
return c.text('${n} must be valid JSON', 400);
|
|
7007
|
+
}
|
|
7008
|
+
}
|
|
6987
7009
|
`:r.type==="date"?`
|
|
6988
7010
|
const raw_${n} = getValue(body['${n}']);
|
|
6989
7011
|
${a}
|
|
@@ -7012,7 +7034,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7012
7034
|
payload.${n} = raw_${n};
|
|
7013
7035
|
}
|
|
7014
7036
|
`}).join(`
|
|
7015
|
-
`)}function
|
|
7037
|
+
`)}function Mt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function It(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function 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">
|
|
7016
7038
|
<div class="drawer drawer-end">
|
|
7017
7039
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
7018
7040
|
<div class="drawer-content">
|
|
@@ -7098,7 +7120,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7098
7120
|
hx-trigger="keyup changed delay:500ms, search"
|
|
7099
7121
|
hx-target="#main-content"
|
|
7100
7122
|
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" />
|
|
7101
|
-
</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>',
|
|
7123
|
+
</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>',T=r?`
|
|
7102
7124
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
7103
7125
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
7104
7126
|
<div class="text-xs text-base-content/70">
|
|
@@ -7317,7 +7339,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7317
7339
|
${p}
|
|
7318
7340
|
</div>
|
|
7319
7341
|
\${tableHtml}
|
|
7320
|
-
${
|
|
7342
|
+
${T}
|
|
7321
7343
|
</div>
|
|
7322
7344
|
<div class="drawer-side z-50">
|
|
7323
7345
|
<label for="create-drawer-${e.exportName}" aria-label="close sidebar" class="drawer-overlay"></label>
|
|
@@ -7483,8 +7505,8 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7483
7505
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7484
7506
|
});
|
|
7485
7507
|
${u}
|
|
7486
|
-
`}function re(e){let t=
|
|
7487
|
-
`+Dt(e.exportName,y,t,
|
|
7508
|
+
`}function re(e){let t=Mt(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>It(e,w)),o=r.filter(w=>Et(e,w)),i=Ft(e),s=qt(e,r),c=jt(e,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",T=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)+`
|
|
7509
|
+
`+Dt(e.exportName,y,t,T,n,i,p,d)}function Vt(){return `
|
|
7488
7510
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7489
7511
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
7490
7512
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
@@ -7849,9 +7871,9 @@ ${Wt()}
|
|
|
7849
7871
|
${zt()}
|
|
7850
7872
|
|
|
7851
7873
|
${Ut()}
|
|
7852
|
-
`}function
|
|
7874
|
+
`}function _t(e){return `${e.tables.map(t=>re(t)).join(`
|
|
7853
7875
|
`)}
|
|
7854
|
-
${ae()}`}function
|
|
7876
|
+
${ae()}`}function Qt(e){return `
|
|
7855
7877
|
<div class="flex items-center justify-between">
|
|
7856
7878
|
<div class="flex items-center gap-3">
|
|
7857
7879
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7957,7 +7979,7 @@ ${ae()}`}function _t(e){return `
|
|
|
7957
7979
|
${r.optional?"":"required"}
|
|
7958
7980
|
/>
|
|
7959
7981
|
</div>`}).join(`
|
|
7960
|
-
`)}function
|
|
7982
|
+
`)}function jr(e){return `
|
|
7961
7983
|
<div class="space-y-4">
|
|
7962
7984
|
<div class="flex items-center justify-between">
|
|
7963
7985
|
<div class="flex flex-col">
|
|
@@ -7974,7 +7996,7 @@ ${ae()}`}function _t(e){return `
|
|
|
7974
7996
|
</div>
|
|
7975
7997
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7976
7998
|
</div>
|
|
7977
|
-
`}function
|
|
7999
|
+
`}function Mr(){return `
|
|
7978
8000
|
<div class="space-y-4">
|
|
7979
8001
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7980
8002
|
<div class="relative group">
|
|
@@ -7991,7 +8013,7 @@ ${ae()}`}function _t(e){return `
|
|
|
7991
8013
|
</div>
|
|
7992
8014
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7993
8015
|
</div>
|
|
7994
|
-
`}function
|
|
8016
|
+
`}function Ir(){return `
|
|
7995
8017
|
<div class="space-y-4">
|
|
7996
8018
|
<div class="flex items-center justify-between">
|
|
7997
8019
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -8026,13 +8048,13 @@ ${ae()}`}function _t(e){return `
|
|
|
8026
8048
|
<!-- Tab Content -->
|
|
8027
8049
|
<div class="flex-1 overflow-y-auto">
|
|
8028
8050
|
<div id="request-tab-args" class="p-5">
|
|
8029
|
-
${
|
|
8051
|
+
${jr(e)}
|
|
8030
8052
|
</div>
|
|
8031
8053
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
8032
|
-
${
|
|
8054
|
+
${Mr()}
|
|
8033
8055
|
</div>
|
|
8034
8056
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
8035
|
-
${
|
|
8057
|
+
${Ir()}
|
|
8036
8058
|
</div>
|
|
8037
8059
|
</div>
|
|
8038
8060
|
|
|
@@ -8826,7 +8848,7 @@ ${ae()}`}function _t(e){return `
|
|
|
8826
8848
|
`}function Zt(e){return `
|
|
8827
8849
|
const content = html\`
|
|
8828
8850
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
8829
|
-
${
|
|
8851
|
+
${Qt(e)}
|
|
8830
8852
|
|
|
8831
8853
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
8832
8854
|
<!-- Request Panel -->
|
|
@@ -9667,7 +9689,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9667
9689
|
\`
|
|
9668
9690
|
}));
|
|
9669
9691
|
});
|
|
9670
|
-
`}function mn(e,t,n){let r=At(t),a=Nt(r),o=Ct(r),i=
|
|
9692
|
+
`}function mn(e,t,n){let r=At(t),a=Nt(r),o=Ct(r),i=_t(t),s=Xt(n),c=un(),l=cn(a,n),u=dn(),p=pn(o);return `import { Hono } from "hono";
|
|
9671
9693
|
import { html, raw } from "hono/html";
|
|
9672
9694
|
import { drizzle } from "drizzle-orm/d1";
|
|
9673
9695
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -9696,8 +9718,8 @@ ${p}
|
|
|
9696
9718
|
app.route('/admin', adminApp);
|
|
9697
9719
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
9698
9720
|
}
|
|
9699
|
-
`}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
|
|
9700
|
-
`}function
|
|
9721
|
+
`}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 _r(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
9722
|
+
`}function Qr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function Kr(e,t,n){if(t.references)return {tableName:t.references.table,fieldName:t.references.column};let r=Object.values(n.relations).find(a=>a.relation==="one"&&a.field===e);if(r)return {tableName:r.targetTable,fieldName:r.referenceField??"id"}}function Jr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.columns)){if(i.type!=="json"||!i.jsonShape)continue;let s=ue(i.jsonShape);a.push(`${g(o)}: { shape: ${s} },`);}a.length!==0&&t.push(`${g(n)}: {
|
|
9701
9723
|
${a.map(o=>` ${o}`).join(`
|
|
9702
9724
|
`)}
|
|
9703
9725
|
},`);}return t.length===0?`export const __appflareJsonColumns = {} as const;
|
|
@@ -9746,7 +9768,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9746
9768
|
${t.map(n=>` ${n}`).join(`
|
|
9747
9769
|
`)}
|
|
9748
9770
|
} as const;
|
|
9749
|
-
`}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
|
|
9771
|
+
`}function Xr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let l of Object.values(e.tables)){for(let u of Qr(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 v;if(h.type==="enum"&&h.enumValues&&h.enumValues.length>0){let R=h.enumRef??`${l}_${b}`,I=q(R),V=h.sqlName??P(b);v=V!==b?`${I}Column(${g(V)})`:`${I}Column()`,h.isArray&&(v+=".array()");}else v=zr(b,h,t);h.uuidPrimaryKey&&(v+=".$defaultFn(() => crypto.randomUUID())"),h.primaryKey&&(v+=h.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),h.notNull&&(v+=".notNull()"),h.sqlDefault!==void 0&&(v+=`.default(${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)}`),v+=`.references(() => ${C.tableName}.${C.fieldName}, { ${R.join(", ")} })`;}else v+=`.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}: ${v},`);}y.length>0?s.push(`export const ${l} = table(
|
|
9750
9772
|
${g(p)},
|
|
9751
9773
|
{
|
|
9752
9774
|
${d.join(`
|
|
@@ -9759,16 +9781,16 @@ ${y.join(`,
|
|
|
9759
9781
|
);`):s.push(`export const ${l} = table(${g(p)}, {
|
|
9760
9782
|
${d.join(`
|
|
9761
9783
|
`)}
|
|
9762
|
-
});`);let
|
|
9763
|
-
fields: [${l}.${
|
|
9764
|
-
references: [${h.targetTable}.${
|
|
9765
|
-
}),`);}for(let[b,h]of A)
|
|
9766
|
-
${
|
|
9784
|
+
});`);let T=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(T.length===0&&A.length===0&&w.length===0)continue;let M=[];for(let[b,h]of T){let v=Ur(l,u,h);M.push(` ${b}: one(${h.targetTable}, {
|
|
9785
|
+
fields: [${l}.${v.sourceField}],
|
|
9786
|
+
references: [${h.targetTable}.${v.targetField}],
|
|
9787
|
+
}),`);}for(let[b,h]of A)M.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of w){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);M.push(` ${b}: many(${h.junctionTable}),`);}c.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
9788
|
+
${M.join(`
|
|
9767
9789
|
`)}
|
|
9768
9790
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9769
9791
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
9770
9792
|
import { relations } from "drizzle-orm";
|
|
9771
|
-
${
|
|
9793
|
+
${_r(r)}
|
|
9772
9794
|
${o.join(`
|
|
9773
9795
|
`)}
|
|
9774
9796
|
${i.join(`
|
|
@@ -9814,14 +9836,14 @@ ${s.join(`
|
|
|
9814
9836
|
${n.join(`
|
|
9815
9837
|
|
|
9816
9838
|
`)}
|
|
9817
|
-
`}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=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),l=na(c,t.exportName),u=Lr(l);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(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(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 readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await kn(a));continue}r.isFile()&&la.has(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.isCallExpression(n);){let l=n.expression;if(!f.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.isStringLiteral(p)||f.isNumericLiteral(p)?a=p.text:p.kind===f.SyntaxKind.TrueKeyword?a="true":p.kind===f.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.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f.isPropertyAssignment(d)&&f.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.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f.isPropertyAssignment(r)&&f.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f.isPropertyAssignment(r)||!f.isIdentifier(r.name)||n.push(de(r.initializer,r.name.text));return n}function ca(e){return f.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f.SyntaxKind.ExportKeyword)??false:false}function Sn(e){return f.isIdentifier(e)?e.text:f.isParenthesizedExpression(e)?Sn(e.expression):null}function da(e){if(!e||!f.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f.isPropertyAssignment(r)||!f.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f.isPropertyAssignment(t))return [];let n=t.initializer;return f.isStringLiteral(n)||f.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f.isArrayLiteralExpression(n)?n.elements.map(r=>f.isStringLiteral(r)||f.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function pa(e,t){let n=f.createSourceFile(t,e,f.ScriptTarget.Latest,true,f.ScriptKind.TS),r=[];for(let a of n.statements)if(ca(a))for(let o of a.declarationList.declarations){if(!f.isIdentifier(o.name)||!o.initializer||!f.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=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(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 readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=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=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
|
|
9818
|
-
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=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function
|
|
9819
|
-
`);let u=dirname(fileURLToPath(import.meta.url)),p=join(dirname(Bun.resolveSync("typescript/package.json",u)),"bin","tsc"),d=join(dirname(Bun.resolveSync("@better-auth/cli/package.json",u)),"dist","index.mjs"),y=resolve(t,"server.ts"),
|
|
9820
|
-
`);let
|
|
9821
|
-
`),...Zn,...Gn,Bun.write(A,zn),Bun.write(w,""),Bun.write(
|
|
9839
|
+
`}function na(e,t){if(t){let n=e[t];if(!oe(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(oe(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function xn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),l=na(c,t.exportName),u=Lr(l);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let p=Xr(u,n),d=ta(u),y=Yr(u);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(u.tables)}}function aa(e){return e.replaceAll("\\","/")}function j(e,t){let n=aa(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 readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await kn(a));continue}r.isFile()&&la.has(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.isCallExpression(n);){let l=n.expression;if(!f.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.isStringLiteral(p)||f.isNumericLiteral(p)?a=p.text:p.kind===f.SyntaxKind.TrueKeyword?a="true":p.kind===f.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.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f.isPropertyAssignment(d)&&f.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.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f.isPropertyAssignment(r)&&f.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f.isPropertyAssignment(r)||!f.isIdentifier(r.name)||n.push(de(r.initializer,r.name.text));return n}function ca(e){return f.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f.SyntaxKind.ExportKeyword)??false:false}function Sn(e){return f.isIdentifier(e)?e.text:f.isParenthesizedExpression(e)?Sn(e.expression):null}function da(e){if(!e||!f.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f.isPropertyAssignment(r)||!f.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f.isPropertyAssignment(t))return [];let n=t.initializer;return f.isStringLiteral(n)||f.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f.isArrayLiteralExpression(n)?n.elements.map(r=>f.isStringLiteral(r)||f.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function pa(e,t){let n=f.createSourceFile(t,e,f.ScriptTarget.Latest,true,f.ScriptKind.TS),r=[];for(let a of n.statements)if(ca(a))for(let o of a.declarationList.declarations){if(!f.isIdentifier(o.name)||!o.initializer||!f.isCallExpression(o.initializer))continue;let i=Sn(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?da(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ua(o.initializer.arguments[0]):[]});}return r}function vn(e,t,n){let r=t.replace(/\\/g,"/"),o=pe(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function ma(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function Tn(e,t){let n=e.replace(/\\/g,"/"),a=pe(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function An(e){let t=[],n=await kn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=relative(e.scanDirAbs,a),c=pa(i,a),l=[{kind:"query",kindDirectory:"queries",exports:c.filter(u=>u.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(u=>u.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(u=>u.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(u=>u.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(u=>u.kind==="storage")}];for(let u of l){if(u.exports.length===0)continue;let p=ma(s,u.kindDirectory);for(let d of u.exports){let y=u.kind==="query"||u.kind==="mutation"?Tn(p,d.exportName):void 0,T=u.kind==="scheduler"||u.kind==="cron"?Tn(p,d.exportName):void 0,A=u.kind==="query"||u.kind==="mutation"?[...pe(p).split("/").filter(Boolean),d.exportName]:void 0,w=u.kind==="query"?vn("queries",p,d.exportName):u.kind==="mutation"?vn("mutations",p,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${T}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:j(e.outDirAbs,a),clientImportPath:j(resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:T,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function ga(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){n+=d,l=false;continue}if(d==="\\"){n+=d,l=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let u=n.trim();return u.length>0&&t.push(u),t}function ha(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let c=0;c<e.length;c+=1){let l=e[c];if(s){s=false;continue}if(l==="\\"){s=true;continue}if(!o&&!i&&l==="'"){a=!a;continue}if(!a&&!i&&l==='"'){o=!o;continue}if(!a&&!o&&l==="`"){i=!i;continue}if(!(a||o||i)){if(l==="("){t+=1;continue}if(l===")"){t-=1;continue}if(l==="{"){n+=1;continue}if(l==="}"){n-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&t===0&&n===0&&r===0)return c}}return -1}function ya(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/mode\s*:\s*["'`]json["'`]/.test(t)||/\.json\s*\(/.test(t)?"json":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ba(e){let t=ga(e),n=[];for(let r of t){let a=ha(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),c=/autoincrement\s*:\s*true/i.test(i),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||c||s;n.push({name:o,expression:i,type:ya(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function wa(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,l=false,u=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!l&&!u&&y==="'"){c=!c;continue}if(!c&&!u&&y==='"'){l=!l;continue}if(!c&&!l&&y==="`"){u=!u;continue}if(!(c||l||u)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let l=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ba(l)}),a=t.exec(e);}return n}async function $n(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=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=resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),c=wa(s);if(c.length>0)return {schemaPath:o,tables:c}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function Ta(e){let t=e.auth.options.plugins;if(!Array.isArray(t))return [];for(let n of t)if(n&&typeof n=="object"){let r=n;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function Ra(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function ka(e,t){let n=await Bun.file(e).text(),r=t.map(o=>`"${o}"`).join(" | "),a=n.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
9840
|
+
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function Sa(e,t){let n=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function jn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=j(t,a),s=resolve(t,"client"),c=j(s,a),l=performance.now();await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]),process.stdout.write(`\u{1F4C1} Directories (${(performance.now()-l).toFixed(0)}ms)
|
|
9841
|
+
`);let u=dirname(fileURLToPath(import.meta.url)),p=join(dirname(Bun.resolveSync("typescript/package.json",u)),"bin","tsc"),d=join(dirname(Bun.resolveSync("@better-auth/cli/package.json",u)),"dist","index.mjs"),y=resolve(t,"server.ts"),T=resolve(t,"client.ts"),A=resolve(t,"auth.config.ts"),w=resolve(t,"auth.schema.ts"),M=resolve(t,"drizzle.config.ts"),b=resolve(n,"wrangler.json"),h=await xn(e),v=await Cn(e,h?[h.schemaPath]:[]),C=j(t,v.schemaPath),R=await An(e);process.stdout.write(`\u{1F50D} ${R.length} handler(s) (${(performance.now()-l).toFixed(0)}ms)
|
|
9842
|
+
`);let I=Ta(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,I,V),zn=ve(i),Un=h?[Sa(o,h.schemaPath),...r.schema.filter(x=>!/(^|\/)schema\.ts$/.test(x))]:r.schema,_n=Ce(Un),Qn=St(e,R),Kn=mn(C,v,R),Jn=resolve(t,"admin.routes.ts"),Gn=Ln.map(x=>Bun.write(resolve(t,x.relativePath),x.source)),Zn=Hn.map(x=>Bun.write(resolve(t,x.relativePath),x.source));await Promise.all([Bun.write(y,he),Bun.write(T,`export * from "./client/index";
|
|
9843
|
+
`),...Zn,...Gn,Bun.write(A,zn),Bun.write(w,""),Bun.write(M,_n),Bun.write(b,`${JSON.stringify(Qn,null,2)}
|
|
9822
9844
|
`),Bun.write(Jn,Kn)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-l).toFixed(0)}ms)
|
|
9823
|
-
`);let
|
|
9824
|
-
`),
|
|
9845
|
+
`);let Q=relative(o,A).replace(/\\/g,"/"),Xn=Q.startsWith(".")?Q:`./${Q}`,K=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)
|
|
9846
|
+
`),I.length>0&&(await ka(w,I),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-l).toFixed(0)}ms)
|
|
9825
9847
|
`));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=resolve(t,"tsconfig.js.json");await Promise.all([Bun.write(be,`${JSON.stringify(er({declaration:true,emitDeclarationOnly:false}),null,2)}
|
|
9826
9848
|
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-l).toFixed(0)}ms)
|
|
9827
9849
|
`);async function tr(x,$){process.stdout.write(`\u2699\uFE0F ${$}... (${(performance.now()-l).toFixed(0)}ms)
|
|
@@ -9830,9 +9852,9 @@ import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["
|
|
|
9830
9852
|
`);let nr=t+"/";async function xe(x){let $=await readdir(x,{withFileTypes:true});for(let k of $){let N=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 rm(N);}}await xe(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-l).toFixed(0)}ms)
|
|
9831
9853
|
`);let rr=resolve(o,"tsconfig.json");if(e.config.build&&existsSync(rr)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-l).toFixed(0)}ms)
|
|
9832
9854
|
`);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)
|
|
9833
|
-
`);}}var
|
|
9855
|
+
`);}}var Mn=z.object({binding:z.string().min(1),databaseName:z.string().min(1),databaseId:z.string().min(1),previewDatabaseId:z.string().min(1).optional(),migrationsDir:z.string().min(1).optional()}).strict(),In=z.object({binding:z.string().min(1),id:z.string().min(1),previewId:z.string().min(1).optional()}).strict(),En=z.object({binding:z.string().min(1),bucketName:z.string().min(1),previewBucketName:z.string().min(1).optional(),jurisdiction:z.string().min(1).optional()}).strict(),Pn=z.object({enabled:z.boolean().optional(),binding:z.string().min(1).optional(),queue:z.string().min(1).optional()}).strict(),Ca=z.object({enabled:z.boolean().optional(),binding:z.string().min(1).optional(),className:z.string().min(1).optional(),objectName:z.string().min(1).optional(),subscribePath:z.string().min(1).optional(),websocketPath:z.string().min(1).optional(),protocol:z.string().min(1).optional()}).strict(),Fa=z.object({scanDir:z.string().min(1),outDir:z.string().min(1),wranglerOutDir:z.string().min(1).optional(),wranglerOutPath:z.string().min(1).optional(),schema:z.array(z.string()).min(1),schemaDsl:z.object({entry:z.string().min(1),exportName:z.string().min(1).optional(),outFile:z.string().min(1).optional(),typesOutFile:z.string().min(1).optional(),zodOutFile:z.string().min(1).optional(),namingStrategy:z.literal("camelToSnake").optional()}).strict().optional(),database:z.union([Mn,z.array(Mn).min(1)]),kv:z.union([In,z.array(In)]).optional(),r2:z.union([En,z.array(En)]).optional(),auth:z.object({enabled:z.boolean(),basePath:z.string().min(1),options:z.custom(e=>typeof e=="object"&&e!==null),clientOptions:z.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:Pn.optional(),realtime:Ca.optional(),wranglerOverrides:z.record(z.string(),z.unknown()).optional(),build: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 ja(e){if(!On(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function Ma(e){let n={...qa(e)??{},...e.scheduler??{}},r=e.realtime??{};return {...e,database:Array.isArray(e.database)?e.database:[e.database],kv:e.kv?Array.isArray(e.kv)?e.kv:[e.kv]:[],r2:e.r2?Array.isArray(e.r2)?e.r2:[e.r2]:[],scheduler:{enabled:n.enabled??true,binding:n.binding??"APPFLARE_SCHEDULER_QUEUE",queue:n.queue},realtime:{enabled:r.enabled??true,binding:r.binding??"APPFLARE_REALTIME",className:r.className??"AppflareRealtimeDurableObject",objectName:r.objectName??"global",subscribePath:r.subscribePath??"/realtime/subscribe",websocketPath:r.websocketPath??"/realtime/ws",protocol:r.protocol??"appflare.realtime.v1"},wranglerOverrides:ja(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function D(e){let t=isAbsolute(e??"")?e:resolve(process.cwd(),e??"appflare.config.ts"),n=dirname(t),o=(await import(pathToFileURL(t).href)).default,i=Fa.parse(o),s=Ma(i);return {configPath:t,configDir:n,scanDirAbs:resolve(n,s.scanDir),outDirAbs:resolve(n,s.outDir),wranglerOutDirAbs:resolve(n,s.wranglerOutDir),config:s}}function Oa(e){let t=e;for(;;){if(existsSync(resolve(t,"package.json")))return t;let n=dirname(t);if(n===t)return e;t=n;}}async function _(e,t={}){let n=await D(e);if(t.build!==void 0&&(n.config.build=t.build),await jn(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
9834
9856
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
9835
|
-
`);}async function Vn(e,t={}){if(await
|
|
9836
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
9857
|
+
`);}async function Vn(e,t={}){if(await _(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 _(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
9858
|
+
`);}finally{r=false,a&&(a=false,await o());}};Ia.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}
|
|
9837
9859
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
9838
|
-
`);}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=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,
|
|
9860
|
+
`);}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=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,T=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${p}`];t.local?T.push("--local"):t.remote&&T.push("--remote");let w=await Bun.spawn(T,{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 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 _(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);});
|
package/index.ts
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
export type {
|
|
2
|
-
AppflareConfig,
|
|
3
|
-
AppflareDatabaseBinding,
|
|
4
|
-
AppflareKVNamespace,
|
|
5
|
-
AppflareR2Bucket,
|
|
6
|
-
LoadedAppflareConfig,
|
|
7
|
-
NormalizedAppflareConfig,
|
|
8
|
-
} from "./cli/types";
|
|
9
|
-
export {
|
|
10
|
-
schema,
|
|
11
|
-
table,
|
|
12
|
-
v,
|
|
13
|
-
isSchemaDefinition,
|
|
14
|
-
type ColumnDefinition,
|
|
15
|
-
type RelationDefinition,
|
|
16
|
-
type SchemaDefinition,
|
|
17
|
-
type TableDefinition,
|
|
18
|
-
} from "./schema";
|
|
1
|
+
export type {
|
|
2
|
+
AppflareConfig,
|
|
3
|
+
AppflareDatabaseBinding,
|
|
4
|
+
AppflareKVNamespace,
|
|
5
|
+
AppflareR2Bucket,
|
|
6
|
+
LoadedAppflareConfig,
|
|
7
|
+
NormalizedAppflareConfig,
|
|
8
|
+
} from "./cli/types";
|
|
9
|
+
export {
|
|
10
|
+
schema,
|
|
11
|
+
table,
|
|
12
|
+
v,
|
|
13
|
+
isSchemaDefinition,
|
|
14
|
+
type ColumnDefinition,
|
|
15
|
+
type RelationDefinition,
|
|
16
|
+
type SchemaDefinition,
|
|
17
|
+
type TableDefinition,
|
|
18
|
+
} from "./schema";
|