@marktiderman/genesis-supabase 0.12.0 → 0.13.0

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/README.md CHANGED
@@ -202,12 +202,30 @@ const client = createAuthFormClient(supabase, {
202
202
  | `signInWithPassword` | `signInWithPassword` |
203
203
  | `sendMagicLink`, `sendEmailCode` | `signInWithOtp` (`shouldCreateUser` follows the form's `allowSignUp`; without sign-up, an unknown email is answered as sent) |
204
204
  | `verifyEmailCode` | `verifyOtp({ email, token, type: "email" })` |
205
- | `signUp` | `signUp`; `confirmEmail` when no session came back |
205
+ | `signUp` | `signUp`, with the form's `signUpFields` as `options.data` (the user's metadata); `confirmEmail` when no session came back |
206
206
  | `sendPasswordReset` | `resetPasswordForEmail` to `resetRedirectTo` |
207
207
  | `updatePassword` | `updateUser({ password })`, on the session the reset link opened (`session_not_found` without one) |
208
- | `signInWithProvider` | `signInWithOAuth` (leaves the page for the provider) |
208
+ | `signInWithProvider` | `signInWithOAuth` to `providerRedirectTo`, with `providerQueryParams` (leaves the page for the provider) |
209
+ | `sendPhoneCode`, `verifyPhoneCode` | `signInWithOtp({ phone })`, then `verifyOtp({ phone, token, type: "sms" })`: the form's `"phone-code"` method |
210
+ | `currentEmail` | `getSession()`: the signed-in email, which the new-password form gives the password manager (no request) |
209
211
  | `providers` | `fetchAuthSettings`: `GET /auth/v1/settings`, the OAuth providers turned on (asked once per client) |
210
212
 
213
+ **Where each link comes back to.** `redirectTo` is the default for all of them. `emailRedirectTo`
214
+ overrides it for the emailed links (a magic link, the sign-up confirmation), `resetRedirectTo` for
215
+ the reset link (default `emailRedirectTo`), and `providerRedirectTo` for the providers: a string,
216
+ or a function of the provider's id that returns `undefined` for the default. `providerQueryParams`
217
+ adds parameters to the provider's authorize URL, for every provider or per provider:
218
+
219
+ ```ts
220
+ const client = createAuthFormClient(supabase, {
221
+ redirectTo: `${location.origin}/auth/callback`,
222
+ providerRedirectTo: (provider) => (provider === "apple" ? `${location.origin}/auth/apple` : undefined),
223
+ providerQueryParams: (provider) => (provider === "google" ? { access_type: "offline", prompt: "consent" } : undefined),
224
+ });
225
+ ```
226
+
227
+ There's no need to override `signInWithProvider` for either.
228
+
211
229
  Every failure resolves as `{ error: { code, message } }` with Auth's code (`network` for a request
212
230
  that got no answer, `session_not_found` for `AuthSessionMissingError`), also on a client made with
213
231
  `throwOnError: true`. The form shows fixed copy for the code; Auth's `message` is never shown, only
@@ -215,7 +233,15 @@ sent to `reportError` when the form has no copy for the code.
215
233
 
216
234
  - **Codes need the template.** Supabase sends the Magic Link email for a link and for a code alike,
217
235
  and the default template has only the link: put `{{ .Token }}` in it to offer `"email-code"`.
218
- - **The redirects** (`redirectTo`, `resetRedirectTo`) must be in the project's redirect allow list.
236
+ With `offerCodeOnConfirm` the form also offers the code after sign-up, so put it in the Confirm
237
+ signup template too (`verifyOtp` with `type: "email"` confirms the account).
238
+ - **The code's length is the project's.** The form's `codeLength` (default 6) must match the
239
+ project's `otp_length` (Auth settings, "Email OTP length"). `/auth/v1/settings` doesn't report
240
+ it, so nothing can check it for you: with a mismatch no code can be entered whole, and code sign-in fails.
241
+ - **A texted code** (`"phone-code"`) needs a phone provider (Twilio, MessageBird…) turned on in
242
+ the project's Auth settings; its code length is the project's SMS OTP length, and the form's
243
+ `codeLength` must match it as for email.
244
+ - **The redirects** (`redirectTo`, `emailRedirectTo`, `resetRedirectTo`, `providerRedirectTo`) must be in the project's redirect allow list.
219
245
  `createGenesisSupabase()` uses the PKCE flow (a plain `createClient` from supabase-js defaults to
220
246
  the implicit flow), and its callback page needs nothing more on the web (`detectSessionInUrl`).
221
247
  A PKCE link only works in the browser that asked for it, where the code verifier is stored: a
@@ -273,13 +273,16 @@ declare function syncFeatureRegistry(client: FeatureRegistryClient, document: Fe
273
273
  /**
274
274
  * Web sign-in on Supabase Auth, for genesis-ui's `AuthForm`: the calls each
275
275
  * of its modes makes (password, magic link, emailed code, sign-up, reset, new
276
- * password, providers) and the provider list read from the project's
276
+ * password, providers, a texted code) and the provider list read from the project's
277
277
  * `/auth/v1/settings`. Platform-neutral; native sign-in is on `/native`.
278
278
  */
279
279
 
280
- /** The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits. */
280
+ /**
281
+ * The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits.
282
+ * `getSession`, when there, gives the new-password form the signed-in email (`currentEmail`).
283
+ */
281
284
  interface AuthFormSupabase {
282
- auth: Pick<SupabaseClient["auth"], "signInWithPassword" | "signInWithOtp" | "verifyOtp" | "signUp" | "resetPasswordForEmail" | "updateUser" | "signInWithOAuth">;
285
+ auth: Pick<SupabaseClient["auth"], "signInWithPassword" | "signInWithOtp" | "verifyOtp" | "signUp" | "resetPasswordForEmail" | "updateUser" | "signInWithOAuth"> & Partial<Pick<SupabaseClient["auth"], "getSession">>;
283
286
  }
284
287
  /**
285
288
  * Why a call failed: Supabase Auth's error `code` (`invalid_credentials`,
@@ -321,9 +324,11 @@ interface AuthFormSupabaseClient {
321
324
  email: string;
322
325
  code: string;
323
326
  }): Promise<AuthCallResult>;
327
+ /** `data`: the new user's metadata (`options.data`, `raw_user_meta_data`), such as `full_name`. */
324
328
  signUp(input: {
325
329
  email: string;
326
330
  password: string;
331
+ data?: Record<string, unknown>;
327
332
  }): Promise<AuthCallResult>;
328
333
  sendPasswordReset(input: {
329
334
  email: string;
@@ -332,6 +337,18 @@ interface AuthFormSupabaseClient {
332
337
  password: string;
333
338
  }): Promise<AuthCallResult>;
334
339
  signInWithProvider(provider: string): Promise<AuthCallResult>;
340
+ /** A code by text message (`signInWithOtp({ phone })`). Needs a phone provider in the project's Auth settings. */
341
+ sendPhoneCode(input: {
342
+ phone: string;
343
+ createUser: boolean;
344
+ }): Promise<AuthCallResult>;
345
+ /** Checks a texted code (`verifyOtp({ phone, token, type: "sms" })`). */
346
+ verifyPhoneCode(input: {
347
+ phone: string;
348
+ code: string;
349
+ }): Promise<AuthCallResult>;
350
+ /** The signed-in user's email, from the session the client holds (no request); null without one. Present when the Supabase client has `getSession`. */
351
+ currentEmail?(): Promise<string | null>;
335
352
  /** Present when `url` and `publishableKey` were given. */
336
353
  providers?(): Promise<string[]>;
337
354
  }
@@ -347,8 +364,22 @@ interface CreateAuthFormClientOptions {
347
364
  * project's redirect allow list. Left out: the project's Site URL.
348
365
  */
349
366
  redirectTo?: string;
350
- /** Where the password-reset link opens: the page that shows `mode="new-password"`. Default `redirectTo`. */
367
+ /** Where the emailed links come back to (a magic link, the sign-up confirmation): overrides `redirectTo` for them. Default `redirectTo`. */
368
+ emailRedirectTo?: string;
369
+ /** Where the password-reset link opens: the page that shows `mode="new-password"`. Default `emailRedirectTo`, then `redirectTo`. */
351
370
  resetRedirectTo?: string;
371
+ /**
372
+ * Where a provider sends the person back to, for every provider or per provider (a function of
373
+ * its id, `undefined` for the default): overrides `redirectTo` for providers. It must be in the
374
+ * project's redirect allow list. Default `redirectTo`.
375
+ */
376
+ providerRedirectTo?: string | ((provider: string) => string | undefined);
377
+ /**
378
+ * Extra query parameters for the provider's authorize URL (`signInWithOAuth`'s
379
+ * `options.queryParams`): Google's `{ access_type: "offline", prompt: "consent" }`, say. One
380
+ * record for every provider, or a function of the provider's id. Default none.
381
+ */
382
+ providerQueryParams?: Record<string, string> | ((provider: string) => Record<string, string> | undefined);
352
383
  /** For the settings request. Default the global `fetch`. */
353
384
  fetch?: typeof fetch;
354
385
  }
@@ -357,7 +388,9 @@ interface CreateAuthFormClientOptions {
357
388
  * link and emailed code (`signInWithOtp`, the code checked with `verifyOtp`),
358
389
  * sign-up (`confirmEmail` when the project confirms emails), the reset email,
359
390
  * the new password (`updateUser`, on the session the reset link opened), and
360
- * OAuth providers (`signInWithOAuth`, which leaves the page). Every failure is
391
+ * OAuth providers (`signInWithOAuth`, which leaves the page; `providerRedirectTo` and
392
+ * `providerQueryParams` shape where it goes), and a code by text message
393
+ * (`signInWithOtp({ phone })`, checked with `verifyOtp` type `"sms"`). Every failure is
361
394
  * `{ error: { code, message } }`, never a throw, also on a client made with
362
395
  * `throwOnError: true`.
363
396
  *
@@ -375,7 +408,10 @@ interface CreateAuthFormClientOptions {
375
408
  *
376
409
  * One email template serves the link and the code: Supabase sends the Magic
377
410
  * Link template for both, so a form offering `"email-code"` needs
378
- * `{{ .Token }}` in it (the default template has only the link).
411
+ * `{{ .Token }}` in it (the default template has only the link). The form's
412
+ * `codeLength` must match the project's `otp_length`, which
413
+ * `/auth/v1/settings` doesn't report: with a mismatch no code can be entered
414
+ * whole, and code sign-in fails.
379
415
  *
380
416
  * ```ts
381
417
  * const client = createAuthFormClient(supabase, {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import '@supabase/supabase-js';
2
- export { A as APPLE_REVOKE_FUNCTION, c as AuthCallError, d as AuthCallResult, e as AuthFormSupabase, f as AuthFormSupabaseClient, g as AuthSettings, C as CreateAuthFormClientOptions, D as DeleteAccountClient, j as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, k as FeatureGateStateOptions, l as FeatureRegistryClient, m as FeatureRegistryDocument, n as FlagStateValue, o as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, p as SUPABASE_OAUTH_PROVIDERS, S as SessionStorage, q as SetTenantFeatureInput, r as StoreAppleTokenOptions, s as StoreAppleTokenResult, t as SupabaseQueryError, u as SyncFeatureRegistryOptions, T as TenantFeatureChange, v as TenantFeatureSetting, w as TenantFeatures, x as TenantFeaturesClient, y as createAuthFormClient, z as createGenesisSupabase, B as deleteMyAccount, H as featureGateState, I as fetchAuthSettings, J as must, K as requestAppleRevocation, L as setTenantFeature, M as storeAppleToken, N as syncFeatureRegistry, O as tenantFeatureHistory, Q as tenantFeatureSettings, R as tenantFeatures } from './index-UjHqJN2X.js';
2
+ export { A as APPLE_REVOKE_FUNCTION, c as AuthCallError, d as AuthCallResult, e as AuthFormSupabase, f as AuthFormSupabaseClient, g as AuthSettings, C as CreateAuthFormClientOptions, D as DeleteAccountClient, j as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, k as FeatureGateStateOptions, l as FeatureRegistryClient, m as FeatureRegistryDocument, n as FlagStateValue, o as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, p as SUPABASE_OAUTH_PROVIDERS, S as SessionStorage, q as SetTenantFeatureInput, r as StoreAppleTokenOptions, s as StoreAppleTokenResult, t as SupabaseQueryError, u as SyncFeatureRegistryOptions, T as TenantFeatureChange, v as TenantFeatureSetting, w as TenantFeatures, x as TenantFeaturesClient, y as createAuthFormClient, z as createGenesisSupabase, B as deleteMyAccount, H as featureGateState, I as fetchAuthSettings, J as must, K as requestAppleRevocation, L as setTenantFeature, M as storeAppleToken, N as syncFeatureRegistry, O as tenantFeatureHistory, Q as tenantFeatureSettings, R as tenantFeatures } from './index-CKloeGaz.js';
3
3
  export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './blocks.js';
4
4
  import '@marktiderman/genesis-features/blocks';
package/dist/index.js CHANGED
@@ -123,20 +123,21 @@ async function call(run) {
123
123
  }
124
124
  }
125
125
  function createAuthFormClient(supabase, options = {}) {
126
- const { url, publishableKey, redirectTo, resetRedirectTo = redirectTo } = options;
126
+ const { url, publishableKey, redirectTo, emailRedirectTo = redirectTo, resetRedirectTo = emailRedirectTo, providerRedirectTo, providerQueryParams } = options;
127
127
  const auth = supabase.auth;
128
128
  const otp = (email, createUser) => call(
129
- () => auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...redirectTo ? { emailRedirectTo: redirectTo } : {} } })
129
+ () => auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...emailRedirectTo ? { emailRedirectTo } : {} } })
130
130
  );
131
131
  const client = {
132
132
  signInWithPassword: ({ email, password }) => call(() => auth.signInWithPassword({ email, password })),
133
133
  sendMagicLink: ({ email, createUser }) => otp(email, createUser),
134
134
  sendEmailCode: ({ email, createUser }) => otp(email, createUser),
135
135
  verifyEmailCode: ({ email, code }) => call(() => auth.verifyOtp({ email, token: code, type: "email" })),
136
- signUp: async ({ email, password }) => {
136
+ signUp: async ({ email, password, data }) => {
137
137
  let confirmEmail = false;
138
+ const signUpOptions = { ...emailRedirectTo ? { emailRedirectTo } : {}, ...data ? { data } : {} };
138
139
  const result = await call(async () => {
139
- const r = await auth.signUp({ email, password, ...redirectTo ? { options: { emailRedirectTo: redirectTo } } : {} });
140
+ const r = await auth.signUp({ email, password, ...Object.keys(signUpOptions).length ? { options: signUpOptions } : {} });
140
141
  confirmEmail = !r.error && !r.data.session;
141
142
  return r;
142
143
  });
@@ -144,13 +145,30 @@ function createAuthFormClient(supabase, options = {}) {
144
145
  },
145
146
  sendPasswordReset: ({ email }) => call(() => auth.resetPasswordForEmail(email, resetRedirectTo ? { redirectTo: resetRedirectTo } : void 0)),
146
147
  updatePassword: ({ password }) => call(() => auth.updateUser({ password })),
147
- signInWithProvider: (provider) => call(
148
- () => auth.signInWithOAuth({
149
- provider,
150
- ...redirectTo ? { options: { redirectTo } } : {}
151
- })
152
- )
148
+ signInWithProvider: (provider) => {
149
+ const back = (typeof providerRedirectTo === "function" ? providerRedirectTo(provider) : providerRedirectTo) ?? redirectTo;
150
+ const queryParams = typeof providerQueryParams === "function" ? providerQueryParams(provider) : providerQueryParams;
151
+ const oauthOptions = { ...back ? { redirectTo: back } : {}, ...queryParams && Object.keys(queryParams).length ? { queryParams } : {} };
152
+ return call(
153
+ () => auth.signInWithOAuth({
154
+ provider,
155
+ ...Object.keys(oauthOptions).length ? { options: oauthOptions } : {}
156
+ })
157
+ );
158
+ },
159
+ sendPhoneCode: ({ phone, createUser }) => call(() => auth.signInWithOtp({ phone, options: { shouldCreateUser: createUser } })),
160
+ verifyPhoneCode: ({ phone, code }) => call(() => auth.verifyOtp({ phone, token: code, type: "sms" }))
153
161
  };
162
+ const getSession = auth.getSession?.bind(auth);
163
+ if (getSession) {
164
+ client.currentEmail = async () => {
165
+ try {
166
+ return (await getSession()).data.session?.user.email ?? null;
167
+ } catch {
168
+ return null;
169
+ }
170
+ };
171
+ }
154
172
  if (url && publishableKey) {
155
173
  let providers;
156
174
  client.providers = () => {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/feature-registry.ts","../src/auth-form-client.ts","../src/index.ts"],"names":[],"mappings":";;;;;AASO,IAAM,qBAAA,GAAwB;AAGrC,IAAM,gBAAA,GAAmB,GAAA;AAEzB,IAAM,iBAAA,GAAoB,GAAA;AAiC1B,eAAsB,gBAAgB,MAAA,EAAyB,EAAE,mBAAmB,QAAA,EAAU,YAAA,GAAe,uBAAsB,EAA2D;AAC5L,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,UAAU,MAAA,CAAO,YAAA,EAAc,EAAE,IAAA,EAAM,EAAE,MAAA,EAAQ,SAAS,IAAA,EAAM,iBAAA,EAAmB,GAAI,QAAA,GAAW,EAAE,QAAA,EAAS,GAAI,EAAC,EAAG,EAAG,OAAA,EAAS,gBAAA,EAAkB,CAAA;AAClL,IAAA,IAAI,OAAO,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,MAAM,MAAA,CAAQ,KAAA,CAAgC,OAAA,IAAW,KAAK,CAAC,CAAA,EAAE;AAC5I,IAAA,OAAO,EAAE,IAAI,IAAA,EAAK;AAAA,EACpB,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAA,EAAE;AAAA,EACvF;AACF;AAQA,eAAsB,sBAAA,CAAuB,MAAA,EAAyB,YAAA,GAAe,qBAAA,EAAyC;AAC5H,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAA,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,EACpB;AACF;AASO,SAAS,KAAQ,MAAA,EAAiF;AACvG,EAAA,IAAI,OAAO,KAAA,EAAO,MAAM,IAAI,kBAAA,CAAmB,OAAO,KAAK,CAAA;AAC3D,EAAA,OAAO,MAAA,CAAO,IAAA;AAChB;AAwCA,eAAsB,eAAA,CAAgB,MAAA,EAA6B,OAAA,GAAkC,EAAC,EAAkB;AACtH,EAAA,IAAA,CAAM,MAAM,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAgF,CAAA;AAC1H,EAAA,MAAM,SAAS,OAAA,CAAQ,iBAAA;AAEvB,EAAA,IAAI,MAAA,IAAU,MAAA,CAAO,SAAA,EAAW,MAAM,uBAAuB,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,EAAG,OAAO,MAAA,KAAW,QAAA,GAAW,SAAS,qBAAqB,CAAA;AAEzJ,EAAA,MAAM,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAE,KAAA,EAAO,SAAS,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\n * The app's side of Sign in with Apple token revocation: hand the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * The feature registry in the database: the client half of\n * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code\n * registry on deploy; anyone building the gate's snapshot reads a tenant's\n * runtime state in one call.\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FeatureRegistryClient {\n // Loose on purpose, as in tenant-features: an app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (\n fn: any,\n ...rest: any[]\n ) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult =\n { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */\nexport type FlagStateValue = boolean | string | number | { readonly [key: string]: unknown };\n\n/**\n * A tenant's runtime state for the gate, shaped to spread into a\n * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.\n *\n * @stability Beta\n */\nexport interface FeatureGateState {\n /** Feature ids the tenant switched off. */\n off: string[];\n /** Feature ids with an active entitlement: the tenant's, plus the person's own (0017). */\n entitlements: string[];\n /** Flag values for the tenant (platform values applied), by flag name. */\n flags: Record<string, FlagStateValue>;\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : [];\n\n/** @stability Beta */\nexport interface FeatureGateStateOptions {\n /**\n * With the service key only: add this person's own entitlements (the app's person id, not a\n * login), for a snapshot built on the server. A signed-in person's client gets their own\n * without it, and is refused (`42501`) with it.\n */\n personId?: string;\n}\n\n/**\n * A tenant's switches, entitlements and flag values: `feature_gate_state`.\n * Works with a signed-in person's client (for tenants they belong to; their own\n * person entitlements are included) or the service key. Throws a\n * `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken\n * for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(\n client: FeatureRegistryClient,\n tenantId: string,\n options: FeatureGateStateOptions = {},\n): Promise<FeatureGateState> {\n const args = options.personId === undefined ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };\n const data = must((await client.rpc(\"feature_gate_state\", args)) as RpcResult);\n // Anything but the expected shape is an error, never \"nothing set\": an empty answer would turn\n // switched-off features back on.\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new TypeError(\"feature_gate_state returned no state\");\n const { off, entitled, flags } = data as Record<string, unknown>;\n if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== \"object\" || Array.isArray(flags)) {\n throw new TypeError(\"feature_gate_state returned an unexpected shape\");\n }\n const values: Record<string, FlagStateValue> = {};\n for (const [key, value] of Object.entries(flags as Record<string, unknown>)) {\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"number\") values[key] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) values[key] = value as { [key: string]: unknown };\n }\n return { off: strings(off), entitlements: strings(entitled), flags: values };\n}\n\n/** `features.json` as `genesis features build` writes it. @stability Beta */\nexport interface FeatureRegistryDocument {\n features: readonly ({ id: string } & Record<string, unknown>)[];\n flags?: Readonly<Record<string, Record<string, unknown>>>;\n}\n\n/** @stability Beta */\nexport interface SyncFeatureRegistryOptions {\n /**\n * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Web sign-in on Supabase Auth, for genesis-ui's `AuthForm`: the calls each\n * of its modes makes (password, magic link, emailed code, sign-up, reset, new\n * password, providers) and the provider list read from the project's\n * `/auth/v1/settings`. Platform-neutral; native sign-in is on `/native`.\n */\nimport { isAuthError, type SupabaseClient } from \"@supabase/supabase-js\";\n\n/** The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits. */\nexport interface AuthFormSupabase {\n auth: Pick<\n SupabaseClient[\"auth\"],\n \"signInWithPassword\" | \"signInWithOtp\" | \"verifyOtp\" | \"signUp\" | \"resetPasswordForEmail\" | \"updateUser\" | \"signInWithOAuth\"\n >;\n}\n\n/**\n * Why a call failed: Supabase Auth's error `code` (`invalid_credentials`,\n * `otp_expired`, `over_email_send_rate_limit`…), `session_not_found` when\n * there is no session (`AuthSessionMissingError`), or `network` when the\n * request never got an answer. The shape genesis-ui's `AuthFormError` reads.\n * `message` is the server's text: the form never shows it (it is not marked\n * `displayable`), only reports it for a code it has no copy for.\n */\nexport interface AuthCallError {\n code?: string;\n message?: string;\n}\n\n/** What each call resolves with. Never throws. */\nexport interface AuthCallResult {\n error?: AuthCallError | null;\n /** From `signUp`: the account waits for its email to be confirmed. */\n confirmEmail?: boolean;\n}\n\n/**\n * The calls genesis-ui's `AuthForm` makes (its `AuthFormClient`), on Supabase Auth.\n *\n * @stability Beta\n */\nexport interface AuthFormSupabaseClient {\n signInWithPassword(input: { email: string; password: string }): Promise<AuthCallResult>;\n sendMagicLink(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n sendEmailCode(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n verifyEmailCode(input: { email: string; code: string }): Promise<AuthCallResult>;\n signUp(input: { email: string; password: string }): Promise<AuthCallResult>;\n sendPasswordReset(input: { email: string }): Promise<AuthCallResult>;\n updatePassword(input: { password: string }): Promise<AuthCallResult>;\n signInWithProvider(provider: string): Promise<AuthCallResult>;\n /** Present when `url` and `publishableKey` were given. */\n providers?(): Promise<string[]>;\n}\n\n/** @stability Beta */\nexport interface CreateAuthFormClientOptions {\n /** The project URL, with `publishableKey`: lets the form discover its providers. */\n url?: string;\n /** The publishable (anon) key. */\n publishableKey?: string;\n /**\n * Where a magic link, a sign-up confirmation and a provider come back to:\n * the app's callback route (`${origin}/auth/callback`). It must be in the\n * project's redirect allow list. Left out: the project's Site URL.\n */\n redirectTo?: string;\n /** Where the password-reset link opens: the page that shows `mode=\"new-password\"`. Default `redirectTo`. */\n resetRedirectTo?: string;\n /** For the settings request. Default the global `fetch`. */\n fetch?: typeof fetch;\n}\n\ntype SupabaseAuthResult = { data?: unknown; error: { code?: string | undefined; message: string; name?: string; status?: number | undefined } | null };\n\ntype SupabaseAuthError = NonNullable<SupabaseAuthResult[\"error\"]>;\n\nfunction toResult(e: SupabaseAuthError | null): AuthCallResult {\n if (!e) return {};\n // supabase-js answers a request that never reached Auth with AuthRetryableFetchError, status 0.\n const network = e.name === \"AuthRetryableFetchError\" || e.status === 0;\n // updateUser with no session: AuthSessionMissingError, which has no code.\n const missingSession = e.name === \"AuthSessionMissingError\";\n const code = e.code ?? (missingSession ? \"session_not_found\" : network ? \"network\" : undefined);\n return { error: { ...(code ? { code } : {}), message: e.message } };\n}\n\nasync function call(run: () => Promise<SupabaseAuthResult>): Promise<AuthCallResult> {\n try {\n return toResult((await run()).error);\n } catch (e) {\n // A client made with `throwOnError: true` throws Auth's errors: read them like a returned one.\n if (isAuthError(e)) return toResult(e as SupabaseAuthError);\n return { error: { code: \"network\", message: e instanceof Error ? e.message : \"The request failed\" } };\n }\n}\n\n/**\n * genesis-ui's `AuthForm` client on Supabase Auth: password sign-in, magic\n * link and emailed code (`signInWithOtp`, the code checked with `verifyOtp`),\n * sign-up (`confirmEmail` when the project confirms emails), the reset email,\n * the new password (`updateUser`, on the session the reset link opened), and\n * OAuth providers (`signInWithOAuth`, which leaves the page). Every failure is\n * `{ error: { code, message } }`, never a throw, also on a client made with\n * `throwOnError: true`.\n *\n * It takes the app's client (from `createGenesisSupabase()`) and makes no\n * client of its own.\n *\n * Without sign-up (`createUser: false`), an email with no account is answered\n * like one with an account: the link or code is \"sent\". Saying otherwise would\n * tell anyone which emails have accounts.\n *\n * The new-password page: show `mode=\"new-password\"` only after the client's\n * `PASSWORD_RECOVERY` event (`supabase.auth.onAuthStateChange`). Without the\n * session the reset link opened, `updatePassword` fails with\n * `session_not_found`.\n *\n * One email template serves the link and the code: Supabase sends the Magic\n * Link template for both, so a form offering `\"email-code\"` needs\n * `{{ .Token }}` in it (the default template has only the link).\n *\n * ```ts\n * const client = createAuthFormClient(supabase, {\n * url: import.meta.env.VITE_SUPABASE_URL,\n * publishableKey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,\n * redirectTo: `${location.origin}/auth/callback`,\n * resetRedirectTo: `${location.origin}/auth/new-password`,\n * });\n * ```\n *\n * @stability Beta\n */\nexport function createAuthFormClient(supabase: AuthFormSupabase, options: CreateAuthFormClientOptions = {}): AuthFormSupabaseClient {\n const { url, publishableKey, redirectTo, resetRedirectTo = redirectTo } = options;\n const auth = supabase.auth;\n // Without sign-up, Auth refuses an unknown email with otp_disabled (\"Signups not allowed for otp\").\n // The client passes it on as it is; AuthForm answers it as sent, so it doesn't say which emails\n // have accounts (one place, for every client).\n const otp = (email: string, createUser: boolean): Promise<AuthCallResult> =>\n call(() =>\n auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...(redirectTo ? { emailRedirectTo: redirectTo } : {}) } }),\n );\n const client: AuthFormSupabaseClient = {\n signInWithPassword: ({ email, password }) => call(() => auth.signInWithPassword({ email, password })),\n sendMagicLink: ({ email, createUser }) => otp(email, createUser),\n sendEmailCode: ({ email, createUser }) => otp(email, createUser),\n verifyEmailCode: ({ email, code }) => call(() => auth.verifyOtp({ email, token: code, type: \"email\" })),\n signUp: async ({ email, password }) => {\n let confirmEmail = false;\n const result = await call(async () => {\n const r = await auth.signUp({ email, password, ...(redirectTo ? { options: { emailRedirectTo: redirectTo } } : {}) });\n confirmEmail = !r.error && !r.data.session;\n return r;\n });\n return confirmEmail ? { ...result, confirmEmail } : result;\n },\n sendPasswordReset: ({ email }) =>\n call(() => auth.resetPasswordForEmail(email, resetRedirectTo ? { redirectTo: resetRedirectTo } : undefined)),\n updatePassword: ({ password }) => call(() => auth.updateUser({ password })),\n signInWithProvider: (provider) =>\n call(() =>\n auth.signInWithOAuth({\n provider: provider as Parameters<typeof auth.signInWithOAuth>[0][\"provider\"],\n ...(redirectTo ? { options: { redirectTo } } : {}),\n }),\n ),\n };\n if (url && publishableKey) {\n // Asked once per client: the form may mount many times, the project's providers don't change.\n let providers: Promise<string[]> | undefined;\n client.providers = () => {\n providers ??= fetchAuthSettings({ url, publishableKey, ...(options.fetch ? { fetch: options.fetch } : {}) }).then(\n (settings) => settings.providers,\n (e: unknown) => {\n providers = undefined; // a failed lookup can be tried again\n throw e;\n },\n );\n return providers;\n };\n }\n return client;\n}\n\n/** What a project's Auth allows, from `/auth/v1/settings`. */\nexport interface AuthSettings {\n /** The OAuth providers turned on, as `signInWithOAuth` names them (`\"google\"`, `\"apple\"`…), sorted. */\n providers: string[];\n /** Email sign-in (password, link or code) is on. */\n email: boolean;\n /** Phone sign-in is on. */\n phone: boolean;\n /** New accounts are refused. */\n signUpDisabled: boolean;\n /** Emails are confirmed without a link. */\n autoConfirm: boolean;\n}\n\n/**\n * The OAuth providers `fetchAuthSettings` reports: the ones `signInWithOAuth`\n * takes and genesis-ui's `AUTH_PROVIDER_NAMES` names. Any other key of the\n * settings' `external` (`email`, `phone`, `saml`, `web3_*`…) isn't a button.\n *\n * @stability Beta\n */\nexport const SUPABASE_OAUTH_PROVIDERS: readonly string[] = [\n \"apple\",\n \"azure\",\n \"bitbucket\",\n \"discord\",\n \"facebook\",\n \"figma\",\n \"github\",\n \"gitlab\",\n \"google\",\n \"kakao\",\n \"keycloak\",\n \"linkedin_oidc\",\n \"notion\",\n \"slack_oidc\",\n \"spotify\",\n \"twitch\",\n \"twitter\",\n \"workos\",\n \"zoom\",\n];\nconst OAUTH_PROVIDERS = new Set(SUPABASE_OAUTH_PROVIDERS);\n\n/** How long the settings request may take. */\nconst SETTINGS_TIMEOUT_MS = 5000;\n\nfunction withoutTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === \"/\") end--;\n return url.slice(0, end);\n}\n\n/**\n * Reads a project's public Auth settings (`GET <url>/auth/v1/settings` with\n * the publishable key): which OAuth providers are on, whether email and phone\n * sign-in are, and whether sign-up is closed. Throws when the request fails,\n * takes over 5 seconds or `signal` aborts it, and refuses a secret key\n * (`sb_secret_…`), which must never reach a browser.\n *\n * @stability Beta\n */\nexport async function fetchAuthSettings({\n url,\n publishableKey,\n fetch: fetcher = globalThis.fetch,\n signal,\n}: {\n url: string;\n publishableKey: string;\n fetch?: typeof fetch;\n /** Cancels the request (an unmounting form, say). */\n signal?: AbortSignal;\n}): Promise<AuthSettings> {\n if (publishableKey.startsWith(\"sb_secret_\")) {\n throw new Error(\"fetchAuthSettings takes the publishable key, not a secret key (sb_secret_…)\");\n }\n // A controller and a timer rather than AbortSignal.timeout/any, which older Safari and React\n // Native's Hermes lack.\n const controller = new AbortController();\n const timer = setTimeout(() => {\n const timedOut = new Error(\"Supabase Auth settings: timed out\");\n timedOut.name = \"TimeoutError\";\n controller.abort(timedOut);\n }, SETTINGS_TIMEOUT_MS);\n const onAbort = () => controller.abort(signal?.reason);\n if (signal?.aborted) onAbort();\n else signal?.addEventListener(\"abort\", onAbort, { once: true });\n let response: Response;\n try {\n response = await fetcher(`${withoutTrailingSlashes(url)}/auth/v1/settings`, {\n headers: { apikey: publishableKey },\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n if (!response.ok) throw new Error(`Supabase Auth settings: ${response.status}`);\n const body = (await response.json()) as {\n external?: Record<string, unknown>;\n disable_signup?: unknown;\n mailer_autoconfirm?: unknown;\n };\n const external = body.external ?? {};\n return {\n providers: Object.keys(external)\n .filter((key) => external[key] === true && OAUTH_PROVIDERS.has(key))\n .sort(),\n email: external.email === true,\n phone: external.phone === true,\n signUpDisabled: body.disable_signup === true,\n autoConfirm: body.mailer_autoconfirm === true,\n };\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FeatureGateStateOptions,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from \"./blocks\";\nexport {\n createAuthFormClient,\n fetchAuthSettings,\n SUPABASE_OAUTH_PROVIDERS,\n type AuthCallError,\n type AuthCallResult,\n type AuthFormSupabase,\n type AuthFormSupabaseClient,\n type AuthSettings,\n type CreateAuthFormClientOptions,\n} from \"./auth-form-client\";\n"]}
1
+ {"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/feature-registry.ts","../src/auth-form-client.ts","../src/index.ts"],"names":[],"mappings":";;;;;AASO,IAAM,qBAAA,GAAwB;AAGrC,IAAM,gBAAA,GAAmB,GAAA;AAEzB,IAAM,iBAAA,GAAoB,GAAA;AAiC1B,eAAsB,gBAAgB,MAAA,EAAyB,EAAE,mBAAmB,QAAA,EAAU,YAAA,GAAe,uBAAsB,EAA2D;AAC5L,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,UAAU,MAAA,CAAO,YAAA,EAAc,EAAE,IAAA,EAAM,EAAE,MAAA,EAAQ,SAAS,IAAA,EAAM,iBAAA,EAAmB,GAAI,QAAA,GAAW,EAAE,QAAA,EAAS,GAAI,EAAC,EAAG,EAAG,OAAA,EAAS,gBAAA,EAAkB,CAAA;AAClL,IAAA,IAAI,OAAO,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,MAAM,MAAA,CAAQ,KAAA,CAAgC,OAAA,IAAW,KAAK,CAAC,CAAA,EAAE;AAC5I,IAAA,OAAO,EAAE,IAAI,IAAA,EAAK;AAAA,EACpB,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAA,EAAE;AAAA,EACvF;AACF;AAQA,eAAsB,sBAAA,CAAuB,MAAA,EAAyB,YAAA,GAAe,qBAAA,EAAy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,CAAA;AACrC,IAAA,IAAA,CAAK,OAAO,KAAA,CAAM,IAAA;AAClB,IAAA,IAAA,CAAK,UAAU,KAAA,CAAM,OAAA;AACrB,IAAA,IAAA,CAAK,OAAO,KAAA,CAAM,IAAA;AAAA,EACpB;AACF;AASO,SAAS,KAAQ,MAAA,EAAiF;AACvG,EAAA,IAAI,OAAO,KAAA,EAAO,MAAM,IAAI,kBAAA,CAAmB,OAAO,KAAK,CAAA;AAC3D,EAAA,OAAO,MAAA,CAAO,IAAA;AAChB;AAwCA,eAAsB,eAAA,CAAgB,MAAA,EAA6B,OAAA,GAAkC,EAAC,EAAkB;AACtH,EAAA,IAAA,CAAM,MAAM,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAgF,CAAA;AAC1H,EAAA,MAAM,SAAS,OAAA,CAAQ,iBAAA;AAEvB,EAAA,IAAI,MAAA,IAAU,MAAA,CAAO,SAAA,EAAW,MAAM,uBAAuB,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,EAAG,OAAO,MAAA,KAAW,QAAA,GAAW,SAAS,qBAAqB,CAAA;AAEzJ,EAAA,MAAM,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAE,KAAA,EAAO,SAAS,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\n * The app's side of Sign in with Apple token revocation: hand the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * The feature registry in the database: the client half of\n * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code\n * registry on deploy; anyone building the gate's snapshot reads a tenant's\n * runtime state in one call.\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FeatureRegistryClient {\n // Loose on purpose, as in tenant-features: an app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (\n fn: any,\n ...rest: any[]\n ) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult =\n { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */\nexport type FlagStateValue = boolean | string | number | { readonly [key: string]: unknown };\n\n/**\n * A tenant's runtime state for the gate, shaped to spread into a\n * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.\n *\n * @stability Beta\n */\nexport interface FeatureGateState {\n /** Feature ids the tenant switched off. */\n off: string[];\n /** Feature ids with an active entitlement: the tenant's, plus the person's own (0017). */\n entitlements: string[];\n /** Flag values for the tenant (platform values applied), by flag name. */\n flags: Record<string, FlagStateValue>;\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : [];\n\n/** @stability Beta */\nexport interface FeatureGateStateOptions {\n /**\n * With the service key only: add this person's own entitlements (the app's person id, not a\n * login), for a snapshot built on the server. A signed-in person's client gets their own\n * without it, and is refused (`42501`) with it.\n */\n personId?: string;\n}\n\n/**\n * A tenant's switches, entitlements and flag values: `feature_gate_state`.\n * Works with a signed-in person's client (for tenants they belong to; their own\n * person entitlements are included) or the service key. Throws a\n * `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken\n * for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(\n client: FeatureRegistryClient,\n tenantId: string,\n options: FeatureGateStateOptions = {},\n): Promise<FeatureGateState> {\n const args = options.personId === undefined ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };\n const data = must((await client.rpc(\"feature_gate_state\", args)) as RpcResult);\n // Anything but the expected shape is an error, never \"nothing set\": an empty answer would turn\n // switched-off features back on.\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new TypeError(\"feature_gate_state returned no state\");\n const { off, entitled, flags } = data as Record<string, unknown>;\n if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== \"object\" || Array.isArray(flags)) {\n throw new TypeError(\"feature_gate_state returned an unexpected shape\");\n }\n const values: Record<string, FlagStateValue> = {};\n for (const [key, value] of Object.entries(flags as Record<string, unknown>)) {\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"number\") values[key] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) values[key] = value as { [key: string]: unknown };\n }\n return { off: strings(off), entitlements: strings(entitled), flags: values };\n}\n\n/** `features.json` as `genesis features build` writes it. @stability Beta */\nexport interface FeatureRegistryDocument {\n features: readonly ({ id: string } & Record<string, unknown>)[];\n flags?: Readonly<Record<string, Record<string, unknown>>>;\n}\n\n/** @stability Beta */\nexport interface SyncFeatureRegistryOptions {\n /**\n * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Web sign-in on Supabase Auth, for genesis-ui's `AuthForm`: the calls each\n * of its modes makes (password, magic link, emailed code, sign-up, reset, new\n * password, providers, a texted code) and the provider list read from the project's\n * `/auth/v1/settings`. Platform-neutral; native sign-in is on `/native`.\n */\nimport { isAuthError, type SupabaseClient } from \"@supabase/supabase-js\";\n\n/**\n * The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits.\n * `getSession`, when there, gives the new-password form the signed-in email (`currentEmail`).\n */\nexport interface AuthFormSupabase {\n auth: Pick<\n SupabaseClient[\"auth\"],\n \"signInWithPassword\" | \"signInWithOtp\" | \"verifyOtp\" | \"signUp\" | \"resetPasswordForEmail\" | \"updateUser\" | \"signInWithOAuth\"\n > &\n Partial<Pick<SupabaseClient[\"auth\"], \"getSession\">>;\n}\n\n/**\n * Why a call failed: Supabase Auth's error `code` (`invalid_credentials`,\n * `otp_expired`, `over_email_send_rate_limit`…), `session_not_found` when\n * there is no session (`AuthSessionMissingError`), or `network` when the\n * request never got an answer. The shape genesis-ui's `AuthFormError` reads.\n * `message` is the server's text: the form never shows it (it is not marked\n * `displayable`), only reports it for a code it has no copy for.\n */\nexport interface AuthCallError {\n code?: string;\n message?: string;\n}\n\n/** What each call resolves with. Never throws. */\nexport interface AuthCallResult {\n error?: AuthCallError | null;\n /** From `signUp`: the account waits for its email to be confirmed. */\n confirmEmail?: boolean;\n}\n\n/**\n * The calls genesis-ui's `AuthForm` makes (its `AuthFormClient`), on Supabase Auth.\n *\n * @stability Beta\n */\nexport interface AuthFormSupabaseClient {\n signInWithPassword(input: { email: string; password: string }): Promise<AuthCallResult>;\n sendMagicLink(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n sendEmailCode(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n verifyEmailCode(input: { email: string; code: string }): Promise<AuthCallResult>;\n /** `data`: the new user's metadata (`options.data`, `raw_user_meta_data`), such as `full_name`. */\n signUp(input: { email: string; password: string; data?: Record<string, unknown> }): Promise<AuthCallResult>;\n sendPasswordReset(input: { email: string }): Promise<AuthCallResult>;\n updatePassword(input: { password: string }): Promise<AuthCallResult>;\n signInWithProvider(provider: string): Promise<AuthCallResult>;\n /** A code by text message (`signInWithOtp({ phone })`). Needs a phone provider in the project's Auth settings. */\n sendPhoneCode(input: { phone: string; createUser: boolean }): Promise<AuthCallResult>;\n /** Checks a texted code (`verifyOtp({ phone, token, type: \"sms\" })`). */\n verifyPhoneCode(input: { phone: string; code: string }): Promise<AuthCallResult>;\n /** The signed-in user's email, from the session the client holds (no request); null without one. Present when the Supabase client has `getSession`. */\n currentEmail?(): Promise<string | null>;\n /** Present when `url` and `publishableKey` were given. */\n providers?(): Promise<string[]>;\n}\n\n/** @stability Beta */\nexport interface CreateAuthFormClientOptions {\n /** The project URL, with `publishableKey`: lets the form discover its providers. */\n url?: string;\n /** The publishable (anon) key. */\n publishableKey?: string;\n /**\n * Where a magic link, a sign-up confirmation and a provider come back to:\n * the app's callback route (`${origin}/auth/callback`). It must be in the\n * project's redirect allow list. Left out: the project's Site URL.\n */\n redirectTo?: string;\n /** Where the emailed links come back to (a magic link, the sign-up confirmation): overrides `redirectTo` for them. Default `redirectTo`. */\n emailRedirectTo?: string;\n /** Where the password-reset link opens: the page that shows `mode=\"new-password\"`. Default `emailRedirectTo`, then `redirectTo`. */\n resetRedirectTo?: string;\n /**\n * Where a provider sends the person back to, for every provider or per provider (a function of\n * its id, `undefined` for the default): overrides `redirectTo` for providers. It must be in the\n * project's redirect allow list. Default `redirectTo`.\n */\n providerRedirectTo?: string | ((provider: string) => string | undefined);\n /**\n * Extra query parameters for the provider's authorize URL (`signInWithOAuth`'s\n * `options.queryParams`): Google's `{ access_type: \"offline\", prompt: \"consent\" }`, say. One\n * record for every provider, or a function of the provider's id. Default none.\n */\n providerQueryParams?: Record<string, string> | ((provider: string) => Record<string, string> | undefined);\n /** For the settings request. Default the global `fetch`. */\n fetch?: typeof fetch;\n}\n\ntype SupabaseAuthResult = { data?: unknown; error: { code?: string | undefined; message: string; name?: string; status?: number | undefined } | null };\n\ntype SupabaseAuthError = NonNullable<SupabaseAuthResult[\"error\"]>;\n\nfunction toResult(e: SupabaseAuthError | null): AuthCallResult {\n if (!e) return {};\n // supabase-js answers a request that never reached Auth with AuthRetryableFetchError, status 0.\n const network = e.name === \"AuthRetryableFetchError\" || e.status === 0;\n // updateUser with no session: AuthSessionMissingError, which has no code.\n const missingSession = e.name === \"AuthSessionMissingError\";\n const code = e.code ?? (missingSession ? \"session_not_found\" : network ? \"network\" : undefined);\n return { error: { ...(code ? { code } : {}), message: e.message } };\n}\n\nasync function call(run: () => Promise<SupabaseAuthResult>): Promise<AuthCallResult> {\n try {\n return toResult((await run()).error);\n } catch (e) {\n // A client made with `throwOnError: true` throws Auth's errors: read them like a returned one.\n if (isAuthError(e)) return toResult(e as SupabaseAuthError);\n return { error: { code: \"network\", message: e instanceof Error ? e.message : \"The request failed\" } };\n }\n}\n\n/**\n * genesis-ui's `AuthForm` client on Supabase Auth: password sign-in, magic\n * link and emailed code (`signInWithOtp`, the code checked with `verifyOtp`),\n * sign-up (`confirmEmail` when the project confirms emails), the reset email,\n * the new password (`updateUser`, on the session the reset link opened), and\n * OAuth providers (`signInWithOAuth`, which leaves the page; `providerRedirectTo` and\n * `providerQueryParams` shape where it goes), and a code by text message\n * (`signInWithOtp({ phone })`, checked with `verifyOtp` type `\"sms\"`). Every failure is\n * `{ error: { code, message } }`, never a throw, also on a client made with\n * `throwOnError: true`.\n *\n * It takes the app's client (from `createGenesisSupabase()`) and makes no\n * client of its own.\n *\n * Without sign-up (`createUser: false`), an email with no account is answered\n * like one with an account: the link or code is \"sent\". Saying otherwise would\n * tell anyone which emails have accounts.\n *\n * The new-password page: show `mode=\"new-password\"` only after the client's\n * `PASSWORD_RECOVERY` event (`supabase.auth.onAuthStateChange`). Without the\n * session the reset link opened, `updatePassword` fails with\n * `session_not_found`.\n *\n * One email template serves the link and the code: Supabase sends the Magic\n * Link template for both, so a form offering `\"email-code\"` needs\n * `{{ .Token }}` in it (the default template has only the link). The form's\n * `codeLength` must match the project's `otp_length`, which\n * `/auth/v1/settings` doesn't report: with a mismatch no code can be entered\n * whole, and code sign-in fails.\n *\n * ```ts\n * const client = createAuthFormClient(supabase, {\n * url: import.meta.env.VITE_SUPABASE_URL,\n * publishableKey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,\n * redirectTo: `${location.origin}/auth/callback`,\n * resetRedirectTo: `${location.origin}/auth/new-password`,\n * });\n * ```\n *\n * @stability Beta\n */\nexport function createAuthFormClient(supabase: AuthFormSupabase, options: CreateAuthFormClientOptions = {}): AuthFormSupabaseClient {\n const { url, publishableKey, redirectTo, emailRedirectTo = redirectTo, resetRedirectTo = emailRedirectTo, providerRedirectTo, providerQueryParams } = options;\n const auth = supabase.auth;\n // Without sign-up, Auth refuses an unknown email with otp_disabled (\"Signups not allowed for otp\").\n // The client passes it on as it is; AuthForm answers it as sent, so it doesn't say which emails\n // have accounts (one place, for every client).\n const otp = (email: string, createUser: boolean): Promise<AuthCallResult> =>\n call(() =>\n auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...(emailRedirectTo ? { emailRedirectTo } : {}) } }),\n );\n const client: AuthFormSupabaseClient = {\n signInWithPassword: ({ email, password }) => call(() => auth.signInWithPassword({ email, password })),\n sendMagicLink: ({ email, createUser }) => otp(email, createUser),\n sendEmailCode: ({ email, createUser }) => otp(email, createUser),\n verifyEmailCode: ({ email, code }) => call(() => auth.verifyOtp({ email, token: code, type: \"email\" })),\n signUp: async ({ email, password, data }) => {\n let confirmEmail = false;\n const signUpOptions = { ...(emailRedirectTo ? { emailRedirectTo } : {}), ...(data ? { data } : {}) };\n const result = await call(async () => {\n const r = await auth.signUp({ email, password, ...(Object.keys(signUpOptions).length ? { options: signUpOptions } : {}) });\n confirmEmail = !r.error && !r.data.session;\n return r;\n });\n return confirmEmail ? { ...result, confirmEmail } : result;\n },\n sendPasswordReset: ({ email }) =>\n call(() => auth.resetPasswordForEmail(email, resetRedirectTo ? { redirectTo: resetRedirectTo } : undefined)),\n updatePassword: ({ password }) => call(() => auth.updateUser({ password })),\n signInWithProvider: (provider) => {\n const back = (typeof providerRedirectTo === \"function\" ? providerRedirectTo(provider) : providerRedirectTo) ?? redirectTo;\n const queryParams = typeof providerQueryParams === \"function\" ? providerQueryParams(provider) : providerQueryParams;\n const oauthOptions = { ...(back ? { redirectTo: back } : {}), ...(queryParams && Object.keys(queryParams).length ? { queryParams } : {}) };\n return call(() =>\n auth.signInWithOAuth({\n provider: provider as Parameters<typeof auth.signInWithOAuth>[0][\"provider\"],\n ...(Object.keys(oauthOptions).length ? { options: oauthOptions } : {}),\n }),\n );\n },\n sendPhoneCode: ({ phone, createUser }) => call(() => auth.signInWithOtp({ phone, options: { shouldCreateUser: createUser } })),\n verifyPhoneCode: ({ phone, code }) => call(() => auth.verifyOtp({ phone, token: code, type: \"sms\" })),\n };\n const getSession = auth.getSession?.bind(auth);\n if (getSession) {\n client.currentEmail = async () => {\n try {\n return (await getSession()).data.session?.user.email ?? null;\n } catch {\n return null;\n }\n };\n }\n if (url && publishableKey) {\n // Asked once per client: the form may mount many times, the project's providers don't change.\n let providers: Promise<string[]> | undefined;\n client.providers = () => {\n providers ??= fetchAuthSettings({ url, publishableKey, ...(options.fetch ? { fetch: options.fetch } : {}) }).then(\n (settings) => settings.providers,\n (e: unknown) => {\n providers = undefined; // a failed lookup can be tried again\n throw e;\n },\n );\n return providers;\n };\n }\n return client;\n}\n\n/** What a project's Auth allows, from `/auth/v1/settings`. */\nexport interface AuthSettings {\n /** The OAuth providers turned on, as `signInWithOAuth` names them (`\"google\"`, `\"apple\"`…), sorted. */\n providers: string[];\n /** Email sign-in (password, link or code) is on. */\n email: boolean;\n /** Phone sign-in is on. */\n phone: boolean;\n /** New accounts are refused. */\n signUpDisabled: boolean;\n /** Emails are confirmed without a link. */\n autoConfirm: boolean;\n}\n\n/**\n * The OAuth providers `fetchAuthSettings` reports: the ones `signInWithOAuth`\n * takes and genesis-ui's `AUTH_PROVIDER_NAMES` names. Any other key of the\n * settings' `external` (`email`, `phone`, `saml`, `web3_*`…) isn't a button.\n *\n * @stability Beta\n */\nexport const SUPABASE_OAUTH_PROVIDERS: readonly string[] = [\n \"apple\",\n \"azure\",\n \"bitbucket\",\n \"discord\",\n \"facebook\",\n \"figma\",\n \"github\",\n \"gitlab\",\n \"google\",\n \"kakao\",\n \"keycloak\",\n \"linkedin_oidc\",\n \"notion\",\n \"slack_oidc\",\n \"spotify\",\n \"twitch\",\n \"twitter\",\n \"workos\",\n \"zoom\",\n];\nconst OAUTH_PROVIDERS = new Set(SUPABASE_OAUTH_PROVIDERS);\n\n/** How long the settings request may take. */\nconst SETTINGS_TIMEOUT_MS = 5000;\n\nfunction withoutTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === \"/\") end--;\n return url.slice(0, end);\n}\n\n/**\n * Reads a project's public Auth settings (`GET <url>/auth/v1/settings` with\n * the publishable key): which OAuth providers are on, whether email and phone\n * sign-in are, and whether sign-up is closed. Throws when the request fails,\n * takes over 5 seconds or `signal` aborts it, and refuses a secret key\n * (`sb_secret_…`), which must never reach a browser.\n *\n * @stability Beta\n */\nexport async function fetchAuthSettings({\n url,\n publishableKey,\n fetch: fetcher = globalThis.fetch,\n signal,\n}: {\n url: string;\n publishableKey: string;\n fetch?: typeof fetch;\n /** Cancels the request (an unmounting form, say). */\n signal?: AbortSignal;\n}): Promise<AuthSettings> {\n if (publishableKey.startsWith(\"sb_secret_\")) {\n throw new Error(\"fetchAuthSettings takes the publishable key, not a secret key (sb_secret_…)\");\n }\n // A controller and a timer rather than AbortSignal.timeout/any, which older Safari and React\n // Native's Hermes lack.\n const controller = new AbortController();\n const timer = setTimeout(() => {\n const timedOut = new Error(\"Supabase Auth settings: timed out\");\n timedOut.name = \"TimeoutError\";\n controller.abort(timedOut);\n }, SETTINGS_TIMEOUT_MS);\n const onAbort = () => controller.abort(signal?.reason);\n if (signal?.aborted) onAbort();\n else signal?.addEventListener(\"abort\", onAbort, { once: true });\n let response: Response;\n try {\n response = await fetcher(`${withoutTrailingSlashes(url)}/auth/v1/settings`, {\n headers: { apikey: publishableKey },\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n if (!response.ok) throw new Error(`Supabase Auth settings: ${response.status}`);\n const body = (await response.json()) as {\n external?: Record<string, unknown>;\n disable_signup?: unknown;\n mailer_autoconfirm?: unknown;\n };\n const external = body.external ?? {};\n return {\n providers: Object.keys(external)\n .filter((key) => external[key] === true && OAUTH_PROVIDERS.has(key))\n .sort(),\n email: external.email === true,\n phone: external.phone === true,\n signUpDisabled: body.disable_signup === true,\n autoConfirm: body.mailer_autoconfirm === true,\n };\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FeatureGateStateOptions,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from \"./blocks\";\nexport {\n createAuthFormClient,\n fetchAuthSettings,\n SUPABASE_OAUTH_PROVIDERS,\n type AuthCallError,\n type AuthCallResult,\n type AuthFormSupabase,\n type AuthFormSupabaseClient,\n type AuthSettings,\n type CreateAuthFormClientOptions,\n} from \"./auth-form-client\";\n"]}
package/dist/native.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SessionStorage } from './index-UjHqJN2X.js';
2
- export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-UjHqJN2X.js';
1
+ import { S as SessionStorage } from './index-CKloeGaz.js';
2
+ export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-CKloeGaz.js';
3
3
  import { Session, SupabaseClient, User } from '@supabase/supabase-js';
4
4
  import './blocks.js';
5
5
  import '@marktiderman/genesis-features/blocks';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-supabase",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,