appflare 0.2.29 → 0.2.31
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 +758 -758
- package/cli/commands/index.ts +238 -238
- package/cli/generate.ts +178 -178
- package/cli/index.ts +120 -120
- package/cli/load-config.ts +184 -184
- package/cli/schema-compiler.ts +1183 -1183
- 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 +748 -748
- 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 +186 -186
- 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 +171 -171
- package/cli/templates/dashboard/builders/functions/render-page/result-panel.ts +85 -85
- package/cli/templates/dashboard/builders/functions/render-page/scripts.ts +554 -554
- package/cli/templates/dashboard/builders/navigation.ts +122 -122
- 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 +217 -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 +388 -388
- 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 +42 -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 +13 -13
- package/cli/templates/handlers/generators/registration/modules/cron.ts +26 -26
- 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 +516 -516
- package/cli/templates/handlers/generators/registration/modules/scheduler.ts +56 -56
- 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 +92 -92
- package/cli/templates/handlers/generators/types/core.ts +106 -106
- package/cli/templates/handlers/generators/types/operations.ts +135 -135
- package/cli/templates/handlers/generators/types/query-definitions/filter-and-where-types.ts +281 -259
- 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 +1103 -1031
- package/cli/templates/handlers/generators/types/query-definitions/schema-and-table-types.ts +278 -246
- 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 +157 -121
- package/cli/templates/handlers/generators/types/query-runtime/runtime-setup.ts +45 -45
- package/cli/templates/handlers/generators/types/query-runtime/runtime-write.ts +697 -676
- package/cli/templates/handlers/generators/types/query-runtime.ts +15 -15
- package/cli/templates/handlers/index.ts +43 -43
- package/cli/templates/handlers/operations.ts +116 -116
- package/cli/templates/handlers/registration.ts +91 -91
- package/cli/templates/handlers/types.ts +15 -15
- package/cli/templates/handlers/utils.ts +48 -48
- package/cli/types.ts +110 -110
- package/cli/utils/handler-discovery.ts +466 -466
- package/cli/utils/json-utils.ts +24 -24
- package/cli/utils/path-utils.ts +19 -19
- package/cli/utils/schema-discovery.ts +399 -399
- package/dist/cli/index.d.mts +2 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +301 -118
- package/dist/cli/index.mjs +301 -118
- package/index.ts +18 -18
- package/package.json +58 -58
- package/react/index.ts +5 -5
- package/react/use-infinite-query.ts +252 -252
- package/react/use-mutation.ts +89 -89
- package/react/use-query.ts +207 -207
- package/schema.ts +415 -415
- 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
|
@@ -166,8 +166,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
166
166
|
): Appflare<Options> {
|
|
167
167
|
return new Appflare(options);
|
|
168
168
|
}
|
|
169
|
-
`}function
|
|
170
|
-
`)}function
|
|
169
|
+
`}function Pn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function ae(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function En(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function oe(e){let t={children:new Map};for(let n of e){let r=t;for(let a of n.segments){let o=r.children.get(a);o||(o={children:new Map},r.children.set(a,o)),r=o;}r.operation=n;}return t}function B(e,t=1){let n=" ".repeat(t),r=" ".repeat(t+1),a=Array.from(e.children.entries()).sort(([i],[s])=>i.localeCompare(s));if(a.length===0)return e.operation?`${e.operation.alias}Route(runtime)`:"{}";let o=["{"];for(let[i,s]of a)o.push(`${r}${En(i)}: ${B(s,t+1)},`);return e.operation&&(o.push(`${r}run: ${e.operation.alias}Route(runtime).run,`),o.push(`${r}schema: ${e.operation.alias}Route(runtime).schema,`),e.operation.kind==="query"&&o.push(`${r}subscribe: ${e.operation.alias}Route(runtime).subscribe,`)),o.push(`${n}}`),o.join(`
|
|
170
|
+
`)}function Dn(e,t){if(e.kind!=="query"&&e.kind!=="mutation")return null;let n=e.clientSegments&&e.clientSegments.length>0?e.clientSegments:e.routePath.replace(/^\//,"").split("/").filter(Boolean).slice(1);if(n.length===0)return null;let r=Pn(`op_${t}_${e.kind}_${n.join("_")}`);return {kind:e.kind,routePath:e.routePath,queryName:e.handlerName??n.join("/"),segments:n,importPath:e.clientImportPath,exportName:e.exportName,alias:r,schemaConst:`${r}Schema`,typeBase:`${ae(e.kind)}${ae(n.join("_"))}`}}function On(e){let t=`${e.typeBase}Input`,n=`${e.typeBase}Output`,r=`${e.typeBase}Schema`,a=e.kind==="query"?"GET":"POST";return e.kind==="query"?`const ${e.alias}Route = (
|
|
171
171
|
runtime: RequestRuntime,
|
|
172
172
|
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
173
173
|
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
@@ -353,7 +353,7 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
353
353
|
schema: ${r},
|
|
354
354
|
run,
|
|
355
355
|
};
|
|
356
|
-
};`}function
|
|
356
|
+
};`}function V(e){let t=e.map((u,c)=>Dn(u,c)).filter(u=>u!==null),n=t.filter(u=>u.kind==="query"),r=t.filter(u=>u.kind==="mutation"),a=t.map(u=>`import { ${u.exportName} as ${u.alias} } from "${u.importPath}";`).join(`
|
|
357
357
|
`),o=t.map(u=>{let c=`${u.typeBase}Input`,f=`${u.typeBase}Output`,d=`${u.typeBase}Schema`;return `const ${u.schemaConst} = z.object(${u.alias}.definition.args);
|
|
358
358
|
export type ${c} = z.input<typeof ${u.schemaConst}>;
|
|
359
359
|
export type ${f} = Awaited<ReturnType<typeof ${u.alias}.definition.handler>>;
|
|
@@ -361,7 +361,7 @@ export const ${d} = ${u.schemaConst};`}).join(`
|
|
|
361
361
|
|
|
362
362
|
`),i=t.map(u=>On(u)).join(`
|
|
363
363
|
|
|
364
|
-
`),s=
|
|
364
|
+
`),s=B(oe(n)),l=B(oe(r));return `import { z } from "zod";
|
|
365
365
|
import type {
|
|
366
366
|
AppflareErrorMode,
|
|
367
367
|
AppflareRequestError,
|
|
@@ -1116,7 +1116,7 @@ export type RealtimeSubscriptionResponse = {
|
|
|
1116
1116
|
};
|
|
1117
1117
|
};
|
|
1118
1118
|
};
|
|
1119
|
-
`}function ce(e,t){return [{relativePath:"client/index.ts",source:ie()},{relativePath:"client/types.ts",source:le(e)},{relativePath:"client/storage.ts",source:se()},{relativePath:"client/handlers.ts",source:
|
|
1119
|
+
`}function ce(e,t){return [{relativePath:"client/index.ts",source:ie()},{relativePath:"client/types.ts",source:le(e)},{relativePath:"client/storage.ts",source:se()},{relativePath:"client/handlers.ts",source:V(t)},{relativePath:"client/appflare.ts",source:re()}]}function ue(e){return `import { defineConfig } from "drizzle-kit";
|
|
1120
1120
|
|
|
1121
1121
|
export default defineConfig({
|
|
1122
1122
|
dialect: "sqlite",
|
|
@@ -1363,7 +1363,7 @@ function createStorageApi(
|
|
|
1363
1363
|
},
|
|
1364
1364
|
};
|
|
1365
1365
|
}
|
|
1366
|
-
`}function
|
|
1366
|
+
`}function ye(e){return `
|
|
1367
1367
|
export async function createSchedulerExecutionContext(
|
|
1368
1368
|
env: Record<string, unknown>,
|
|
1369
1369
|
options: RegisterHandlersOptions,
|
|
@@ -1461,7 +1461,7 @@ export async function createExecutionContext(
|
|
|
1461
1461
|
ctx.storage = createStorageApi(ctx, storageBucket);
|
|
1462
1462
|
return ctx;
|
|
1463
1463
|
}
|
|
1464
|
-
`}function
|
|
1464
|
+
`}function be(e){return `import type { Context } from "hono";
|
|
1465
1465
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
1466
1466
|
import { createAuth } from "./auth.config";
|
|
1467
1467
|
import {
|
|
@@ -1492,7 +1492,7 @@ ${fe()}
|
|
|
1492
1492
|
|
|
1493
1493
|
${he()}
|
|
1494
1494
|
|
|
1495
|
-
${
|
|
1495
|
+
${ye(e)}
|
|
1496
1496
|
`}function we(){return `
|
|
1497
1497
|
export async function executeOperation<
|
|
1498
1498
|
TShape extends ZodRawShape,
|
|
@@ -1542,7 +1542,7 @@ import {
|
|
|
1542
1542
|
} from "./handlers";
|
|
1543
1543
|
|
|
1544
1544
|
${we()}
|
|
1545
|
-
`}function
|
|
1545
|
+
`}function Te(){return `import { betterAuth } from "better-auth";
|
|
1546
1546
|
import { auth } from "./auth.config";
|
|
1547
1547
|
import {
|
|
1548
1548
|
and,
|
|
@@ -1645,7 +1645,7 @@ export async function isStorageAllowed(
|
|
|
1645
1645
|
|
|
1646
1646
|
return false;
|
|
1647
1647
|
}
|
|
1648
|
-
`}function
|
|
1648
|
+
`}function ve(){return `type Primitive = string | number | boolean | Date;
|
|
1649
1649
|
type NonNil<T> = Exclude<T, null | undefined>;
|
|
1650
1650
|
type Friendly<T> = T extends Date ? Date | number : T;
|
|
1651
1651
|
type Comparable<T> = Friendly<Extract<NonNil<T>, Primitive>>;
|
|
@@ -1712,15 +1712,25 @@ type WhereFieldValue<T, TFieldKey extends string> =
|
|
|
1712
1712
|
| Friendly<NonNil<T>>
|
|
1713
1713
|
| FieldOperators<T, TFieldKey>;
|
|
1714
1714
|
|
|
1715
|
-
|
|
1716
|
-
[K in keyof TModel]?:
|
|
1717
|
-
TModel[K],
|
|
1718
|
-
|
|
1719
|
-
>;
|
|
1715
|
+
type RelationWhereInput<TModel extends Record<string, unknown>, TName extends TableName | any = any> = {
|
|
1716
|
+
[K in keyof TModel]?:
|
|
1717
|
+
| WhereFieldValue<TModel[K], Extract<keyof TModel, string>>
|
|
1718
|
+
| (TModel[K] extends Record<string, unknown> ? RelationWhereInput<TModel[K]> : never);
|
|
1720
1719
|
} & {
|
|
1721
1720
|
geoWithin?: GeoWithinOperandForField<Extract<keyof TModel, string>>;
|
|
1722
1721
|
$geoWithin?: GeoWithinOperandForField<Extract<keyof TModel, string>>;
|
|
1723
|
-
}
|
|
1722
|
+
} & (TName extends TableName ? {
|
|
1723
|
+
[TRelation in keyof NativeFindManyWith<TName>]?: NativeFindManyWith<TName>[TRelation] extends infer TRelationConfig
|
|
1724
|
+
? TRelationConfig extends Record<string, unknown>
|
|
1725
|
+
? RelationWhereInput<
|
|
1726
|
+
RelationModelFromConfig<TRelationConfig>,
|
|
1727
|
+
any
|
|
1728
|
+
>
|
|
1729
|
+
: never
|
|
1730
|
+
: never;
|
|
1731
|
+
} : {});
|
|
1732
|
+
|
|
1733
|
+
export type WhereInput<TModel extends Record<string, unknown>, TName extends TableName | any = any> = RelationWhereInput<TModel, TName>;
|
|
1724
1734
|
|
|
1725
1735
|
type ColumnData<TColumn> = TColumn extends { _: { data: infer TData } }
|
|
1726
1736
|
? TData
|
|
@@ -1736,6 +1746,10 @@ type InferRelationWhereFields<TConfig> = TConfig extends { where?: infer TWhere
|
|
|
1736
1746
|
: never
|
|
1737
1747
|
: never;
|
|
1738
1748
|
|
|
1749
|
+
type InferRelationNativeWith<TConfig> = TConfig extends { with?: infer TWith }
|
|
1750
|
+
? TWith
|
|
1751
|
+
: never;
|
|
1752
|
+
|
|
1739
1753
|
type RelationModelFromConfig<TConfig extends Record<string, unknown>> =
|
|
1740
1754
|
InferRelationWhereFields<TConfig> extends infer TFields
|
|
1741
1755
|
? TFields extends Record<string, unknown>
|
|
@@ -1760,15 +1774,15 @@ type RelationAggregateSelectionInput<TModel extends Record<string, unknown>> = {
|
|
|
1760
1774
|
_avg?: RelationAvgSelectionInput<TModel>;
|
|
1761
1775
|
};
|
|
1762
1776
|
|
|
1763
|
-
type QueryNativeWithRelationInput<TEntry> =
|
|
1777
|
+
type QueryNativeWithRelationInput<TEntry, TTargetTable> =
|
|
1764
1778
|
| (Extract<TEntry, true> extends never ? never : true)
|
|
1765
1779
|
| (Extract<TEntry, Record<string, unknown>> extends infer TRelation
|
|
1766
1780
|
? TRelation extends Record<string, unknown>
|
|
1767
1781
|
? Omit<TRelation, "where" | "with" | "_count" | "_avg"> &
|
|
1768
1782
|
RelationAggregateSelectionInput<RelationModelFromConfig<TRelation>> & {
|
|
1769
|
-
where?: WhereInput<RelationModelFromConfig<TRelation>>;
|
|
1783
|
+
where?: WhereInput<RelationModelFromConfig<TRelation>, Extract<TTargetTable, TableName>>;
|
|
1770
1784
|
with?: TRelation extends { with?: infer TNestedWith }
|
|
1771
|
-
? QueryWithInputForTable<
|
|
1785
|
+
? QueryWithInputForTable<Extract<TTargetTable, TableName>, TNestedWith>
|
|
1772
1786
|
: never;
|
|
1773
1787
|
}
|
|
1774
1788
|
: never
|
|
@@ -1778,7 +1792,7 @@ type QueryManyToManyWithRelationInput<TTargetTable extends TableName> =
|
|
|
1778
1792
|
| true
|
|
1779
1793
|
| (Omit<NonNullable<TableFindManyArgs<TTargetTable>>, "where" | "with"> &
|
|
1780
1794
|
RelationAggregateSelectionInput<TableModel<TTargetTable>> & {
|
|
1781
|
-
where?: WhereInput<TableModel<TTargetTable
|
|
1795
|
+
where?: WhereInput<TableModel<TTargetTable>, TTargetTable>;
|
|
1782
1796
|
with?: QueryWithInputForTable<
|
|
1783
1797
|
TTargetTable,
|
|
1784
1798
|
NativeFindManyWith<TTargetTable>
|
|
@@ -1790,7 +1804,7 @@ type QueryWithRelationInputForTable<
|
|
|
1790
1804
|
TRelationName extends string,
|
|
1791
1805
|
TEntry,
|
|
1792
1806
|
> = [ManyToManyTargetTableName<TSourceTable, TRelationName>] extends [never]
|
|
1793
|
-
? QueryNativeWithRelationInput<TEntry
|
|
1807
|
+
? QueryNativeWithRelationInput<TEntry, RuntimeRelationTargetTable<TSourceTable, TRelationName>>
|
|
1794
1808
|
: QueryManyToManyWithRelationInput<
|
|
1795
1809
|
Extract<ManyToManyTargetTableName<TSourceTable, TRelationName>, TableName>
|
|
1796
1810
|
>;
|
|
@@ -1813,20 +1827,28 @@ type QueryWithInput<TName extends TableName, TWith> = QueryWithInputForTable<
|
|
|
1813
1827
|
TWith
|
|
1814
1828
|
>;
|
|
1815
1829
|
|
|
1830
|
+
export type OrderByDirection = "asc" | "desc";
|
|
1831
|
+
|
|
1832
|
+
export type OrderByInput<TName extends TableName> =
|
|
1833
|
+
| { column: Extract<keyof TableModel<TName>, string>; direction?: OrderByDirection }
|
|
1834
|
+
| Array<{ column: Extract<keyof TableModel<TName>, string>; direction?: OrderByDirection }>;
|
|
1835
|
+
|
|
1816
1836
|
export type QueryFindManyArgs<TName extends TableName> = Omit<
|
|
1817
1837
|
NonNullable<TableFindManyArgs<TName>>,
|
|
1818
|
-
"where" | "with"
|
|
1838
|
+
"where" | "with" | "orderBy"
|
|
1819
1839
|
> & {
|
|
1820
|
-
where?: WhereInput<TableModel<TName
|
|
1840
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1821
1841
|
with?: QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1842
|
+
orderBy?: OrderByInput<TName>;
|
|
1822
1843
|
};
|
|
1823
1844
|
|
|
1824
1845
|
export type QueryFindFirstArgs<TName extends TableName> = Omit<
|
|
1825
1846
|
NonNullable<TableFindFirstArgs<TName>>,
|
|
1826
|
-
"where" | "with"
|
|
1847
|
+
"where" | "with" | "orderBy"
|
|
1827
1848
|
> & {
|
|
1828
|
-
where?: WhereInput<TableModel<TName
|
|
1849
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1829
1850
|
with?: QueryWithInput<TName, NativeFindFirstWith<TName>>;
|
|
1851
|
+
orderBy?: OrderByInput<TName>;
|
|
1830
1852
|
};
|
|
1831
1853
|
|
|
1832
1854
|
type RelationInsertItem<TTargetTable extends TableName> =
|
|
@@ -1893,12 +1915,12 @@ export type QueryInsertArgs<TName extends TableName> = {
|
|
|
1893
1915
|
|
|
1894
1916
|
export type QueryUpdateArgs<TName extends TableName> = {
|
|
1895
1917
|
set: Partial<TableInsertModel<TName>>;
|
|
1896
|
-
where?: WhereInput<TableModel<TName
|
|
1918
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1897
1919
|
limit?: number;
|
|
1898
1920
|
};
|
|
1899
1921
|
|
|
1900
1922
|
export type QueryDeleteArgs<TName extends TableName> = {
|
|
1901
|
-
where?: WhereInput<TableModel<TName
|
|
1923
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1902
1924
|
limit?: number;
|
|
1903
1925
|
};
|
|
1904
1926
|
`}function Re(){return `type AggregateWithInput<TName extends TableName> =
|
|
@@ -1971,14 +1993,14 @@ type ApplyFindFirstWithAggregateResult<TResult, TArgs> =
|
|
|
1971
1993
|
: TResult;
|
|
1972
1994
|
|
|
1973
1995
|
export type QueryCountArgs<TName extends TableName> = {
|
|
1974
|
-
where?: WhereInput<TableModel<TName
|
|
1996
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1975
1997
|
field?: Extract<keyof TableModel<TName>, string> | string;
|
|
1976
1998
|
distinct?: boolean;
|
|
1977
1999
|
with?: AggregateWithInput<TName>;
|
|
1978
2000
|
};
|
|
1979
2001
|
|
|
1980
2002
|
export type QueryAvgArgs<TName extends TableName> = {
|
|
1981
|
-
where?: WhereInput<TableModel<TName
|
|
2003
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1982
2004
|
field: NumericFieldKey<TName> | string;
|
|
1983
2005
|
distinct?: boolean;
|
|
1984
2006
|
with?: AggregateWithInput<TName>;
|
|
@@ -2293,6 +2315,21 @@ function buildWhereFilterFromFields(
|
|
|
2293
2315
|
|
|
2294
2316
|
const field = fields[fieldName];
|
|
2295
2317
|
if (!field) {
|
|
2318
|
+
if (isRecord(fieldValue) && tableName) {
|
|
2319
|
+
const relation = getRuntimeRelation(tableName, fieldName);
|
|
2320
|
+
if (relation) {
|
|
2321
|
+
const relationFilter = buildRelationFilter(
|
|
2322
|
+
relation,
|
|
2323
|
+
fieldValue,
|
|
2324
|
+
tableName,
|
|
2325
|
+
fields,
|
|
2326
|
+
);
|
|
2327
|
+
if (relationFilter) {
|
|
2328
|
+
filters.push(relationFilter);
|
|
2329
|
+
}
|
|
2330
|
+
continue;
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2296
2333
|
continue;
|
|
2297
2334
|
}
|
|
2298
2335
|
|
|
@@ -2443,6 +2480,63 @@ function getRuntimeRelation(
|
|
|
2443
2480
|
return runtimeRelationMap[tableName]?.[relationName];
|
|
2444
2481
|
}
|
|
2445
2482
|
|
|
2483
|
+
function buildRelationFilter(
|
|
2484
|
+
relation: RuntimeRelation,
|
|
2485
|
+
whereValue: Record<string, unknown>,
|
|
2486
|
+
sourceTableName: string,
|
|
2487
|
+
sourceFields: Record<string, unknown>
|
|
2488
|
+
): SQL | undefined {
|
|
2489
|
+
const rawTargetTable = (mergedSchema as Record<string, unknown>)[relation.targetTable];
|
|
2490
|
+
if (!rawTargetTable) {
|
|
2491
|
+
return undefined;
|
|
2492
|
+
}
|
|
2493
|
+
|
|
2494
|
+
const targetFields = getTableColumns(rawTargetTable as never) as Record<string, unknown>;
|
|
2495
|
+
const relationFilter = buildWhereFilterFromFields(
|
|
2496
|
+
targetFields,
|
|
2497
|
+
whereValue,
|
|
2498
|
+
relation.targetTable,
|
|
2499
|
+
);
|
|
2500
|
+
|
|
2501
|
+
if (!relationFilter) {
|
|
2502
|
+
return undefined;
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
if (relation.kind === "one") {
|
|
2506
|
+
const sourceField = relation.sourceField || (relation.targetTable + "Id");
|
|
2507
|
+
const targetFieldCol = targetFields[relation.referenceField || "id"];
|
|
2508
|
+
const sourceFieldCol = sourceFields[sourceField];
|
|
2509
|
+
if (!targetFieldCol || !sourceFieldCol) return undefined;
|
|
2510
|
+
return sql\`exists (select 1 from \${rawTargetTable as never} where \${eq(targetFieldCol as never, sourceFieldCol as never)} and \${relationFilter})\`;
|
|
2511
|
+
}
|
|
2512
|
+
|
|
2513
|
+
if (relation.kind === "many") {
|
|
2514
|
+
const sourceFieldCol = sourceFields[relation.sourceField || "id"];
|
|
2515
|
+
const targetFieldCol = targetFields[relation.referenceField || (sourceTableName + "Id")];
|
|
2516
|
+
if (!targetFieldCol || !sourceFieldCol) return undefined;
|
|
2517
|
+
return sql\`exists (select 1 from \${rawTargetTable as never} where \${eq(targetFieldCol as never, sourceFieldCol as never)} and \${relationFilter})\`;
|
|
2518
|
+
}
|
|
2519
|
+
|
|
2520
|
+
if (relation.kind === "manyToMany") {
|
|
2521
|
+
const junctionTableName = (relation as RuntimeRelationManyToMany).junctionTable;
|
|
2522
|
+
const junctionTable = (mergedSchema as Record<string, unknown>)[junctionTableName];
|
|
2523
|
+
if (!junctionTable) return undefined;
|
|
2524
|
+
const junctionFields = getTableColumns(junctionTable as never) as Record<string, unknown>;
|
|
2525
|
+
|
|
2526
|
+
const sourceFieldCol = sourceFields[(relation as RuntimeRelationManyToMany).sourceField || "id"];
|
|
2527
|
+
const targetFieldCol = targetFields[(relation as RuntimeRelationManyToMany).targetField || "id"];
|
|
2528
|
+
|
|
2529
|
+
const junctionSourceRefCol = junctionFields[(relation as RuntimeRelationManyToMany).referenceField || (sourceTableName + "Id")];
|
|
2530
|
+
const junctionTargetRefCol = junctionFields[(relation as RuntimeRelationManyToMany).targetReferenceField || (relation.targetTable + "Id")];
|
|
2531
|
+
|
|
2532
|
+
if (!sourceFieldCol || !targetFieldCol || !junctionSourceRefCol || !junctionTargetRefCol) return undefined;
|
|
2533
|
+
|
|
2534
|
+
return sql\`exists (select 1 from \${junctionTable as never} inner join \${rawTargetTable as never} on \${eq(junctionTargetRefCol as never, targetFieldCol as never)} where \${eq(junctionSourceRefCol as never, sourceFieldCol as never)} and \${relationFilter})\`;
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
return undefined;
|
|
2538
|
+
}
|
|
2539
|
+
|
|
2446
2540
|
type ManyToManyRuntimeMap = Record<
|
|
2447
2541
|
string,
|
|
2448
2542
|
Record<string, ManyToManyRuntimeRelation>
|
|
@@ -3085,6 +3179,18 @@ type NativeFindManyWith<TName extends TableName> =
|
|
|
3085
3179
|
NonNullable<TableFindManyArgs<TName>> extends { with?: infer TWith }
|
|
3086
3180
|
? TWith
|
|
3087
3181
|
: never;
|
|
3182
|
+
type NormalizeWhereInWith<TWith, TNativeWith> = TWith extends Record<string, unknown>
|
|
3183
|
+
? {
|
|
3184
|
+
[K in keyof TWith]: K extends keyof TNativeWith
|
|
3185
|
+
? TWith[K] extends Record<string, unknown>
|
|
3186
|
+
? Omit<TWith[K], 'where'> & { where?: NonNullable<Extract<TNativeWith[K], Record<string, unknown>>['where']> } & (TWith[K] extends { with: infer TNestedWith }
|
|
3187
|
+
? { with: NormalizeWhereInWith<TNestedWith, TNativeWith[K]> }
|
|
3188
|
+
: {})
|
|
3189
|
+
: TWith[K]
|
|
3190
|
+
: TWith[K];
|
|
3191
|
+
}
|
|
3192
|
+
: TWith;
|
|
3193
|
+
|
|
3088
3194
|
type ResolveNativeFindManyWith<
|
|
3089
3195
|
TName extends TableName,
|
|
3090
3196
|
TArgs extends QueryFindManyArgs<TName> | undefined,
|
|
@@ -3092,7 +3198,7 @@ type ResolveNativeFindManyWith<
|
|
|
3092
3198
|
? Extract<TWith, NativeFindManyWith<TName>> extends infer TResolved
|
|
3093
3199
|
? [TResolved] extends [never]
|
|
3094
3200
|
? TWith extends Record<string, unknown>
|
|
3095
|
-
? NativeFindManyWith<TName
|
|
3201
|
+
? NormalizeWhereInWith<TWith, NativeFindManyWith<TName>>
|
|
3096
3202
|
: never
|
|
3097
3203
|
: TResolved
|
|
3098
3204
|
: never
|
|
@@ -3165,6 +3271,16 @@ type RuntimeRelationTargetTable<
|
|
|
3165
3271
|
}
|
|
3166
3272
|
? Extract<TTarget, TableName>
|
|
3167
3273
|
: never;
|
|
3274
|
+
|
|
3275
|
+
type TargetTableForRelation<
|
|
3276
|
+
TSource extends TableName,
|
|
3277
|
+
TRelation extends string,
|
|
3278
|
+
> = RuntimeRelationTargetTable<TSource, TRelation> extends never
|
|
3279
|
+
? ManyToManyTargetTableName<TSource, TRelation> extends never
|
|
3280
|
+
? never
|
|
3281
|
+
: Extract<ManyToManyTargetTableName<TSource, TRelation>, TableName>
|
|
3282
|
+
: RuntimeRelationTargetTable<TSource, TRelation>;
|
|
3283
|
+
|
|
3168
3284
|
type TableInsertScalarModel<TName extends TableName> = TableInsertModel<TName>;
|
|
3169
3285
|
type FindManyWithFromArgs<TArgs> = TArgs extends { with?: infer TWith }
|
|
3170
3286
|
? TWith
|
|
@@ -3186,7 +3302,7 @@ type ManyToManyRelationRows<
|
|
|
3186
3302
|
>
|
|
3187
3303
|
: Array<TableModel<TTargetTable>>;
|
|
3188
3304
|
type ReplaceManyToManyRelationsInRow<
|
|
3189
|
-
TSourceTable extends
|
|
3305
|
+
TSourceTable extends string,
|
|
3190
3306
|
TRow,
|
|
3191
3307
|
TWith,
|
|
3192
3308
|
> = TRow extends Record<string, unknown>
|
|
@@ -3194,17 +3310,27 @@ type ReplaceManyToManyRelationsInRow<
|
|
|
3194
3310
|
[K in keyof TRow]: K extends string
|
|
3195
3311
|
? TWith extends Record<string, unknown>
|
|
3196
3312
|
? K extends keyof TWith
|
|
3197
|
-
? [ManyToManyTargetTableName<TSourceTable, K>] extends [never]
|
|
3198
|
-
?
|
|
3313
|
+
? [ManyToManyTargetTableName<Extract<TSourceTable, TableName>, K>] extends [never]
|
|
3314
|
+
? ReplaceManyToManyRelationsInRow<
|
|
3315
|
+
[RuntimeRelationTargetTable<Extract<TSourceTable, TableName>, K>] extends [never]
|
|
3316
|
+
? K
|
|
3317
|
+
: RuntimeRelationTargetTable<Extract<TSourceTable, TableName>, K>,
|
|
3318
|
+
TRow[K],
|
|
3319
|
+
TWith[K] extends { with: infer TNestedWith }
|
|
3320
|
+
? TNestedWith
|
|
3321
|
+
: undefined
|
|
3322
|
+
>
|
|
3199
3323
|
: ManyToManyRelationRows<
|
|
3200
|
-
Extract<ManyToManyTargetTableName<TSourceTable, K>, TableName>,
|
|
3324
|
+
Extract<ManyToManyTargetTableName<Extract<TSourceTable, TableName>, K>, TableName>,
|
|
3201
3325
|
TWith[K]
|
|
3202
3326
|
>
|
|
3203
3327
|
: TRow[K]
|
|
3204
3328
|
: TRow[K]
|
|
3205
3329
|
: TRow[K];
|
|
3206
3330
|
}
|
|
3207
|
-
: TRow
|
|
3331
|
+
: TRow extends Array<infer TEntry>
|
|
3332
|
+
? Array<ReplaceManyToManyRelationsInRow<TSourceTable, TEntry, TWith>>
|
|
3333
|
+
: TRow;
|
|
3208
3334
|
type ApplyManyToManyFindManyResult<
|
|
3209
3335
|
TSourceTable extends TableName,
|
|
3210
3336
|
TArgs extends QueryFindManyArgs<TSourceTable> | undefined,
|
|
@@ -3269,7 +3395,7 @@ type ResolveNativeFindFirstWith<
|
|
|
3269
3395
|
? Extract<TWith, NativeFindFirstWith<TName>> extends infer TResolved
|
|
3270
3396
|
? [TResolved] extends [never]
|
|
3271
3397
|
? TWith extends Record<string, unknown>
|
|
3272
|
-
? NativeFindFirstWith<TName
|
|
3398
|
+
? NormalizeWhereInWith<TWith, NativeFindFirstWith<TName>>
|
|
3273
3399
|
: never
|
|
3274
3400
|
: TResolved
|
|
3275
3401
|
: never
|
|
@@ -3304,7 +3430,7 @@ type TableFindFirstResult<
|
|
|
3304
3430
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3305
3431
|
(typeof mergedSchema)[TName]
|
|
3306
3432
|
>;
|
|
3307
|
-
`}function Ae(){return [Se(),
|
|
3433
|
+
`}function Ae(){return [Se(),ve(),Re(),ke()].join(`
|
|
3308
3434
|
|
|
3309
3435
|
`)}function Ne(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3310
3436
|
const withValue = args?.with;
|
|
@@ -3487,7 +3613,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3487
3613
|
this.payload = payload;
|
|
3488
3614
|
}
|
|
3489
3615
|
}
|
|
3490
|
-
`}function
|
|
3616
|
+
`}function Ce(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
3491
3617
|
const where = isRecord(args?.where)
|
|
3492
3618
|
? (args?.where as Record<string, unknown>)
|
|
3493
3619
|
: undefined;
|
|
@@ -3497,9 +3623,14 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3497
3623
|
? (() => {
|
|
3498
3624
|
const nextArgs = { ...(args ?? {}) };
|
|
3499
3625
|
delete nextArgs.where;
|
|
3626
|
+
delete nextArgs.orderBy;
|
|
3500
3627
|
return nextArgs;
|
|
3501
3628
|
})()
|
|
3502
|
-
:
|
|
3629
|
+
: (() => {
|
|
3630
|
+
const nextArgs = { ...(args ?? {}) };
|
|
3631
|
+
delete nextArgs.orderBy;
|
|
3632
|
+
return nextArgs;
|
|
3633
|
+
})();
|
|
3503
3634
|
const withValue = args?.with;
|
|
3504
3635
|
const transformedWithResult =
|
|
3505
3636
|
withValue === undefined
|
|
@@ -3514,11 +3645,23 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3514
3645
|
tableName,
|
|
3515
3646
|
withValue,
|
|
3516
3647
|
);
|
|
3648
|
+
const orderByValue = args?.orderBy;
|
|
3649
|
+
const transformedOrderBy = orderByValue
|
|
3650
|
+
? (Array.isArray(orderByValue) ? orderByValue : [orderByValue]).map(
|
|
3651
|
+
(item: Record<string, unknown>) => {
|
|
3652
|
+
const column = item.column as string;
|
|
3653
|
+
const direction = (item.direction as string) ?? "asc";
|
|
3654
|
+
const col = (table as Record<string, { asc: () => unknown; desc: () => unknown }>)[column];
|
|
3655
|
+
return direction === "desc" ? col.desc() : col.asc();
|
|
3656
|
+
},
|
|
3657
|
+
)
|
|
3658
|
+
: undefined;
|
|
3517
3659
|
if (
|
|
3518
3660
|
!whereFilter &&
|
|
3519
3661
|
transformedWith === withValue &&
|
|
3520
3662
|
!aggregatePlan &&
|
|
3521
|
-
!requiresManyToManyFlatten
|
|
3663
|
+
!requiresManyToManyFlatten &&
|
|
3664
|
+
!transformedOrderBy
|
|
3522
3665
|
) {
|
|
3523
3666
|
return queryTable.findMany(passthroughArgs);
|
|
3524
3667
|
}
|
|
@@ -3527,6 +3670,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3527
3670
|
...(passthroughArgs ?? {}),
|
|
3528
3671
|
...(whereFilter ? { where: () => whereFilter } : {}),
|
|
3529
3672
|
...(transformedWith !== undefined ? { with: transformedWith } : {}),
|
|
3673
|
+
...(transformedOrderBy ? { orderBy: transformedOrderBy } : {}),
|
|
3530
3674
|
});
|
|
3531
3675
|
|
|
3532
3676
|
return queryPromise.then((result) => {
|
|
@@ -3556,9 +3700,14 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3556
3700
|
? (() => {
|
|
3557
3701
|
const nextArgs = { ...(args ?? {}) };
|
|
3558
3702
|
delete nextArgs.where;
|
|
3703
|
+
delete nextArgs.orderBy;
|
|
3559
3704
|
return nextArgs;
|
|
3560
3705
|
})()
|
|
3561
|
-
:
|
|
3706
|
+
: (() => {
|
|
3707
|
+
const nextArgs = { ...(args ?? {}) };
|
|
3708
|
+
delete nextArgs.orderBy;
|
|
3709
|
+
return nextArgs;
|
|
3710
|
+
})();
|
|
3562
3711
|
const withValue = args?.with;
|
|
3563
3712
|
const transformedWithResult =
|
|
3564
3713
|
withValue === undefined
|
|
@@ -3573,11 +3722,23 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3573
3722
|
tableName,
|
|
3574
3723
|
withValue,
|
|
3575
3724
|
);
|
|
3725
|
+
const orderByValue = args?.orderBy;
|
|
3726
|
+
const transformedOrderBy = orderByValue
|
|
3727
|
+
? (Array.isArray(orderByValue) ? orderByValue : [orderByValue]).map(
|
|
3728
|
+
(item: Record<string, unknown>) => {
|
|
3729
|
+
const column = item.column as string;
|
|
3730
|
+
const direction = (item.direction as string) ?? "asc";
|
|
3731
|
+
const col = (table as Record<string, { asc: () => unknown; desc: () => unknown }>)[column];
|
|
3732
|
+
return direction === "desc" ? col.desc() : col.asc();
|
|
3733
|
+
},
|
|
3734
|
+
)
|
|
3735
|
+
: undefined;
|
|
3576
3736
|
if (
|
|
3577
3737
|
!whereFilter &&
|
|
3578
3738
|
transformedWith === withValue &&
|
|
3579
3739
|
!aggregatePlan &&
|
|
3580
|
-
!requiresManyToManyFlatten
|
|
3740
|
+
!requiresManyToManyFlatten &&
|
|
3741
|
+
!transformedOrderBy
|
|
3581
3742
|
) {
|
|
3582
3743
|
return queryTable.findFirst(passthroughArgs);
|
|
3583
3744
|
}
|
|
@@ -3586,6 +3747,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3586
3747
|
...(passthroughArgs ?? {}),
|
|
3587
3748
|
...(whereFilter ? { where: () => whereFilter } : {}),
|
|
3588
3749
|
...(transformedWith !== undefined ? { with: transformedWith } : {}),
|
|
3750
|
+
...(transformedOrderBy ? { orderBy: transformedOrderBy } : {}),
|
|
3589
3751
|
});
|
|
3590
3752
|
|
|
3591
3753
|
return queryPromise.then((result) => {
|
|
@@ -3605,7 +3767,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3605
3767
|
);
|
|
3606
3768
|
});
|
|
3607
3769
|
},
|
|
3608
|
-
`}function
|
|
3770
|
+
`}function qe(){return `export function createQueryDb(
|
|
3609
3771
|
$db: AppflareDb,
|
|
3610
3772
|
options?: QueryDbOptions,
|
|
3611
3773
|
): AppflareQueryDb {
|
|
@@ -3647,7 +3809,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3647
3809
|
};
|
|
3648
3810
|
|
|
3649
3811
|
const tableApi = {
|
|
3650
|
-
`}function
|
|
3812
|
+
`}function Me(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
3651
3813
|
const transaction = ($db as any).transaction;
|
|
3652
3814
|
|
|
3653
3815
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -3854,6 +4016,11 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3854
4016
|
});
|
|
3855
4017
|
continue;
|
|
3856
4018
|
}
|
|
4019
|
+
|
|
4020
|
+
if (fieldValue === undefined) {
|
|
4021
|
+
continue;
|
|
4022
|
+
}
|
|
4023
|
+
|
|
3857
4024
|
scalarValues[fieldName] = fieldValue;
|
|
3858
4025
|
}
|
|
3859
4026
|
|
|
@@ -4209,9 +4376,18 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4209
4376
|
args.where as Record<string, unknown> | undefined,
|
|
4210
4377
|
tableName,
|
|
4211
4378
|
);
|
|
4379
|
+
|
|
4380
|
+
const setPayload = args.set as Record<string, unknown>;
|
|
4381
|
+
const cleanSetPayload: Record<string, unknown> = {};
|
|
4382
|
+
for (const [key, value] of Object.entries(setPayload)) {
|
|
4383
|
+
if (value !== undefined) {
|
|
4384
|
+
cleanSetPayload[key] = value;
|
|
4385
|
+
}
|
|
4386
|
+
}
|
|
4387
|
+
|
|
4212
4388
|
let updateQuery: any = ($db as any)
|
|
4213
4389
|
.update(table as any)
|
|
4214
|
-
.set(
|
|
4390
|
+
.set(cleanSetPayload as any);
|
|
4215
4391
|
|
|
4216
4392
|
if (whereFilter) {
|
|
4217
4393
|
updateQuery = updateQuery.where(whereFilter);
|
|
@@ -4266,7 +4442,14 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4266
4442
|
);
|
|
4267
4443
|
}
|
|
4268
4444
|
|
|
4269
|
-
const
|
|
4445
|
+
const rawSetPayload = (args.set ?? valuesArray[0] ?? {}) as Record<string, unknown>;
|
|
4446
|
+
const setPayload: Record<string, unknown> = {};
|
|
4447
|
+
for (const [key, value] of Object.entries(rawSetPayload)) {
|
|
4448
|
+
if (value !== undefined) {
|
|
4449
|
+
setPayload[key] = value;
|
|
4450
|
+
}
|
|
4451
|
+
}
|
|
4452
|
+
|
|
4270
4453
|
let upsertQuery: any = ($db as any)
|
|
4271
4454
|
.insert(table as any)
|
|
4272
4455
|
.values(values as any)
|
|
@@ -4320,9 +4503,9 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4320
4503
|
);
|
|
4321
4504
|
return rows;
|
|
4322
4505
|
},
|
|
4323
|
-
`}function
|
|
4506
|
+
`}function Ie(){return [qe(),Ce(),Me(),Ne(),$e()].join(`
|
|
4324
4507
|
|
|
4325
|
-
`)}function
|
|
4508
|
+
`)}function Fe(){return `type AuthSession = typeof auth.$Infer.Session;
|
|
4326
4509
|
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4327
4510
|
type User = AuthSession['user']
|
|
4328
4511
|
type Session = AuthSession['session']
|
|
@@ -4411,7 +4594,7 @@ export type AppflareContext = {
|
|
|
4411
4594
|
storage: AppflareStorage;
|
|
4412
4595
|
error: (status: number, message: string, details?: unknown) => never;
|
|
4413
4596
|
};
|
|
4414
|
-
`}function
|
|
4597
|
+
`}function Pe(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
4415
4598
|
|
|
4416
4599
|
export type SchedulerEnqueueOptions = {
|
|
4417
4600
|
delaySeconds?: number;
|
|
@@ -4543,20 +4726,20 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
4543
4726
|
definition,
|
|
4544
4727
|
};
|
|
4545
4728
|
}
|
|
4546
|
-
`}function
|
|
4729
|
+
`}function Ee(){return [Te(),Ae(),Ie(),Fe(),Pe()].join(`
|
|
4547
4730
|
|
|
4548
|
-
`)}function
|
|
4731
|
+
`)}function De(e){return `import type { Context } from "hono";
|
|
4549
4732
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
4550
4733
|
import { drizzle } from "drizzle-orm/d1";
|
|
4551
4734
|
import { z, type ZodRawShape } from "zod";
|
|
4552
4735
|
import * as authSchema from "./auth.schema";
|
|
4553
4736
|
import * as schema from "${e}";
|
|
4554
4737
|
|
|
4555
|
-
${
|
|
4556
|
-
`}function jn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function
|
|
4557
|
-
`)}function
|
|
4558
|
-
`)}function
|
|
4559
|
-
`)}function
|
|
4738
|
+
${Ee()}
|
|
4739
|
+
`}function jn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function Bn(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return jn(`op_${t}_${n}`)}function Vn(e){return e.map((t,n)=>({operation:t,index:n,alias:Bn(t,n)}))}function Wn(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
4740
|
+
`)}function Hn(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
4741
|
+
`)}function zn(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({alias:t})=>`const ${`${t}SchedulerSchema`} = ${t}.definition.args ? z.object(${t}.definition.args) : z.undefined();`).join(`
|
|
4742
|
+
`)}function Ln(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
4560
4743
|
app.get(
|
|
4561
4744
|
"${t.routePath}",
|
|
4562
4745
|
sValidator("query", ${r}),
|
|
@@ -4603,7 +4786,7 @@ ${Fe()}
|
|
|
4603
4786
|
},`}).join(`
|
|
4604
4787
|
`)}function Jn(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
4605
4788
|
${t}.definition.handler,`).join(`
|
|
4606
|
-
`)}function Oe(e){let t=
|
|
4789
|
+
`)}function Oe(e){let t=Vn(e);return {imports:Wn(t),operationSchemas:Hn(t),schedulerSchemas:zn(t),queryRoutes:Ln(t),mutationRoutes:Un(t),queryRegistryEntries:Qn(t),schedulerEntries:_n(t),schedulerPayloadMapEntries:Kn(t),cronEntries:Gn(t),storageHandlersEntries:Jn(t)}}var je=`
|
|
4607
4790
|
function getRealtimeStub(
|
|
4608
4791
|
env: Record<string, unknown>,
|
|
4609
4792
|
options: RegisterHandlersOptions,
|
|
@@ -4677,7 +4860,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
4677
4860
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
4678
4861
|
return url.toString();
|
|
4679
4862
|
}
|
|
4680
|
-
`;var
|
|
4863
|
+
`;var Be=`
|
|
4681
4864
|
export class AppflareRealtimeDurableObject {
|
|
4682
4865
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
4683
4866
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -4820,7 +5003,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
4820
5003
|
return new Response("Not found", { status: 404 });
|
|
4821
5004
|
}
|
|
4822
5005
|
}
|
|
4823
|
-
`;var
|
|
5006
|
+
`;var Ve=`
|
|
4824
5007
|
async function publishMutationEvents(
|
|
4825
5008
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
4826
5009
|
options: RegisterHandlersOptions,
|
|
@@ -4921,7 +5104,7 @@ async function publishMutationEvents(
|
|
|
4921
5104
|
}
|
|
4922
5105
|
}
|
|
4923
5106
|
}
|
|
4924
|
-
`;var
|
|
5107
|
+
`;var We=`
|
|
4925
5108
|
function registerRealtimeRoutes(
|
|
4926
5109
|
app: Hono<WorkerEnv>,
|
|
4927
5110
|
options: RegisterHandlersOptions,
|
|
@@ -5084,7 +5267,7 @@ function registerRealtimeRoutes(
|
|
|
5084
5267
|
return stub.fetch(c.req.raw);
|
|
5085
5268
|
});
|
|
5086
5269
|
}
|
|
5087
|
-
`;var
|
|
5270
|
+
`;var He=`
|
|
5088
5271
|
type RealtimeSubscription = {
|
|
5089
5272
|
token: string;
|
|
5090
5273
|
signature: string;
|
|
@@ -5113,7 +5296,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5113
5296
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5114
5297
|
? string
|
|
5115
5298
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5116
|
-
`;var
|
|
5299
|
+
`;var ze=`
|
|
5117
5300
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5118
5301
|
return typeof value === "object" && value !== null;
|
|
5119
5302
|
}
|
|
@@ -5628,7 +5811,7 @@ function doesSubscriptionMatchMutation(
|
|
|
5628
5811
|
|
|
5629
5812
|
return false;
|
|
5630
5813
|
}
|
|
5631
|
-
`;var
|
|
5814
|
+
`;var Le=[He,ze,je,Ve,We,Be].join(`
|
|
5632
5815
|
|
|
5633
5816
|
`);var Ue=`
|
|
5634
5817
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
@@ -5967,7 +6150,7 @@ setStorageHandlers([...storageHandlers]);
|
|
|
5967
6150
|
|
|
5968
6151
|
${Qe}
|
|
5969
6152
|
|
|
5970
|
-
${
|
|
6153
|
+
${Le}
|
|
5971
6154
|
|
|
5972
6155
|
export function registerGeneratedHandlers(
|
|
5973
6156
|
app: Hono<WorkerEnv>,
|
|
@@ -5983,7 +6166,7 @@ export function registerGeneratedHandlers(
|
|
|
5983
6166
|
${Ue}
|
|
5984
6167
|
|
|
5985
6168
|
${_e}
|
|
5986
|
-
`}function
|
|
6169
|
+
`}function W(e,t,n){let r=De(e),a=be(n),o=xe(),i=Ke(t);return [{relativePath:"handlers.ts",source:r},{relativePath:"handlers.context.ts",source:a},{relativePath:"handlers.execution.ts",source:o},{relativePath:"handlers.routes.ts",source:i}]}function Zn(e){return e?`,
|
|
5987
6170
|
KV: c.env["${e}"] as KVNamespace`:""}function Ge(e,t){return `{
|
|
5988
6171
|
DATABASE: c.env["${e}"] as D1Database${Zn(t)}
|
|
5989
6172
|
}`}function Je(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
@@ -6081,7 +6264,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6081
6264
|
`}function rt(){return `type WorkerEnv = {
|
|
6082
6265
|
Bindings: Record<string, unknown>;
|
|
6083
6266
|
};
|
|
6084
|
-
`}function at(e,t,n,r,a,o,i,s,l,u){return nt()+rt()+Xe()+tt(t,n,r,a,o,i,s,l,u)+Ye(e,t,n)+et()}function ot(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function
|
|
6267
|
+
`}function at(e,t,n,r,a,o,i,s,l,u){return nt()+rt()+Xe()+tt(t,n,r,a,o,i,s,l,u)+Ye(e,t,n)+et()}function ot(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function H(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(ot(o)&&ot(a)){n[r]=H(o,a);continue}n[r]=a;}return n}function er(e){return Array.from(new Set(e.filter(t=>t.length>0)))}function it(e,t){let n=t.filter(d=>d.kind==="scheduler"||d.kind==="cron"),r=er(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",l=e.config.scheduler.queue??`${s}-scheduler`,u={name:s,main:"./src/index.ts",d1_databases:e.config.database.map(d=>({binding:d.binding,database_name:d.databaseName,database_id:d.databaseId,preview_database_id:d.previewDatabaseId??d.databaseId,...d.migrationsDir?{migrations_dir:d.migrationsDir}:{}})),kv_namespaces:e.config.kv.map(d=>({binding:d.binding,id:d.id,...d.previewId?{preview_id:d.previewId}:{}})),r2_buckets:e.config.r2.map(d=>({binding:d.binding,bucket_name:d.bucketName,...d.previewBucketName?{preview_bucket_name:d.previewBucketName}:{},...d.jurisdiction?{jurisdiction:d.jurisdiction}:{}})),...a?{queues:{producers:[{binding:e.config.scheduler.binding,queue:l}],consumers:[{queue:l}]}}:{},...r.length>0?{triggers:{crons:r}}:{},...o?{durable_objects:{bindings:[{name:e.config.realtime.binding,class_name:e.config.realtime.className}]},migrations:[{tag:"appflare-realtime-v1",new_sqlite_classes:[e.config.realtime.className]}]}:{}};if(!e.config.wranglerOverrides)return u;let{scheduler:c,...f}=e.config.wranglerOverrides;return H(u,f)}function st(e){return e.tables.map(t=>({exportName:t.exportName,tableName:t.tableName,columns:t.columns.map(n=>n.name)}))}function lt(e){return `<li data-name="users">
|
|
6085
6268
|
<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">
|
|
6086
6269
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6087
6270
|
<span class="truncate">users</span>
|
|
@@ -6158,7 +6341,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6158
6341
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6159
6342
|
</a>
|
|
6160
6343
|
</th>
|
|
6161
|
-
`}).join("")}function mt(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function
|
|
6344
|
+
`}).join("")}function mt(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function z(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"?`
|
|
6162
6345
|
<div class="form-control">
|
|
6163
6346
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6164
6347
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6196,7 +6379,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6196
6379
|
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6197
6380
|
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm"${a} />
|
|
6198
6381
|
</div>
|
|
6199
|
-
`}function
|
|
6382
|
+
`}function L(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n);if(!r)return "";let a=r.optional?"":`
|
|
6200
6383
|
if (raw_${n} === '') {
|
|
6201
6384
|
return c.text('${n} is required', 400);
|
|
6202
6385
|
}
|
|
@@ -6241,7 +6424,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6241
6424
|
payload.${n} = raw_${n};
|
|
6242
6425
|
}
|
|
6243
6426
|
`}).join(`
|
|
6244
|
-
`)}function gt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function ft(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function ht(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function
|
|
6427
|
+
`)}function gt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function ft(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function ht(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function yt(e,t,n,r){return t?`<td class="text-right">
|
|
6245
6428
|
<div class="drawer drawer-end">
|
|
6246
6429
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6247
6430
|
<div class="drawer-content">
|
|
@@ -6294,7 +6477,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6294
6477
|
</div>
|
|
6295
6478
|
</div>
|
|
6296
6479
|
</div>
|
|
6297
|
-
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function
|
|
6480
|
+
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function q(e){return `
|
|
6298
6481
|
<div class="flex flex-col sm:flex-row justify-between items-center mt-4 gap-3 py-3 px-1">
|
|
6299
6482
|
<div class="text-xs text-base-content/40">
|
|
6300
6483
|
Total found: <span class="font-medium text-base-content/60">\${total}</span>
|
|
@@ -6316,7 +6499,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6316
6499
|
\` : html\`<button class="join-item btn btn-sm btn-ghost btn-disabled"><iconify-icon icon="mdi:chevron-right" width="16" height="16"></iconify-icon></button>\`}
|
|
6317
6500
|
</div>
|
|
6318
6501
|
\` : ''}
|
|
6319
|
-
</div>`}function
|
|
6502
|
+
</div>`}function M(e,t="Search term or filter..."){return `
|
|
6320
6503
|
<div class="form-control w-full md:w-auto relative">
|
|
6321
6504
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
6322
6505
|
<input type="text"
|
|
@@ -6327,7 +6510,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6327
6510
|
hx-trigger="keyup changed delay:500ms, search"
|
|
6328
6511
|
hx-target="#main-content"
|
|
6329
6512
|
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" />
|
|
6330
|
-
</div>`}function
|
|
6513
|
+
</div>`}function bt(e,t,n,r,a,o,i,s,l,u){let c=q(`/admin/table/${e.exportName}`),f=M(`/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>',b=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>',w=r?`
|
|
6331
6514
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
6332
6515
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
6333
6516
|
<div class="text-xs text-base-content/70">
|
|
@@ -6495,7 +6678,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6495
6678
|
<tbody>
|
|
6496
6679
|
\${data.map((row, rowIndex) => html\`
|
|
6497
6680
|
<tr class="hover:bg-base-200/30 transition-colors">
|
|
6498
|
-
${
|
|
6681
|
+
${b}
|
|
6499
6682
|
${s}
|
|
6500
6683
|
${l}
|
|
6501
6684
|
</tr>
|
|
@@ -6712,15 +6895,15 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6712
6895
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
6713
6896
|
});
|
|
6714
6897
|
${c}
|
|
6715
|
-
`}function U(e){let t=gt(e),n=!!t,r=e.columns.map(m=>m.name),a=r.filter(m=>ft(e,m)),o=r.filter(m=>ht(e,m)),i=dt(e),s=pt(e,r),l=mt(r,t),u=a.map(m=>
|
|
6716
|
-
`+wt(e.exportName,
|
|
6898
|
+
`}function U(e){let t=gt(e),n=!!t,r=e.columns.map(m=>m.name),a=r.filter(m=>ft(e,m)),o=r.filter(m=>ht(e,m)),i=dt(e),s=pt(e,r),l=mt(r,t),u=a.map(m=>z(e,m,"create")).join(""),c=o.map(m=>z(e,m,"edit")).join(""),f=L(e,a),d=L(e,o),b=n?t:r[0]||"id",w=e.columns.find(m=>m.name===t)?.type,y=yt(e,n,t,c);return bt(e,b,t,n,r,i,s,l,y,u)+`
|
|
6899
|
+
`+wt(e.exportName,b,t,w,n,i,f,d)}function xt(){return `
|
|
6717
6900
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
6718
6901
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
6719
6902
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
6720
6903
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
6721
6904
|
const search = params.search ? params.search : '';
|
|
6722
6905
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
6723
|
-
};`}function
|
|
6906
|
+
};`}function Tt(){return `
|
|
6724
6907
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6725
6908
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6726
6909
|
<div class="modal">
|
|
@@ -6741,7 +6924,7 @@ ${c}
|
|
|
6741
6924
|
</div>
|
|
6742
6925
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
6743
6926
|
</div>
|
|
6744
|
-
\`}`}function
|
|
6927
|
+
\`}`}function vt(){return `
|
|
6745
6928
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6746
6929
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6747
6930
|
<div class="modal">
|
|
@@ -6763,7 +6946,7 @@ ${c}
|
|
|
6763
6946
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
6764
6947
|
</div>
|
|
6765
6948
|
\`}`}var nr=["id","name","email","role","createdAt","banned"],rr={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function ar(e){let t=rr[e]||"mdi:format-text";return `<th><a href="#" hx-get="/admin/users?page=\${page}&search=\${search}&sort=${e}&order=\${sort === '${e}' && order === 'asc' ? 'desc' : 'asc'}" hx-target="#main-content" hx-push-url="true" class="hover:text-primary flex items-center gap-1.5 transition-colors whitespace-nowrap"><iconify-icon icon="${t}" width="14" height="14" class="opacity-40"></iconify-icon>${e} <span class="text-[10px] opacity-30">\${sort === '${e}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span></a></th>`}function Rt(){let e=nr.map(ar).join(`
|
|
6766
|
-
`),t=
|
|
6949
|
+
`),t=q("/admin/users");return `
|
|
6767
6950
|
const tableHtml = html\`
|
|
6768
6951
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
6769
6952
|
<div class="overflow-x-auto">
|
|
@@ -6831,8 +7014,8 @@ ${c}
|
|
|
6831
7014
|
</div>
|
|
6832
7015
|
</div>
|
|
6833
7016
|
</div>
|
|
6834
|
-
${vt()}
|
|
6835
7017
|
${Tt()}
|
|
7018
|
+
${vt()}
|
|
6836
7019
|
</td>
|
|
6837
7020
|
</tr>
|
|
6838
7021
|
\`)}
|
|
@@ -6860,7 +7043,7 @@ ${Tt()}
|
|
|
6860
7043
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
6861
7044
|
</button>
|
|
6862
7045
|
</div>
|
|
6863
|
-
${
|
|
7046
|
+
${M("/admin/users","Search users...")}
|
|
6864
7047
|
</div>
|
|
6865
7048
|
\${tableHtml}
|
|
6866
7049
|
</div>
|
|
@@ -7174,7 +7357,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7174
7357
|
</div>
|
|
7175
7358
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
7176
7359
|
</div>
|
|
7177
|
-
`}function
|
|
7360
|
+
`}function Ct(e){return `
|
|
7178
7361
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
7179
7362
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
7180
7363
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -7219,7 +7402,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7219
7402
|
</form>
|
|
7220
7403
|
</div>
|
|
7221
7404
|
</div>
|
|
7222
|
-
`}function
|
|
7405
|
+
`}function qt(){return `
|
|
7223
7406
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
7224
7407
|
<!-- Panel Header -->
|
|
7225
7408
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -7301,7 +7484,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7301
7484
|
|
|
7302
7485
|
</div>
|
|
7303
7486
|
</div>
|
|
7304
|
-
`}function
|
|
7487
|
+
`}function Mt(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
7305
7488
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
7306
7489
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
7307
7490
|
|
|
@@ -7843,21 +8026,21 @@ ${Q()}`}function $t(e){return `
|
|
|
7843
8026
|
_rtEnabled = false;
|
|
7844
8027
|
});
|
|
7845
8028
|
</script>
|
|
7846
|
-
`}function
|
|
8029
|
+
`}function It(e){return `
|
|
7847
8030
|
const content = html\`
|
|
7848
8031
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
7849
8032
|
${$t(e)}
|
|
7850
8033
|
|
|
7851
8034
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
7852
8035
|
<!-- Request Panel -->
|
|
7853
|
-
${
|
|
8036
|
+
${Ct(e)}
|
|
7854
8037
|
|
|
7855
8038
|
<!-- Result Panel -->
|
|
7856
|
-
${
|
|
8039
|
+
${qt()}
|
|
7857
8040
|
</div>
|
|
7858
8041
|
</div>
|
|
7859
8042
|
|
|
7860
|
-
${
|
|
8043
|
+
${Mt(e)}
|
|
7861
8044
|
\`;
|
|
7862
8045
|
|
|
7863
8046
|
if (c.req.header('hx-request')) {
|
|
@@ -7867,11 +8050,11 @@ ${Q()}`}function $t(e){return `
|
|
|
7867
8050
|
return c.html(Layout({
|
|
7868
8051
|
title: "${e.exportName} - Functions",
|
|
7869
8052
|
children: content
|
|
7870
|
-
}));`}function
|
|
8053
|
+
}));`}function Ft(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
7871
8054
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
7872
|
-
${
|
|
8055
|
+
${It(n)}
|
|
7873
8056
|
});`).join(`
|
|
7874
|
-
`)}function
|
|
8057
|
+
`)}function Pt(){return `
|
|
7875
8058
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
7876
8059
|
const r2Binding = (options as any).r2Binding;
|
|
7877
8060
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -7940,7 +8123,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7940
8123
|
const parts = prefix.split('/').filter(Boolean);
|
|
7941
8124
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
7942
8125
|
};
|
|
7943
|
-
`}function
|
|
8126
|
+
`}function Et(){return `
|
|
7944
8127
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
7945
8128
|
const parts = prefix.split('/').filter(Boolean);
|
|
7946
8129
|
const breadcrumbs: any[] = [];
|
|
@@ -8067,7 +8250,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8067
8250
|
</div>
|
|
8068
8251
|
\`;
|
|
8069
8252
|
};
|
|
8070
|
-
`}function
|
|
8253
|
+
`}function Dt(){return `
|
|
8071
8254
|
const handleStorageListRoute = async (c: any) => {
|
|
8072
8255
|
const bucket = getStorageBucket(c);
|
|
8073
8256
|
if (!bucket) {
|
|
@@ -8122,7 +8305,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8122
8305
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
8123
8306
|
return c.html('');
|
|
8124
8307
|
});
|
|
8125
|
-
`}function
|
|
8308
|
+
`}function Bt(){return `
|
|
8126
8309
|
adminApp.post('/storage/directory', async (c) => {
|
|
8127
8310
|
const bucket = getStorageBucket(c);
|
|
8128
8311
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8148,7 +8331,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8148
8331
|
|
|
8149
8332
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8150
8333
|
});
|
|
8151
|
-
`}function
|
|
8334
|
+
`}function Vt(){return `
|
|
8152
8335
|
adminApp.get('/storage/download', async (c) => {
|
|
8153
8336
|
const bucket = getStorageBucket(c);
|
|
8154
8337
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8168,7 +8351,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8168
8351
|
|
|
8169
8352
|
return new Response(object.body, { headers });
|
|
8170
8353
|
});
|
|
8171
|
-
`}function
|
|
8354
|
+
`}function Wt(){return `
|
|
8172
8355
|
adminApp.get('/storage/preview', async (c) => {
|
|
8173
8356
|
const bucket = getStorageBucket(c);
|
|
8174
8357
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8186,25 +8369,25 @@ ${Q()}`}function $t(e){return `
|
|
|
8186
8369
|
|
|
8187
8370
|
return new Response(object.body, { headers });
|
|
8188
8371
|
});
|
|
8189
|
-
`}function
|
|
8190
|
-
${
|
|
8372
|
+
`}function Ht(){return `
|
|
8373
|
+
${Vt()}
|
|
8191
8374
|
|
|
8192
|
-
${
|
|
8375
|
+
${Wt()}
|
|
8193
8376
|
|
|
8194
8377
|
${Ot()}
|
|
8195
8378
|
|
|
8196
8379
|
${jt()}
|
|
8197
8380
|
|
|
8198
|
-
${
|
|
8381
|
+
${Bt()}
|
|
8199
8382
|
|
|
8200
|
-
${Et()}
|
|
8201
|
-
`}function Lt(){return `
|
|
8202
8383
|
${Dt()}
|
|
8384
|
+
`}function zt(){return `
|
|
8385
|
+
${Pt()}
|
|
8203
8386
|
|
|
8204
|
-
${
|
|
8387
|
+
${Et()}
|
|
8205
8388
|
|
|
8206
|
-
${
|
|
8207
|
-
`}function
|
|
8389
|
+
${Ht()}
|
|
8390
|
+
`}function Lt(e,t){let n=ct(t);return `
|
|
8208
8391
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
8209
8392
|
return html\`<!DOCTYPE html>
|
|
8210
8393
|
<html lang="en" data-theme="light">
|
|
@@ -8655,7 +8838,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8655
8838
|
\`
|
|
8656
8839
|
}));
|
|
8657
8840
|
});
|
|
8658
|
-
`}function _t(e,t,n){let r=st(t),a=lt(r),o=ut(r),i=Nt(t),s=
|
|
8841
|
+
`}function _t(e,t,n){let r=st(t),a=lt(r),o=ut(r),i=Nt(t),s=Ft(n),l=zt(),u=Lt(a,n),c=Ut(),f=Qt(o);return `import { Hono } from "hono";
|
|
8659
8842
|
import { html, raw } from "hono/html";
|
|
8660
8843
|
import { drizzle } from "drizzle-orm/d1";
|
|
8661
8844
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -8684,8 +8867,8 @@ ${f}
|
|
|
8684
8867
|
app.route('/admin', adminApp);
|
|
8685
8868
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
8686
8869
|
}
|
|
8687
|
-
`}function _(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"}function
|
|
8688
|
-
`}function
|
|
8870
|
+
`}function _(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"}function I(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function P(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function J(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 h(e){return JSON.stringify(e)}function dr(e){if(typeof e=="string")return h(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return "null";if(e instanceof Date)return h(e.toISOString());throw new Error(`Unsupported SQL default value '${String(e)}'. Use string, number, boolean, null, or Date.`)}function pr(e){return {kind:"schema",tables:Object.fromEntries(Object.entries(e.tables).map(([t,n])=>[t,{kind:"table",sqlName:n.sqlName,columns:Object.fromEntries(Object.entries(n.columns).map(([r,a])=>[r,{...a}])),relations:Object.fromEntries(Object.entries(n.relations).map(([r,a])=>[r,{...a}]))}]))}}function F(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function Kt(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 Gt(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 Jt(e,t){return `${e}:${t}`}function mr(e,t,n,r){let a=Jt(e,t),o=Jt(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 gr(e,t){return `${e}${P(t)}Links`}function Zt(e,t,n){let r=J(e),a=J(t);return r===a?`${n}${P(r)}Id`:`${r}Id`}function fr(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 hr(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=mr(n,o,a.targetTable,i),l=Zt(s.leftTable,s.rightTable,"source"),u=Zt(s.rightTable,s.leftTable,"target"),c={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??gr(s.leftTable,s.rightTable),leftField:s.sourceIsLeft?a.sourceField??l:a.targetField??l,rightField:s.sourceIsLeft?a.targetField??u:a.sourceField??u,leftSqlName:s.sourceIsLeft?a.sourceSqlName:a.targetSqlName,rightSqlName:s.sourceIsLeft?a.targetSqlName:a.sourceSqlName,onDelete:a.onDelete,onUpdate:a.onUpdate};if(c.leftField===c.rightField)throw new Error(`manyToMany pair '${s.key}' resolves to duplicate junction fields '${c.leftField}'. Set sourceField/targetField explicitly.`);let f=t.get(s.key);f?fr(f,c,s.key):t.set(s.key,c),a.referenceField=o,a.targetReferenceField=i,a.junctionTable=c.junctionTable,a.sourceField=s.sourceIsLeft?c.leftField:c.rightField,a.targetField=s.sourceIsLeft?c.rightField:c.leftField,a.sourceSqlName=s.sourceIsLeft?c.leftSqlName:c.rightSqlName,a.targetSqlName=s.sourceIsLeft?c.rightSqlName:c.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=F(e,n.leftTable,n.leftReferenceField)??"string",a=F(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 yr(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 br(e){yr(e);let t=pr(e);for(let[n,r]of Object.entries(t.tables))for(let[a,o]of Object.entries(r.relations)){if(o.relation!=="one")continue;let i=o.referenceField??"id",s=o.field??`${a}Id`;o.field=s;let l=F(t,o.targetTable,i)??o.fkType??"string";Kt(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:Gt(`${n}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},l);}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??`${J(n)}Id`;a.field=s;let l=F(t,n,i)??a.fkType??"string";Kt(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:Gt(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},l);}return hr(t),t}function Xt(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function $(e){return e.notNull!==true}function wr(e,t,n){let r=t.sqlName??I(e),a=r!==e;return t.type==="int"?a?`t.int(${h(r)})`:"t.int()":t.type==="string"?t.length!==void 0?a?`t.text(${h(r)}, { length: ${t.length} })`:`t.text({ length: ${t.length} })`:a?`t.text(${h(r)})`:"t.text()":t.type==="boolean"?a?`t.int(${h(r)}, { mode: "boolean" })`:'t.int({ mode: "boolean" })':t.type==="date"?a?`t.int(${h(r)}, { mode: "timestamp_ms" })`:'t.int({ mode: "timestamp_ms" })':n==="camelToSnake"&&a?`t.text(${h(r)})`:"t.text()"}function xr(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 Tr(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
8871
|
+
`}function vr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function Rr(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 kr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations))i.relation==="manyToMany"&&i.junctionTable&&a.push(`${h(o)}: {
|
|
8689
8872
|
targetTable: ${h(i.targetTable)},
|
|
8690
8873
|
junctionTable: ${h(i.junctionTable)},
|
|
8691
8874
|
sourceField: ${h(i.sourceField??"")},
|
|
@@ -8724,7 +8907,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8724
8907
|
${t.map(n=>` ${n}`).join(`
|
|
8725
8908
|
`)}
|
|
8726
8909
|
} as const;
|
|
8727
|
-
`}function Ar(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let i of Object.values(e.tables)){for(let s of
|
|
8910
|
+
`}function Ar(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let i of Object.values(e.tables)){for(let s of vr(i))n.has(s)||r.add(s);for(let s of Object.values(i.columns))s.references&&!n.has(s.references.table)&&r.add(s.references.table);}let a=[],o=[];for(let[i,s]of Object.entries(e.tables)){let l=s.sqlName??I(i),u=[],c=[];for(let[y,m]of Object.entries(s.columns)){let x=wr(y,m,t);m.uuidPrimaryKey&&(x+=".$defaultFn(() => crypto.randomUUID())"),m.primaryKey&&(x+=m.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),m.notNull&&(x+=".notNull()"),m.sqlDefault!==void 0&&(x+=`.default(${dr(m.sqlDefault)})`);let v=Rr(y,m,s);if(v)if(m.references?.onDelete||m.references?.onUpdate){let R=[];m.references.onDelete&&R.push(`onDelete: ${h(m.references.onDelete)}`),m.references.onUpdate&&R.push(`onUpdate: ${h(m.references.onUpdate)}`),x+=`.references(() => ${v.tableName}.${v.fieldName}, { ${R.join(", ")} })`;}else x+=`.references(() => ${v.tableName}.${v.fieldName})`;if(m.unique){let R=typeof m.unique=="object"&&m.unique.name?m.unique.name:`${l}_${I(y)}_unique_idx`;c.push(` t.uniqueIndex(${h(R)}).on(table.${y})`);}if(m.index){let R=typeof m.index=="object"&&m.index.name?m.index.name:`${l}_${I(y)}_idx`;c.push(` t.index(${h(R)}).on(table.${y})`);}u.push(` ${y}: ${x},`);}c.length>0?a.push(`export const ${i} = table(
|
|
8728
8911
|
${h(l)},
|
|
8729
8912
|
{
|
|
8730
8913
|
${u.join(`
|
|
@@ -8737,16 +8920,16 @@ ${c.join(`,
|
|
|
8737
8920
|
);`):a.push(`export const ${i} = table(${h(l)}, {
|
|
8738
8921
|
${u.join(`
|
|
8739
8922
|
`)}
|
|
8740
|
-
});`);let f=Object.entries(s.relations).filter(([,
|
|
8923
|
+
});`);let f=Object.entries(s.relations).filter(([,y])=>y.relation==="one"),d=Object.entries(s.relations).filter(([,y])=>y.relation==="many"),b=Object.entries(s.relations).filter(([,y])=>y.relation==="manyToMany");if(f.length===0&&d.length===0&&b.length===0)continue;let w=[];for(let[y,m]of f){let x=xr(i,s,m);w.push(` ${y}: one(${m.targetTable}, {
|
|
8741
8924
|
fields: [${i}.${x.sourceField}],
|
|
8742
8925
|
references: [${m.targetTable}.${x.targetField}],
|
|
8743
|
-
}),`);}for(let[
|
|
8926
|
+
}),`);}for(let[y,m]of d)w.push(` ${y}: many(${m.targetTable}),`);for(let[y,m]of b){if(!m.junctionTable)throw new Error(`manyToMany relation '${i}.${y}' is missing junctionTable after normalization.`);w.push(` ${y}: many(${m.junctionTable}),`);}o.push(`export const ${i}Relations = relations(${i}, ({ one, many }) => ({
|
|
8744
8927
|
${w.join(`
|
|
8745
8928
|
`)}
|
|
8746
8929
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
8747
8930
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
8748
8931
|
import { relations } from "drizzle-orm";
|
|
8749
|
-
${
|
|
8932
|
+
${Tr(r)}
|
|
8750
8933
|
${a.join(`
|
|
8751
8934
|
|
|
8752
8935
|
`)}
|
|
@@ -8758,7 +8941,7 @@ ${o.join(`
|
|
|
8758
8941
|
${kr(e)}
|
|
8759
8942
|
|
|
8760
8943
|
${Sr(e)}
|
|
8761
|
-
`}function Yt(e,t,n){let r="z.unknown()";return e.type==="int"?r="z.number().int()":e.type==="string"?(r="z.string()",e.length!==void 0&&(r+=`.max(${e.length})`)):e.type==="boolean"?r="z.boolean()":e.type==="date"&&(r="z.date()"),t&&(r+=".optional()"),n&&(r+=".nullable()"),r}function Nr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=
|
|
8944
|
+
`}function Yt(e,t,n){let r="z.unknown()";return e.type==="int"?r="z.number().int()":e.type==="string"?(r="z.string()",e.length!==void 0&&(r+=`.max(${e.length})`)):e.type==="boolean"?r="z.boolean()":e.type==="date"&&(r="z.date()"),t&&(r+=".optional()"),n&&(r+=".nullable()"),r}function Nr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=P(n),o=[],i=[];for(let[s,l]of Object.entries(r.columns))o.push(` ${s}: ${Yt(l,Xt(l),$(l))},`),i.push(` ${s}: ${Yt(l,$(l),$(l))},`);t.push(`export const ${n}InsertSchema = z.object({
|
|
8762
8945
|
${o.join(`
|
|
8763
8946
|
`)}
|
|
8764
8947
|
});
|
|
@@ -8772,7 +8955,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
8772
8955
|
`);}return `import { z } from "zod";
|
|
8773
8956
|
|
|
8774
8957
|
${t.join(`
|
|
8775
|
-
`)}`}function $r(e){return e.type==="int"?"number":e.type==="string"?"string":e.type==="boolean"?"boolean":e.type==="date"?"Date":"unknown"}function
|
|
8958
|
+
`)}`}function $r(e){return e.type==="int"?"number":e.type==="string"?"string":e.type==="boolean"?"boolean":e.type==="date"?"Date":"unknown"}function Cr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=P(n),o=[],i=[];for(let[s,l]of Object.entries(r.columns)){let u=$r(l),c=$(l)?" | null":"";o.push(` ${s}${$(l)?"?":""}: ${u}${c};`),i.push(` ${s}${Xt(l)?"?":""}: ${u}${c};`);}t.push(`export type ${a} = {
|
|
8776
8959
|
${o.join(`
|
|
8777
8960
|
`)}
|
|
8778
8961
|
};
|
|
@@ -8783,11 +8966,11 @@ ${i.join(`
|
|
|
8783
8966
|
};`);}return `${t.join(`
|
|
8784
8967
|
|
|
8785
8968
|
`)}
|
|
8786
|
-
`}function Cr(e,t){if(t){let n=e[t];if(!_(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(_(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function en(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")),l=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),u=Cr(l,t.exportName),c=yr(u);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let f=Ar(c,n),d=qr(c),y=Nr(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Mr(e){return e.replaceAll("\\","/")}function A(e,t){let n=Mr(relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Er=new Set([".ts",".tsx",".mts",".cts"]);async function an(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 an(a));continue}r.isFile()&&Er.has(extname(r.name))&&n.push(a);}return n}function Z(e){return e.replace(/\.[cm]?tsx?$/,"")}function Or(e,t){let n=e,r=false,a,o="unknown";for(;g.isCallExpression(n);){let i=n.expression;if(!g.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let l=n.arguments[0];l&&(g.isStringLiteral(l)||g.isNumericLiteral(l)?a=l.text:l.kind===g.SyntaxKind.TrueKeyword?a="true":l.kind===g.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function jr(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g.isPropertyAssignment(r)&&g.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)||n.push(Or(r.initializer,r.name.text));return n}function Vr(e){return g.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g.SyntaxKind.ExportKeyword)??false:false}function on(e){return g.isIdentifier(e)?e.text:g.isParenthesizedExpression(e)?on(e.expression):null}function Br(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g.isPropertyAssignment(t))return [];let n=t.initializer;return g.isStringLiteral(n)||g.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g.isArrayLiteralExpression(n)?n.elements.map(r=>g.isStringLiteral(r)||g.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Hr(e,t){let n=g.createSourceFile(t,e,g.ScriptTarget.Latest,true,g.ScriptKind.TS),r=[];for(let a of n.statements)if(Vr(a))for(let o of a.declarationList.declarations){if(!g.isIdentifier(o.name)||!o.initializer||!g.isCallExpression(o.initializer))continue;let i=on(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"?Br(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?jr(o.initializer.arguments[0]):[]});}return r}function tn(e,t,n){let r=t.replace(/\\/g,"/"),o=Z(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Wr(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 nn(e,t){let n=e.replace(/\\/g,"/"),a=Z(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 sn(e){let t=[],n=await an(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),l=Hr(i,a),u=[{kind:"query",kindDirectory:"queries",exports:l.filter(c=>c.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:l.filter(c=>c.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:l.filter(c=>c.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:l.filter(c=>c.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:l.filter(c=>c.kind==="storage")}];for(let c of u){if(c.exports.length===0)continue;let f=Wr(s,c.kindDirectory);for(let d of c.exports){let y=c.kind==="query"||c.kind==="mutation"?nn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?nn(f,d.exportName):void 0,b=c.kind==="query"||c.kind==="mutation"?[...Z(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?tn("queries",f,d.exportName):c.kind==="mutation"?tn("mutations",f,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${w}`;t.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:A(e.outDirAbs,a),clientImportPath:A(resolve(e.outDirAbs,"client"),a),routePath:m,handlerName:y,clientSegments:b,taskName:w,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 zr(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,l=false,u=false;for(let f=0;f<e.length;f+=1){let d=e[f];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=true;continue}if(!s&&!l&&d==="'"){i=!i,n+=d;continue}if(!i&&!l&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){l=!l,n+=d;continue}if(i||s||l){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 c=n.trim();return c.length>0&&t.push(c),t}function Ur(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let l=0;l<e.length;l+=1){let u=e[l];if(s){s=false;continue}if(u==="\\"){s=true;continue}if(!o&&!i&&u==="'"){a=!a;continue}if(!a&&!i&&u==='"'){o=!o;continue}if(!a&&!o&&u==="`"){i=!i;continue}if(!(a||o||i)){if(u==="("){t+=1;continue}if(u===")"){t-=1;continue}if(u==="{"){n+=1;continue}if(u==="}"){n-=1;continue}if(u==="["){r+=1;continue}if(u==="]"){r-=1;continue}if(u===":"&&t===0&&n===0&&r===0)return l}}return -1}function Qr(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 _r(e){let t=zr(e),n=[];for(let r of t){let a=Ur(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),l=/autoincrement\s*:\s*true/i.test(i),u=/\.default\s*\(/i.test(i),f=!/\.notnull\s*\(/i.test(i)||u||l||s;n.push({name:o,expression:i,type:Qr(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function Kr(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,l=false,u=false,c=false,f=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(f){f=false;continue}if(y==="\\"){f=true;continue}if(!u&&!c&&y==="'"){l=!l;continue}if(!l&&!c&&y==='"'){u=!u;continue}if(!l&&!u&&y==="`"){c=!c;continue}if(!(l||u||c)){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 l=r(e,s);if(l===-1){a=t.exec(e);continue}let u=e.slice(s+1,l);n.push({exportName:o,tableName:i,columns:_r(u)}),a=t.exec(e);}return n}async function cn(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 cn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function un(e,t=[]){let n=await cn(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(),l=Kr(s);if(l.length>0)return {schemaPath:o,tables:l}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function Jr(e,t){let n=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function dn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=A(t,a),s=resolve(t,"client"),l=A(s,a);await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]);let u=resolve(t,"server.ts"),c=resolve(t,"client.ts"),f=resolve(t,"auth.config.ts"),d=resolve(t,"auth.schema.ts"),y=resolve(t,"drizzle.config.ts"),w=resolve(n,"wrangler.json"),b=await en(e),m=await un(e,b?[b.schemaPath]:[]),x=A(t,m.schemaPath),T=await sn(e),R=at(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),vn=ce(l,T),Tn=H(x,T,r.r2[0]?.binding),Rn=ne(i),kn=b?[Jr(o,b.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,Sn=ue(kn),An=it(e,T),Nn=_t(x,m,T),$n=resolve(t,"admin.routes.ts"),qn=Tn.map(k=>Bun.write(resolve(t,k.relativePath),k.source)),Cn=vn.map(k=>Bun.write(resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8787
|
-
`),...Cn
|
|
8788
|
-
`),Bun.write($n,Nn)]);let O=relative(o,f).replace(/\\/g,"/"),
|
|
8969
|
+
`}function qr(e,t){if(t){let n=e[t];if(!_(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(_(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function en(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")),l=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),u=qr(l,t.exportName),c=br(u);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let f=Ar(c,n),d=Cr(c),b=Nr(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,b)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Ir(e){return e.replaceAll("\\","/")}function A(e,t){let n=Ir(relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Dr=new Set([".ts",".tsx",".mts",".cts"]);async function an(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 an(a));continue}r.isFile()&&Dr.has(extname(r.name))&&n.push(a);}return n}function Z(e){return e.replace(/\.[cm]?tsx?$/,"")}function Or(e,t){let n=e,r=false,a,o="unknown";for(;g.isCallExpression(n);){let i=n.expression;if(!g.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let l=n.arguments[0];l&&(g.isStringLiteral(l)||g.isNumericLiteral(l)?a=l.text:l.kind===g.SyntaxKind.TrueKeyword?a="true":l.kind===g.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function jr(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g.isPropertyAssignment(r)&&g.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)||n.push(Or(r.initializer,r.name.text));return n}function Br(e){return g.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g.SyntaxKind.ExportKeyword)??false:false}function on(e){return g.isIdentifier(e)?e.text:g.isParenthesizedExpression(e)?on(e.expression):null}function Vr(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g.isPropertyAssignment(t))return [];let n=t.initializer;return g.isStringLiteral(n)||g.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g.isArrayLiteralExpression(n)?n.elements.map(r=>g.isStringLiteral(r)||g.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Wr(e,t){let n=g.createSourceFile(t,e,g.ScriptTarget.Latest,true,g.ScriptKind.TS),r=[];for(let a of n.statements)if(Br(a))for(let o of a.declarationList.declarations){if(!g.isIdentifier(o.name)||!o.initializer||!g.isCallExpression(o.initializer))continue;let i=on(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"?Vr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?jr(o.initializer.arguments[0]):[]});}return r}function tn(e,t,n){let r=t.replace(/\\/g,"/"),o=Z(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Hr(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 nn(e,t){let n=e.replace(/\\/g,"/"),a=Z(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 sn(e){let t=[],n=await an(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),l=Wr(i,a),u=[{kind:"query",kindDirectory:"queries",exports:l.filter(c=>c.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:l.filter(c=>c.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:l.filter(c=>c.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:l.filter(c=>c.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:l.filter(c=>c.kind==="storage")}];for(let c of u){if(c.exports.length===0)continue;let f=Hr(s,c.kindDirectory);for(let d of c.exports){let b=c.kind==="query"||c.kind==="mutation"?nn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?nn(f,d.exportName):void 0,y=c.kind==="query"||c.kind==="mutation"?[...Z(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?tn("queries",f,d.exportName):c.kind==="mutation"?tn("mutations",f,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${w}`;t.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:A(e.outDirAbs,a),clientImportPath:A(resolve(e.outDirAbs,"client"),a),routePath:m,handlerName:b,clientSegments:y,taskName:w,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 Lr(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,l=false,u=false;for(let f=0;f<e.length;f+=1){let d=e[f];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=true;continue}if(!s&&!l&&d==="'"){i=!i,n+=d;continue}if(!i&&!l&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){l=!l,n+=d;continue}if(i||s||l){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 b=n.trim();b.length>0&&t.push(b),n="";continue}n+=d;}let c=n.trim();return c.length>0&&t.push(c),t}function Ur(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let l=0;l<e.length;l+=1){let u=e[l];if(s){s=false;continue}if(u==="\\"){s=true;continue}if(!o&&!i&&u==="'"){a=!a;continue}if(!a&&!i&&u==='"'){o=!o;continue}if(!a&&!o&&u==="`"){i=!i;continue}if(!(a||o||i)){if(u==="("){t+=1;continue}if(u===")"){t-=1;continue}if(u==="{"){n+=1;continue}if(u==="}"){n-=1;continue}if(u==="["){r+=1;continue}if(u==="]"){r-=1;continue}if(u===":"&&t===0&&n===0&&r===0)return l}}return -1}function Qr(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 _r(e){let t=Lr(e),n=[];for(let r of t){let a=Ur(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),l=/autoincrement\s*:\s*true/i.test(i),u=/\.default\s*\(/i.test(i),f=!/\.notnull\s*\(/i.test(i)||u||l||s;n.push({name:o,expression:i,type:Qr(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function Kr(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,l=false,u=false,c=false,f=false;for(let d=i;d<o.length;d+=1){let b=o[d];if(f){f=false;continue}if(b==="\\"){f=true;continue}if(!u&&!c&&b==="'"){l=!l;continue}if(!l&&!c&&b==='"'){u=!u;continue}if(!l&&!u&&b==="`"){c=!c;continue}if(!(l||u||c)){if(b==="{"){s+=1;continue}if(b==="}"&&(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 l=r(e,s);if(l===-1){a=t.exec(e);continue}let u=e.slice(s+1,l);n.push({exportName:o,tableName:i,columns:_r(u)}),a=t.exec(e);}return n}async function cn(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 cn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function un(e,t=[]){let n=await cn(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(),l=Kr(s);if(l.length>0)return {schemaPath:o,tables:l}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function Jr(e,t){let n=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function dn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=A(t,a),s=resolve(t,"client"),l=A(s,a);await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]);let u=resolve(t,"server.ts"),c=resolve(t,"client.ts"),f=resolve(t,"auth.config.ts"),d=resolve(t,"auth.schema.ts"),b=resolve(t,"drizzle.config.ts"),w=resolve(n,"wrangler.json"),y=await en(e),m=await un(e,y?[y.schemaPath]:[]),x=A(t,m.schemaPath),v=await sn(e),R=at(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),Tn=ce(l,v),vn=W(x,v,r.r2[0]?.binding),Rn=ne(i),kn=y?[Jr(o,y.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,Sn=ue(kn),An=it(e,v),Nn=_t(x,m,v),$n=resolve(t,"admin.routes.ts"),Cn=vn.map(k=>Bun.write(resolve(t,k.relativePath),k.source)),qn=Tn.map(k=>Bun.write(resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8970
|
+
`),...qn,...Cn,Bun.write(f,Rn),Bun.write(d,""),Bun.write(b,Sn),Bun.write(w,`${JSON.stringify(An,null,2)}
|
|
8971
|
+
`),Bun.write($n,Nn)]);let O=relative(o,f).replace(/\\/g,"/"),Mn=O.startsWith(".")?O:`./${O}`,j=relative(o,d).replace(/\\/g,"/"),In=j.startsWith(".")?j:`./${j}`,ee=await Bun.spawn(["npx","@better-auth/cli","generate","--config",Mn,"--output",In,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(ee!==0)throw new Error(`better-auth generation failed with exit code ${ee}`);let Fn=resolve(o,"tsconfig.json");if(e.config.build&&existsSync(Fn)){let k=process.platform==="win32"?"npx.cmd":"npx",te=await Bun.spawn([k,"--yes","-p","typescript","tsc","--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(te!==0)throw new Error(`TypeScript build failed with exit code ${te}`)}}var pn=z$1.object({binding:z$1.string().min(1),databaseName:z$1.string().min(1),databaseId:z$1.string().min(1),previewDatabaseId:z$1.string().min(1).optional(),migrationsDir:z$1.string().min(1).optional()}).strict(),mn=z$1.object({binding:z$1.string().min(1),id:z$1.string().min(1),previewId:z$1.string().min(1).optional()}).strict(),gn=z$1.object({binding:z$1.string().min(1),bucketName:z$1.string().min(1),previewBucketName:z$1.string().min(1).optional(),jurisdiction:z$1.string().min(1).optional()}).strict(),fn=z$1.object({enabled:z$1.boolean().optional(),binding:z$1.string().min(1).optional(),queue:z$1.string().min(1).optional()}).strict(),ea=z$1.object({enabled:z$1.boolean().optional(),binding:z$1.string().min(1).optional(),className:z$1.string().min(1).optional(),objectName:z$1.string().min(1).optional(),subscribePath:z$1.string().min(1).optional(),websocketPath:z$1.string().min(1).optional(),protocol:z$1.string().min(1).optional()}).strict(),ta=z$1.object({scanDir:z$1.string().min(1),outDir:z$1.string().min(1),wranglerOutDir:z$1.string().min(1).optional(),wranglerOutPath:z$1.string().min(1).optional(),schema:z$1.array(z$1.string()).min(1),schemaDsl:z$1.object({entry:z$1.string().min(1),exportName:z$1.string().min(1).optional(),outFile:z$1.string().min(1).optional(),typesOutFile:z$1.string().min(1).optional(),zodOutFile:z$1.string().min(1).optional(),namingStrategy:z$1.literal("camelToSnake").optional()}).strict().optional(),database:z$1.union([pn,z$1.array(pn).min(1)]),kv:z$1.union([mn,z$1.array(mn)]).optional(),r2:z$1.union([gn,z$1.array(gn)]).optional(),auth:z$1.object({enabled:z$1.boolean(),basePath:z$1.string().min(1),options:z$1.custom(e=>typeof e=="object"&&e!==null),clientOptions:z$1.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:fn.optional(),realtime:ea.optional(),wranglerOverrides:z$1.record(z$1.string(),z$1.unknown()).optional(),build:z$1.boolean().optional()}).strict();function hn(e){return typeof e=="object"&&e!==null}function na(e){let t=hn(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=fn.safeParse(t);return n.success?n.data:{}}function ra(e){if(!hn(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function aa(e){let n={...na(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:ra(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function C(e){let t=isAbsolute(e??"")?e:resolve(process.cwd(),e??"appflare.config.ts"),n=dirname(t),o=(await import(pathToFileURL(t).href)).default,i=ta.parse(o),s=aa(i);return {configPath:t,configDir:n,scanDirAbs:resolve(n,s.scanDir),outDirAbs:resolve(n,s.outDir),wranglerOutDirAbs:resolve(n,s.wranglerOutDir),config:s}}function la(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 D(e,t={}){let n=await C(e);if(t.build!==void 0&&(n.config.build=t.build),await dn(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
8789
8972
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
8790
|
-
`);}async function
|
|
8973
|
+
`);}async function bn(e,t={}){if(await D(e,{build:t.build}),!t.watch)return;let n=await C(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await D(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
8791
8974
|
`);}finally{r=false,a&&(a=false,await o());}};oa.watch(n.scanDirAbs,{ignoreInitial:true}).on("all",async(s,l)=>{process.stdout.write(`\u{1F504} Change detected: ${l}
|
|
8792
8975
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
8793
|
-
`);}async function wn(e,t={}){let n=await
|
|
8976
|
+
`);}async function wn(e,t={}){let n=await C(e),r=la(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.ts"),i=process.platform==="win32"?"npx.cmd":"npx",l=await Bun.spawn([i,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(l!==0)throw new Error(`drizzle-kit generate failed with exit code ${l}`);let u=n.config.database[0].databaseName,c=[i,"wrangler","d1","migrations","apply",u];t.local?c.push("--local"):t.remote?c.push("--remote"):t.preview&&c.push("--preview");let d=await Bun.spawn(c,{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 xn(e,t={name:"",email:"",password:""}){let n=await C(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(),l=Date.now(),u=t.name.replace(/'/g,"''"),c=t.email.replace(/'/g,"''"),f=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${u}', '${c}', 1, ${l}, ${l}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${c}', 'credential', '${i}', '${o}', ${l}, ${l});`].join(" "),d=n.config.database[0].databaseName,w=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${f}`];t.local?w.push("--local"):t.remote&&w.push("--remote");let m=await Bun.spawn(w,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(m!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${m}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var N=new Command;N.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");N.command("build").description("Generate server.ts, client.ts, auth.config.ts, drizzle.config.ts, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--no-build","Skip TypeScript build step").action(async e=>{await D(e.config,{build:e.build});});N.command("dev").description("Run generator in development mode").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("-w, --watch","Watch scanDir and regenerate on changes",false).option("--no-build","Skip TypeScript build step").action(async e=>{await bn(e.config,{watch:e.watch,build:e.build});});N.command("migrate").description("Generate drizzle migration files from outDir/auth.schema.ts and apply them to the configured D1 database").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute commands/files against a local DB for use with wrangler dev",false).option("--remote","Execute commands/files against a remote DB for use with wrangler dev --remote",false).option("--preview","Execute commands/files against a preview D1 DB",false).action(async e=>{await wn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});N.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 xn(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 N.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|