@staticbot/base44-supabase-shim 0.3.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.
@@ -0,0 +1,159 @@
1
+ import { SupabaseClient } from '@supabase/supabase-js';
2
+ import * as _supabase_auth_js from '@supabase/auth-js';
3
+ import { makeIntegrations, IntegrationsOptions } from './integrations.cjs';
4
+ import * as _supabase_storage_js from '@supabase/storage-js';
5
+ import { O as OrderBy, C as ClientOptions, E as EntityMapping, a as EntitiesProxy } from './types-HIZDZaWa.cjs';
6
+ export { b as EntityApi, F as FilterObject, c as FilterValue, J as Json, M as MongoFilter } from './types-HIZDZaWa.cjs';
7
+
8
+ interface SignInArgs {
9
+ email: string;
10
+ password: string;
11
+ }
12
+ interface SignUpArgs {
13
+ email: string;
14
+ password: string;
15
+ metadata?: Record<string, unknown>;
16
+ }
17
+ interface AuthOptions {
18
+ /**
19
+ * Browser path the redirectToLogin() shim should send users to.
20
+ * Default: '/login'.
21
+ */
22
+ loginPath?: string;
23
+ }
24
+ declare function makeAuth(client: SupabaseClient, opts?: AuthOptions): {
25
+ signIn({ email, password }: SignInArgs): Promise<{
26
+ user: _supabase_auth_js.User;
27
+ session: _supabase_auth_js.Session;
28
+ weakPassword?: _supabase_auth_js.WeakPassword;
29
+ }>;
30
+ signUp({ email, password, metadata }: SignUpArgs): Promise<{
31
+ user: _supabase_auth_js.User | null;
32
+ session: _supabase_auth_js.Session | null;
33
+ }>;
34
+ signOut(): Promise<void>;
35
+ /** Base44 alias for signOut. */
36
+ logout(): Promise<void>;
37
+ getUser(): Promise<_supabase_auth_js.User>;
38
+ /** Base44 alias for getUser. Returns the current user object or throws if not signed in. */
39
+ me(): Promise<_supabase_auth_js.User>;
40
+ /**
41
+ * Base44 alias for updating the current user's metadata. Accepts arbitrary
42
+ * key/value pairs that get stored in `user_metadata`.
43
+ */
44
+ updateMe(metadata: Record<string, unknown>): Promise<_supabase_auth_js.User>;
45
+ getSession(): Promise<_supabase_auth_js.Session | null>;
46
+ /**
47
+ * Base44 used to redirect SPA users to its hosted login page. Self-host
48
+ * has no hosted login, so this just navigates to the configured local
49
+ * loginPath. Override the path via createClient({ ..., authLoginPath: '/x' }).
50
+ */
51
+ redirectToLogin(returnUrl?: string): void;
52
+ onAuthStateChange(cb: Parameters<SupabaseClient["auth"]["onAuthStateChange"]>[0]): {
53
+ data: {
54
+ subscription: _supabase_auth_js.Subscription;
55
+ };
56
+ };
57
+ };
58
+
59
+ /** Mirror of base44.functions — Supabase Edge Functions invoke wrapper.
60
+ *
61
+ * Returns the raw body. On HTTP error, throws an Error with the response body attached.
62
+ */
63
+ declare function makeFunctions(client: SupabaseClient): {
64
+ /** Invoke an edge function by name, passing JSON body. Returns parsed JSON. */
65
+ invoke<T = unknown>(name: string, payload?: Record<string, unknown>): Promise<T>;
66
+ /** Lower-level: invoke and return Response so caller can handle non-JSON. */
67
+ fetch(name: string, init?: RequestInit): Promise<Response>;
68
+ };
69
+
70
+ /**
71
+ * Stub for `base44.appLogs` — Base44 cloud's per-page activity tracker.
72
+ * Writes a row to core.audit_log if the table exists, otherwise silently
73
+ * succeeds. App code wraps this in .catch(() => {}) anyway, so any failure
74
+ * is non-fatal.
75
+ */
76
+ declare function makeAppLogs(client: SupabaseClient, app: string): {
77
+ logUserInApp(pageName: string): Promise<void>;
78
+ };
79
+ /**
80
+ * Stub for `base44.users` — admin-only user management. Self-host equivalent
81
+ * uses Supabase Auth admin API but requires a service_role key, which the
82
+ * browser client doesn't have. So inviteUser here logs a warning and returns
83
+ * a benign error so callers can show a "not supported" message.
84
+ */
85
+ declare function makeUsers(): {
86
+ inviteUser(_args: {
87
+ email: string;
88
+ [key: string]: unknown;
89
+ }): Promise<never>;
90
+ };
91
+
92
+ interface UploadFileArgs {
93
+ /** Supabase Storage bucket name. Defaults to schemaPrefix from client options. */
94
+ bucket?: string;
95
+ /** Object path within the bucket (e.g. 'invoices/2026/inv-001.pdf'). */
96
+ path: string;
97
+ /** File contents. */
98
+ file: Blob | File | ArrayBuffer | Uint8Array;
99
+ /** Content-Type. Inferred from File if omitted. */
100
+ contentType?: string;
101
+ /** Overwrite existing object at path. Default false. */
102
+ upsert?: boolean;
103
+ }
104
+ declare function makeStorage(client: SupabaseClient, defaultBucket: string): {
105
+ /** Upload a file to a bucket. Returns the public URL. */
106
+ uploadFile({ bucket, path, file, contentType, upsert, }: UploadFileArgs): Promise<{
107
+ path: string;
108
+ url: string;
109
+ }>;
110
+ /** Get a public URL for a stored object. */
111
+ getPublicUrl(path: string, bucket?: string): string;
112
+ /** Generate a time-limited signed URL for private buckets. */
113
+ createSignedUrl(path: string, expiresInSec?: number, bucket?: string): Promise<string>;
114
+ /** Delete one or more objects. */
115
+ remove(paths: string | string[], bucket?: string): Promise<void>;
116
+ /** List objects in a bucket prefix. */
117
+ list(prefix?: string, bucket?: string): Promise<_supabase_storage_js.FileObject[]>;
118
+ };
119
+
120
+ /** PascalCase → snake_case + naive pluralization (s, ies, es). */
121
+ declare function defaultEntityToTable(entityName: string): string;
122
+ declare function resolveEntityMapping(entityName: string, opts: Required<Pick<ClientOptions, 'schemaPrefix'>> & Pick<ClientOptions, 'sharedSchema' | 'sharedEntities' | 'entityMap'>): EntityMapping;
123
+ /**
124
+ * Parse Base44-style orderBy:
125
+ * - string '-created_date' → { field: 'created_date', ascending: false }
126
+ * - string 'name' → { field: 'name', ascending: true }
127
+ * - object passes through.
128
+ */
129
+ declare function parseOrderBy(input: string | OrderBy | undefined): OrderBy | undefined;
130
+
131
+ interface ExtendedClientOptions extends ClientOptions {
132
+ /** Auth-related options (login redirect path, etc). */
133
+ authOptions?: AuthOptions;
134
+ /** Integration stub configuration (storage default bucket, edge function names). */
135
+ integrations?: Partial<IntegrationsOptions>;
136
+ }
137
+ interface Base44Client {
138
+ /** Underlying Supabase client (anon key). */
139
+ supabase: SupabaseClient;
140
+ entities: EntitiesProxy;
141
+ auth: ReturnType<typeof makeAuth>;
142
+ functions: ReturnType<typeof makeFunctions>;
143
+ storage: ReturnType<typeof makeStorage>;
144
+ integrations: ReturnType<typeof makeIntegrations>;
145
+ /** Per-page activity logger. Writes to core.audit_log; errors are swallowed. */
146
+ appLogs: ReturnType<typeof makeAppLogs>;
147
+ /** Admin user management; browser-side calls throw (use Studio instead). */
148
+ users: ReturnType<typeof makeUsers>;
149
+ /** Empty placeholder for base44.app property access. */
150
+ app: Record<string, unknown>;
151
+ /** Service-role-scoped namespace for trusted server contexts. Throws if no service key supplied. */
152
+ asServiceRole: {
153
+ entities: EntitiesProxy;
154
+ };
155
+ }
156
+ /** Create a Base44-compatible client backed by Supabase. */
157
+ declare function createClient(options: ExtendedClientOptions): Base44Client;
158
+
159
+ export { type Base44Client, ClientOptions, EntitiesProxy, EntityMapping, type ExtendedClientOptions, OrderBy, createClient, defaultEntityToTable, parseOrderBy, resolveEntityMapping };
@@ -0,0 +1,159 @@
1
+ import { SupabaseClient } from '@supabase/supabase-js';
2
+ import * as _supabase_auth_js from '@supabase/auth-js';
3
+ import { makeIntegrations, IntegrationsOptions } from './integrations.js';
4
+ import * as _supabase_storage_js from '@supabase/storage-js';
5
+ import { O as OrderBy, C as ClientOptions, E as EntityMapping, a as EntitiesProxy } from './types-HIZDZaWa.js';
6
+ export { b as EntityApi, F as FilterObject, c as FilterValue, J as Json, M as MongoFilter } from './types-HIZDZaWa.js';
7
+
8
+ interface SignInArgs {
9
+ email: string;
10
+ password: string;
11
+ }
12
+ interface SignUpArgs {
13
+ email: string;
14
+ password: string;
15
+ metadata?: Record<string, unknown>;
16
+ }
17
+ interface AuthOptions {
18
+ /**
19
+ * Browser path the redirectToLogin() shim should send users to.
20
+ * Default: '/login'.
21
+ */
22
+ loginPath?: string;
23
+ }
24
+ declare function makeAuth(client: SupabaseClient, opts?: AuthOptions): {
25
+ signIn({ email, password }: SignInArgs): Promise<{
26
+ user: _supabase_auth_js.User;
27
+ session: _supabase_auth_js.Session;
28
+ weakPassword?: _supabase_auth_js.WeakPassword;
29
+ }>;
30
+ signUp({ email, password, metadata }: SignUpArgs): Promise<{
31
+ user: _supabase_auth_js.User | null;
32
+ session: _supabase_auth_js.Session | null;
33
+ }>;
34
+ signOut(): Promise<void>;
35
+ /** Base44 alias for signOut. */
36
+ logout(): Promise<void>;
37
+ getUser(): Promise<_supabase_auth_js.User>;
38
+ /** Base44 alias for getUser. Returns the current user object or throws if not signed in. */
39
+ me(): Promise<_supabase_auth_js.User>;
40
+ /**
41
+ * Base44 alias for updating the current user's metadata. Accepts arbitrary
42
+ * key/value pairs that get stored in `user_metadata`.
43
+ */
44
+ updateMe(metadata: Record<string, unknown>): Promise<_supabase_auth_js.User>;
45
+ getSession(): Promise<_supabase_auth_js.Session | null>;
46
+ /**
47
+ * Base44 used to redirect SPA users to its hosted login page. Self-host
48
+ * has no hosted login, so this just navigates to the configured local
49
+ * loginPath. Override the path via createClient({ ..., authLoginPath: '/x' }).
50
+ */
51
+ redirectToLogin(returnUrl?: string): void;
52
+ onAuthStateChange(cb: Parameters<SupabaseClient["auth"]["onAuthStateChange"]>[0]): {
53
+ data: {
54
+ subscription: _supabase_auth_js.Subscription;
55
+ };
56
+ };
57
+ };
58
+
59
+ /** Mirror of base44.functions — Supabase Edge Functions invoke wrapper.
60
+ *
61
+ * Returns the raw body. On HTTP error, throws an Error with the response body attached.
62
+ */
63
+ declare function makeFunctions(client: SupabaseClient): {
64
+ /** Invoke an edge function by name, passing JSON body. Returns parsed JSON. */
65
+ invoke<T = unknown>(name: string, payload?: Record<string, unknown>): Promise<T>;
66
+ /** Lower-level: invoke and return Response so caller can handle non-JSON. */
67
+ fetch(name: string, init?: RequestInit): Promise<Response>;
68
+ };
69
+
70
+ /**
71
+ * Stub for `base44.appLogs` — Base44 cloud's per-page activity tracker.
72
+ * Writes a row to core.audit_log if the table exists, otherwise silently
73
+ * succeeds. App code wraps this in .catch(() => {}) anyway, so any failure
74
+ * is non-fatal.
75
+ */
76
+ declare function makeAppLogs(client: SupabaseClient, app: string): {
77
+ logUserInApp(pageName: string): Promise<void>;
78
+ };
79
+ /**
80
+ * Stub for `base44.users` — admin-only user management. Self-host equivalent
81
+ * uses Supabase Auth admin API but requires a service_role key, which the
82
+ * browser client doesn't have. So inviteUser here logs a warning and returns
83
+ * a benign error so callers can show a "not supported" message.
84
+ */
85
+ declare function makeUsers(): {
86
+ inviteUser(_args: {
87
+ email: string;
88
+ [key: string]: unknown;
89
+ }): Promise<never>;
90
+ };
91
+
92
+ interface UploadFileArgs {
93
+ /** Supabase Storage bucket name. Defaults to schemaPrefix from client options. */
94
+ bucket?: string;
95
+ /** Object path within the bucket (e.g. 'invoices/2026/inv-001.pdf'). */
96
+ path: string;
97
+ /** File contents. */
98
+ file: Blob | File | ArrayBuffer | Uint8Array;
99
+ /** Content-Type. Inferred from File if omitted. */
100
+ contentType?: string;
101
+ /** Overwrite existing object at path. Default false. */
102
+ upsert?: boolean;
103
+ }
104
+ declare function makeStorage(client: SupabaseClient, defaultBucket: string): {
105
+ /** Upload a file to a bucket. Returns the public URL. */
106
+ uploadFile({ bucket, path, file, contentType, upsert, }: UploadFileArgs): Promise<{
107
+ path: string;
108
+ url: string;
109
+ }>;
110
+ /** Get a public URL for a stored object. */
111
+ getPublicUrl(path: string, bucket?: string): string;
112
+ /** Generate a time-limited signed URL for private buckets. */
113
+ createSignedUrl(path: string, expiresInSec?: number, bucket?: string): Promise<string>;
114
+ /** Delete one or more objects. */
115
+ remove(paths: string | string[], bucket?: string): Promise<void>;
116
+ /** List objects in a bucket prefix. */
117
+ list(prefix?: string, bucket?: string): Promise<_supabase_storage_js.FileObject[]>;
118
+ };
119
+
120
+ /** PascalCase → snake_case + naive pluralization (s, ies, es). */
121
+ declare function defaultEntityToTable(entityName: string): string;
122
+ declare function resolveEntityMapping(entityName: string, opts: Required<Pick<ClientOptions, 'schemaPrefix'>> & Pick<ClientOptions, 'sharedSchema' | 'sharedEntities' | 'entityMap'>): EntityMapping;
123
+ /**
124
+ * Parse Base44-style orderBy:
125
+ * - string '-created_date' → { field: 'created_date', ascending: false }
126
+ * - string 'name' → { field: 'name', ascending: true }
127
+ * - object passes through.
128
+ */
129
+ declare function parseOrderBy(input: string | OrderBy | undefined): OrderBy | undefined;
130
+
131
+ interface ExtendedClientOptions extends ClientOptions {
132
+ /** Auth-related options (login redirect path, etc). */
133
+ authOptions?: AuthOptions;
134
+ /** Integration stub configuration (storage default bucket, edge function names). */
135
+ integrations?: Partial<IntegrationsOptions>;
136
+ }
137
+ interface Base44Client {
138
+ /** Underlying Supabase client (anon key). */
139
+ supabase: SupabaseClient;
140
+ entities: EntitiesProxy;
141
+ auth: ReturnType<typeof makeAuth>;
142
+ functions: ReturnType<typeof makeFunctions>;
143
+ storage: ReturnType<typeof makeStorage>;
144
+ integrations: ReturnType<typeof makeIntegrations>;
145
+ /** Per-page activity logger. Writes to core.audit_log; errors are swallowed. */
146
+ appLogs: ReturnType<typeof makeAppLogs>;
147
+ /** Admin user management; browser-side calls throw (use Studio instead). */
148
+ users: ReturnType<typeof makeUsers>;
149
+ /** Empty placeholder for base44.app property access. */
150
+ app: Record<string, unknown>;
151
+ /** Service-role-scoped namespace for trusted server contexts. Throws if no service key supplied. */
152
+ asServiceRole: {
153
+ entities: EntitiesProxy;
154
+ };
155
+ }
156
+ /** Create a Base44-compatible client backed by Supabase. */
157
+ declare function createClient(options: ExtendedClientOptions): Base44Client;
158
+
159
+ export { type Base44Client, ClientOptions, EntitiesProxy, EntityMapping, type ExtendedClientOptions, OrderBy, createClient, defaultEntityToTable, parseOrderBy, resolveEntityMapping };
package/dist/index.js ADDED
@@ -0,0 +1,249 @@
1
+ import {
2
+ makeIntegrations
3
+ } from "./chunk-PUROQAXO.js";
4
+ import {
5
+ defaultEntityToTable,
6
+ makeEntitiesProxy,
7
+ parseOrderBy,
8
+ resolveEntityMapping
9
+ } from "./chunk-SWURHLDN.js";
10
+
11
+ // src/index.ts
12
+ import { createClient as createSupabase } from "@supabase/supabase-js";
13
+
14
+ // src/auth.ts
15
+ function makeAuth(client, opts = {}) {
16
+ const loginPath = opts.loginPath ?? "/login";
17
+ return {
18
+ async signIn({ email, password }) {
19
+ const { data, error } = await client.auth.signInWithPassword({ email, password });
20
+ if (error) throw error;
21
+ return data;
22
+ },
23
+ async signUp({ email, password, metadata }) {
24
+ const { data, error } = await client.auth.signUp({
25
+ email,
26
+ password,
27
+ options: { data: metadata ?? {} }
28
+ });
29
+ if (error) throw error;
30
+ return data;
31
+ },
32
+ async signOut() {
33
+ const { error } = await client.auth.signOut();
34
+ if (error) throw error;
35
+ },
36
+ /** Base44 alias for signOut. */
37
+ async logout() {
38
+ const { error } = await client.auth.signOut();
39
+ if (error) throw error;
40
+ },
41
+ async getUser() {
42
+ const { data, error } = await client.auth.getUser();
43
+ if (error) throw error;
44
+ return data.user;
45
+ },
46
+ /** Base44 alias for getUser. Returns the current user object or throws if not signed in. */
47
+ async me() {
48
+ const { data, error } = await client.auth.getUser();
49
+ if (error) throw error;
50
+ if (!data.user) throw new Error("Not authenticated");
51
+ return data.user;
52
+ },
53
+ /**
54
+ * Base44 alias for updating the current user's metadata. Accepts arbitrary
55
+ * key/value pairs that get stored in `user_metadata`.
56
+ */
57
+ async updateMe(metadata) {
58
+ const { data, error } = await client.auth.updateUser({ data: metadata });
59
+ if (error) throw error;
60
+ return data.user;
61
+ },
62
+ async getSession() {
63
+ const { data, error } = await client.auth.getSession();
64
+ if (error) throw error;
65
+ return data.session;
66
+ },
67
+ /**
68
+ * Base44 used to redirect SPA users to its hosted login page. Self-host
69
+ * has no hosted login, so this just navigates to the configured local
70
+ * loginPath. Override the path via createClient({ ..., authLoginPath: '/x' }).
71
+ */
72
+ redirectToLogin(returnUrl) {
73
+ if (typeof window === "undefined") return;
74
+ if (window.location.pathname === loginPath) return;
75
+ let safeReturn = returnUrl;
76
+ if (safeReturn) {
77
+ const looksCyclic = safeReturn.includes(`${loginPath}?next=`) || safeReturn.includes(`${loginPath}%3F`);
78
+ if (looksCyclic || safeReturn.length > 1024) safeReturn = void 0;
79
+ }
80
+ const url = safeReturn ? `${loginPath}?next=${encodeURIComponent(safeReturn)}` : loginPath;
81
+ window.location.assign(url);
82
+ },
83
+ onAuthStateChange(cb) {
84
+ return client.auth.onAuthStateChange(cb);
85
+ }
86
+ };
87
+ }
88
+
89
+ // src/functions.ts
90
+ function makeFunctions(client) {
91
+ return {
92
+ /** Invoke an edge function by name, passing JSON body. Returns parsed JSON. */
93
+ async invoke(name, payload) {
94
+ const { data, error } = await client.functions.invoke(name, {
95
+ body: payload
96
+ });
97
+ if (error) throw error;
98
+ return data;
99
+ },
100
+ /** Lower-level: invoke and return Response so caller can handle non-JSON. */
101
+ async fetch(name, init) {
102
+ const url = `${client.supabaseUrl}/functions/v1/${name}`;
103
+ const headers = new Headers(init?.headers);
104
+ const session = await client.auth.getSession();
105
+ const token = session.data.session?.access_token;
106
+ if (token) headers.set("Authorization", `Bearer ${token}`);
107
+ headers.set("apikey", client.supabaseKey);
108
+ return fetch(url, { ...init, headers });
109
+ }
110
+ };
111
+ }
112
+
113
+ // src/misc.ts
114
+ function makeAppLogs(client, app2) {
115
+ return {
116
+ async logUserInApp(pageName) {
117
+ try {
118
+ await client.schema("core").from("audit_logs").insert({
119
+ app: app2,
120
+ action: "page_view",
121
+ module: pageName
122
+ });
123
+ } catch {
124
+ }
125
+ }
126
+ };
127
+ }
128
+ function makeUsers() {
129
+ return {
130
+ async inviteUser(_args) {
131
+ throw new Error(
132
+ "inviteUser is admin-only and not exposed to the browser shim. Use the Studio dashboard or an edge function with service_role to invite users."
133
+ );
134
+ }
135
+ };
136
+ }
137
+ var app = {};
138
+
139
+ // src/storage.ts
140
+ function makeStorage(client, defaultBucket) {
141
+ return {
142
+ /** Upload a file to a bucket. Returns the public URL. */
143
+ async uploadFile({
144
+ bucket,
145
+ path,
146
+ file,
147
+ contentType,
148
+ upsert = false
149
+ }) {
150
+ const b = bucket ?? defaultBucket;
151
+ const { error } = await client.storage.from(b).upload(path, file, {
152
+ contentType,
153
+ upsert
154
+ });
155
+ if (error) throw error;
156
+ const { data } = client.storage.from(b).getPublicUrl(path);
157
+ return { path, url: data.publicUrl };
158
+ },
159
+ /** Get a public URL for a stored object. */
160
+ getPublicUrl(path, bucket) {
161
+ const b = bucket ?? defaultBucket;
162
+ const { data } = client.storage.from(b).getPublicUrl(path);
163
+ return data.publicUrl;
164
+ },
165
+ /** Generate a time-limited signed URL for private buckets. */
166
+ async createSignedUrl(path, expiresInSec = 3600, bucket) {
167
+ const b = bucket ?? defaultBucket;
168
+ const { data, error } = await client.storage.from(b).createSignedUrl(path, expiresInSec);
169
+ if (error) throw error;
170
+ return data.signedUrl;
171
+ },
172
+ /** Delete one or more objects. */
173
+ async remove(paths, bucket) {
174
+ const b = bucket ?? defaultBucket;
175
+ const list = Array.isArray(paths) ? paths : [paths];
176
+ const { error } = await client.storage.from(b).remove(list);
177
+ if (error) throw error;
178
+ },
179
+ /** List objects in a bucket prefix. */
180
+ async list(prefix, bucket) {
181
+ const b = bucket ?? defaultBucket;
182
+ const { data, error } = await client.storage.from(b).list(prefix);
183
+ if (error) throw error;
184
+ return data ?? [];
185
+ }
186
+ };
187
+ }
188
+
189
+ // src/index.ts
190
+ function createClient(options) {
191
+ if (!options.supabaseUrl) throw new Error("createClient: supabaseUrl is required");
192
+ if (!options.supabaseAnonKey) throw new Error("createClient: supabaseAnonKey is required");
193
+ if (!options.schemaPrefix) throw new Error("createClient: schemaPrefix is required");
194
+ const supabase = options.client ?? createSupabase(options.supabaseUrl, options.supabaseAnonKey);
195
+ const entities = makeEntitiesProxy(supabase, {
196
+ schemaPrefix: options.schemaPrefix,
197
+ sharedSchema: options.sharedSchema,
198
+ sharedEntities: options.sharedEntities,
199
+ entityMap: options.entityMap
200
+ });
201
+ const asServiceRole = /* @__PURE__ */ (() => {
202
+ let serviceClient = null;
203
+ let serviceEntities = null;
204
+ return {
205
+ get entities() {
206
+ if (!options.supabaseServiceRoleKey) {
207
+ throw new Error(
208
+ "asServiceRole.entities accessed but supabaseServiceRoleKey was not provided. Only set this in trusted server contexts (edge functions, scripts)."
209
+ );
210
+ }
211
+ if (!serviceClient) {
212
+ serviceClient = createSupabase(options.supabaseUrl, options.supabaseServiceRoleKey);
213
+ }
214
+ if (!serviceEntities) {
215
+ serviceEntities = makeEntitiesProxy(serviceClient, {
216
+ schemaPrefix: options.schemaPrefix,
217
+ sharedSchema: options.sharedSchema,
218
+ sharedEntities: options.sharedEntities,
219
+ entityMap: options.entityMap
220
+ });
221
+ }
222
+ return serviceEntities;
223
+ }
224
+ };
225
+ })();
226
+ return {
227
+ supabase,
228
+ entities,
229
+ auth: makeAuth(supabase, options.authOptions),
230
+ functions: makeFunctions(supabase),
231
+ storage: makeStorage(supabase, options.schemaPrefix),
232
+ integrations: makeIntegrations(supabase, {
233
+ defaultBucket: options.integrations?.defaultBucket ?? options.schemaPrefix,
234
+ sendEmailFunction: options.integrations?.sendEmailFunction,
235
+ invokeLlmFunction: options.integrations?.invokeLlmFunction
236
+ }),
237
+ appLogs: makeAppLogs(supabase, options.schemaPrefix),
238
+ users: makeUsers(),
239
+ app,
240
+ asServiceRole
241
+ };
242
+ }
243
+ export {
244
+ createClient,
245
+ defaultEntityToTable,
246
+ parseOrderBy,
247
+ resolveEntityMapping
248
+ };
249
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/auth.ts","../src/functions.ts","../src/misc.ts","../src/storage.ts"],"sourcesContent":["import { createClient as createSupabase, type SupabaseClient } from '@supabase/supabase-js';\nimport { makeAuth, type AuthOptions } from './auth.js';\nimport { makeEntitiesProxy } from './entities.js';\nimport { makeFunctions } from './functions.js';\nimport { makeIntegrations, type IntegrationsOptions } from './integrations.js';\nimport { app, makeAppLogs, makeUsers } from './misc.js';\nimport { makeStorage } from './storage.js';\nimport type { ClientOptions, EntitiesProxy } from './types.js';\n\nexport type * from './types.js';\nexport { defaultEntityToTable, resolveEntityMapping, parseOrderBy } from './entities.js';\n\nexport interface ExtendedClientOptions extends ClientOptions {\n /** Auth-related options (login redirect path, etc). */\n authOptions?: AuthOptions;\n /** Integration stub configuration (storage default bucket, edge function names). */\n integrations?: Partial<IntegrationsOptions>;\n}\n\nexport interface Base44Client {\n /** Underlying Supabase client (anon key). */\n supabase: SupabaseClient;\n entities: EntitiesProxy;\n auth: ReturnType<typeof makeAuth>;\n functions: ReturnType<typeof makeFunctions>;\n storage: ReturnType<typeof makeStorage>;\n integrations: ReturnType<typeof makeIntegrations>;\n /** Per-page activity logger. Writes to core.audit_log; errors are swallowed. */\n appLogs: ReturnType<typeof makeAppLogs>;\n /** Admin user management; browser-side calls throw (use Studio instead). */\n users: ReturnType<typeof makeUsers>;\n /** Empty placeholder for base44.app property access. */\n app: Record<string, unknown>;\n /** Service-role-scoped namespace for trusted server contexts. Throws if no service key supplied. */\n asServiceRole: { entities: EntitiesProxy };\n}\n\n/** Create a Base44-compatible client backed by Supabase. */\nexport function createClient(options: ExtendedClientOptions): Base44Client {\n if (!options.supabaseUrl) throw new Error('createClient: supabaseUrl is required');\n if (!options.supabaseAnonKey) throw new Error('createClient: supabaseAnonKey is required');\n if (!options.schemaPrefix) throw new Error('createClient: schemaPrefix is required');\n\n const supabase =\n options.client ?? createSupabase(options.supabaseUrl, options.supabaseAnonKey);\n\n const entities = makeEntitiesProxy(supabase, {\n schemaPrefix: options.schemaPrefix,\n sharedSchema: options.sharedSchema,\n sharedEntities: options.sharedEntities,\n entityMap: options.entityMap,\n });\n\n const asServiceRole = (() => {\n let serviceClient: SupabaseClient | null = null;\n let serviceEntities: EntitiesProxy | null = null;\n return {\n get entities(): EntitiesProxy {\n if (!options.supabaseServiceRoleKey) {\n throw new Error(\n 'asServiceRole.entities accessed but supabaseServiceRoleKey was not provided. ' +\n 'Only set this in trusted server contexts (edge functions, scripts).',\n );\n }\n if (!serviceClient) {\n serviceClient = createSupabase(options.supabaseUrl, options.supabaseServiceRoleKey);\n }\n if (!serviceEntities) {\n serviceEntities = makeEntitiesProxy(serviceClient, {\n schemaPrefix: options.schemaPrefix,\n sharedSchema: options.sharedSchema,\n sharedEntities: options.sharedEntities,\n entityMap: options.entityMap,\n });\n }\n return serviceEntities;\n },\n };\n })();\n\n return {\n supabase,\n entities,\n auth: makeAuth(supabase, options.authOptions),\n functions: makeFunctions(supabase),\n storage: makeStorage(supabase, options.schemaPrefix),\n integrations: makeIntegrations(supabase, {\n defaultBucket: options.integrations?.defaultBucket ?? options.schemaPrefix,\n sendEmailFunction: options.integrations?.sendEmailFunction,\n invokeLlmFunction: options.integrations?.invokeLlmFunction,\n }),\n appLogs: makeAppLogs(supabase, options.schemaPrefix),\n users: makeUsers(),\n app,\n asServiceRole,\n };\n}\n","import type { SupabaseClient } from '@supabase/supabase-js';\n\nexport interface SignInArgs {\n email: string;\n password: string;\n}\n\nexport interface SignUpArgs {\n email: string;\n password: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface AuthOptions {\n /**\n * Browser path the redirectToLogin() shim should send users to.\n * Default: '/login'.\n */\n loginPath?: string;\n}\n\nexport function makeAuth(client: SupabaseClient, opts: AuthOptions = {}) {\n const loginPath = opts.loginPath ?? '/login';\n\n return {\n async signIn({ email, password }: SignInArgs) {\n const { data, error } = await client.auth.signInWithPassword({ email, password });\n if (error) throw error;\n return data;\n },\n async signUp({ email, password, metadata }: SignUpArgs) {\n const { data, error } = await client.auth.signUp({\n email,\n password,\n options: { data: metadata ?? {} },\n });\n if (error) throw error;\n return data;\n },\n async signOut() {\n const { error } = await client.auth.signOut();\n if (error) throw error;\n },\n /** Base44 alias for signOut. */\n async logout() {\n const { error } = await client.auth.signOut();\n if (error) throw error;\n },\n async getUser() {\n const { data, error } = await client.auth.getUser();\n if (error) throw error;\n return data.user;\n },\n /** Base44 alias for getUser. Returns the current user object or throws if not signed in. */\n async me() {\n const { data, error } = await client.auth.getUser();\n if (error) throw error;\n if (!data.user) throw new Error('Not authenticated');\n return data.user;\n },\n /**\n * Base44 alias for updating the current user's metadata. Accepts arbitrary\n * key/value pairs that get stored in `user_metadata`.\n */\n async updateMe(metadata: Record<string, unknown>) {\n const { data, error } = await client.auth.updateUser({ data: metadata });\n if (error) throw error;\n return data.user;\n },\n async getSession() {\n const { data, error } = await client.auth.getSession();\n if (error) throw error;\n return data.session;\n },\n /**\n * Base44 used to redirect SPA users to its hosted login page. Self-host\n * has no hosted login, so this just navigates to the configured local\n * loginPath. Override the path via createClient({ ..., authLoginPath: '/x' }).\n */\n redirectToLogin(returnUrl?: string) {\n if (typeof window === 'undefined') return;\n // Already on the login route → no-op. Prevents redirect loops when an\n // unauthenticated check on /login itself fires another redirectToLogin.\n if (window.location.pathname === loginPath) return;\n // Defensive: if the returnUrl already points back to a login page (cyclic\n // chain from old buggy state), drop it. Also drop if it's absurdly long.\n let safeReturn: string | undefined = returnUrl;\n if (safeReturn) {\n const looksCyclic = safeReturn.includes(`${loginPath}?next=`) || safeReturn.includes(`${loginPath}%3F`);\n if (looksCyclic || safeReturn.length > 1024) safeReturn = undefined;\n }\n const url = safeReturn\n ? `${loginPath}?next=${encodeURIComponent(safeReturn)}`\n : loginPath;\n window.location.assign(url);\n },\n onAuthStateChange(cb: Parameters<SupabaseClient['auth']['onAuthStateChange']>[0]) {\n return client.auth.onAuthStateChange(cb);\n },\n };\n}\n","import type { SupabaseClient } from '@supabase/supabase-js';\n\n/** Mirror of base44.functions — Supabase Edge Functions invoke wrapper.\n *\n * Returns the raw body. On HTTP error, throws an Error with the response body attached.\n */\nexport function makeFunctions(client: SupabaseClient) {\n return {\n /** Invoke an edge function by name, passing JSON body. Returns parsed JSON. */\n async invoke<T = unknown>(name: string, payload?: Record<string, unknown>): Promise<T> {\n const { data, error } = await client.functions.invoke<T>(name, {\n body: payload,\n });\n if (error) throw error;\n return data as T;\n },\n /** Lower-level: invoke and return Response so caller can handle non-JSON. */\n async fetch(name: string, init?: RequestInit): Promise<Response> {\n const url = `${(client as unknown as { supabaseUrl: string }).supabaseUrl}/functions/v1/${name}`;\n const headers = new Headers(init?.headers);\n const session = await client.auth.getSession();\n const token = session.data.session?.access_token;\n if (token) headers.set('Authorization', `Bearer ${token}`);\n headers.set('apikey', (client as unknown as { supabaseKey: string }).supabaseKey);\n return fetch(url, { ...init, headers });\n },\n };\n}\n","import type { SupabaseClient } from '@supabase/supabase-js';\n\n/**\n * Stub for `base44.appLogs` — Base44 cloud's per-page activity tracker.\n * Writes a row to core.audit_log if the table exists, otherwise silently\n * succeeds. App code wraps this in .catch(() => {}) anyway, so any failure\n * is non-fatal.\n */\nexport function makeAppLogs(client: SupabaseClient, app: string) {\n return {\n async logUserInApp(pageName: string): Promise<void> {\n try {\n await client.schema('core' as never).from('audit_logs').insert({\n app,\n action: 'page_view',\n module: pageName,\n });\n } catch {\n // best-effort; analytics errors must never break the app\n }\n },\n };\n}\n\n/**\n * Stub for `base44.users` — admin-only user management. Self-host equivalent\n * uses Supabase Auth admin API but requires a service_role key, which the\n * browser client doesn't have. So inviteUser here logs a warning and returns\n * a benign error so callers can show a \"not supported\" message.\n */\nexport function makeUsers() {\n return {\n async inviteUser(_args: { email: string; [key: string]: unknown }): Promise<never> {\n throw new Error(\n 'inviteUser is admin-only and not exposed to the browser shim. ' +\n 'Use the Studio dashboard or an edge function with service_role to invite users.',\n );\n },\n };\n}\n\n/** Empty placeholder for `base44.app` — kept defined so property access doesn't crash. */\nexport const app: Record<string, unknown> = {};\n","import type { SupabaseClient } from '@supabase/supabase-js';\n\nexport interface UploadFileArgs {\n /** Supabase Storage bucket name. Defaults to schemaPrefix from client options. */\n bucket?: string;\n /** Object path within the bucket (e.g. 'invoices/2026/inv-001.pdf'). */\n path: string;\n /** File contents. */\n file: Blob | File | ArrayBuffer | Uint8Array;\n /** Content-Type. Inferred from File if omitted. */\n contentType?: string;\n /** Overwrite existing object at path. Default false. */\n upsert?: boolean;\n}\n\nexport function makeStorage(client: SupabaseClient, defaultBucket: string) {\n return {\n /** Upload a file to a bucket. Returns the public URL. */\n async uploadFile({\n bucket,\n path,\n file,\n contentType,\n upsert = false,\n }: UploadFileArgs): Promise<{ path: string; url: string }> {\n const b = bucket ?? defaultBucket;\n const { error } = await client.storage.from(b).upload(path, file, {\n contentType,\n upsert,\n });\n if (error) throw error;\n const { data } = client.storage.from(b).getPublicUrl(path);\n return { path, url: data.publicUrl };\n },\n /** Get a public URL for a stored object. */\n getPublicUrl(path: string, bucket?: string): string {\n const b = bucket ?? defaultBucket;\n const { data } = client.storage.from(b).getPublicUrl(path);\n return data.publicUrl;\n },\n /** Generate a time-limited signed URL for private buckets. */\n async createSignedUrl(path: string, expiresInSec = 3600, bucket?: string): Promise<string> {\n const b = bucket ?? defaultBucket;\n const { data, error } = await client.storage.from(b).createSignedUrl(path, expiresInSec);\n if (error) throw error;\n return data.signedUrl;\n },\n /** Delete one or more objects. */\n async remove(paths: string | string[], bucket?: string): Promise<void> {\n const b = bucket ?? defaultBucket;\n const list = Array.isArray(paths) ? paths : [paths];\n const { error } = await client.storage.from(b).remove(list);\n if (error) throw error;\n },\n /** List objects in a bucket prefix. */\n async list(prefix?: string, bucket?: string) {\n const b = bucket ?? defaultBucket;\n const { data, error } = await client.storage.from(b).list(prefix);\n if (error) throw error;\n return data ?? [];\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,gBAAgB,sBAA2C;;;ACqB7D,SAAS,SAAS,QAAwB,OAAoB,CAAC,GAAG;AACvE,QAAM,YAAY,KAAK,aAAa;AAEpC,SAAO;AAAA,IACL,MAAM,OAAO,EAAE,OAAO,SAAS,GAAe;AAC5C,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK,mBAAmB,EAAE,OAAO,SAAS,CAAC;AAChF,UAAI,MAAO,OAAM;AACjB,aAAO;AAAA,IACT;AAAA,IACA,MAAM,OAAO,EAAE,OAAO,UAAU,SAAS,GAAe;AACtD,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK,OAAO;AAAA,QAC/C;AAAA,QACA;AAAA,QACA,SAAS,EAAE,MAAM,YAAY,CAAC,EAAE;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SAAS,YAAY,UAAU,QAAQ,YAAY;AAAA,IACnD,cAAc,iBAAiB,UAAU;AAAA,MACvC,eAAe,QAAQ,cAAc,iBAAiB,QAAQ;AAAA,MAC9D,mBAAmB,QAAQ,cAAc;AAAA,MACzC,mBAAmB,QAAQ,cAAc;AAAA,IAC3C,CAAC;AAAA,IACD,SAAS,YAAY,UAAU,QAAQ,YAAY;AAAA,IACnD,OAAO,UAAU;AAAA,IACjB;AAAA,IACA;AAAA,EACF;AACF;","names":["app"]}
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/integrations.ts
21
+ var integrations_exports = {};
22
+ __export(integrations_exports, {
23
+ makeIntegrations: () => makeIntegrations
24
+ });
25
+ module.exports = __toCommonJS(integrations_exports);
26
+ function makeIntegrations(client, opts) {
27
+ const Core = {
28
+ async UploadFile({
29
+ file,
30
+ bucket,
31
+ path,
32
+ contentType
33
+ }) {
34
+ const b = bucket ?? opts.defaultBucket;
35
+ const p = path ?? `uploads/${Date.now()}-${Math.random().toString(36).slice(2, 8)}-${file?.name ?? "file"}`;
36
+ const { error } = await client.storage.from(b).upload(p, file, {
37
+ contentType: contentType ?? file?.type,
38
+ upsert: false
39
+ });
40
+ if (error) throw error;
41
+ const { data } = client.storage.from(b).getPublicUrl(p);
42
+ return { url: data.publicUrl, path: p };
43
+ },
44
+ async SendEmail(payload) {
45
+ if (!opts.sendEmailFunction) {
46
+ throw new Error(
47
+ "SendEmail not configured. Set integrations.sendEmailFunction in createClient() and deploy a corresponding Supabase Edge Function (e.g. send-email)."
48
+ );
49
+ }
50
+ const { error } = await client.functions.invoke(opts.sendEmailFunction, { body: payload });
51
+ if (error) throw error;
52
+ return { ok: true };
53
+ },
54
+ async InvokeLLM(payload) {
55
+ if (!opts.invokeLlmFunction) {
56
+ throw new Error(
57
+ "InvokeLLM not configured. AI features are disabled in this self-host build. Set integrations.invokeLlmFunction in createClient() and deploy an edge function that proxies to your LLM endpoint (Ollama / internal gateway)."
58
+ );
59
+ }
60
+ const { data, error } = await client.functions.invoke(opts.invokeLlmFunction, {
61
+ body: payload
62
+ });
63
+ if (error) throw error;
64
+ return data;
65
+ }
66
+ };
67
+ return { Core };
68
+ }
69
+ // Annotate the CommonJS export names for ESM import in node:
70
+ 0 && (module.exports = {
71
+ makeIntegrations
72
+ });
73
+ //# sourceMappingURL=integrations.cjs.map