@midsummer-ai/sdk 0.1.0-staging.3653 → 0.1.0-staging.3662

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.
Files changed (44) hide show
  1. package/THIRD-PARTY-NOTICES +1279 -0
  2. package/auth/client.d.mts +222 -18
  3. package/auth/client.mjs +321 -40
  4. package/auth/contract.d.mts +10 -1
  5. package/auth/contract.mjs +347 -30
  6. package/auth/files.d.mts +2 -28
  7. package/auth/files.mjs +2 -231
  8. package/auth/impersonate.d.mts +33 -0
  9. package/auth/impersonate.mjs +42 -0
  10. package/auth/import.d.mts +71 -0
  11. package/auth/import.mjs +195 -0
  12. package/auth/index.d.mts +5 -198
  13. package/auth/index.mjs +3 -2
  14. package/auth/mail.d.mts +23 -5
  15. package/auth/mail.mjs +93 -39
  16. package/auth/password.d.mts +10 -2
  17. package/auth/password.mjs +14 -2
  18. package/auth/react.d.mts +86 -0
  19. package/auth/react.mjs +865 -0
  20. package/auth/stand-in.d.mts +14 -3
  21. package/auth/stand-in.mjs +162 -29
  22. package/auth-D50wCpNm.mjs +1837 -0
  23. package/authorize-BzDrbYtI-0gOzDrp2.mjs +18783 -0
  24. package/{client-BX56cXDt.mjs → connection-C_JSWUrt.mjs} +3 -668
  25. package/database/client.mjs +665 -1
  26. package/dist-DXtY-DJA.mjs +343 -0
  27. package/engine-BhA0XgI7.mjs +48423 -0
  28. package/esm-E3EvzsGX.mjs +1518 -0
  29. package/factory-9jfDGyc1.mjs +1138 -0
  30. package/files-C-FvBxT4.d.mts +75 -0
  31. package/files-DAFOuID_.mjs +692 -0
  32. package/get-id-field-vhOArqXN.mjs +1455 -0
  33. package/index-CsgQ_ouh.d.mts +246 -0
  34. package/package.json +24 -7
  35. package/qr-C1mfuCT9.mjs +1163 -0
  36. package/request-state-BaLB2Hrt.mjs +85 -0
  37. package/rolldown-runtime-CL6CfywC.mjs +36 -0
  38. package/schemas-DTJTcCdK.mjs +6046 -0
  39. package/settings-si8iBtwc.d.mts +47 -0
  40. package/store-CeIGY-xT.d.mts +16 -0
  41. package/{store-B-1coCxW.mjs → store-CsBhnabU.mjs} +1 -1
  42. package/{tabs-CDplCS02.mjs → tabs-gHJHkhm2.mjs} +1 -1
  43. package/auth-Bf7IuulG.mjs +0 -754
  44. package/store-gCz6XVaG.d.mts +0 -15
package/auth/contract.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { n as AuthError } from "../auth-Bf7IuulG.mjs";
1
+ import { c as LIMIT_WINDOW_MS, l as SETTINGS_TTL_MS, n as AuthError, s as LIMITS } from "../auth-D50wCpNm.mjs";
2
+ import { IMPERSONATION_TOKEN_MS, startImpersonation } from "./impersonate.mjs";
2
3
  //#region src/auth/contract.ts
