better-supabase 0.0.0 → 0.1.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.
Files changed (154) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +88 -1
  3. package/bin/better-supabase.js +3 -0
  4. package/dist/casing-da0uRTqt.js +14 -0
  5. package/dist/cli/bin.d.ts +1 -0
  6. package/dist/cli/bin.js +15 -0
  7. package/dist/cli/index.d.ts +226 -0
  8. package/dist/cli/index.js +3 -0
  9. package/dist/cli-CoByWYja.js +6472 -0
  10. package/dist/client/index.d.ts +2 -0
  11. package/dist/client/index.js +112 -0
  12. package/dist/compiler-DL18ukPe.d.ts +14 -0
  13. package/dist/config/index.d.ts +3 -0
  14. package/dist/config/index.js +3 -0
  15. package/dist/config-D-aR2ZoN.js +276 -0
  16. package/dist/define-CTfWw-SS.d.ts +662 -0
  17. package/dist/define-QGkq04oe.js +1068 -0
  18. package/dist/edge/index.d.ts +43 -0
  19. package/dist/edge/index.js +103 -0
  20. package/dist/entitlements-BBg61DQZ.d.ts +20 -0
  21. package/dist/entitlements-BC_khwRy.js +17 -0
  22. package/dist/env/index.d.ts +2 -0
  23. package/dist/env/index.js +2 -0
  24. package/dist/env-BEToab0I.js +204 -0
  25. package/dist/errors-Bl3rkOzo.js +196 -0
  26. package/dist/events/index.d.ts +2 -0
  27. package/dist/events/index.js +2 -0
  28. package/dist/events-2OJsVG_d.d.ts +84 -0
  29. package/dist/events-BuzTgn2D.js +135 -0
  30. package/dist/executor-Bazhgsgq.d.ts +195 -0
  31. package/dist/executor-Bje4suQF.d.ts +25 -0
  32. package/dist/executor-Ceq60hPM.js +89 -0
  33. package/dist/hono/index.d.ts +45 -0
  34. package/dist/hono/index.js +70 -0
  35. package/dist/index-BD6wKthp.d.ts +597 -0
  36. package/dist/index-DQVvHzjW.d.ts +74 -0
  37. package/dist/index-DRid0qIv.d.ts +76 -0
  38. package/dist/index-Dup-nSe9.d.ts +117 -0
  39. package/dist/index-Dy6kuF0P.d.ts +71 -0
  40. package/dist/index-Hf8PP9sP.d.ts +116 -0
  41. package/dist/index-JXHBuS53.d.ts +144 -0
  42. package/dist/index-Nxo3TJcm.d.ts +208 -0
  43. package/dist/index-Sw43J8HG.d.ts +62 -0
  44. package/dist/index-cEeweTeM.d.ts +38 -0
  45. package/dist/index.d.ts +110 -0
  46. package/dist/index.js +42 -0
  47. package/dist/invalidate-DbxuL2jL.js +18 -0
  48. package/dist/jobs/index.d.ts +173 -0
  49. package/dist/jobs/index.js +477 -0
  50. package/dist/json-schema-BbwO2mZg.js +181 -0
  51. package/dist/lint/index.d.ts +75 -0
  52. package/dist/lint/index.js +167 -0
  53. package/dist/list/index.d.ts +2 -0
  54. package/dist/list/index.js +410 -0
  55. package/dist/live-6b9i72Ux.d.ts +180 -0
  56. package/dist/live-D8rV1Ldw.js +168 -0
  57. package/dist/mcp/index.d.ts +105 -0
  58. package/dist/mcp/index.js +330 -0
  59. package/dist/mfa-CpogP66z.js +521 -0
  60. package/dist/mfa-TVia554c.d.ts +44 -0
  61. package/dist/next/image/index.d.ts +34 -0
  62. package/dist/next/image/index.js +40 -0
  63. package/dist/next/index.d.ts +210 -0
  64. package/dist/next/index.js +426 -0
  65. package/dist/openapi/index.d.ts +2 -0
  66. package/dist/openapi/index.js +332 -0
  67. package/dist/orpc/index.d.ts +46 -0
  68. package/dist/orpc/index.js +50 -0
  69. package/dist/otel/index.d.ts +40 -0
  70. package/dist/otel/index.js +168 -0
  71. package/dist/path-Cv__-OTj.d.ts +17 -0
  72. package/dist/plugin-BqR6wKMB.js +23 -0
  73. package/dist/plugin-HvGqCurB.d.ts +118 -0
  74. package/dist/plugins/actor/index.d.ts +13 -0
  75. package/dist/plugins/actor/index.js +43 -0
  76. package/dist/plugins/rules/index.d.ts +88 -0
  77. package/dist/plugins/rules/index.js +174 -0
  78. package/dist/plugins/soft-delete/index.d.ts +38 -0
  79. package/dist/plugins/soft-delete/index.js +69 -0
  80. package/dist/plugins/tenant/index.d.ts +43 -0
  81. package/dist/plugins/tenant/index.js +73 -0
  82. package/dist/plugins/timestamps/index.d.ts +9 -0
  83. package/dist/plugins/timestamps/index.js +37 -0
  84. package/dist/plugins/validation/index.d.ts +24 -0
  85. package/dist/plugins/validation/index.js +59 -0
  86. package/dist/pool-BFeqzwQS.d.ts +37 -0
  87. package/dist/postgres/index.d.ts +28 -0
  88. package/dist/postgres/index.js +79 -0
  89. package/dist/postgrest-Dm-vhY6R.d.ts +43 -0
  90. package/dist/problem-DPu6Fh-t.js +97 -0
  91. package/dist/problem-DlgB0lYl.d.ts +47 -0
  92. package/dist/query/index.d.ts +2 -0
  93. package/dist/query/index.js +3 -0
  94. package/dist/query-ChvDbsDE.js +186 -0
  95. package/dist/react/index.d.ts +7 -0
  96. package/dist/react/index.js +5 -0
  97. package/dist/react/server.d.ts +13 -0
  98. package/dist/react/server.js +25 -0
  99. package/dist/react/session.d.ts +2 -0
  100. package/dist/react/session.js +3 -0
  101. package/dist/react-CrOvrnIP.js +241 -0
  102. package/dist/read-set-DhX2d04c.js +216 -0
  103. package/dist/realtime/index.d.ts +3 -0
  104. package/dist/realtime/index.js +253 -0
  105. package/dist/resolve-DW8h9NPm.d.ts +155 -0
  106. package/dist/resource-CYiu6Ygi.js +175 -0
  107. package/dist/resource-SkPTRJDD.d.ts +65 -0
  108. package/dist/respond-4-dhoV7x.js +380 -0
  109. package/dist/respond-PoTpy5DT.d.ts +169 -0
  110. package/dist/result-CTkCZ6JA.d.ts +198 -0
  111. package/dist/result-DWXatkd6.js +103 -0
  112. package/dist/scope-CDHcS7dE.js +90 -0
  113. package/dist/seed-CzecODcJ.js +101 -0
  114. package/dist/server/index.d.ts +42 -0
  115. package/dist/server/index.js +68 -0
  116. package/dist/session-C3osL21k.d.ts +21 -0
  117. package/dist/session-CD-3orO_.js +19 -0
  118. package/dist/shared-_6-uPL7E.js +57 -0
  119. package/dist/simplify-oHiDKRVQ.js +665 -0
  120. package/dist/spec-pins-CJPVghHy.d.ts +20 -0
  121. package/dist/spec-pins-t6sPaHvl.js +20 -0
  122. package/dist/sql-M8l3fnS0.js +260 -0
  123. package/dist/ssr/index.d.ts +5 -0
  124. package/dist/ssr/index.js +4 -0
  125. package/dist/standard-CyhRzctb.d.ts +7 -0
  126. package/dist/standard-FUi3Z3-7.js +21 -0
  127. package/dist/stats-3iy8u3_P.js +566 -0
  128. package/dist/storage/index.d.ts +4 -0
  129. package/dist/storage/index.js +2 -0
  130. package/dist/storage-BWXVUXGk.js +461 -0
  131. package/dist/tables-rZxRxNPW.js +59 -0
  132. package/dist/template-BeOGnynM.js +93 -0
  133. package/dist/template-mbvlysOo.d.ts +6 -0
  134. package/dist/testing/index.d.ts +294 -0
  135. package/dist/testing/index.js +751 -0
  136. package/dist/types-6cYK9pbJ.js +29 -0
  137. package/dist/types-C2fslP1z.d.ts +195 -0
  138. package/dist/version-Cqq1m3UY.js +4 -0
  139. package/dist/view-B0ltUmTi.d.ts +43 -0
  140. package/dist/view-B6F9QbG-.js +35 -0
  141. package/dist/webhooks/index.d.ts +152 -0
  142. package/dist/webhooks/index.js +2 -0
  143. package/dist/webhooks-DbMTJJX2.js +139 -0
  144. package/package.json +246 -17
  145. package/schemas/config-v1.json +328 -0
  146. package/schemas/doctor-report-v1.json +105 -0
  147. package/schemas/snapshot-v2.json +1002 -0
  148. package/skills/better-supabase/SKILL.md +84 -0
  149. package/skills/better-supabase/references/plugins.md +56 -0
  150. package/skills/better-supabase/references/troubleshooting.md +39 -0
  151. package/skills/better-supabase-api/SKILL.md +67 -0
  152. package/skills/better-supabase-api/references/adapters.md +108 -0
  153. package/skills/better-supabase-testing/SKILL.md +65 -0
  154. package/index.js +0 -1
