appflare 0.2.46 → 0.2.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Documentation.md +898 -898
- package/cli/commands/index.ts +247 -247
- package/cli/generate.ts +360 -360
- package/cli/index.ts +120 -120
- package/cli/load-config.ts +184 -184
- package/cli/schema-compiler.ts +1366 -1366
- package/cli/templates/auth/README.md +156 -156
- package/cli/templates/auth/config.ts +61 -61
- package/cli/templates/auth/route-config.ts +1 -1
- package/cli/templates/auth/route-handler.ts +1 -1
- package/cli/templates/auth/route-request-utils.ts +5 -5
- package/cli/templates/auth/route.config.ts +18 -18
- package/cli/templates/auth/route.handler.ts +18 -18
- package/cli/templates/auth/route.request-utils.ts +55 -55
- package/cli/templates/auth/route.ts +14 -14
- package/cli/templates/core/README.md +266 -266
- package/cli/templates/core/app-creation.ts +19 -19
- package/cli/templates/core/client/appflare.ts +112 -112
- package/cli/templates/core/client/handlers/index.ts +763 -763
- package/cli/templates/core/client/handlers.ts +1 -1
- package/cli/templates/core/client/index.ts +7 -7
- package/cli/templates/core/client/storage.ts +195 -195
- package/cli/templates/core/client/types.ts +187 -187
- package/cli/templates/core/client-modules/appflare.ts +1 -1
- package/cli/templates/core/client-modules/handlers.ts +1 -1
- package/cli/templates/core/client-modules/index.ts +1 -1
- package/cli/templates/core/client-modules/storage.ts +1 -1
- package/cli/templates/core/client-modules/types.ts +1 -1
- package/cli/templates/core/client.artifacts.ts +39 -39
- package/cli/templates/core/client.ts +4 -4
- package/cli/templates/core/drizzle.ts +15 -15
- package/cli/templates/core/export.ts +14 -14
- package/cli/templates/core/handlers.route.ts +24 -24
- package/cli/templates/core/handlers.ts +1 -1
- package/cli/templates/core/imports.ts +9 -9
- package/cli/templates/core/server.ts +38 -38
- package/cli/templates/core/types.ts +6 -6
- package/cli/templates/core/wrangler.ts +109 -109
- package/cli/templates/dashboard/builders/functions/index.ts +17 -17
- package/cli/templates/dashboard/builders/functions/render-page/header.ts +20 -20
- package/cli/templates/dashboard/builders/functions/render-page/index.ts +33 -33
- package/cli/templates/dashboard/builders/functions/render-page/request-panel.ts +271 -271
- package/cli/templates/dashboard/builders/functions/render-page/result-panel.ts +85 -85
- package/cli/templates/dashboard/builders/functions/render-page/scripts.ts +703 -703
- package/cli/templates/dashboard/builders/functions/tree-builder.ts +47 -47
- package/cli/templates/dashboard/builders/navigation.ts +155 -155
- package/cli/templates/dashboard/builders/storage/index.ts +13 -13
- package/cli/templates/dashboard/builders/storage/routes/create-directory-route.ts +29 -29
- package/cli/templates/dashboard/builders/storage/routes/delete-route.ts +18 -18
- package/cli/templates/dashboard/builders/storage/routes/download-route.ts +23 -23
- package/cli/templates/dashboard/builders/storage/routes/index.ts +22 -22
- package/cli/templates/dashboard/builders/storage/routes/list-route.ts +25 -25
- package/cli/templates/dashboard/builders/storage/routes/preview-route.ts +21 -21
- package/cli/templates/dashboard/builders/storage/routes/upload-route.ts +21 -21
- package/cli/templates/dashboard/builders/storage/runtime/helpers.ts +72 -72
- package/cli/templates/dashboard/builders/storage/runtime/storage-page.ts +130 -130
- package/cli/templates/dashboard/builders/table-routes/common/drawer-panel.ts +27 -27
- package/cli/templates/dashboard/builders/table-routes/common/pagination.ts +30 -30
- package/cli/templates/dashboard/builders/table-routes/common/search-bar.ts +23 -23
- package/cli/templates/dashboard/builders/table-routes/fragments.ts +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 +420 -420
- package/cli/templates/dashboard/components/login-page.ts +65 -65
- package/cli/templates/dashboard/index.ts +61 -61
- package/cli/templates/dashboard/types.ts +9 -9
- package/cli/templates/handlers/README.md +353 -353
- package/cli/templates/handlers/auth.ts +37 -37
- package/cli/templates/handlers/execution.ts +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 +14 -14
- package/cli/templates/handlers/generators/registration/modules/cron.ts +35 -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 +510 -510
- package/cli/templates/handlers/generators/registration/modules/scheduler.ts +65 -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 +121 -121
- package/cli/templates/handlers/generators/types/core.ts +108 -106
- package/cli/templates/handlers/generators/types/operations.ts +135 -135
- package/cli/templates/handlers/generators/types/query-definitions/filter-and-where-types.ts +291 -291
- package/cli/templates/handlers/generators/types/query-definitions/query-api-types.ts +135 -135
- package/cli/templates/handlers/generators/types/query-definitions/query-helper-functions.ts +1382 -1382
- package/cli/templates/handlers/generators/types/query-definitions/schema-and-table-types.ts +278 -278
- package/cli/templates/handlers/generators/types/query-definitions.ts +13 -13
- package/cli/templates/handlers/generators/types/query-runtime/handled-error.ts +13 -13
- package/cli/templates/handlers/generators/types/query-runtime/runtime-aggregate-and-footer.ts +174 -174
- package/cli/templates/handlers/generators/types/query-runtime/runtime-read.ts +158 -157
- package/cli/templates/handlers/generators/types/query-runtime/runtime-setup.ts +45 -45
- package/cli/templates/handlers/generators/types/query-runtime/runtime-write.ts +958 -958
- package/cli/templates/handlers/generators/types/query-runtime.ts +15 -15
- package/cli/templates/handlers/index.ts +47 -47
- package/cli/templates/handlers/operations.ts +116 -116
- package/cli/templates/handlers/registration.ts +91 -91
- package/cli/templates/handlers/types.ts +17 -17
- package/cli/templates/handlers/utils.ts +48 -48
- package/cli/types.ts +110 -110
- package/cli/utils/handler-discovery.ts +501 -501
- package/cli/utils/json-utils.ts +24 -24
- package/cli/utils/path-utils.ts +19 -19
- package/cli/utils/schema-discovery.ts +399 -399
- package/dist/cli/index.js +43 -23
- package/dist/cli/index.mjs +43 -23
- package/dist/react/index.js +1 -1
- package/dist/react/index.mjs +1 -1
- package/index.ts +18 -18
- package/package.json +58 -58
- package/react/index.ts +5 -5
- package/react/use-infinite-query.ts +255 -255
- package/react/use-mutation.ts +89 -89
- package/react/use-query.ts +210 -210
- package/schema.ts +641 -641
- package/test-better-auth-hash.ts +2 -2
- package/tsconfig.json +6 -6
- package/tsup.config.ts +82 -82
package/dist/cli/index.js
CHANGED
|
@@ -1205,7 +1205,7 @@ type R2BucketBinding = {
|
|
|
1205
1205
|
options?: { expiresIn?: number },
|
|
1206
1206
|
) => Promise<URL>;
|
|
1207
1207
|
};
|
|
1208
|
-
`}function
|
|
1208
|
+
`}function Me(){return `
|
|
1209
1209
|
export function createScheduler(
|
|
1210
1210
|
queue?: SchedulerQueueBinding,
|
|
1211
1211
|
): Scheduler {
|
|
@@ -1226,7 +1226,7 @@ export function createScheduler(
|
|
|
1226
1226
|
},
|
|
1227
1227
|
};
|
|
1228
1228
|
}
|
|
1229
|
-
`}function
|
|
1229
|
+
`}function Ie(){return `
|
|
1230
1230
|
function createContextErrorHelpers() {
|
|
1231
1231
|
return {
|
|
1232
1232
|
error: (status: number, message: string, details?: unknown) => {
|
|
@@ -1490,10 +1490,10 @@ ${qe()}
|
|
|
1490
1490
|
|
|
1491
1491
|
${Fe()}
|
|
1492
1492
|
|
|
1493
|
-
${Ie()}
|
|
1494
|
-
|
|
1495
1493
|
${Me()}
|
|
1496
1494
|
|
|
1495
|
+
${Ie()}
|
|
1496
|
+
|
|
1497
1497
|
${je()}
|
|
1498
1498
|
|
|
1499
1499
|
${Ee()}
|
|
@@ -1564,6 +1564,8 @@ import {
|
|
|
1564
1564
|
isNotNull,
|
|
1565
1565
|
getTableColumns,
|
|
1566
1566
|
sql,
|
|
1567
|
+
asc,
|
|
1568
|
+
desc,
|
|
1567
1569
|
type InferInsertModel,
|
|
1568
1570
|
type InferSelectModel,
|
|
1569
1571
|
type SQL,
|
|
@@ -3946,8 +3948,8 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3946
3948
|
(item: Record<string, unknown>) => {
|
|
3947
3949
|
const column = item.column as string;
|
|
3948
3950
|
const direction = (item.direction as string) ?? "asc";
|
|
3949
|
-
const col = (table as Record<string,
|
|
3950
|
-
return direction === "desc" ?
|
|
3951
|
+
const col = (table as Record<string, any>)[column];
|
|
3952
|
+
return direction === "desc" ? desc(col) : asc(col);
|
|
3951
3953
|
},
|
|
3952
3954
|
)
|
|
3953
3955
|
: undefined;
|
|
@@ -4023,8 +4025,8 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4023
4025
|
(item: Record<string, unknown>) => {
|
|
4024
4026
|
const column = item.column as string;
|
|
4025
4027
|
const direction = (item.direction as string) ?? "asc";
|
|
4026
|
-
const col = (table as Record<string,
|
|
4027
|
-
return direction === "desc" ?
|
|
4028
|
+
const col = (table as Record<string, any>)[column];
|
|
4029
|
+
return direction === "desc" ? desc(col) : asc(col);
|
|
4028
4030
|
},
|
|
4029
4031
|
)
|
|
4030
4032
|
: undefined;
|
|
@@ -6614,6 +6616,15 @@ export async function executeScheduledBatch(
|
|
|
6614
6616
|
const payloadValue = body.payload === null ? undefined : body.payload;
|
|
6615
6617
|
const parsed = operation.schema.parse(payloadValue);
|
|
6616
6618
|
await operation.definition.handler(ctx, parsed);
|
|
6619
|
+
|
|
6620
|
+
if (typeof publishMutationEvents === "function") {
|
|
6621
|
+
await publishMutationEvents(
|
|
6622
|
+
{ req: { raw: new Request("http://localhost") }, env },
|
|
6623
|
+
options,
|
|
6624
|
+
ctx.mutationEvents,
|
|
6625
|
+
);
|
|
6626
|
+
}
|
|
6627
|
+
ctx.mutationEvents.length = 0;
|
|
6617
6628
|
} catch (error) {
|
|
6618
6629
|
if (error instanceof ZodError) {
|
|
6619
6630
|
console.error("Invalid scheduler payload", task, error.issues);
|
|
@@ -6644,6 +6655,15 @@ export async function executeCronTriggers(
|
|
|
6644
6655
|
|
|
6645
6656
|
try {
|
|
6646
6657
|
await cronEntry.definition.handler(ctx);
|
|
6658
|
+
|
|
6659
|
+
if (typeof publishMutationEvents === "function") {
|
|
6660
|
+
await publishMutationEvents(
|
|
6661
|
+
{ req: { raw: new Request("http://localhost") }, env },
|
|
6662
|
+
options,
|
|
6663
|
+
ctx.mutationEvents,
|
|
6664
|
+
);
|
|
6665
|
+
}
|
|
6666
|
+
ctx.mutationEvents.length = 0;
|
|
6647
6667
|
} catch (error) {
|
|
6648
6668
|
console.error("Cron task failed", cronEntry.taskName, error);
|
|
6649
6669
|
}
|
|
@@ -6909,7 +6929,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6909
6929
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6910
6930
|
</a>
|
|
6911
6931
|
</th>
|
|
6912
|
-
`}).join("")}function
|
|
6932
|
+
`}).join("")}function Mt(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function te(e,t,n){let r=e.columns.find(i=>i.name===t);if(!r)return "";let a=r.optional?"":" required",o=r.type==="number"?"number":r.type==="date"?"date":"text";if(r.type==="boolean")return n==="edit"?`
|
|
6913
6933
|
<div class="form-control">
|
|
6914
6934
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6915
6935
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6992,7 +7012,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6992
7012
|
payload.${n} = raw_${n};
|
|
6993
7013
|
}
|
|
6994
7014
|
`}).join(`
|
|
6995
|
-
`)}function
|
|
7015
|
+
`)}function It(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function jt(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function Et(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function Pt(e,t,n,r){return t?`<td class="text-right">
|
|
6996
7016
|
<div class="drawer drawer-end">
|
|
6997
7017
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6998
7018
|
<div class="drawer-content">
|
|
@@ -7463,7 +7483,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7463
7483
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7464
7484
|
});
|
|
7465
7485
|
${u}
|
|
7466
|
-
`}function re(e){let t=
|
|
7486
|
+
`}function re(e){let t=It(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>jt(e,w)),o=r.filter(w=>Et(e,w)),i=Ft(e),s=qt(e,r),c=Mt(r,t),l=a.map(w=>te(e,w,"create")).join(""),u=o.map(w=>te(e,w,"edit")).join(""),p=ne(e,a),d=ne(e,o),y=n?t:r[0]||"id",v=e.columns.find(w=>w.name===t)?.type,A=Pt(e,n,t,u);return Ot(e,y,t,n,r,i,s,c,A,l)+`
|
|
7467
7487
|
`+Dt(e.exportName,y,t,v,n,i,p,d)}function Vt(){return `
|
|
7468
7488
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7469
7489
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
@@ -7937,7 +7957,7 @@ ${ae()}`}function _t(e){return `
|
|
|
7937
7957
|
${r.optional?"":"required"}
|
|
7938
7958
|
/>
|
|
7939
7959
|
</div>`}).join(`
|
|
7940
|
-
`)}function
|
|
7960
|
+
`)}function Mr(e){return `
|
|
7941
7961
|
<div class="space-y-4">
|
|
7942
7962
|
<div class="flex items-center justify-between">
|
|
7943
7963
|
<div class="flex flex-col">
|
|
@@ -7954,7 +7974,7 @@ ${ae()}`}function _t(e){return `
|
|
|
7954
7974
|
</div>
|
|
7955
7975
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7956
7976
|
</div>
|
|
7957
|
-
`}function
|
|
7977
|
+
`}function Ir(){return `
|
|
7958
7978
|
<div class="space-y-4">
|
|
7959
7979
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7960
7980
|
<div class="relative group">
|
|
@@ -8006,10 +8026,10 @@ ${ae()}`}function _t(e){return `
|
|
|
8006
8026
|
<!-- Tab Content -->
|
|
8007
8027
|
<div class="flex-1 overflow-y-auto">
|
|
8008
8028
|
<div id="request-tab-args" class="p-5">
|
|
8009
|
-
${
|
|
8029
|
+
${Mr(e)}
|
|
8010
8030
|
</div>
|
|
8011
8031
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
8012
|
-
${
|
|
8032
|
+
${Ir()}
|
|
8013
8033
|
</div>
|
|
8014
8034
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
8015
8035
|
${jr()}
|
|
@@ -9739,11 +9759,11 @@ ${y.join(`,
|
|
|
9739
9759
|
);`):s.push(`export const ${l} = table(${g(p)}, {
|
|
9740
9760
|
${d.join(`
|
|
9741
9761
|
`)}
|
|
9742
|
-
});`);let v=Object.entries(u.relations).filter(([,b])=>b.relation==="one"),A=Object.entries(u.relations).filter(([,b])=>b.relation==="many"),w=Object.entries(u.relations).filter(([,b])=>b.relation==="manyToMany");if(v.length===0&&A.length===0&&w.length===0)continue;let
|
|
9762
|
+
});`);let v=Object.entries(u.relations).filter(([,b])=>b.relation==="one"),A=Object.entries(u.relations).filter(([,b])=>b.relation==="many"),w=Object.entries(u.relations).filter(([,b])=>b.relation==="manyToMany");if(v.length===0&&A.length===0&&w.length===0)continue;let I=[];for(let[b,h]of v){let T=Ur(l,u,h);I.push(` ${b}: one(${h.targetTable}, {
|
|
9743
9763
|
fields: [${l}.${T.sourceField}],
|
|
9744
9764
|
references: [${h.targetTable}.${T.targetField}],
|
|
9745
|
-
}),`);}for(let[b,h]of A)
|
|
9746
|
-
${
|
|
9765
|
+
}),`);}for(let[b,h]of A)I.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of w){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);I.push(` ${b}: many(${h.junctionTable}),`);}c.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
9766
|
+
${I.join(`
|
|
9747
9767
|
`)}
|
|
9748
9768
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9749
9769
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
@@ -9794,11 +9814,11 @@ ${s.join(`
|
|
|
9794
9814
|
${n.join(`
|
|
9795
9815
|
|
|
9796
9816
|
`)}
|
|
9797
|
-
`}function na(e,t){if(t){let n=e[t];if(!oe(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(oe(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function xn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),l=na(c,t.exportName),u=Lr(l);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(i),{recursive:true})]);let p=Xr(u,n),d=ta(u),y=Yr(u);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(u.tables)}}function aa(e){return e.replaceAll("\\","/")}function I(e,t){let n=aa(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var la=new Set([".ts",".tsx",".mts",".cts"]);async function kn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await kn(a));continue}r.isFile()&&la.has(path.extname(r.name))&&n.push(a);}return n}function pe(e){return e.replace(/\.[cm]?tsx?$/,"")}function de(e,t){let n=e,r=false,a,o="unknown",i,s,c;for(;f__namespace.isCallExpression(n);){let l=n.expression;if(!f__namespace.isPropertyAccessExpression(l))break;let u=l.name.text;if(u==="optional"||u==="nullable")r=true,n=l.expression;else if(u==="default"){r=true;let p=n.arguments[0];p&&(f__namespace.isStringLiteral(p)||f__namespace.isNumericLiteral(p)?a=p.text:p.kind===f__namespace.SyntaxKind.TrueKeyword?a="true":p.kind===f__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=l.expression;}else if(u==="string"||u==="uuid"||u==="email"||u==="url"){o="string";break}else if(u==="number"||u==="int"||u==="float"){o="number";break}else if(u==="boolean"){o="boolean";break}else if(u==="date"){o="date";break}else if(u==="object"){o="object";let p=n.arguments[0];if(p&&f__namespace.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f__namespace.isPropertyAssignment(d)&&f__namespace.isIdentifier(d.name)&&i.push(de(d.initializer,d.name.text));}break}else if(u==="array"){o="array";let p=n.arguments[0];if(p){let d=de(p,"");s=d.type==="array"?"unknown":d.type,d.type==="object"&&(c=d.fields);}break}else n=l.expression;}return {name:t,type:o,optional:r,defaultValue:a,fields:i,itemType:s,itemFields:c}}function ua(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f__namespace.isPropertyAssignment(r)&&f__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)||n.push(de(r.initializer,r.name.text));return n}function ca(e){return f__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f__namespace.SyntaxKind.ExportKeyword)??false:false}function Sn(e){return f__namespace.isIdentifier(e)?e.text:f__namespace.isParenthesizedExpression(e)?Sn(e.expression):null}function da(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return f__namespace.isStringLiteral(n)||f__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>f__namespace.isStringLiteral(r)||f__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function pa(e,t){let n=f__namespace.createSourceFile(t,e,f__namespace.ScriptTarget.Latest,true,f__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(ca(a))for(let o of a.declarationList.declarations){if(!f__namespace.isIdentifier(o.name)||!o.initializer||!f__namespace.isCallExpression(o.initializer))continue;let i=Sn(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?da(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ua(o.initializer.arguments[0]):[]});}return r}function Tn(e,t,n){let r=t.replace(/\\/g,"/"),o=pe(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function ma(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function vn(e,t){let n=e.replace(/\\/g,"/"),a=pe(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function An(e){let t=[],n=await kn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),c=pa(i,a),l=[{kind:"query",kindDirectory:"queries",exports:c.filter(u=>u.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(u=>u.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(u=>u.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(u=>u.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(u=>u.kind==="storage")}];for(let u of l){if(u.exports.length===0)continue;let p=ma(s,u.kindDirectory);for(let d of u.exports){let y=u.kind==="query"||u.kind==="mutation"?vn(p,d.exportName):void 0,v=u.kind==="scheduler"||u.kind==="cron"?vn(p,d.exportName):void 0,A=u.kind==="query"||u.kind==="mutation"?[...pe(p).split("/").filter(Boolean),d.exportName]:void 0,w=u.kind==="query"?Tn("queries",p,d.exportName):u.kind==="mutation"?Tn("mutations",p,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${v}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:I(e.outDirAbs,a),clientImportPath:I(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:v,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function ga(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){n+=d,l=false;continue}if(d==="\\"){n+=d,l=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let u=n.trim();return u.length>0&&t.push(u),t}function ha(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let c=0;c<e.length;c+=1){let l=e[c];if(s){s=false;continue}if(l==="\\"){s=true;continue}if(!o&&!i&&l==="'"){a=!a;continue}if(!a&&!i&&l==='"'){o=!o;continue}if(!a&&!o&&l==="`"){i=!i;continue}if(!(a||o||i)){if(l==="("){t+=1;continue}if(l===")"){t-=1;continue}if(l==="{"){n+=1;continue}if(l==="}"){n-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&t===0&&n===0&&r===0)return c}}return -1}function ya(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ba(e){let t=ga(e),n=[];for(let r of t){let a=ha(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),c=/autoincrement\s*:\s*true/i.test(i),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||c||s;n.push({name:o,expression:i,type:ya(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function wa(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,l=false,u=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!l&&!u&&y==="'"){c=!c;continue}if(!c&&!u&&y==='"'){l=!l;continue}if(!c&&!l&&y==="`"){u=!u;continue}if(!(c||l||u)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let l=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ba(l)}),a=t.exec(e);}return n}async function $n(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await $n(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function Cn(e,t=[]){let n=await $n(e.scanDirAbs).catch(()=>[]),r=path.resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),c=wa(s);if(c.length>0)return {schemaPath:o,tables:c}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function va(e){let t=e.auth.options.plugins;if(!Array.isArray(t))return [];for(let n of t)if(n&&typeof n=="object"){let r=n;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function Ra(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function ka(e,t){let n=await Bun.file(e).text(),r=t.map(o=>`"${o}"`).join(" | "),a=n.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
9798
|
-
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function Sa(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function
|
|
9799
|
-
`);let u=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),p=path.join(path.dirname(Bun.resolveSync("typescript/package.json",u)),"bin","tsc"),d=path.join(path.dirname(Bun.resolveSync("@better-auth/cli/package.json",u)),"dist","index.mjs"),y=path.resolve(t,"server.ts"),v=path.resolve(t,"client.ts"),A=path.resolve(t,"auth.config.ts"),w=path.resolve(t,"auth.schema.ts"),
|
|
9817
|
+
`}function na(e,t){if(t){let n=e[t];if(!oe(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(oe(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function xn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),l=na(c,t.exportName),u=Lr(l);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(i),{recursive:true})]);let p=Xr(u,n),d=ta(u),y=Yr(u);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(u.tables)}}function aa(e){return e.replaceAll("\\","/")}function M(e,t){let n=aa(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var la=new Set([".ts",".tsx",".mts",".cts"]);async function kn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await kn(a));continue}r.isFile()&&la.has(path.extname(r.name))&&n.push(a);}return n}function pe(e){return e.replace(/\.[cm]?tsx?$/,"")}function de(e,t){let n=e,r=false,a,o="unknown",i,s,c;for(;f__namespace.isCallExpression(n);){let l=n.expression;if(!f__namespace.isPropertyAccessExpression(l))break;let u=l.name.text;if(u==="optional"||u==="nullable")r=true,n=l.expression;else if(u==="default"){r=true;let p=n.arguments[0];p&&(f__namespace.isStringLiteral(p)||f__namespace.isNumericLiteral(p)?a=p.text:p.kind===f__namespace.SyntaxKind.TrueKeyword?a="true":p.kind===f__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=l.expression;}else if(u==="string"||u==="uuid"||u==="email"||u==="url"){o="string";break}else if(u==="number"||u==="int"||u==="float"){o="number";break}else if(u==="boolean"){o="boolean";break}else if(u==="date"){o="date";break}else if(u==="object"){o="object";let p=n.arguments[0];if(p&&f__namespace.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f__namespace.isPropertyAssignment(d)&&f__namespace.isIdentifier(d.name)&&i.push(de(d.initializer,d.name.text));}break}else if(u==="array"){o="array";let p=n.arguments[0];if(p){let d=de(p,"");s=d.type==="array"?"unknown":d.type,d.type==="object"&&(c=d.fields);}break}else n=l.expression;}return {name:t,type:o,optional:r,defaultValue:a,fields:i,itemType:s,itemFields:c}}function ua(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f__namespace.isPropertyAssignment(r)&&f__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)||n.push(de(r.initializer,r.name.text));return n}function ca(e){return f__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f__namespace.SyntaxKind.ExportKeyword)??false:false}function Sn(e){return f__namespace.isIdentifier(e)?e.text:f__namespace.isParenthesizedExpression(e)?Sn(e.expression):null}function da(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return f__namespace.isStringLiteral(n)||f__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>f__namespace.isStringLiteral(r)||f__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function pa(e,t){let n=f__namespace.createSourceFile(t,e,f__namespace.ScriptTarget.Latest,true,f__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(ca(a))for(let o of a.declarationList.declarations){if(!f__namespace.isIdentifier(o.name)||!o.initializer||!f__namespace.isCallExpression(o.initializer))continue;let i=Sn(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?da(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ua(o.initializer.arguments[0]):[]});}return r}function Tn(e,t,n){let r=t.replace(/\\/g,"/"),o=pe(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function ma(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function vn(e,t){let n=e.replace(/\\/g,"/"),a=pe(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function An(e){let t=[],n=await kn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),c=pa(i,a),l=[{kind:"query",kindDirectory:"queries",exports:c.filter(u=>u.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(u=>u.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(u=>u.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(u=>u.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(u=>u.kind==="storage")}];for(let u of l){if(u.exports.length===0)continue;let p=ma(s,u.kindDirectory);for(let d of u.exports){let y=u.kind==="query"||u.kind==="mutation"?vn(p,d.exportName):void 0,v=u.kind==="scheduler"||u.kind==="cron"?vn(p,d.exportName):void 0,A=u.kind==="query"||u.kind==="mutation"?[...pe(p).split("/").filter(Boolean),d.exportName]:void 0,w=u.kind==="query"?Tn("queries",p,d.exportName):u.kind==="mutation"?Tn("mutations",p,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${v}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:M(e.outDirAbs,a),clientImportPath:M(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:v,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function ga(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){n+=d,l=false;continue}if(d==="\\"){n+=d,l=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let u=n.trim();return u.length>0&&t.push(u),t}function ha(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let c=0;c<e.length;c+=1){let l=e[c];if(s){s=false;continue}if(l==="\\"){s=true;continue}if(!o&&!i&&l==="'"){a=!a;continue}if(!a&&!i&&l==='"'){o=!o;continue}if(!a&&!o&&l==="`"){i=!i;continue}if(!(a||o||i)){if(l==="("){t+=1;continue}if(l===")"){t-=1;continue}if(l==="{"){n+=1;continue}if(l==="}"){n-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&t===0&&n===0&&r===0)return c}}return -1}function ya(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ba(e){let t=ga(e),n=[];for(let r of t){let a=ha(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),c=/autoincrement\s*:\s*true/i.test(i),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||c||s;n.push({name:o,expression:i,type:ya(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function wa(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,l=false,u=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!l&&!u&&y==="'"){c=!c;continue}if(!c&&!u&&y==='"'){l=!l;continue}if(!c&&!l&&y==="`"){u=!u;continue}if(!(c||l||u)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let l=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ba(l)}),a=t.exec(e);}return n}async function $n(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await $n(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function Cn(e,t=[]){let n=await $n(e.scanDirAbs).catch(()=>[]),r=path.resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),c=wa(s);if(c.length>0)return {schemaPath:o,tables:c}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function va(e){let t=e.auth.options.plugins;if(!Array.isArray(t))return [];for(let n of t)if(n&&typeof n=="object"){let r=n;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function Ra(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function ka(e,t){let n=await Bun.file(e).text(),r=t.map(o=>`"${o}"`).join(" | "),a=n.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
9818
|
+
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function Sa(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function Mn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=M(t,a),s=path.resolve(t,"client"),c=M(s,a),l=performance.now();await Promise.all([promises.mkdir(t,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]),process.stdout.write(`\u{1F4C1} Directories (${(performance.now()-l).toFixed(0)}ms)
|
|
9819
|
+
`);let u=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),p=path.join(path.dirname(Bun.resolveSync("typescript/package.json",u)),"bin","tsc"),d=path.join(path.dirname(Bun.resolveSync("@better-auth/cli/package.json",u)),"dist","index.mjs"),y=path.resolve(t,"server.ts"),v=path.resolve(t,"client.ts"),A=path.resolve(t,"auth.config.ts"),w=path.resolve(t,"auth.schema.ts"),I=path.resolve(t,"drizzle.config.ts"),b=path.resolve(n,"wrangler.json"),h=await xn(e),T=await Cn(e,h?[h.schemaPath]:[]),C=M(t,T.schemaPath),R=await An(e);process.stdout.write(`\u{1F50D} ${R.length} handler(s) (${(performance.now()-l).toFixed(0)}ms)
|
|
9800
9820
|
`);let j=va(r),V=Ra(r),he=Rt(r.auth.basePath,r.database[0].binding,r.kv[0]?.binding,r.scheduler.binding,r.r2[0]?.binding,r.realtime.binding,r.realtime.objectName,r.realtime.subscribePath,r.realtime.websocketPath,r.realtime.protocol),Hn=$e(c,R),Ln=Z(C,R,r.r2[0]?.binding,j,V),zn=Te(i),Un=h?[Sa(o,h.schemaPath),...r.schema.filter(x=>!/(^|\/)schema\.ts$/.test(x))]:r.schema,Qn=Ce(Un),_n=St(e,R),Kn=mn(C,T,R),Jn=path.resolve(t,"admin.routes.ts"),Gn=Ln.map(x=>Bun.write(path.resolve(t,x.relativePath),x.source)),Zn=Hn.map(x=>Bun.write(path.resolve(t,x.relativePath),x.source));await Promise.all([Bun.write(y,he),Bun.write(v,`export * from "./client/index";
|
|
9801
|
-
`),...Zn,...Gn,Bun.write(A,zn),Bun.write(w,""),Bun.write(
|
|
9821
|
+
`),...Zn,...Gn,Bun.write(A,zn),Bun.write(w,""),Bun.write(I,Qn),Bun.write(b,`${JSON.stringify(_n,null,2)}
|
|
9802
9822
|
`),Bun.write(Jn,Kn)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-l).toFixed(0)}ms)
|
|
9803
9823
|
`);let _=path.relative(o,A).replace(/\\/g,"/"),Xn=_.startsWith(".")?_:`./${_}`,K=path.relative(o,w).replace(/\\/g,"/"),Yn=K.startsWith(".")?K:`./${K}`,ye=await Bun.spawn([process.execPath,d,"generate","--config",Xn,"--output",Yn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(ye!==0)throw new Error(`better-auth generation failed with exit code ${ye}`);process.stdout.write(`\u{1F510} Auth schema (${(performance.now()-l).toFixed(0)}ms)
|
|
9804
9824
|
`),j.length>0&&(await ka(w,j),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-l).toFixed(0)}ms)
|
|
@@ -9810,7 +9830,7 @@ import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["
|
|
|
9810
9830
|
`);let nr=t+"/";async function xe(x){let $=await promises.readdir(x,{withFileTypes:true});for(let k of $){let N=path.join(x,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith(".")||N===t)continue;await xe(N);}else !N.startsWith(nr)&&(k.name.endsWith(".d.ts")||k.name.endsWith(".js"))&&await promises.rm(N);}}await xe(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-l).toFixed(0)}ms)
|
|
9811
9831
|
`);let rr=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(rr)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-l).toFixed(0)}ms)
|
|
9812
9832
|
`);let $=await Bun.spawn([process.execPath,p,"--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if($!==0)throw new Error(`TypeScript build failed with exit code ${$}`);process.stdout.write(`\u2705 Build complete (${(performance.now()-l).toFixed(0)}ms)
|
|
9813
|
-
`);}}var
|
|
9833
|
+
`);}}var In=zod.z.object({binding:zod.z.string().min(1),databaseName:zod.z.string().min(1),databaseId:zod.z.string().min(1),previewDatabaseId:zod.z.string().min(1).optional(),migrationsDir:zod.z.string().min(1).optional()}).strict(),jn=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),En=zod.z.object({binding:zod.z.string().min(1),bucketName:zod.z.string().min(1),previewBucketName:zod.z.string().min(1).optional(),jurisdiction:zod.z.string().min(1).optional()}).strict(),Pn=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),queue:zod.z.string().min(1).optional()}).strict(),Ca=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),className:zod.z.string().min(1).optional(),objectName:zod.z.string().min(1).optional(),subscribePath:zod.z.string().min(1).optional(),websocketPath:zod.z.string().min(1).optional(),protocol:zod.z.string().min(1).optional()}).strict(),Fa=zod.z.object({scanDir:zod.z.string().min(1),outDir:zod.z.string().min(1),wranglerOutDir:zod.z.string().min(1).optional(),wranglerOutPath:zod.z.string().min(1).optional(),schema:zod.z.array(zod.z.string()).min(1),schemaDsl:zod.z.object({entry:zod.z.string().min(1),exportName:zod.z.string().min(1).optional(),outFile:zod.z.string().min(1).optional(),typesOutFile:zod.z.string().min(1).optional(),zodOutFile:zod.z.string().min(1).optional(),namingStrategy:zod.z.literal("camelToSnake").optional()}).strict().optional(),database:zod.z.union([In,zod.z.array(In).min(1)]),kv:zod.z.union([jn,zod.z.array(jn)]).optional(),r2:zod.z.union([En,zod.z.array(En)]).optional(),auth:zod.z.object({enabled:zod.z.boolean(),basePath:zod.z.string().min(1),options:zod.z.custom(e=>typeof e=="object"&&e!==null),clientOptions:zod.z.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:Pn.optional(),realtime:Ca.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),build:zod.z.boolean().optional()}).strict();function On(e){return typeof e=="object"&&e!==null}function qa(e){let t=On(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=Pn.safeParse(t);return n.success?n.data:{}}function Ma(e){if(!On(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function Ia(e){let n={...qa(e)??{},...e.scheduler??{}},r=e.realtime??{};return {...e,database:Array.isArray(e.database)?e.database:[e.database],kv:e.kv?Array.isArray(e.kv)?e.kv:[e.kv]:[],r2:e.r2?Array.isArray(e.r2)?e.r2:[e.r2]:[],scheduler:{enabled:n.enabled??true,binding:n.binding??"APPFLARE_SCHEDULER_QUEUE",queue:n.queue},realtime:{enabled:r.enabled??true,binding:r.binding??"APPFLARE_REALTIME",className:r.className??"AppflareRealtimeDurableObject",objectName:r.objectName??"global",subscribePath:r.subscribePath??"/realtime/subscribe",websocketPath:r.websocketPath??"/realtime/ws",protocol:r.protocol??"appflare.realtime.v1"},wranglerOverrides:Ma(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function D(e){let t=path.isAbsolute(e??"")?e:path.resolve(process.cwd(),e??"appflare.config.ts"),n=path.dirname(t),o=(await import(url.pathToFileURL(t).href)).default,i=Fa.parse(o),s=Ia(i);return {configPath:t,configDir:n,scanDirAbs:path.resolve(n,s.scanDir),outDirAbs:path.resolve(n,s.outDir),wranglerOutDirAbs:path.resolve(n,s.wranglerOutDir),config:s}}function Oa(e){let t=e;for(;;){if(fs.existsSync(path.resolve(t,"package.json")))return t;let n=path.dirname(t);if(n===t)return e;t=n;}}async function Q(e,t={}){let n=await D(e);if(t.build!==void 0&&(n.config.build=t.build),await Mn(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
9814
9834
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
9815
9835
|
`);}async function Vn(e,t={}){if(await Q(e,{build:t.build}),!t.watch)return;let n=await D(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await Q(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
9816
9836
|
`);}finally{r=false,a&&(a=false,await o());}};ja__default.default.watch(n.scanDirAbs,{ignoreInitial:true,ignored:s=>s.includes("/_generated/")||s.includes("/dist/")||s.includes("/out/")||s.includes("/node_modules/")||s.endsWith(".d.ts")}).on("all",async(s,c)=>{process.stdout.write(`\u{1F504} Change detected: ${c}
|
package/dist/cli/index.mjs
CHANGED
|
@@ -1205,7 +1205,7 @@ type R2BucketBinding = {
|
|
|
1205
1205
|
options?: { expiresIn?: number },
|
|
1206
1206
|
) => Promise<URL>;
|
|
1207
1207
|
};
|
|
1208
|
-
`}function
|
|
1208
|
+
`}function Me(){return `
|
|
1209
1209
|
export function createScheduler(
|
|
1210
1210
|
queue?: SchedulerQueueBinding,
|
|
1211
1211
|
): Scheduler {
|
|
@@ -1226,7 +1226,7 @@ export function createScheduler(
|
|
|
1226
1226
|
},
|
|
1227
1227
|
};
|
|
1228
1228
|
}
|
|
1229
|
-
`}function
|
|
1229
|
+
`}function Ie(){return `
|
|
1230
1230
|
function createContextErrorHelpers() {
|
|
1231
1231
|
return {
|
|
1232
1232
|
error: (status: number, message: string, details?: unknown) => {
|
|
@@ -1490,10 +1490,10 @@ ${qe()}
|
|
|
1490
1490
|
|
|
1491
1491
|
${Fe()}
|
|
1492
1492
|
|
|
1493
|
-
${Ie()}
|
|
1494
|
-
|
|
1495
1493
|
${Me()}
|
|
1496
1494
|
|
|
1495
|
+
${Ie()}
|
|
1496
|
+
|
|
1497
1497
|
${je()}
|
|
1498
1498
|
|
|
1499
1499
|
${Ee()}
|
|
@@ -1564,6 +1564,8 @@ import {
|
|
|
1564
1564
|
isNotNull,
|
|
1565
1565
|
getTableColumns,
|
|
1566
1566
|
sql,
|
|
1567
|
+
asc,
|
|
1568
|
+
desc,
|
|
1567
1569
|
type InferInsertModel,
|
|
1568
1570
|
type InferSelectModel,
|
|
1569
1571
|
type SQL,
|
|
@@ -3946,8 +3948,8 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3946
3948
|
(item: Record<string, unknown>) => {
|
|
3947
3949
|
const column = item.column as string;
|
|
3948
3950
|
const direction = (item.direction as string) ?? "asc";
|
|
3949
|
-
const col = (table as Record<string,
|
|
3950
|
-
return direction === "desc" ?
|
|
3951
|
+
const col = (table as Record<string, any>)[column];
|
|
3952
|
+
return direction === "desc" ? desc(col) : asc(col);
|
|
3951
3953
|
},
|
|
3952
3954
|
)
|
|
3953
3955
|
: undefined;
|
|
@@ -4023,8 +4025,8 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4023
4025
|
(item: Record<string, unknown>) => {
|
|
4024
4026
|
const column = item.column as string;
|
|
4025
4027
|
const direction = (item.direction as string) ?? "asc";
|
|
4026
|
-
const col = (table as Record<string,
|
|
4027
|
-
return direction === "desc" ?
|
|
4028
|
+
const col = (table as Record<string, any>)[column];
|
|
4029
|
+
return direction === "desc" ? desc(col) : asc(col);
|
|
4028
4030
|
},
|
|
4029
4031
|
)
|
|
4030
4032
|
: undefined;
|
|
@@ -6614,6 +6616,15 @@ export async function executeScheduledBatch(
|
|
|
6614
6616
|
const payloadValue = body.payload === null ? undefined : body.payload;
|
|
6615
6617
|
const parsed = operation.schema.parse(payloadValue);
|
|
6616
6618
|
await operation.definition.handler(ctx, parsed);
|
|
6619
|
+
|
|
6620
|
+
if (typeof publishMutationEvents === "function") {
|
|
6621
|
+
await publishMutationEvents(
|
|
6622
|
+
{ req: { raw: new Request("http://localhost") }, env },
|
|
6623
|
+
options,
|
|
6624
|
+
ctx.mutationEvents,
|
|
6625
|
+
);
|
|
6626
|
+
}
|
|
6627
|
+
ctx.mutationEvents.length = 0;
|
|
6617
6628
|
} catch (error) {
|
|
6618
6629
|
if (error instanceof ZodError) {
|
|
6619
6630
|
console.error("Invalid scheduler payload", task, error.issues);
|
|
@@ -6644,6 +6655,15 @@ export async function executeCronTriggers(
|
|
|
6644
6655
|
|
|
6645
6656
|
try {
|
|
6646
6657
|
await cronEntry.definition.handler(ctx);
|
|
6658
|
+
|
|
6659
|
+
if (typeof publishMutationEvents === "function") {
|
|
6660
|
+
await publishMutationEvents(
|
|
6661
|
+
{ req: { raw: new Request("http://localhost") }, env },
|
|
6662
|
+
options,
|
|
6663
|
+
ctx.mutationEvents,
|
|
6664
|
+
);
|
|
6665
|
+
}
|
|
6666
|
+
ctx.mutationEvents.length = 0;
|
|
6647
6667
|
} catch (error) {
|
|
6648
6668
|
console.error("Cron task failed", cronEntry.taskName, error);
|
|
6649
6669
|
}
|
|
@@ -6909,7 +6929,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6909
6929
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6910
6930
|
</a>
|
|
6911
6931
|
</th>
|
|
6912
|
-
`}).join("")}function
|
|
6932
|
+
`}).join("")}function Mt(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function te(e,t,n){let r=e.columns.find(i=>i.name===t);if(!r)return "";let a=r.optional?"":" required",o=r.type==="number"?"number":r.type==="date"?"date":"text";if(r.type==="boolean")return n==="edit"?`
|
|
6913
6933
|
<div class="form-control">
|
|
6914
6934
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6915
6935
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6992,7 +7012,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6992
7012
|
payload.${n} = raw_${n};
|
|
6993
7013
|
}
|
|
6994
7014
|
`}).join(`
|
|
6995
|
-
`)}function
|
|
7015
|
+
`)}function It(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function jt(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function Et(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function Pt(e,t,n,r){return t?`<td class="text-right">
|
|
6996
7016
|
<div class="drawer drawer-end">
|
|
6997
7017
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6998
7018
|
<div class="drawer-content">
|
|
@@ -7463,7 +7483,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7463
7483
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7464
7484
|
});
|
|
7465
7485
|
${u}
|
|
7466
|
-
`}function re(e){let t=
|
|
7486
|
+
`}function re(e){let t=It(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>jt(e,w)),o=r.filter(w=>Et(e,w)),i=Ft(e),s=qt(e,r),c=Mt(r,t),l=a.map(w=>te(e,w,"create")).join(""),u=o.map(w=>te(e,w,"edit")).join(""),p=ne(e,a),d=ne(e,o),y=n?t:r[0]||"id",v=e.columns.find(w=>w.name===t)?.type,A=Pt(e,n,t,u);return Ot(e,y,t,n,r,i,s,c,A,l)+`
|
|
7467
7487
|
`+Dt(e.exportName,y,t,v,n,i,p,d)}function Vt(){return `
|
|
7468
7488
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7469
7489
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
@@ -7937,7 +7957,7 @@ ${ae()}`}function _t(e){return `
|
|
|
7937
7957
|
${r.optional?"":"required"}
|
|
7938
7958
|
/>
|
|
7939
7959
|
</div>`}).join(`
|
|
7940
|
-
`)}function
|
|
7960
|
+
`)}function Mr(e){return `
|
|
7941
7961
|
<div class="space-y-4">
|
|
7942
7962
|
<div class="flex items-center justify-between">
|
|
7943
7963
|
<div class="flex flex-col">
|
|
@@ -7954,7 +7974,7 @@ ${ae()}`}function _t(e){return `
|
|
|
7954
7974
|
</div>
|
|
7955
7975
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7956
7976
|
</div>
|
|
7957
|
-
`}function
|
|
7977
|
+
`}function Ir(){return `
|
|
7958
7978
|
<div class="space-y-4">
|
|
7959
7979
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7960
7980
|
<div class="relative group">
|
|
@@ -8006,10 +8026,10 @@ ${ae()}`}function _t(e){return `
|
|
|
8006
8026
|
<!-- Tab Content -->
|
|
8007
8027
|
<div class="flex-1 overflow-y-auto">
|
|
8008
8028
|
<div id="request-tab-args" class="p-5">
|
|
8009
|
-
${
|
|
8029
|
+
${Mr(e)}
|
|
8010
8030
|
</div>
|
|
8011
8031
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
8012
|
-
${
|
|
8032
|
+
${Ir()}
|
|
8013
8033
|
</div>
|
|
8014
8034
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
8015
8035
|
${jr()}
|
|
@@ -9739,11 +9759,11 @@ ${y.join(`,
|
|
|
9739
9759
|
);`):s.push(`export const ${l} = table(${g(p)}, {
|
|
9740
9760
|
${d.join(`
|
|
9741
9761
|
`)}
|
|
9742
|
-
});`);let v=Object.entries(u.relations).filter(([,b])=>b.relation==="one"),A=Object.entries(u.relations).filter(([,b])=>b.relation==="many"),w=Object.entries(u.relations).filter(([,b])=>b.relation==="manyToMany");if(v.length===0&&A.length===0&&w.length===0)continue;let
|
|
9762
|
+
});`);let v=Object.entries(u.relations).filter(([,b])=>b.relation==="one"),A=Object.entries(u.relations).filter(([,b])=>b.relation==="many"),w=Object.entries(u.relations).filter(([,b])=>b.relation==="manyToMany");if(v.length===0&&A.length===0&&w.length===0)continue;let I=[];for(let[b,h]of v){let T=Ur(l,u,h);I.push(` ${b}: one(${h.targetTable}, {
|
|
9743
9763
|
fields: [${l}.${T.sourceField}],
|
|
9744
9764
|
references: [${h.targetTable}.${T.targetField}],
|
|
9745
|
-
}),`);}for(let[b,h]of A)
|
|
9746
|
-
${
|
|
9765
|
+
}),`);}for(let[b,h]of A)I.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of w){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);I.push(` ${b}: many(${h.junctionTable}),`);}c.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
9766
|
+
${I.join(`
|
|
9747
9767
|
`)}
|
|
9748
9768
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9749
9769
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
@@ -9794,11 +9814,11 @@ ${s.join(`
|
|
|
9794
9814
|
${n.join(`
|
|
9795
9815
|
|
|
9796
9816
|
`)}
|
|
9797
|
-
`}function na(e,t){if(t){let n=e[t];if(!oe(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(oe(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function xn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),l=na(c,t.exportName),u=Lr(l);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let p=Xr(u,n),d=ta(u),y=Yr(u);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(u.tables)}}function aa(e){return e.replaceAll("\\","/")}function I(e,t){let n=aa(relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var la=new Set([".ts",".tsx",".mts",".cts"]);async function kn(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await kn(a));continue}r.isFile()&&la.has(extname(r.name))&&n.push(a);}return n}function pe(e){return e.replace(/\.[cm]?tsx?$/,"")}function de(e,t){let n=e,r=false,a,o="unknown",i,s,c;for(;f.isCallExpression(n);){let l=n.expression;if(!f.isPropertyAccessExpression(l))break;let u=l.name.text;if(u==="optional"||u==="nullable")r=true,n=l.expression;else if(u==="default"){r=true;let p=n.arguments[0];p&&(f.isStringLiteral(p)||f.isNumericLiteral(p)?a=p.text:p.kind===f.SyntaxKind.TrueKeyword?a="true":p.kind===f.SyntaxKind.FalseKeyword&&(a="false")),n=l.expression;}else if(u==="string"||u==="uuid"||u==="email"||u==="url"){o="string";break}else if(u==="number"||u==="int"||u==="float"){o="number";break}else if(u==="boolean"){o="boolean";break}else if(u==="date"){o="date";break}else if(u==="object"){o="object";let p=n.arguments[0];if(p&&f.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f.isPropertyAssignment(d)&&f.isIdentifier(d.name)&&i.push(de(d.initializer,d.name.text));}break}else if(u==="array"){o="array";let p=n.arguments[0];if(p){let d=de(p,"");s=d.type==="array"?"unknown":d.type,d.type==="object"&&(c=d.fields);}break}else n=l.expression;}return {name:t,type:o,optional:r,defaultValue:a,fields:i,itemType:s,itemFields:c}}function ua(e){if(!e||!f.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f.isPropertyAssignment(r)&&f.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f.isPropertyAssignment(r)||!f.isIdentifier(r.name)||n.push(de(r.initializer,r.name.text));return n}function ca(e){return f.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f.SyntaxKind.ExportKeyword)??false:false}function Sn(e){return f.isIdentifier(e)?e.text:f.isParenthesizedExpression(e)?Sn(e.expression):null}function da(e){if(!e||!f.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f.isPropertyAssignment(r)||!f.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f.isPropertyAssignment(t))return [];let n=t.initializer;return f.isStringLiteral(n)||f.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f.isArrayLiteralExpression(n)?n.elements.map(r=>f.isStringLiteral(r)||f.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function pa(e,t){let n=f.createSourceFile(t,e,f.ScriptTarget.Latest,true,f.ScriptKind.TS),r=[];for(let a of n.statements)if(ca(a))for(let o of a.declarationList.declarations){if(!f.isIdentifier(o.name)||!o.initializer||!f.isCallExpression(o.initializer))continue;let i=Sn(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?da(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ua(o.initializer.arguments[0]):[]});}return r}function Tn(e,t,n){let r=t.replace(/\\/g,"/"),o=pe(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function ma(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function vn(e,t){let n=e.replace(/\\/g,"/"),a=pe(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function An(e){let t=[],n=await kn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=relative(e.scanDirAbs,a),c=pa(i,a),l=[{kind:"query",kindDirectory:"queries",exports:c.filter(u=>u.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(u=>u.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(u=>u.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(u=>u.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(u=>u.kind==="storage")}];for(let u of l){if(u.exports.length===0)continue;let p=ma(s,u.kindDirectory);for(let d of u.exports){let y=u.kind==="query"||u.kind==="mutation"?vn(p,d.exportName):void 0,v=u.kind==="scheduler"||u.kind==="cron"?vn(p,d.exportName):void 0,A=u.kind==="query"||u.kind==="mutation"?[...pe(p).split("/").filter(Boolean),d.exportName]:void 0,w=u.kind==="query"?Tn("queries",p,d.exportName):u.kind==="mutation"?Tn("mutations",p,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${v}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:I(e.outDirAbs,a),clientImportPath:I(resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:v,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function ga(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){n+=d,l=false;continue}if(d==="\\"){n+=d,l=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let u=n.trim();return u.length>0&&t.push(u),t}function ha(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let c=0;c<e.length;c+=1){let l=e[c];if(s){s=false;continue}if(l==="\\"){s=true;continue}if(!o&&!i&&l==="'"){a=!a;continue}if(!a&&!i&&l==='"'){o=!o;continue}if(!a&&!o&&l==="`"){i=!i;continue}if(!(a||o||i)){if(l==="("){t+=1;continue}if(l===")"){t-=1;continue}if(l==="{"){n+=1;continue}if(l==="}"){n-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&t===0&&n===0&&r===0)return c}}return -1}function ya(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ba(e){let t=ga(e),n=[];for(let r of t){let a=ha(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),c=/autoincrement\s*:\s*true/i.test(i),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||c||s;n.push({name:o,expression:i,type:ya(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function wa(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,l=false,u=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!l&&!u&&y==="'"){c=!c;continue}if(!c&&!u&&y==='"'){l=!l;continue}if(!c&&!l&&y==="`"){u=!u;continue}if(!(c||l||u)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let l=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ba(l)}),a=t.exec(e);}return n}async function $n(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await $n(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function Cn(e,t=[]){let n=await $n(e.scanDirAbs).catch(()=>[]),r=resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),c=wa(s);if(c.length>0)return {schemaPath:o,tables:c}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function va(e){let t=e.auth.options.plugins;if(!Array.isArray(t))return [];for(let n of t)if(n&&typeof n=="object"){let r=n;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function Ra(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function ka(e,t){let n=await Bun.file(e).text(),r=t.map(o=>`"${o}"`).join(" | "),a=n.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
9798
|
-
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function Sa(e,t){let n=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function
|
|
9799
|
-
`);let u=dirname(fileURLToPath(import.meta.url)),p=join(dirname(Bun.resolveSync("typescript/package.json",u)),"bin","tsc"),d=join(dirname(Bun.resolveSync("@better-auth/cli/package.json",u)),"dist","index.mjs"),y=resolve(t,"server.ts"),v=resolve(t,"client.ts"),A=resolve(t,"auth.config.ts"),w=resolve(t,"auth.schema.ts"),
|
|
9817
|
+
`}function na(e,t){if(t){let n=e[t];if(!oe(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(oe(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function xn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),l=na(c,t.exportName),u=Lr(l);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let p=Xr(u,n),d=ta(u),y=Yr(u);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(u.tables)}}function aa(e){return e.replaceAll("\\","/")}function M(e,t){let n=aa(relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var la=new Set([".ts",".tsx",".mts",".cts"]);async function kn(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await kn(a));continue}r.isFile()&&la.has(extname(r.name))&&n.push(a);}return n}function pe(e){return e.replace(/\.[cm]?tsx?$/,"")}function de(e,t){let n=e,r=false,a,o="unknown",i,s,c;for(;f.isCallExpression(n);){let l=n.expression;if(!f.isPropertyAccessExpression(l))break;let u=l.name.text;if(u==="optional"||u==="nullable")r=true,n=l.expression;else if(u==="default"){r=true;let p=n.arguments[0];p&&(f.isStringLiteral(p)||f.isNumericLiteral(p)?a=p.text:p.kind===f.SyntaxKind.TrueKeyword?a="true":p.kind===f.SyntaxKind.FalseKeyword&&(a="false")),n=l.expression;}else if(u==="string"||u==="uuid"||u==="email"||u==="url"){o="string";break}else if(u==="number"||u==="int"||u==="float"){o="number";break}else if(u==="boolean"){o="boolean";break}else if(u==="date"){o="date";break}else if(u==="object"){o="object";let p=n.arguments[0];if(p&&f.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f.isPropertyAssignment(d)&&f.isIdentifier(d.name)&&i.push(de(d.initializer,d.name.text));}break}else if(u==="array"){o="array";let p=n.arguments[0];if(p){let d=de(p,"");s=d.type==="array"?"unknown":d.type,d.type==="object"&&(c=d.fields);}break}else n=l.expression;}return {name:t,type:o,optional:r,defaultValue:a,fields:i,itemType:s,itemFields:c}}function ua(e){if(!e||!f.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f.isPropertyAssignment(r)&&f.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f.isPropertyAssignment(r)||!f.isIdentifier(r.name)||n.push(de(r.initializer,r.name.text));return n}function ca(e){return f.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f.SyntaxKind.ExportKeyword)??false:false}function Sn(e){return f.isIdentifier(e)?e.text:f.isParenthesizedExpression(e)?Sn(e.expression):null}function da(e){if(!e||!f.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f.isPropertyAssignment(r)||!f.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f.isPropertyAssignment(t))return [];let n=t.initializer;return f.isStringLiteral(n)||f.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f.isArrayLiteralExpression(n)?n.elements.map(r=>f.isStringLiteral(r)||f.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function pa(e,t){let n=f.createSourceFile(t,e,f.ScriptTarget.Latest,true,f.ScriptKind.TS),r=[];for(let a of n.statements)if(ca(a))for(let o of a.declarationList.declarations){if(!f.isIdentifier(o.name)||!o.initializer||!f.isCallExpression(o.initializer))continue;let i=Sn(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?da(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ua(o.initializer.arguments[0]):[]});}return r}function Tn(e,t,n){let r=t.replace(/\\/g,"/"),o=pe(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function ma(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function vn(e,t){let n=e.replace(/\\/g,"/"),a=pe(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function An(e){let t=[],n=await kn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=relative(e.scanDirAbs,a),c=pa(i,a),l=[{kind:"query",kindDirectory:"queries",exports:c.filter(u=>u.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(u=>u.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(u=>u.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(u=>u.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(u=>u.kind==="storage")}];for(let u of l){if(u.exports.length===0)continue;let p=ma(s,u.kindDirectory);for(let d of u.exports){let y=u.kind==="query"||u.kind==="mutation"?vn(p,d.exportName):void 0,v=u.kind==="scheduler"||u.kind==="cron"?vn(p,d.exportName):void 0,A=u.kind==="query"||u.kind==="mutation"?[...pe(p).split("/").filter(Boolean),d.exportName]:void 0,w=u.kind==="query"?Tn("queries",p,d.exportName):u.kind==="mutation"?Tn("mutations",p,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${v}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:M(e.outDirAbs,a),clientImportPath:M(resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:v,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function ga(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){n+=d,l=false;continue}if(d==="\\"){n+=d,l=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let u=n.trim();return u.length>0&&t.push(u),t}function ha(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let c=0;c<e.length;c+=1){let l=e[c];if(s){s=false;continue}if(l==="\\"){s=true;continue}if(!o&&!i&&l==="'"){a=!a;continue}if(!a&&!i&&l==='"'){o=!o;continue}if(!a&&!o&&l==="`"){i=!i;continue}if(!(a||o||i)){if(l==="("){t+=1;continue}if(l===")"){t-=1;continue}if(l==="{"){n+=1;continue}if(l==="}"){n-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&t===0&&n===0&&r===0)return c}}return -1}function ya(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ba(e){let t=ga(e),n=[];for(let r of t){let a=ha(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),c=/autoincrement\s*:\s*true/i.test(i),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||c||s;n.push({name:o,expression:i,type:ya(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function wa(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,l=false,u=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!l&&!u&&y==="'"){c=!c;continue}if(!c&&!u&&y==='"'){l=!l;continue}if(!c&&!l&&y==="`"){u=!u;continue}if(!(c||l||u)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let l=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ba(l)}),a=t.exec(e);}return n}async function $n(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await $n(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function Cn(e,t=[]){let n=await $n(e.scanDirAbs).catch(()=>[]),r=resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),c=wa(s);if(c.length>0)return {schemaPath:o,tables:c}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function va(e){let t=e.auth.options.plugins;if(!Array.isArray(t))return [];for(let n of t)if(n&&typeof n=="object"){let r=n;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function Ra(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function ka(e,t){let n=await Bun.file(e).text(),r=t.map(o=>`"${o}"`).join(" | "),a=n.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
9818
|
+
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function Sa(e,t){let n=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function Mn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=M(t,a),s=resolve(t,"client"),c=M(s,a),l=performance.now();await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]),process.stdout.write(`\u{1F4C1} Directories (${(performance.now()-l).toFixed(0)}ms)
|
|
9819
|
+
`);let u=dirname(fileURLToPath(import.meta.url)),p=join(dirname(Bun.resolveSync("typescript/package.json",u)),"bin","tsc"),d=join(dirname(Bun.resolveSync("@better-auth/cli/package.json",u)),"dist","index.mjs"),y=resolve(t,"server.ts"),v=resolve(t,"client.ts"),A=resolve(t,"auth.config.ts"),w=resolve(t,"auth.schema.ts"),I=resolve(t,"drizzle.config.ts"),b=resolve(n,"wrangler.json"),h=await xn(e),T=await Cn(e,h?[h.schemaPath]:[]),C=M(t,T.schemaPath),R=await An(e);process.stdout.write(`\u{1F50D} ${R.length} handler(s) (${(performance.now()-l).toFixed(0)}ms)
|
|
9800
9820
|
`);let j=va(r),V=Ra(r),he=Rt(r.auth.basePath,r.database[0].binding,r.kv[0]?.binding,r.scheduler.binding,r.r2[0]?.binding,r.realtime.binding,r.realtime.objectName,r.realtime.subscribePath,r.realtime.websocketPath,r.realtime.protocol),Hn=$e(c,R),Ln=Z(C,R,r.r2[0]?.binding,j,V),zn=Te(i),Un=h?[Sa(o,h.schemaPath),...r.schema.filter(x=>!/(^|\/)schema\.ts$/.test(x))]:r.schema,Qn=Ce(Un),_n=St(e,R),Kn=mn(C,T,R),Jn=resolve(t,"admin.routes.ts"),Gn=Ln.map(x=>Bun.write(resolve(t,x.relativePath),x.source)),Zn=Hn.map(x=>Bun.write(resolve(t,x.relativePath),x.source));await Promise.all([Bun.write(y,he),Bun.write(v,`export * from "./client/index";
|
|
9801
|
-
`),...Zn,...Gn,Bun.write(A,zn),Bun.write(w,""),Bun.write(
|
|
9821
|
+
`),...Zn,...Gn,Bun.write(A,zn),Bun.write(w,""),Bun.write(I,Qn),Bun.write(b,`${JSON.stringify(_n,null,2)}
|
|
9802
9822
|
`),Bun.write(Jn,Kn)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-l).toFixed(0)}ms)
|
|
9803
9823
|
`);let _=relative(o,A).replace(/\\/g,"/"),Xn=_.startsWith(".")?_:`./${_}`,K=relative(o,w).replace(/\\/g,"/"),Yn=K.startsWith(".")?K:`./${K}`,ye=await Bun.spawn([process.execPath,d,"generate","--config",Xn,"--output",Yn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(ye!==0)throw new Error(`better-auth generation failed with exit code ${ye}`);process.stdout.write(`\u{1F510} Auth schema (${(performance.now()-l).toFixed(0)}ms)
|
|
9804
9824
|
`),j.length>0&&(await ka(w,j),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-l).toFixed(0)}ms)
|
|
@@ -9810,7 +9830,7 @@ import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["
|
|
|
9810
9830
|
`);let nr=t+"/";async function xe(x){let $=await readdir(x,{withFileTypes:true});for(let k of $){let N=join(x,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith(".")||N===t)continue;await xe(N);}else !N.startsWith(nr)&&(k.name.endsWith(".d.ts")||k.name.endsWith(".js"))&&await rm(N);}}await xe(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-l).toFixed(0)}ms)
|
|
9811
9831
|
`);let rr=resolve(o,"tsconfig.json");if(e.config.build&&existsSync(rr)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-l).toFixed(0)}ms)
|
|
9812
9832
|
`);let $=await Bun.spawn([process.execPath,p,"--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if($!==0)throw new Error(`TypeScript build failed with exit code ${$}`);process.stdout.write(`\u2705 Build complete (${(performance.now()-l).toFixed(0)}ms)
|
|
9813
|
-
`);}}var
|
|
9833
|
+
`);}}var In=z.object({binding:z.string().min(1),databaseName:z.string().min(1),databaseId:z.string().min(1),previewDatabaseId:z.string().min(1).optional(),migrationsDir:z.string().min(1).optional()}).strict(),jn=z.object({binding:z.string().min(1),id:z.string().min(1),previewId:z.string().min(1).optional()}).strict(),En=z.object({binding:z.string().min(1),bucketName:z.string().min(1),previewBucketName:z.string().min(1).optional(),jurisdiction:z.string().min(1).optional()}).strict(),Pn=z.object({enabled:z.boolean().optional(),binding:z.string().min(1).optional(),queue:z.string().min(1).optional()}).strict(),Ca=z.object({enabled:z.boolean().optional(),binding:z.string().min(1).optional(),className:z.string().min(1).optional(),objectName:z.string().min(1).optional(),subscribePath:z.string().min(1).optional(),websocketPath:z.string().min(1).optional(),protocol:z.string().min(1).optional()}).strict(),Fa=z.object({scanDir:z.string().min(1),outDir:z.string().min(1),wranglerOutDir:z.string().min(1).optional(),wranglerOutPath:z.string().min(1).optional(),schema:z.array(z.string()).min(1),schemaDsl:z.object({entry:z.string().min(1),exportName:z.string().min(1).optional(),outFile:z.string().min(1).optional(),typesOutFile:z.string().min(1).optional(),zodOutFile:z.string().min(1).optional(),namingStrategy:z.literal("camelToSnake").optional()}).strict().optional(),database:z.union([In,z.array(In).min(1)]),kv:z.union([jn,z.array(jn)]).optional(),r2:z.union([En,z.array(En)]).optional(),auth:z.object({enabled:z.boolean(),basePath:z.string().min(1),options:z.custom(e=>typeof e=="object"&&e!==null),clientOptions:z.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:Pn.optional(),realtime:Ca.optional(),wranglerOverrides:z.record(z.string(),z.unknown()).optional(),build:z.boolean().optional()}).strict();function On(e){return typeof e=="object"&&e!==null}function qa(e){let t=On(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=Pn.safeParse(t);return n.success?n.data:{}}function Ma(e){if(!On(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function Ia(e){let n={...qa(e)??{},...e.scheduler??{}},r=e.realtime??{};return {...e,database:Array.isArray(e.database)?e.database:[e.database],kv:e.kv?Array.isArray(e.kv)?e.kv:[e.kv]:[],r2:e.r2?Array.isArray(e.r2)?e.r2:[e.r2]:[],scheduler:{enabled:n.enabled??true,binding:n.binding??"APPFLARE_SCHEDULER_QUEUE",queue:n.queue},realtime:{enabled:r.enabled??true,binding:r.binding??"APPFLARE_REALTIME",className:r.className??"AppflareRealtimeDurableObject",objectName:r.objectName??"global",subscribePath:r.subscribePath??"/realtime/subscribe",websocketPath:r.websocketPath??"/realtime/ws",protocol:r.protocol??"appflare.realtime.v1"},wranglerOverrides:Ma(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function D(e){let t=isAbsolute(e??"")?e:resolve(process.cwd(),e??"appflare.config.ts"),n=dirname(t),o=(await import(pathToFileURL(t).href)).default,i=Fa.parse(o),s=Ia(i);return {configPath:t,configDir:n,scanDirAbs:resolve(n,s.scanDir),outDirAbs:resolve(n,s.outDir),wranglerOutDirAbs:resolve(n,s.wranglerOutDir),config:s}}function Oa(e){let t=e;for(;;){if(existsSync(resolve(t,"package.json")))return t;let n=dirname(t);if(n===t)return e;t=n;}}async function Q(e,t={}){let n=await D(e);if(t.build!==void 0&&(n.config.build=t.build),await Mn(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
9814
9834
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
9815
9835
|
`);}async function Vn(e,t={}){if(await Q(e,{build:t.build}),!t.watch)return;let n=await D(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await Q(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
9816
9836
|
`);}finally{r=false,a&&(a=false,await o());}};ja.watch(n.scanDirAbs,{ignoreInitial:true,ignored:s=>s.includes("/_generated/")||s.includes("/dist/")||s.includes("/out/")||s.includes("/node_modules/")||s.endsWith(".d.ts")}).on("all",async(s,c)=>{process.stdout.write(`\u{1F504} Change detected: ${c}
|
package/dist/react/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var reactQuery=require('@tanstack/react-query'),react=require('react');function O(r){let a=new Error(r.message);return r.status!==void 0&&(a.status=r.status),a}function b(r,...a){let t=a[0]??{},e=a[1],o=reactQuery.useQueryClient(),i=react.useRef(e?.realtime?.onChange),p=react.useRef(e?.realtime?.onError);react.useEffect(()=>{i.current=e?.realtime?.onChange,p.current=e?.realtime?.onError;},[e?.realtime?.onChange,e?.realtime?.onError]);let u=react.useMemo(()=>e?.queryOptions?.queryKey??(r.queryKey?r.queryKey(t):["appflare","query",r,t]),[t,e?.queryOptions?.queryKey,r]),d=react.useMemo(()=>reactQuery.hashKey(u),[u]),f=react.useMemo(()=>reactQuery.hashKey([t]),[t]),A=react.useMemo(()=>reactQuery.hashKey([e?.realtime?.requestOptions]),[e?.realtime?.requestOptions]),m=reactQuery.useQuery({...e?.queryOptions,queryKey:u,queryFn:async()=>{let s=await r.run(t,e?.requestOptions);if(s.error)throw O(s.error);return s.data}});return react.useEffect(()=>{if(e?.realtime?.enabled
|
|
1
|
+
'use strict';var reactQuery=require('@tanstack/react-query'),react=require('react');function O(r){let a=new Error(r.message);return r.status!==void 0&&(a.status=r.status),a}function b(r,...a){let t=a[0]??{},e=a[1],o=reactQuery.useQueryClient(),i=react.useRef(e?.realtime?.onChange),p=react.useRef(e?.realtime?.onError);react.useEffect(()=>{i.current=e?.realtime?.onChange,p.current=e?.realtime?.onError;},[e?.realtime?.onChange,e?.realtime?.onError]);let u=react.useMemo(()=>e?.queryOptions?.queryKey??(r.queryKey?r.queryKey(t):["appflare","query",r,t]),[t,e?.queryOptions?.queryKey,r]),d=react.useMemo(()=>reactQuery.hashKey(u),[u]),f=react.useMemo(()=>reactQuery.hashKey([t]),[t]),A=react.useMemo(()=>reactQuery.hashKey([e?.realtime?.requestOptions]),[e?.realtime?.requestOptions]),m=reactQuery.useQuery({...e?.queryOptions,queryKey:u,queryFn:async()=>{let s=await r.run(t,e?.requestOptions);if(s.error)throw O(s.error);return s.data}});return react.useEffect(()=>{if(!e?.realtime?.enabled||!r.subscribe)return;let s=new AbortController,y=r.subscribe({args:t,authToken:e?.realtime?.authToken,requestOptions:e?.realtime?.requestOptions,signal:s.signal,onChange:(n,c)=>{o.setQueryData(u,n),i.current?.(n,c);},onError:n=>{p.current?.(n);}});return ()=>{s.abort(),y.remove();}},[f,e?.realtime?.authToken,e?.realtime?.enabled,A,r.subscribe,o,d]),m}function h(r){let a=new Error(r.message);return r.status!==void 0&&(a.status=r.status),a}function P(r,...a){let t=a[0]??{},e=a[1],o=reactQuery.useQueryClient(),i=react.useRef(e?.realtime?.onChange),p=react.useRef(e?.realtime?.onError);react.useEffect(()=>{i.current=e?.realtime?.onChange,p.current=e?.realtime?.onError;},[e?.realtime?.onChange,e?.realtime?.onError]);let u=react.useMemo(()=>e?.queryOptions?.queryKey??(r.queryKey?r.queryKey(t):["appflare","infinite-query",r,t]),[t,e?.queryOptions?.queryKey,r]),d=react.useMemo(()=>reactQuery.hashKey(u),[u]),f=react.useMemo(()=>reactQuery.hashKey([t]),[t]),A=react.useMemo(()=>reactQuery.hashKey([e?.realtime?.requestOptions]),[e?.realtime?.requestOptions]),m=reactQuery.useInfiniteQuery({...e?.queryOptions,queryKey:u,queryFn:async({pageParam:s})=>{let y=s===void 0||!e?.pageParamToArgs?t:e.pageParamToArgs(t,s),n=await r.run(y,e?.requestOptions);if(n.error)throw h(n.error);return n.data}});return react.useEffect(()=>{if(!e?.realtime?.enabled||!r.subscribe)return;let s=new AbortController,y=r.subscribe({args:t,authToken:e?.realtime?.authToken,requestOptions:e?.realtime?.requestOptions,signal:s.signal,onChange:(n,c)=>{o.setQueryData(u,T=>!T||T.pages.length===0?T:{...T,pages:[n,...T.pages.slice(1)]}),i.current?.(n,c);},onError:n=>{p.current?.(n);}});return ()=>{s.abort(),y.remove();}},[f,e?.realtime?.authToken,e?.realtime?.enabled,A,r.subscribe,o,d]),m}function L(r){let a=new Error(r.message);return r.status!==void 0&&(a.status=r.status),a}function C(r,a){return reactQuery.useMutation({...a,mutationFn:async t=>{let e=await r.run(t??{});if(e.error)throw L(e.error);return e.data}})}exports.useInfiniteQuery=P;exports.useMutation=C;exports.useQuery=b;
|
package/dist/react/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {useQueryClient,hashKey,useQuery,useInfiniteQuery,useMutation}from'@tanstack/react-query';import {useRef,useEffect,useMemo}from'react';function O(r){let a=new Error(r.message);return r.status!==void 0&&(a.status=r.status),a}function b(r,...a){let t=a[0]??{},e=a[1],o=useQueryClient(),i=useRef(e?.realtime?.onChange),p=useRef(e?.realtime?.onError);useEffect(()=>{i.current=e?.realtime?.onChange,p.current=e?.realtime?.onError;},[e?.realtime?.onChange,e?.realtime?.onError]);let u=useMemo(()=>e?.queryOptions?.queryKey??(r.queryKey?r.queryKey(t):["appflare","query",r,t]),[t,e?.queryOptions?.queryKey,r]),d=useMemo(()=>hashKey(u),[u]),f=useMemo(()=>hashKey([t]),[t]),A=useMemo(()=>hashKey([e?.realtime?.requestOptions]),[e?.realtime?.requestOptions]),m=useQuery({...e?.queryOptions,queryKey:u,queryFn:async()=>{let s=await r.run(t,e?.requestOptions);if(s.error)throw O(s.error);return s.data}});return useEffect(()=>{if(e?.realtime?.enabled
|
|
1
|
+
import {useQueryClient,hashKey,useQuery,useInfiniteQuery,useMutation}from'@tanstack/react-query';import {useRef,useEffect,useMemo}from'react';function O(r){let a=new Error(r.message);return r.status!==void 0&&(a.status=r.status),a}function b(r,...a){let t=a[0]??{},e=a[1],o=useQueryClient(),i=useRef(e?.realtime?.onChange),p=useRef(e?.realtime?.onError);useEffect(()=>{i.current=e?.realtime?.onChange,p.current=e?.realtime?.onError;},[e?.realtime?.onChange,e?.realtime?.onError]);let u=useMemo(()=>e?.queryOptions?.queryKey??(r.queryKey?r.queryKey(t):["appflare","query",r,t]),[t,e?.queryOptions?.queryKey,r]),d=useMemo(()=>hashKey(u),[u]),f=useMemo(()=>hashKey([t]),[t]),A=useMemo(()=>hashKey([e?.realtime?.requestOptions]),[e?.realtime?.requestOptions]),m=useQuery({...e?.queryOptions,queryKey:u,queryFn:async()=>{let s=await r.run(t,e?.requestOptions);if(s.error)throw O(s.error);return s.data}});return useEffect(()=>{if(!e?.realtime?.enabled||!r.subscribe)return;let s=new AbortController,y=r.subscribe({args:t,authToken:e?.realtime?.authToken,requestOptions:e?.realtime?.requestOptions,signal:s.signal,onChange:(n,c)=>{o.setQueryData(u,n),i.current?.(n,c);},onError:n=>{p.current?.(n);}});return ()=>{s.abort(),y.remove();}},[f,e?.realtime?.authToken,e?.realtime?.enabled,A,r.subscribe,o,d]),m}function h(r){let a=new Error(r.message);return r.status!==void 0&&(a.status=r.status),a}function P(r,...a){let t=a[0]??{},e=a[1],o=useQueryClient(),i=useRef(e?.realtime?.onChange),p=useRef(e?.realtime?.onError);useEffect(()=>{i.current=e?.realtime?.onChange,p.current=e?.realtime?.onError;},[e?.realtime?.onChange,e?.realtime?.onError]);let u=useMemo(()=>e?.queryOptions?.queryKey??(r.queryKey?r.queryKey(t):["appflare","infinite-query",r,t]),[t,e?.queryOptions?.queryKey,r]),d=useMemo(()=>hashKey(u),[u]),f=useMemo(()=>hashKey([t]),[t]),A=useMemo(()=>hashKey([e?.realtime?.requestOptions]),[e?.realtime?.requestOptions]),m=useInfiniteQuery({...e?.queryOptions,queryKey:u,queryFn:async({pageParam:s})=>{let y=s===void 0||!e?.pageParamToArgs?t:e.pageParamToArgs(t,s),n=await r.run(y,e?.requestOptions);if(n.error)throw h(n.error);return n.data}});return useEffect(()=>{if(!e?.realtime?.enabled||!r.subscribe)return;let s=new AbortController,y=r.subscribe({args:t,authToken:e?.realtime?.authToken,requestOptions:e?.realtime?.requestOptions,signal:s.signal,onChange:(n,c)=>{o.setQueryData(u,T=>!T||T.pages.length===0?T:{...T,pages:[n,...T.pages.slice(1)]}),i.current?.(n,c);},onError:n=>{p.current?.(n);}});return ()=>{s.abort(),y.remove();}},[f,e?.realtime?.authToken,e?.realtime?.enabled,A,r.subscribe,o,d]),m}function L(r){let a=new Error(r.message);return r.status!==void 0&&(a.status=r.status),a}function C(r,a){return useMutation({...a,mutationFn:async t=>{let e=await r.run(t??{});if(e.error)throw L(e.error);return e.data}})}export{P as useInfiniteQuery,C as useMutation,b as useQuery};
|