3
4
  /**
4
5
  * Sign-in's contract: what every store promises, as cases any test runner can run. Each case is given sign-in
@@ -86,7 +87,301 @@ async function refusal(work) {
86
87
  }
87
88
  }
88
89
  const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
90
+ /** The app's settings, as the platform writes them into `authSettings`. */
91
+ const settle = (store, settings) => store.call("create", {
92
+ model: "authSettings",
93
+ data: {
94
+ key: "settings",
95
+ ...settings,
96
+ updatedAt: Date.now()
97
+ }
98
+ });
99
+ async function refusalOf(response) {
100
+ const body = await response.json().catch(() => ({}));
101
+ return [response.status, body.code ?? null];
102
+ }
103
+ /** A sign-in as a browser at `ip` sends it. */
104
+ const tryFrom = (auth, ip, email) => auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/sign-in/email`, {
105
+ method: "POST",
106
+ headers: {
107
+ origin: CONTRACT_ORIGIN,
108
+ "content-type": "application/json",
109
+ "x-forwarded-for": ip
110
+ },
111
+ body: JSON.stringify({
112
+ email,
113
+ password: "wrong horse battery"
114
+ })
115
+ }));
89
116
  const authContract = [
117
+ {
118
+ name: "a user's public metadata reaches the app and the browser, their private metadata only the server, and no browser sets either",
119
+ async run({ auth }) {
120
+ const jar = new Jar();
121
+ const id = await signUp(auth, jar, "meg@example.com");
122
+ await auth.users.setMetadata(id, {
123
+ public: { plan: "pro" },
124
+ private: { customer: "cus_123" }
125
+ });
126
+ const browser = await (await ask(auth, jar, "/get-session?disableCookieCache=true")).json();
127
+ equal([browser.user.publicMetadata, "privateMetadata" in browser.user], [{ plan: "pro" }, false], "what the browser reads");
128
+ equal((await auth.session(asPerson(jar), { fresh: true }))?.user.publicMetadata, { plan: "pro" }, "what the app's routes read");
129
+ equal((await auth.users.get(id))?.privateMetadata, { customer: "cus_123" }, "what the server reads");
130
+ await ask(auth, jar, "/update-user", {
131
+ publicMetadata: { plan: "free" },
132
+ privateMetadata: { customer: "mine" }
133
+ });
134
+ equal([(await auth.users.get(id))?.publicMetadata, (await auth.users.get(id))?.privateMetadata], [{ plan: "pro" }, { customer: "cus_123" }], "after a browser tried to set them");
135
+ equal((await refusal(() => auth.users.setMetadata(id, { public: { text: "x".repeat(9e3) } })))?.code, "invalid", "metadata past 8 KB");
136
+ }
137
+ },
138
+ {
139
+ name: "the platform's sign in as makes one session that says who opened it, ends by itself, is used once, and is the platform's alone",
140
+ async run({ auth, store }) {
141
+ const ada = new Jar();
142
+ const id = await signUp(auth, ada, "ada@example.com");
143
+ const started = await startImpersonation({
144
+ userId: id,
145
+ by: "Owner Olsen (owner@acme.dev)",
146
+ reason: "Checking a bug report",
147
+ now: Date.now()
148
+ });
149
+ await store.call("create", {
150
+ model: "authVerifications",
151
+ data: started.row
152
+ });
153
+ const owner = new Jar();
154
+ const opened = owner.take(await auth.handler(new Request(`${CONTRACT_ORIGIN}${started.path}`)));
155
+ equal([opened.status, opened.headers.get("location")], [302, "/"], "opening the link");
156
+ const signedIn = await auth.session(asPerson(owner), { fresh: true });
157
+ equal([signedIn?.user.email, signedIn?.session.impersonatedBy], ["ada@example.com", "Owner Olsen (owner@acme.dev)"], "who the session is, and who opened it");
158
+ const ends = new Date(signedIn.session.expiresAt).getTime();
159
+ equal(ends <= Date.now() + 18e5 && ends > Date.now() + 174e4, true, "it ends within half an hour");
160
+ equal(new Date((await auth.session(asPerson(owner), { fresh: true })).session.expiresAt).getTime(), ends, "its end after another read");
161
+ equal((await (await ask(auth, ada, "/account/sessions")).json()).map((one) => one.impersonatedBy ?? null), ["Owner Olsen (owner@acme.dev)", null], "Ada's sessions, newest first");
162
+ equal((await auth.handler(new Request(`${CONTRACT_ORIGIN}${started.path}`))).status, 400, "the same link again");
163
+ const old = await startImpersonation({
164
+ userId: id,
165
+ by: "Owner",
166
+ reason: "Late",
167
+ now: Date.now() - IMPERSONATION_TOKEN_MS - 1
168
+ });
169
+ await store.call("create", {
170
+ model: "authVerifications",
171
+ data: old.row
172
+ });
173
+ equal((await auth.handler(new Request(`${CONTRACT_ORIGIN}${old.path}`))).status, 400, "a link past its minute");
174
+ equal((await ask(auth, ada, "/admin/impersonate-user", { userId: id })).status, 404, "the app's own way");
175
+ }
176
+ },
177
+ {
178
+ name: "a password that appeared in a leak is refused at sign-up and as a new one",
179
+ async run({ auth }) {
180
+ equal(await refusalOf(await ask(auth, new Jar(), "/sign-up/email", {
181
+ email: "pat@example.com",
182
+ password: "password1234",
183
+ name: "Pat"
184
+ })), [400, "PASSWORD_COMPROMISED"], "signing up with it");
185
+ const jar = new Jar();
186
+ await signUp(auth, jar, "pat@example.com");
187
+ equal(await refusalOf(await ask(auth, jar, "/change-password", {
188
+ currentPassword: "correct horse battery",
189
+ newPassword: "password1234"
190
+ })), [400, "PASSWORD_COMPROMISED"], "changing to it");
191
+ }
192
+ },
193
+ {
194
+ name: "an address that tries to sign in too often is refused for a minute, and no other address is",
195
+ async run({ auth, later }) {
196
+ for (let n = 0; n < LIMITS["sign-in"]; n++) equal((await tryFrom(auth, "198.51.100.7", "ada@example.com")).status, 401, `try ${n + 1}`);
197
+ const refused = await tryFrom(auth, "198.51.100.7", "ada@example.com");
198
+ equal([...await refusalOf(refused), refused.headers.get("retry-after")], [
199
+ 429,
200
+ "TOO_MANY_REQUESTS",
201
+ "60"
202
+ ], "one try too many");
203
+ equal((await tryFrom(auth, "198.51.100.8", "ada@example.com")).status, 401, "another address");
204
+ later(LIMIT_WINDOW_MS);
205
+ equal((await tryFrom(auth, "198.51.100.7", "ada@example.com")).status, 401, "a minute later");
206
+ }
207
+ },
208
+ {
209
+ name: "with a bot check set, sign-up and sign-in need its token, and take one that passes",
210
+ async run({ auth, store }) {
211
+ await settle(store, { captcha: {
212
+ provider: "turnstile",
213
+ siteKey: "site-key",
214
+ secretName: "CAPTCHA_SECRET"
215
+ } });
216
+ const signUpWith = (token) => auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/sign-up/email`, {
217
+ method: "POST",
218
+ headers: {
219
+ origin: CONTRACT_ORIGIN,
220
+ "content-type": "application/json",
221
+ ...token ? { "x-captcha-response": token } : {}
222
+ },
223
+ body: JSON.stringify({
224
+ email: "bo@example.com",
225
+ password: "correct horse battery",
226
+ name: "Bo"
227
+ })
228
+ }));
229
+ equal(await refusalOf(await signUpWith()), [400, "CAPTCHA_REQUIRED"], "with no token");
230
+ equal(await refusalOf(await signUpWith("robot")), [400, "CAPTCHA_FAILED"], "with a token that fails");
231
+ equal((await signUpWith("human")).status, 200, "with one that passes");
232
+ equal((await (await auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/settings`))).json()).captcha, {
233
+ provider: "turnstile",
234
+ siteKey: "site-key"
235
+ }, "what a browser reads of it");
236
+ }
237
+ },
238
+ {
239
+ name: "the settings the platform writes turn a way in off and brand the mail, with nothing restarted",
240
+ async run({ auth, store, outbox }) {
241
+ await settle(store, {
242
+ methods: {
243
+ password: false,
244
+ code: true,
245
+ link: true,
246
+ passkey: true,
247
+ google: true,
248
+ github: true
249
+ },
250
+ branding: {
251
+ name: "Acme Shop",
252
+ logo: "https://shop.example/logo.png",
253
+ color: "#0a7cff"
254
+ }
255
+ });
256
+ const jar = new Jar();
257
+ equal(await refusalOf(await ask(auth, jar, "/sign-up/email", {
258
+ email: "ada@example.com",
259
+ password: "correct horse battery",
260
+ name: "Ada"
261
+ })), [403, "METHOD_OFF"], "signing up with a password, turned off");
262
+ equal((await ask(auth, jar, "/email-otp/send-verification-otp", {
263
+ email: "ada@example.com",
264
+ type: "sign-in"
265
+ })).status, 200, "asking for a code, still on");
266
+ equal([outbox().at(-1)?.app, outbox().at(-1)?.brand], ["Acme Shop", {
267
+ logo: "https://shop.example/logo.png",
268
+ color: "#0a7cff"
269
+ }], "the mail, in the app's name and look");
270
+ const shown = await (await auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/settings`))).json();
271
+ equal([
272
+ shown.methods.password,
273
+ shown.branding.name,
274
+ JSON.stringify(shown).includes("secretName") ? "secret" : "none"
275
+ ], [
276
+ false,
277
+ "Acme Shop",
278
+ "none"
279
+ ], "the settings a browser reads");
280
+ }
281
+ },
282
+ {
283
+ name: "sign-up open only to some email domains takes theirs and refuses the rest",
284
+ async run({ auth, store }) {
285
+ await settle(store, { signUp: {
286
+ policy: "domains",
287
+ domains: ["acme.dev"]
288
+ } });
289
+ equal((await ask(auth, new Jar(), "/sign-up/email", {
290
+ email: "ada@acme.dev",
291
+ password: "correct horse battery",
292
+ name: "Ada"
293
+ })).status, 200, "an email at acme.dev");
294
+ equal(await refusalOf(await ask(auth, new Jar(), "/sign-up/email", {
295
+ email: "lin@example.com",
296
+ password: "correct horse battery",
297
+ name: "Lin"
298
+ })), [403, "SIGN_UP_DOMAIN"], "an email elsewhere");
299
+ await ask(auth, new Jar(), "/email-otp/send-verification-otp", {
300
+ email: "kay@example.com",
301
+ type: "sign-in"
302
+ });
303
+ equal(await store.call("findOne", {
304
+ model: "users",
305
+ where: [{
306
+ field: "email",
307
+ value: "kay@example.com"
308
+ }]
309
+ }), null, "no user made by a code elsewhere");
310
+ }
311
+ },
312
+ {
313
+ name: "invite-only sign-up takes only who the owner approved, and people who are users already still sign in",
314
+ async run({ auth, store, later }) {
315
+ await signUp(auth, new Jar(), "old@example.com");
316
+ await settle(store, { signUp: {
317
+ policy: "invite",
318
+ domains: []
319
+ } });
320
+ later(SETTINGS_TTL_MS);
321
+ equal(await refusalOf(await ask(auth, new Jar(), "/sign-up/email", {
322
+ email: "new@example.com",
323
+ password: "correct horse battery",
324
+ name: "New"
325
+ })), [403, "SIGN_UP_INVITE_ONLY"], "someone not invited");
326
+ await store.call("create", {
327
+ model: "authWaitlist",
328
+ data: {
329
+ email: "new@example.com",
330
+ status: "approved",
331
+ createdAt: Date.now(),
332
+ decidedAt: Date.now(),
333
+ decidedBy: "Owner"
334
+ }
335
+ });
336
+ equal((await ask(auth, new Jar(), "/sign-up/email", {
337
+ email: "New@Example.com",
338
+ password: "correct horse battery",
339
+ name: "New"
340
+ })).status, 200, "someone the owner approved, in any case");
341
+ equal((await ask(auth, new Jar(), "/sign-in/email", {
342
+ email: "old@example.com",
343
+ password: "correct horse battery"
344
+ })).status, 200, "a user from before");
345
+ }
346
+ },
347
+ {
348
+ name: "a waitlist keeps who asks, and lets them sign up once the owner approves them",
349
+ async run({ auth, store }) {
350
+ await settle(store, { signUp: {
351
+ policy: "waitlist",
352
+ domains: []
353
+ } });
354
+ equal(await refusalOf(await ask(auth, new Jar(), "/sign-up/email", {
355
+ email: "wes@example.com",
356
+ password: "correct horse battery",
357
+ name: "Wes"
358
+ })), [403, "SIGN_UP_WAITLIST"], "asking to sign up");
359
+ equal((await store.call("findOne", {
360
+ model: "authWaitlist",
361
+ where: [{
362
+ field: "email",
363
+ value: "wes@example.com"
364
+ }]
365
+ }))?.status, "waiting", "the waitlist");
366
+ await store.call("update", {
367
+ model: "authWaitlist",
368
+ where: [{
369
+ field: "email",
370
+ value: "wes@example.com"
371
+ }],
372
+ update: {
373
+ status: "approved",
374
+ decidedAt: Date.now(),
375
+ decidedBy: "Owner"
376
+ }
377
+ });
378
+ equal((await ask(auth, new Jar(), "/sign-up/email", {
379
+ email: "wes@example.com",
380
+ password: "correct horse battery",
381
+ name: "Wes"
382
+ })).status, 200, "signing up once approved");
383
+ }
384
+ },
90
385
  {
91
386
  name: "signing up with an email and a password signs the person in",
92
387
  async run({ auth }) {
@@ -174,28 +469,42 @@ const authContract = [
174
469
  },
175
470
  {
176
471
  name: "a revoked session is refused once its cookie is not trusted on its own",
177
- async run({ auth }) {
472
+ async run({ auth, store }) {
178
473
  const jar = new Jar();
179
474
  await signUp(auth, jar, "ola@example.com");
180
- const context = await auth.at(CONTRACT_ORIGIN).$context;
181
- const signedIn = await auth.session(new Request(`${CONTRACT_ORIGIN}/`, { headers: { cookie: jar.header } }));
182
- await context.internalAdapter.deleteSession(signedIn.session.token);
183
- equal(await auth.at(CONTRACT_ORIGIN).api.getSession({
184
- headers: new Headers({ cookie: jar.header }),
185
- query: { disableCookieCache: true }
186
- }), null, "the session read from its row");
475
+ const signedIn = await auth.session(asPerson(jar));
476
+ await store.call("deleteMany", {
477
+ model: "authSessions",
478
+ where: [{
479
+ field: "id",
480
+ value: signedIn.session.id
481
+ }]
482
+ });
483
+ equal(await auth.session(asPerson(jar), { fresh: true }), null, "the session read from its row");
187
484
  }
188
485
  },
189
486
  {
190
487
  name: "a banned user can't sign in",
191
- async run({ auth }) {
488
+ async run({ auth, store }) {
192
489
  const id = await signUp(auth, new Jar(), "zed@example.com");
193
- const context = await auth.at(CONTRACT_ORIGIN).$context;
194
- await context.internalAdapter.updateUser(id, {
195
- banned: true,
196
- banReason: "spam"
490
+ await store.call("update", {
491
+ model: "users",
492
+ where: [{
493
+ field: "id",
494
+ value: id
495
+ }],
496
+ update: {
497
+ banned: true,
498
+ banReason: "spam"
499
+ }
500
+ });
501
+ await store.call("deleteMany", {
502
+ model: "authSessions",
503
+ where: [{
504
+ field: "userId",
505
+ value: id
506
+ }]
197
507
  });
198
- await context.internalAdapter.deleteUserSessions(id);
199
508
  equal((await ask(auth, new Jar(), "/sign-in/email", {
200
509
  email: "zed@example.com",
201
510
  password: "correct horse battery"
@@ -252,7 +561,7 @@ const authContract = [
252
561
  },
253
562
  {
254
563
  name: "a revoked key, an expired key, an unknown key and a banned person's key sign no one in",
255
- async run({ auth }) {
564
+ async run({ auth, store }) {
256
565
  const jar = new Jar();
257
566
  await signUp(auth, jar, "jo@example.com");
258
567
  const gone = await auth.keys.create(asPerson(jar), {
@@ -265,14 +574,13 @@ const authContract = [
265
574
  expiresIn: 86400
266
575
  });
267
576
  await auth.keys.revoke(asPerson(jar), gone.id);
268
- const context = await auth.at(CONTRACT_ORIGIN).$context;
269
- await context.adapter.update({
270
- model: "apikey",
577
+ await store.call("update", {
578
+ model: "authKeys",
271
579
  where: [{
272
580
  field: "id",
273
581
  value: old.id
274
582
  }],
275
- update: { expiresAt: /* @__PURE__ */ new Date(Date.now() - 1e3) }
583
+ update: { expiresAt: Date.now() - 1e3 }
276
584
  });
277
585
  equal(await auth.session(asAgent(gone.key), { scope: "notes:read" }), null, "a revoked key");
278
586
  equal(await auth.session(asAgent(old.key), { scope: "notes:read" }), null, "an expired key");
@@ -282,7 +590,14 @@ const authContract = [
282
590
  name: "live",
283
591
  scopes: ["notes:read"]
284
592
  });
285
- await context.internalAdapter.updateUser((await auth.session(asPerson(jar))).user.id, { banned: true });
593
+ await store.call("update", {
594
+ model: "users",
595
+ where: [{
596
+ field: "id",
597
+ value: (await auth.session(asPerson(jar))).user.id
598
+ }],
599
+ update: { banned: true }
600
+ });
286
601
  equal(await auth.session(asAgent(live.key), { scope: "notes:read" }), null, "a banned person's key");
287
602
  }
288
603
  },
@@ -303,17 +618,19 @@ const authContract = [
303
618
  },
304
619
  {
305
620
  name: "a new store has no keys, clients or grants",
306
- async run({ auth }) {
621
+ async run({ auth, store }) {
307
622
  const jar = new Jar();
308
623
  await signUp(auth, jar, "una@example.com");
309
624
  equal([await auth.keys.list(asPerson(jar)), await auth.grants.list(asPerson(jar))], [[], []], "a new person's keys and grants");
310
- const context = await auth.at(CONTRACT_ORIGIN).$context;
311
- equal(await Promise.all([
312
- "apikey",
313
- "oauthClient",
314
- "oauthConsent",
315
- "oauthRefreshToken"
316
- ].map((model) => context.adapter.count({ model }))), [
625
+ equal((await Promise.all([
626
+ "authKeys",
627
+ "authClients",
628
+ "authGrants",
629
+ "authRefreshTokens"
630
+ ].map((model) => store.call("page", {
631
+ model,
632
+ numItems: 1
633
+ })))).map((one) => one.page.length), [
317
634
  0,
318
635
  0,
319
636
  0,
@@ -379,7 +696,7 @@ const authContract = [
379
696
  const jar = new Jar();
380
697
  const toSignIn = await auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/oauth2/authorize?${asked}`));
381
698
  const signInAt = new URL(toSignIn.headers.get("location") ?? "", CONTRACT_ORIGIN);
382
- equal([toSignIn.status, signInAt.pathname], [302, "/sign-in"], "authorizing signed out");
699
+ equal([toSignIn.status, signInAt.pathname], [302, "/api/auth/ui/sign-in"], "authorizing signed out");
383
700
  const signedUp = await ask(auth, jar, "/sign-up/email", {
384
701
  email: "mia@example.com",
385
702
  password: "correct horse battery",
package/auth/files.d.mts CHANGED
@@ -1,28 +1,2 @@
1
- import { BetterAuthOptions } from "better-auth";
2
- //#region src/auth/files.d.ts
3
- /** The tables sign-in keeps, by table name: each field's shape, and the fields rows are looked up by. */
4
- interface AuthTable {
5
- readonly fields: Readonly<Record<string, string>>;
6
- readonly indexed: ReadonlyArray<string>;
7
- readonly unique: ReadonlyArray<string>;
8
- }
9
- /**
10
- * The tables better-auth asks for under `options` (its plugins add theirs), as the Database keeps them. A
11
- * field is looked up by an index when better-auth marks it unique or indexed, when it names another row, and
12
- * for `expiresAt`, by which old rows are cleared.
13
- */
14
- declare function authTablesOf(options: BetterAuthOptions): Readonly<Record<string, AuthTable>>;
15
- /** `db/authTables.ts`: each table as `defineTable(...)` with its indexes, and the fields each is looked up by. */
16
- declare function tablesFile(tables: Readonly<Record<string, AuthTable>>): string;
17
- /** The lines db/schema.ts names sign-in's tables with, inside `defineSchema({ ... })`. */
18
- declare function schemaLines(tables: Readonly<Record<string, AuthTable>>): string;
19
- /**
20
- * `db/auth.ts`: what `@midsummer-ai/sdk/auth` calls, `auth.create`, `auth.findOne`, `auth.findMany`,
21
- * `auth.count`, `auth.update`, `auth.updateMany`, `auth.deleteMany`, `auth.increment` and `auth.consume`. A `where` is
22
- * better-auth's: clauses of `{ field, operator, value, connector, mode }`, `id` meaning the row's `_id`. All
23
- * joined by AND with an `eq` (or a range) on a field looked up by reads only that index's rows; anything else
24
- * reads the table.
25
- */
26
- declare const FUNCTIONS_FILE = "// Written by `midsummer auth init`: what @midsummer-ai/sdk/auth keeps your app's users with. Write it again with that command; don't edit it.\nimport { mutation, query, v } from \"./_generated/server\"\nimport { authLookups } from \"./authTables\"\n\nconst where = v.optional(v.array(v.any()))\n\nfunction server(ctx) {\n if (!ctx.identity.server) throw new Error(\"Only the app's own server reads and writes sign-in's tables.\")\n}\nfunction table(model) {\n if (!Object.hasOwn(authLookups, model)) throw new Error(`${model} is not one of sign-in's tables`)\n return model\n}\n/** A row as better-auth takes it: its `_id` as `id`. */\nfunction shown(doc) {\n if (!doc) return null\n const { _id, _creationTime, _version, ...fields } = doc\n return { id: _id, ...fields }\n}\nconst text = (value) => (typeof value === \"string\" ? value.toLowerCase() : value)\nfunction holds(row, clause) {\n const { field, value, operator = \"eq\", mode } = clause\n const have = row[field], loose = mode === \"insensitive\"\n const same = (a, b) => (loose ? text(a) === text(b) : a === b)\n switch (operator) {\n case \"eq\": return value === null ? have == null : same(have, value)\n case \"ne\": return value === null ? have != null : !same(have, value)\n case \"in\": return Array.isArray(value) && value.some((one) => same(have, one))\n case \"not_in\": return Array.isArray(value) && !value.some((one) => same(have, one))\n case \"lt\": return value != null && have != null && have < value\n case \"lte\": return value != null && have != null && have <= value\n case \"gt\": return value != null && have != null && have > value\n case \"gte\": return value != null && have != null && have >= value\n case \"contains\": return typeof have === \"string\" && typeof value === \"string\" && (loose ? text(have).includes(text(value)) : have.includes(value))\n case \"starts_with\": return typeof have === \"string\" && typeof value === \"string\" && (loose ? text(have).startsWith(text(value)) : have.startsWith(value))\n case \"ends_with\": return typeof have === \"string\" && typeof value === \"string\" && (loose ? text(have).endsWith(text(value)) : have.endsWith(value))\n default: throw new Error(`sign-in asked with an operator the Database's sign-in tables don't take: ${operator}`)\n }\n}\n/** Whether a row matches a where: its clauses in order, each joined to those before by its own connector. */\nfunction matches(row, clauses) {\n if (!clauses?.length) return true\n let result = holds(row, clauses[0])\n for (const clause of clauses.slice(1)) result = clause.connector === \"OR\" ? result || holds(row, clause) : result && holds(row, clause)\n return result\n}\nconst RANGE = { lt: \"lt\", lte: \"lte\", gt: \"gt\", gte: \"gte\" }\n/** The rows of `model` a where can hold: by id, through the index of a field it asks for by value, or the whole table. */\nasync function candidates(ctx, model, clauses) {\n const all = clauses ?? []\n const ands = all.every((clause, index) => index === 0 || clause.connector !== \"OR\")\n if (ands) {\n const byId = all.find((clause) => clause.field === \"id\" && (clause.operator ?? \"eq\") === \"eq\")\n if (byId) {\n const id = typeof byId.value === \"string\" ? ctx.db.normalizeId(model, byId.value) : null\n const doc = id ? await ctx.db.get(model, id) : null\n return doc ? [doc] : []\n }\n const ids = all.find((clause) => clause.field === \"id\" && clause.operator === \"in\" && Array.isArray(clause.value))\n if (ids) return (await Promise.all(ids.value.map((one) => (typeof one === \"string\" && ctx.db.normalizeId(model, one) ? ctx.db.get(model, one) : null)))).filter(Boolean)\n const lookups = authLookups[model]\n // Of the fields it asks for by value, the one listed first finds the fewest rows: a unique one, a key or a token.\n const exact = all.filter((clause) => (clause.operator ?? \"eq\") === \"eq\" && clause.mode !== \"insensitive\" && clause.value !== null && lookups.includes(clause.field)).sort((a, b) => lookups.indexOf(a.field) - lookups.indexOf(b.field))[0]\n if (exact) return ctx.db.query(model).withIndex(`by_${exact.field}`, (q) => q.eq(exact.field, exact.value)).collect()\n const ranged = all.find((clause) => RANGE[clause.operator] && clause.value != null && lookups.includes(clause.field))\n if (ranged) return ctx.db.query(model).withIndex(`by_${ranged.field}`, (q) => q[RANGE[ranged.operator]](ranged.field, ranged.value)).collect()\n }\n return ctx.db.query(model).collect()\n}\nasync function found(ctx, model, clauses) {\n return (await candidates(ctx, model, clauses)).map(shown).filter((row) => matches(row, clauses))\n}\nfunction ordered(rows, sortBy) {\n if (!sortBy) return rows\n const sign = sortBy.direction === \"desc\" ? -1 : 1\n return [...rows].sort((a, b) => {\n const x = a[sortBy.field], y = b[sortBy.field]\n return x == null && y == null ? 0 : x == null ? -sign : y == null ? sign : x < y ? -sign : x > y ? sign : 0\n })\n}\n/** A row's fields as written: better-auth's id is the Database's, and `undefined` takes a field out. */\nconst fieldsOf = (data) => Object.fromEntries(Object.entries(data ?? {}).filter(([field]) => field !== \"id\" && field !== \"_id\"))\n\nexport const create = mutation({\n args: { model: v.string(), data: v.any() },\n handler: async (ctx, { model, data }) => {\n server(ctx)\n const id = await ctx.db.insert(table(model), fieldsOf(data))\n return shown(await ctx.db.get(model, id))\n },\n})\nexport const findOne = query({\n args: { model: v.string(), where },\n handler: async (ctx, { model, where }) => {\n server(ctx)\n return (await found(ctx, table(model), where))[0] ?? null\n },\n})\nexport const findMany = query({\n args: { model: v.string(), where, limit: v.optional(v.number()), offset: v.optional(v.number()), sortBy: v.optional(v.any()) },\n handler: async (ctx, { model, where, limit, offset, sortBy }) => {\n server(ctx)\n const rows = ordered(await found(ctx, table(model), where), sortBy)\n return rows.slice(offset ?? 0, limit === undefined ? undefined : (offset ?? 0) + limit)\n },\n})\nexport const count = query({\n args: { model: v.string(), where },\n handler: async (ctx, { model, where }) => {\n server(ctx)\n return (await found(ctx, table(model), where)).length\n },\n})\nexport const update = mutation({\n args: { model: v.string(), where, update: v.any() },\n handler: async (ctx, { model, where, update }) => {\n server(ctx)\n const row = (await found(ctx, table(model), where))[0]\n if (!row) return null\n await ctx.db.patch(model, row.id, fieldsOf(update))\n return shown(await ctx.db.get(model, row.id))\n },\n})\nexport const updateMany = mutation({\n args: { model: v.string(), where, update: v.any() },\n handler: async (ctx, { model, where, update }) => {\n server(ctx)\n const rows = await found(ctx, table(model), where)\n await Promise.all(rows.map((row) => ctx.db.patch(model, row.id, fieldsOf(update))))\n return rows.length\n },\n})\nexport const deleteMany = mutation({\n args: { model: v.string(), where },\n handler: async (ctx, { model, where }) => {\n server(ctx)\n const rows = await found(ctx, table(model), where)\n await Promise.all(rows.map((row) => ctx.db.delete(model, row.id)))\n return rows.length\n },\n})\n/** Adds to a row's numbers and sets its fields in one step, returning the row, or null when the where finds none: a count is never passed by two at once. */\nexport const increment = mutation({\n args: { model: v.string(), where, increment: v.any(), set: v.optional(v.any()) },\n handler: async (ctx, { model, where, increment, set }) => {\n server(ctx)\n const row = (await found(ctx, table(model), where))[0]\n if (!row) return null\n const next = fieldsOf(set)\n for (const [field, delta] of Object.entries(increment ?? {})) next[field] = (row[field] ?? 0) + delta\n await ctx.db.patch(model, row.id, next)\n return shown(await ctx.db.get(model, row.id))\n },\n})\n/** Deletes the first row a where holds and returns it, in one step: a code or a link is used once. */\nexport const consume = mutation({\n args: { model: v.string(), where },\n handler: async (ctx, { model, where }) => {\n server(ctx)\n const row = (await found(ctx, table(model), where))[0]\n if (!row) return null\n await ctx.db.delete(model, row.id)\n return row\n },\n})\n";
27
- //#endregion
28
- export { AuthTable, FUNCTIONS_FILE, authTablesOf, schemaLines, tablesFile };
1
+ import { a as authTables, c as tablesFromEngine, i as authFiles, n as EngineField, o as schemaLines, r as FUNCTIONS_FILE, s as tablesFile, t as AuthTable } from "../files-C-FvBxT4.mjs";
2
+ export { AuthTable, EngineField, FUNCTIONS_FILE, authFiles, authTables, schemaLines, tablesFile, tablesFromEngine };