@@ -0,0 +1,208 @@
1
+ import { p as DbError, t as AsyncResult } from "./result-CTkCZ6JA.js";
2
+ import { n as StoragePath, t as PathIn } from "./path-Cv__-OTj.js";
3
+ import { n as TemplateValues, t as TemplateParams } from "./template-mbvlysOo.js";
4
+ import { SupabaseClient } from "@supabase/supabase-js";
5
+ //#region src/storage/index.d.ts
6
+ type BucketPolicy = "tenant" | "owner" | "public" | "none";
7
+ interface BucketConfig<P extends string = string, Id extends string = string> {
8
+ /** Bucket id, e.g. `customer-logos`. */
9
+ readonly id: Id;
10
+ /** Object path template, e.g. `{orgId}/{customerId}/logo/{version}.webp`. */
11
+ readonly path: P;
12
+ readonly public?: boolean;
13
+ /**
14
+ * Generated `storage.objects` policies. `tenant` and `owner` match a path
15
+ * segment against the JWT; `public` allows reads; `none` leaves access to
16
+ * the secret key. Defaults to `none`.
17
+ */
18
+ readonly policy?: BucketPolicy;
19
+ /** `'5MiB'`, `'500KB'` or bytes. */
20
+ readonly fileSizeLimit?: string | number;
21
+ /** `['image/png', 'image/*']`. */
22
+ readonly allowedMimeTypes?: readonly string[];
23
+ readonly tenant?: {
24
+ /** Placeholder holding the tenant id. Defaults to `orgId`. */
25
+ readonly param?: string;
26
+ /** JWT claim paths, first match wins. Defaults to `org_id`, then `app_metadata.org_id`. */
27
+ readonly claim?: string | readonly string[];
28
+ /** SQL expression for the tenant id, instead of `claim`. */
29
+ readonly sql?: string;
30
+ };
31
+ readonly owner?: {
32
+ /** Placeholder holding the user id. Defaults to `userId`. */
33
+ readonly param?: string;
34
+ };
35
+ }
36
+ /**
37
+ * A path from the template's values, or an existing path string (checked
38
+ * against the template). `StoragePath`s of other buckets are rejected.
39
+ */
40
+ type ObjectTarget<P extends string, Id extends string = string> = TemplateValues<P> | PathIn<Id>;
41
+ declare const TTL: {
42
+ readonly minute: 60;
43
+ readonly hour: 3600;
44
+ readonly day: 86_400;
45
+ readonly week: 604_800;
46
+ };
47
+ type TtlPreset = keyof typeof TTL;
48
+ interface TransformOptions {
49
+ readonly width?: number;
50
+ readonly height?: number;
51
+ readonly resize?: "cover" | "contain" | "fill";
52
+ readonly quality?: number;
53
+ readonly format?: "origin";
54
+ }
55
+ type UploadBody = Blob | ArrayBuffer | ArrayBufferView | ReadableStream<Uint8Array> | FormData | string;
56
+ interface UploadOptions {
57
+ readonly contentType?: string;
58
+ readonly cacheControl?: string;
59
+ readonly upsert?: boolean;
60
+ readonly metadata?: Readonly<Record<string, unknown>>;
61
+ readonly signal?: AbortSignal;
62
+ }
63
+ interface UrlOptions {
64
+ /** Seconds or a preset. Defaults to `hour`. */
65
+ readonly ttl?: number | TtlPreset;
66
+ readonly transform?: TransformOptions;
67
+ /** Serve as an attachment, optionally with a file name. */
68
+ readonly download?: boolean | string;
69
+ }
70
+ interface StoredObject {
71
+ readonly path: string;
72
+ readonly size?: number;
73
+ readonly contentType?: string;
74
+ readonly createdAt: string | null;
75
+ readonly updatedAt: string | null;
76
+ }
77
+ interface Reservation {
78
+ readonly path: string;
79
+ readonly token: string;
80
+ readonly signedUrl: string;
81
+ }
82
+ interface ReplaceOptions<Id extends string = string> extends UploadOptions {
83
+ /** Path the object replaces. Removed after `commit` succeeds. */
84
+ readonly previous?: string | null;
85
+ /**
86
+ * Store the new path, e.g. update the row. Throwing or returning an error
87
+ * `Result` removes the new object and keeps the previous one.
88
+ */
89
+ readonly commit?: (path: StoragePath<Id>) => unknown;
90
+ }
91
+ interface ReplaceResult<Id extends string = string> {
92
+ readonly path: StoragePath<Id>;
93
+ readonly removed: string | null;
94
+ /** Set when the previous object could not be removed. */
95
+ readonly cleanup?: DbError;
96
+ }
97
+ interface SweepOptions<P extends string> {
98
+ /** Only look under the path prefix these values fill. */
99
+ readonly within?: Partial<TemplateValues<P>>;
100
+ /** Minimum age in milliseconds, or a cutoff date. */
101
+ readonly olderThan: number | Date;
102
+ /** Returns which of `paths` are still referenced. */
103
+ readonly referenced: (paths: readonly string[]) => PromiseLike<Iterable<string>> | Iterable<string>;
104
+ readonly dryRun?: boolean;
105
+ readonly batchSize?: number;
106
+ readonly signal?: AbortSignal;
107
+ readonly now?: () => number;
108
+ }
109
+ interface SweepResult {
110
+ readonly scanned: number;
111
+ readonly orphans: readonly string[];
112
+ readonly removed: readonly string[];
113
+ }
114
+ interface BucketDrift {
115
+ readonly field: "missing" | "public" | "fileSizeLimit" | "allowedMimeTypes";
116
+ readonly expected: unknown;
117
+ readonly actual: unknown;
118
+ readonly message: string;
119
+ }
120
+ /** Bucket state as stored in `storage.buckets` (or `better-supabase` introspection). */
121
+ interface ActualBucket {
122
+ readonly public: boolean;
123
+ readonly fileSizeLimit?: number | null;
124
+ readonly allowedMimeTypes?: readonly string[] | null;
125
+ }
126
+ type StorageClient = Pick<SupabaseClient, "storage">;
127
+ interface BucketClient<P extends string, Id extends string = string> {
128
+ readonly bucket: Bucket<P, Id>;
129
+ upload(target: ObjectTarget<P, Id>, body: UploadBody, options?: UploadOptions): AsyncResult<{
130
+ path: StoragePath<Id>;
131
+ }>;
132
+ download(target: ObjectTarget<P, Id>, options?: {
133
+ signal?: AbortSignal;
134
+ }): AsyncResult<Blob>;
135
+ exists(target: ObjectTarget<P, Id>): AsyncResult<boolean>;
136
+ remove(targets: readonly ObjectTarget<P, Id>[]): AsyncResult<readonly string[]>;
137
+ list(within?: Partial<TemplateValues<P>>, options?: {
138
+ signal?: AbortSignal;
139
+ }): AsyncResult<readonly StoredObject[]>;
140
+ signedUrl(target: ObjectTarget<P, Id>, options?: UrlOptions): AsyncResult<string>;
141
+ signedUrls(targets: readonly ObjectTarget<P, Id>[], options?: Omit<UrlOptions, "transform">): AsyncResult<readonly string[]>;
142
+ /** URL for public buckets. No request is made. */
143
+ publicUrl(target: ObjectTarget<P, Id>, options?: Omit<UrlOptions, "ttl">): string;
144
+ /** Image transform URL: public for public buckets, signed otherwise. */
145
+ renderUrl(target: ObjectTarget<P, Id>, transform: TransformOptions, options?: Omit<UrlOptions, "transform">): AsyncResult<string>;
146
+ /** Upload the new object, run `commit`, then remove the previous object. */
147
+ replace(target: ObjectTarget<P, Id>, body: UploadBody, options?: ReplaceOptions<Id>): AsyncResult<ReplaceResult<Id>>;
148
+ /** A signed upload URL for a browser or another service. */
149
+ reserve(target: ObjectTarget<P, Id>, options?: {
150
+ upsert?: boolean;
151
+ }): AsyncResult<Reservation>;
152
+ uploadReserved(reservation: Pick<Reservation, "path" | "token">, body: UploadBody, options?: UploadOptions): AsyncResult<{
153
+ path: StoragePath<Id>;
154
+ }>;
155
+ /** Removes objects that match the template, are old enough and are not referenced. */
156
+ sweep(options: SweepOptions<P>): AsyncResult<SweepResult>;
157
+ }
158
+ interface Bucket<P extends string, Id extends string = string> {
159
+ readonly id: Id;
160
+ readonly template: P;
161
+ readonly params: readonly TemplateParams<P>[];
162
+ readonly public: boolean;
163
+ readonly policy: BucketPolicy;
164
+ /**
165
+ * Placeholder holding the owning user's id: `owner.param` for `owner`
166
+ * buckets, otherwise `userId` when the template has it. Account deletion
167
+ * removes the objects it fills.
168
+ */
169
+ readonly owner: string | undefined;
170
+ readonly fileSizeLimit: number | undefined;
171
+ readonly allowedMimeTypes: readonly string[] | undefined;
172
+ path(values: TemplateValues<P>): StoragePath<Id>;
173
+ match(path: string): TemplateValues<P> | null;
174
+ /** Folder prefix filled by `values`, for listing. */
175
+ prefix(values?: Partial<TemplateValues<P>>): string;
176
+ /** Checks a size and content type against the bucket limits. */
177
+ check(file: {
178
+ size?: number;
179
+ type?: string;
180
+ }): DbError | undefined;
181
+ /** `insert into storage.buckets` plus `storage.objects` policies. Idempotent. */
182
+ sql(): string;
183
+ /** A `[storage.buckets.<id>]` section for `supabase/config.toml`. */
184
+ toml(): string;
185
+ drift(actual: ActualBucket | undefined): readonly BucketDrift[];
186
+ connect(client: StorageClient): BucketClient<P, Id>;
187
+ }
188
+ declare function parseSize(value: string | number): number;
189
+ /** Maps a Storage error (`StorageApiError`, fetch failures) to a `DbError`. */
190
+ declare function fromStorageError(raw: unknown, table?: string): DbError;
191
+ /**
192
+ * A typed Storage bucket: path builders from a template, limits, generated
193
+ * SQL policies and `config.toml`, and helpers for the multi-step work apps
194
+ * repeat (replace, signed uploads, orphan cleanup).
195
+ *
196
+ * ```ts
197
+ * export const logos = defineBucket({
198
+ * id: 'customer-logos',
199
+ * path: '{orgId}/{customerId}/logo/{version}.webp',
200
+ * policy: 'tenant',
201
+ * fileSizeLimit: '5MiB',
202
+ * allowedMimeTypes: ['image/webp'],
203
+ * });
204
+ * ```
205
+ */
206
+ declare function defineBucket<const P extends string, const Id extends string = string>(config: BucketConfig<P, Id>): Bucket<P, Id>;
207
+ //#endregion
208
+ export { parseSize as C, fromStorageError as S, TtlPreset as _, BucketDrift as a, UrlOptions as b, ReplaceOptions as c, StorageClient as d, StoredObject as f, TransformOptions as g, TTL as h, BucketConfig as i, ReplaceResult as l, SweepResult as m, Bucket as n, BucketPolicy as o, SweepOptions as p, BucketClient as r, ObjectTarget as s, ActualBucket as t, Reservation as u, UploadBody as v, defineBucket as x, UploadOptions as y };
@@ -0,0 +1,62 @@
1
+ import { n as AnyModels, t as AnyFunctions } from "./types-C2fslP1z.js";
2
+ import { t as BetterSupabase, y as Db } from "./define-CTfWw-SS.js";
3
+ import { c as PublicEnv } from "./index-Dy6kuF0P.js";
4
+ import { i as Queries } from "./index-Dup-nSe9.js";
5
+ import { SupabaseClient } from "@supabase/supabase-js";
6
+ //#region src/client/index.d.ts
7
+ interface BrowserOptions {
8
+ /** URL and publishable key. Not needed when `client` is given. */
9
+ readonly env?: PublicEnv;
10
+ /** Bring your own supabase-js client (React Native, custom storage). */
11
+ readonly client?: SupabaseClient;
12
+ /**
13
+ * `cookies` (default) shares the session with the server through
14
+ * `@supabase/ssr`; `local` keeps it in localStorage for SPAs without a server.
15
+ */
16
+ readonly storage?: "cookies" | "local";
17
+ }
18
+ interface AuthUser {
19
+ readonly id: string;
20
+ readonly email?: string;
21
+ readonly role?: string;
22
+ }
23
+ /** What the UI needs to know. Claims are decoded, not verified: RLS enforces access. */
24
+ type AuthSnapshot = {
25
+ readonly status: "loading";
26
+ readonly user: null;
27
+ readonly claims: null;
28
+ } | {
29
+ readonly status: "signed-out";
30
+ readonly user: null;
31
+ readonly claims: null;
32
+ } | {
33
+ readonly status: "signed-in";
34
+ readonly user: AuthUser;
35
+ readonly claims: Readonly<Record<string, unknown>>;
36
+ };
37
+ interface BrowserAuth {
38
+ readonly current: () => AuthSnapshot;
39
+ /** `useSyncExternalStore`-compatible. */
40
+ readonly subscribe: (listener: () => void) => () => void;
41
+ }
42
+ interface BetterBrowser<M extends AnyModels, F extends AnyFunctions, E, C = unknown> {
43
+ /** The definition the browser was created from (schema metadata, specs, live queries). */
44
+ readonly sb: BetterSupabase<M, unknown, F, E, C>;
45
+ readonly supabase: SupabaseClient;
46
+ /** Repositories with the current session's actor and claims. */
47
+ readonly db: Db<M, F, E, SupabaseClient>;
48
+ /** TanStack Query option factories over `db`. */
49
+ readonly queries: Queries<M, E, F>;
50
+ readonly auth: BrowserAuth;
51
+ }
52
+ /**
53
+ * The browser side: a supabase-js client, repositories that follow the
54
+ * session, TanStack Query options and an auth store for UI state.
55
+ *
56
+ * ```ts
57
+ * export const browser = createBrowser(sb, { env: { url, publishableKey } });
58
+ * ```
59
+ */
60
+ declare function createBrowser<M extends AnyModels, D, F extends AnyFunctions, E, C = unknown>(sb: BetterSupabase<M, D, F, E, C>, options?: BrowserOptions): BetterBrowser<M, F, E, C>;
61
+ //#endregion
62
+ export { BrowserOptions as a, BrowserAuth as i, AuthUser as n, createBrowser as o, BetterBrowser as r, AuthSnapshot as t };
@@ -0,0 +1,38 @@
1
+ import { m as StoredSession } from "./resolve-DW8h9NPm.js";
2
+ import "./view-B0ltUmTi.js";
3
+ import "./entitlements-BBg61DQZ.js";
4
+ //#region src/auth/refresh.d.ts
5
+ interface RefreshOptions {
6
+ readonly url: string;
7
+ readonly publishableKey: string;
8
+ /**
9
+ * Sends `Sb-Forwarded-For: ip` with the secret key, so Auth rate-limits the
10
+ * refresh by the user's IP (when IP forwarding is on for the project).
11
+ */
12
+ readonly forwardedFor?: {
13
+ readonly ip: string;
14
+ readonly secretKey: string;
15
+ };
16
+ readonly fetch?: typeof fetch;
17
+ readonly now?: () => number;
18
+ }
19
+ type RefreshOutcome = {
20
+ readonly ok: true;
21
+ readonly session: StoredSession;
22
+ /** Served from a concurrent or just-finished refresh of the same token. */
23
+ readonly shared?: boolean;
24
+ } | {
25
+ readonly ok: false;
26
+ /** `rejected`: the refresh token is dead, sign the user out. `network`: keep the session and retry later. */
27
+ readonly reason: "rejected" | "network";
28
+ readonly status?: number;
29
+ readonly message: string;
30
+ };
31
+ /**
32
+ * Exchanges a refresh token for a new session. Concurrent calls with the same
33
+ * token share one request, and a successful result is reused for a short
34
+ * window so parallel requests carrying the old cookie converge on one session.
35
+ */
36
+ declare function refreshSession(refreshToken: string, options: RefreshOptions): Promise<RefreshOutcome>;
37
+ //#endregion
38
+ export { RefreshOutcome as n, refreshSession as r, RefreshOptions as t };
@@ -0,0 +1,110 @@
1
+ import { A as TableMeta, C as Relations, D as Simplify, E as SchemaMeta, M as UniqueKeyName, N as UniqueWhere, O as TableFlags, P as Update, S as RelationShape, T as Schema, _ as ModelsOf, a as CheckConstraint, b as RealtimeTableMeta, c as DatabaseOf, d as ForeignKeyConstraint, f as FunctionMeta, g as ModelShape, h as Insert, i as Casing, j as UniqueConstraint, k as TableKey, l as Flags, m as FunctionsOf, n as AnyModels, o as Codec, p as FunctionShape, r as BucketMeta, s as ColumnMeta, t as AnyFunctions, u as FlagsShape, v as PrimaryKeyColumn, w as Row, x as RelationMeta, y as PrimaryKeyValue } from "./types-C2fslP1z.js";
2
+ import { C as and, E as or, S as UpdateOp, T as not, _ as OrderTerm, a as AggregateFn, b as SelectOp, c as Condition, d as FunctionSource, f as Include, g as Operation, h as MutationOp, i as RpcContext, l as CountMode, m as Measure, n as ExecuteResult, o as Aggregation, p as InsertOp, r as Executor, s as ColumnOp, t as ExecuteContext, u as DeleteOp, v as Quantifier, w as column, x as Selection, y as SelectColumn } from "./executor-Bazhgsgq.js";
3
+ import { C as isConflict, D as statusOf, E as mapDbError, S as isCheck, T as isForeignKey, _ as DbException, a as Ok, b as ValidationIssue, c as err, d as toBetterResult, f as toDbError, g as DbErrorOf, h as DbErrorKinds, i as Err, l as fromBetterResult, m as DbErrorKind, n as BetterResultApi, o as Result, p as DbError, r as BetterResultShape, t as AsyncResult, u as ok, v as ErrorMapper, w as isDbError, x as dbError, y as RawDbError } from "./result-CTkCZ6JA.js";
4
+ import { a as EventHub, c as QueryEvent, d as LogFields, f as Logger, i as EventHandler, l as RefreshEvent, m as silentLogger, n as BetterSupabaseEvents, o as EventName, p as consoleLogger, r as ErrorEvent, s as MutationNotice, t as AuthEvent, u as RpcNotice } from "./events-2OJsVG_d.js";
5
+ import { $ as Specs, A as RpcOptions, B as ReadSet, C as FindExt, Ct as WhereInput, D as Repository, E as PageOf, F as EMPTY_STATS, G as ReadSetParams, H as ReadSetParamType, I as StatsRecorder, J as isReadSet, K as ReadSetResult, L as recordStats, M as UpsertArgs, N as WriteArgs, O as RepositoryOf, P as DbStats, Q as ReadMethod, R as SearchArgs, S as DeleteExt, St as SortDirection, T as OffsetPageArgs, U as ReadSetParamTypes, V as ReadSetOptions, W as ReadSetParamValue, X as InferResult, Y as readSetTables, Z as QuerySpec, _ as CursorPage, _t as OrderByInput, a as defineSupabase, at as AggregateRow, b as DbHelpers, bt as RelationMeasureArg, c as postgrestExecutor, ct as FieldFilter, d as MemoryCache, dt as IncludeArg, et as TableSpecs, f as cacheTargetOf, ft as IncludeArgs, g as ConflictTarget, gt as OrderByArg, h as rpcCacheTargets, ht as NumericMeasureArg, i as RpcDefinition, it as AggregateResult, j as UpdateArgs, k as Returned, l as CacheAdapter, lt as FindFirstArgs, m as rowKey, mt as MeasureKey, n as ConnectOptions, nt as specTables, o as PostgrestClientLike, ot as CountArg, p as memoryCache, pt as MeasureArg, q as defineReadSet, r as DefineSupabaseOptions, rt as AggregateArgs, s as explainPostgrest, st as CountArgs, t as BetterSupabase, tt as isQuerySpec, u as CacheTarget, ut as FindManyArgs, v as CursorPageArgs, vt as Payload, w as OffsetPage, x as DeleteArgs, xt as SelectArg, y as Db, yt as ReadArgs, z as InferReadSetParams } from "./define-CTfWw-SS.js";
6
+ import { _ as definePlugin, a as ExtensionOf, c as MutationEvent, d as PLUGIN_API_VERSION, f as Plugin, g as WithExtension, h as RequestContext, i as CallOptions, l as MutationKind, m as RepositoryExtension, n as AnyPlugin, o as HasFlag, p as RepositoryApi, r as ApplyExtension, s as HookArgs, t as Actor, u as NoExtension } from "./plugin-HvGqCurB.js";
7
+ import { n as validate, t as StandardSchemaV1 } from "./standard-CyhRzctb.js";
8
+ import { a as compilePostgrest, i as PostgrestPlan, n as PlanLimit, r as PlanOrder, t as PlanFilter } from "./postgrest-Dm-vhY6R.js";
9
+ import { n as StoragePath } from "./path-Cv__-OTj.js";
10
+ import { n as postgrestCompiler, t as Compiler } from "./compiler-DL18ukPe.js";
11
+ import { a as ProblemResponseOptions, c as problemResponse, i as ProblemOptions, l as toProblem, n as PROBLEM_TYPE_BASE, o as fromProblem, r as ProblemDetails, s as isProblem, t as PROBLEM_CONTENT_TYPE } from "./problem-DlgB0lYl.js";
12
+ import { t as SPEC_PINS } from "./spec-pins-CJPVghHy.js";
13
+ //#region src/core/define-repository.d.ts
14
+ /** Adds `Methods` to the repository of `Table` only. */
15
+ interface TableRepositoryExtension<Table extends string, Methods> extends RepositoryExtension {
16
+ readonly methods: this["T"] extends Table ? Methods : unknown;
17
+ }
18
+ /**
19
+ * Domain methods for one table, installed with `use()`. `base` is the
20
+ * repository at call time, with every other plugin's methods.
21
+ *
22
+ * ```ts
23
+ * const customers = defineRepository(sb, 'customers', (base) => ({
24
+ * active: () => base.findMany({ where: { status: 'active' } }),
25
+ * }));
26
+ * export const app = sb.use(customers);
27
+ * await app.connect(client).customers.active();
28
+ * ```
29
+ */
30
+ export declare function defineRepository<M extends AnyModels, D, F extends AnyFunctions, E, const Table extends TableKey<M>, Methods extends object>(sb: BetterSupabase<M, D, F, E>, table: Table, build: (base: RepositoryOf<M, Table, E>) => Methods): Plugin<`repository:${Table}`, TableRepositoryExtension<Table, Methods>>;
31
+ //#endregion
32
+ //#region src/ir/tables.d.ts
33
+ /**
34
+ * App keys of every table an operation reads or writes: its own table, each
35
+ * included relation and each relation used in a filter. Cached reads of these
36
+ * tables go stale when any of them changes.
37
+ */
38
+ export declare function touchedTables(op: Operation): string[];
39
+ /**
40
+ * Tables whose rows can change when rows of `table` change: the table itself
41
+ * plus every table whose foreign key cascades or sets a value on delete,
42
+ * followed through chains of cascades.
43
+ */
44
+ export declare function invalidationTargets(meta: SchemaMeta, table: string): string[];
45
+ //#endregion
46
+ //#region src/core/cursor.d.ts
47
+ /** Opaque, URL-safe keyset cursor. */
48
+ export declare function encodeCursor(values: readonly unknown[]): string;
49
+ export declare function decodeCursor(cursor: string): unknown[] | undefined;
50
+ //#endregion
51
+ //#region src/schema/define.d.ts
52
+ /**
53
+ * Binds generated model types to runtime metadata. Called from the generated
54
+ * module; apps import the returned `schema`, never call this themselves.
55
+ */
56
+ export declare function defineSchema<M extends AnyModels, D = unknown, F extends AnyFunctions = AnyFunctions>(meta: SchemaMeta): Schema<M, D, F>;
57
+ export declare function tableMeta(meta: SchemaMeta, table: string): TableMeta;
58
+ //#endregion
59
+ //#region src/schema/enrich.d.ts
60
+ type Override<R, O> = { [K in keyof R]: K extends keyof O ? null extends R[K] ? O[K] | null : O[K] : R[K]; };
61
+ type EnrichTables<Tables, O> = { [T in keyof Tables]: T extends keyof O ? { [P in keyof Tables[T]]: P extends "Row" | "Insert" | "Update" ? Override<Tables[T][P], O[T]> : Tables[T][P]; } : Tables[T]; };
62
+ type EnrichSchema<S, O> = { [P in keyof S]: P extends "Tables" | "Views" ? EnrichTables<S[P], O> : S[P]; };
63
+ /**
64
+ * Narrows column types of a `supabase gen types` `Database`: CHECK-constraint
65
+ * unions and typed jsonb. Overrides are keyed `{ schema: { table: { column } } }`.
66
+ */
67
+ type EnrichDatabase<D, O> = { [S in keyof D]: S extends keyof O ? EnrichSchema<D[S], O[S]> : D[S]; };
68
+ //#endregion
69
+ //#region src/ir/build.d.ts
70
+ /** Escapes LIKE wildcards so user input matches literally. */
71
+ export declare function escapeLike(value: string): string;
72
+ //#endregion
73
+ //#region src/ir/codec.d.ts
74
+ /** Wire form of an app value: `Date` to ISO text, `bigint` to decimal text. */
75
+ export declare function encodeValue(value: unknown): unknown;
76
+ /** Applies column codecs to returned rows, including embedded relations. */
77
+ export declare function decodeRows(selection: Selection | undefined, rows: readonly Record<string, unknown>[]): Record<string, unknown>[];
78
+ //#endregion
79
+ //#region src/ir/scope.d.ts
80
+ /** Returns the filter that always applies to rows of `table`, if any. */
81
+ type ScopeFor = (table: TableMeta) => Condition | undefined;
82
+ /**
83
+ * Applies `scopeFor` to every relation filter in a condition. `every(W)`
84
+ * becomes `none(S and not W)` so out-of-scope rows (soft-deleted, other
85
+ * tenants) neither satisfy nor fail it.
86
+ */
87
+ export declare function scopeCondition(condition: Condition | undefined, scopeFor: ScopeFor): Condition | undefined;
88
+ /** Applies `scopeFor` to every include and to filters inside includes. */
89
+ export declare function scopeSelection(selection: Selection, scopeFor: ScopeFor): Selection;
90
+ /**
91
+ * Scopes a whole operation: the root table's rows (reads, updates, deletes),
92
+ * relation filters, includes and returned embeds. Inserts only get their
93
+ * returning selection scoped.
94
+ */
95
+ export declare function scopeOperation(op: Operation, scopeFor: ScopeFor, root?: boolean): Operation;
96
+ //#endregion
97
+ //#region src/ir/simplify.d.ts
98
+ /**
99
+ * Folds constant conditions. `true` means "no filter", `false` means "matches
100
+ * nothing", so executors can skip the request entirely.
101
+ */
102
+ export declare function simplify(condition: Condition | undefined): Condition | boolean;
103
+ //#endregion
104
+ //#region src/casing/index.d.ts
105
+ /** `first_name` to `firstName`. Leaves already camel-cased names untouched. */
106
+ export declare function toCamel(name: string): string;
107
+ /** `firstName` to `first_name`. */
108
+ export declare function toSnake(name: string): string;
109
+ //#endregion
110
+ export { type Actor, type AggregateArgs, type AggregateFn, type AggregateResult, type AggregateRow, type Aggregation, type AnyFunctions, type AnyModels, type AnyPlugin, type ApplyExtension, AsyncResult, type AuthEvent, type BetterResultApi, type BetterResultShape, BetterSupabase, type BetterSupabaseEvents, type BucketMeta, type CacheAdapter, type CacheTarget, type CallOptions, type Casing, type CheckConstraint, type Codec, type ColumnMeta, type ColumnOp, type Compiler, type Condition, type ConflictTarget, type ConnectOptions, type CountArg, type CountArgs, type CountMode, type CursorPage, type CursorPageArgs, type DatabaseOf, type Db, type DbError, type DbErrorKind, type DbErrorKinds, type DbErrorOf, DbException, type DbHelpers, type DbStats, type DefineSupabaseOptions, type DeleteArgs, type DeleteExt, type DeleteOp, EMPTY_STATS, type EnrichDatabase, type Err, type ErrorEvent, type ErrorMapper, type EventHandler, EventHub, type EventName, type ExecuteContext, type ExecuteResult, type Executor, type ExtensionOf, type FieldFilter, type FindExt, type FindFirstArgs, type FindManyArgs, type Flags, type FlagsShape, type ForeignKeyConstraint, type FunctionMeta, type FunctionShape, type FunctionSource, type FunctionsOf, type HasFlag, type HookArgs, type Include, type IncludeArg, type IncludeArgs, type InferReadSetParams, type InferResult, type Insert, type InsertOp, type LogFields, type Logger, type Measure, type MeasureArg, type MeasureKey, type MemoryCache, type ModelShape, type ModelsOf, type MutationEvent, type MutationKind, type MutationNotice, type MutationOp, type NoExtension, type NumericMeasureArg, type OffsetPage, type OffsetPageArgs, type Ok, type Operation, type OrderByArg, type OrderByInput, type OrderTerm, PLUGIN_API_VERSION, PROBLEM_CONTENT_TYPE, PROBLEM_TYPE_BASE, type PageOf, type Payload, type PlanFilter, type PlanLimit, type PlanOrder, type Plugin, type PostgrestClientLike, type PostgrestPlan, type PrimaryKeyColumn, type PrimaryKeyValue, type ProblemDetails, type ProblemOptions, type ProblemResponseOptions, type Quantifier, type QueryEvent, type QuerySpec, type RawDbError, type ReadArgs, type ReadMethod, type ReadSet, type ReadSetOptions, type ReadSetParamType, type ReadSetParamTypes, type ReadSetParamValue, type ReadSetParams, type ReadSetResult, type RealtimeTableMeta, type RefreshEvent, type RelationMeasureArg, type RelationMeta, type RelationShape, type Relations, type Repository, type RepositoryApi, type RepositoryExtension, type RepositoryOf, type RequestContext, type Result, type Returned, type Row, type RpcContext, type RpcDefinition, type RpcNotice, type RpcOptions, SPEC_PINS, type Schema, type SchemaMeta, type ScopeFor, type SearchArgs, type SelectArg, type SelectColumn, type SelectOp, type Selection, type Simplify, type SortDirection, type Specs, type StandardSchemaV1, StatsRecorder, type StoragePath, type TableFlags, type TableKey, type TableMeta, type TableRepositoryExtension, type TableSpecs, type UniqueConstraint, type UniqueKeyName, type UniqueWhere, type Update, type UpdateArgs, type UpdateOp, type UpsertArgs, type ValidationIssue, type WhereInput, type WithExtension, type WriteArgs, and, cacheTargetOf, column, compilePostgrest, consoleLogger, dbError, definePlugin, defineReadSet, defineSupabase, err, explainPostgrest, fromBetterResult, fromProblem, isCheck, isConflict, isDbError, isForeignKey, isProblem, isQuerySpec, isReadSet, mapDbError, memoryCache, not, ok, or, postgrestCompiler, postgrestExecutor, problemResponse, readSetTables, recordStats, rowKey, rpcCacheTargets, silentLogger, specTables, statusOf, toBetterResult, toDbError, toProblem, validate };
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ import { a as isConflict, c as mapDbError, i as isCheck, l as statusOf, n as dbError, o as isDbError, s as isForeignKey, t as DbException } from "./errors-Bl3rkOzo.js";
2
+ import { i as escapeLike, l as defineSchema, o as decodeRows, s as encodeValue, t as simplify, u as tableMeta } from "./simplify-oHiDKRVQ.js";
3
+ import { i as or, n as column, r as not, t as and } from "./types-6cYK9pbJ.js";
4
+ import { a as toBetterResult, i as ok, n as err, o as toDbError, r as fromBetterResult, t as AsyncResult } from "./result-DWXatkd6.js";
5
+ import { a as EventHub, c as cacheTargetOf, d as rpcCacheTargets, i as encodeCursor, l as memoryCache, n as defineSupabase, o as consoleLogger, r as decodeCursor, s as silentLogger, t as BetterSupabase, u as rowKey } from "./define-QGkq04oe.js";
6
+ import { n as touchedTables, t as invalidationTargets } from "./tables-rZxRxNPW.js";
7
+ import { n as definePlugin, t as PLUGIN_API_VERSION } from "./plugin-BqR6wKMB.js";
8
+ import { a as postgrestExecutor, i as explainPostgrest, n as StatsRecorder, o as compilePostgrest, r as recordStats, t as EMPTY_STATS } from "./stats-3iy8u3_P.js";
9
+ import { c as readSetTables, d as isQuerySpec, f as specTables, i as defineReadSet, o as isReadSet } from "./read-set-DhX2d04c.js";
10
+ import { t as validate } from "./standard-FUi3Z3-7.js";
11
+ import { a as problemResponse, i as isProblem, n as PROBLEM_TYPE_BASE, o as toProblem, r as fromProblem, t as PROBLEM_CONTENT_TYPE } from "./problem-DPu6Fh-t.js";
12
+ import { t as SPEC_PINS } from "./spec-pins-t6sPaHvl.js";
13
+ import { n as scopeOperation, r as scopeSelection, t as scopeCondition } from "./scope-CDHcS7dE.js";
14
+ import { n as toCamel, r as toSnake } from "./casing-da0uRTqt.js";
15
+ //#region src/core/define-repository.ts
16
+ /**
17
+ * Domain methods for one table, installed with `use()`. `base` is the
18
+ * repository at call time, with every other plugin's methods.
19
+ *
20
+ * ```ts
21
+ * const customers = defineRepository(sb, 'customers', (base) => ({
22
+ * active: () => base.findMany({ where: { status: 'active' } }),
23
+ * }));
24
+ * export const app = sb.use(customers);
25
+ * await app.connect(client).customers.active();
26
+ * ```
27
+ */
28
+ function defineRepository(sb, table, build) {
29
+ if (!(table in sb.meta.tables)) throw new TypeError(`better-supabase: defineRepository: unknown table "${table}"`);
30
+ return definePlugin({
31
+ name: `repository:${table}`,
32
+ repository: ({ table: meta, base }) => meta.key === table ? build(base) : void 0
33
+ });
34
+ }
35
+ //#endregion
36
+ //#region src/core/compiler.ts
37
+ const postgrestCompiler = {
38
+ target: "postgrest",
39
+ compile: compilePostgrest
40
+ };
41
+ //#endregion
42
+ export { AsyncResult, BetterSupabase, DbException, EMPTY_STATS, EventHub, PLUGIN_API_VERSION, PROBLEM_CONTENT_TYPE, PROBLEM_TYPE_BASE, SPEC_PINS, StatsRecorder, and, cacheTargetOf, column, compilePostgrest, consoleLogger, dbError, decodeCursor, decodeRows, definePlugin, defineReadSet, defineRepository, defineSchema, defineSupabase, encodeCursor, encodeValue, err, escapeLike, explainPostgrest, fromBetterResult, fromProblem, invalidationTargets, isCheck, isConflict, isDbError, isForeignKey, isProblem, isQuerySpec, isReadSet, mapDbError, memoryCache, not, ok, or, postgrestCompiler, postgrestExecutor, problemResponse, readSetTables, recordStats, rowKey, rpcCacheTargets, scopeCondition, scopeOperation, scopeSelection, silentLogger, simplify, specTables, statusOf, tableMeta, toBetterResult, toCamel, toDbError, toProblem, toSnake, touchedTables, validate };
@@ -0,0 +1,18 @@
1
+ //#region src/query/invalidate.ts
2
+ function queryTables(query) {
3
+ const tables = query.meta?.["bsTables"];
4
+ if (Array.isArray(tables)) return tables.filter((t) => typeof t === "string");
5
+ const [prefix, table] = query.queryKey;
6
+ return prefix === "bs" && typeof table === "string" ? [table] : void 0;
7
+ }
8
+ /**
9
+ * Invalidates every query that read one of `tables`: better-supabase queries
10
+ * by their `meta.bsTables`, and other `['bs', table, ...]` keys by prefix.
11
+ */
12
+ function invalidateTables(client, tables) {
13
+ if (tables.length === 0) return Promise.resolve();
14
+ const changed = new Set(tables);
15
+ return client.invalidateQueries({ predicate: (query) => queryTables(query)?.some((table) => changed.has(table)) ?? false });
16
+ }
17
+ //#endregion
18
+ export { invalidateTables as t };