@mitway/sdk 0.5.0 → 0.7.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/dist/index.d.cts CHANGED
@@ -34,15 +34,56 @@ interface User {
34
34
  * Token Manager for the MITWAY-BaaS SDK.
35
35
  *
36
36
  * Stores the access token + user in memory and optionally persists them
37
- * to `localStorage` so sessions survive page reloads (F5). Browser CSRF
38
- * token lives in a cookie for the cookie-based refresh flow.
37
+ * via a pluggable `StorageAdapter`. By default, a browser-`localStorage`-
38
+ * backed adapter is used (with an SSR-safe noop when `localStorage` is not
39
+ * available). Consumers can inject a custom adapter to back the session
40
+ * with something else: cookies, a native secure store, an SSR cache, an
41
+ * in-memory stub for tests, etc. Browser CSRF token lives in a cookie
42
+ * for the cookie-based refresh flow.
39
43
  */
40
44
 
45
+ /**
46
+ * Synchronous key/value contract consumed by the `TokenManager` to read
47
+ * and write persisted sessions. Intentionally narrow: the three methods
48
+ * are the only primitives the SDK calls. Adapters can freely decide
49
+ * where and how the value is stored (localStorage, cookie jar, native
50
+ * secure storage, in-memory, ...). All methods are sync to match what
51
+ * persisted-session consumers expect on the restore path (F5 reload).
52
+ */
53
+ interface StorageAdapter {
54
+ getItem(key: string): string | null;
55
+ setItem(key: string, value: string): void;
56
+ removeItem(key: string): void;
57
+ }
58
+ /**
59
+ * Default adapter that wraps browser `localStorage`. Degrades to a noop
60
+ * when `localStorage` is not available (Node, SSR, sandboxed iframes
61
+ * with storage access disabled). Exposed so consumers that want to
62
+ * compose on top of the default (e.g. dual-write to cookies) can import
63
+ * it rather than re-implement.
64
+ */
65
+ declare function createLocalStorageAdapter(): StorageAdapter;
41
66
  interface TokenManagerOptions {
42
- /** Persist session to localStorage so it survives page reloads. Default: true. */
67
+ /** Persist session so it survives page reloads. Default: true. */
43
68
  persistSession?: boolean;
44
- /** localStorage key. Default: 'mitway_baas_session'. */
69
+ /** Storage key. Default: 'mitway_baas_session'. */
45
70
  storageKey?: string;
71
+ /**
72
+ * Storage backend. Default: browser `localStorage` (SSR-safe). Pass a
73
+ * custom adapter to back the session with cookies, native secure
74
+ * storage, or an in-memory stub for tests.
75
+ */
76
+ storage?: StorageAdapter;
77
+ /**
78
+ * Sync session state across browser tabs via the `storage` event.
79
+ * When enabled, a sign-in / sign-out / token-refresh performed in one
80
+ * tab is reflected in every other tab sharing the same origin. Only
81
+ * useful when the configured storage is (or wraps) `localStorage` —
82
+ * the browser `storage` event only fires on `localStorage` /
83
+ * `sessionStorage` mutations. Default: true in a browser context,
84
+ * no-op otherwise.
85
+ */
86
+ multiTab?: boolean;
46
87
  }
47
88
  declare class TokenManager {
48
89
  private accessToken;
@@ -50,9 +91,24 @@ declare class TokenManager {
50
91
  private user;
51
92
  private readonly persistSession;
52
93
  private readonly storageKey;
94
+ private readonly storage;
53
95
  /** Fired when the access token changes (used by long-lived consumers). */
54
96
  onTokenChange: (() => void) | null;
55
97
  constructor(opts?: TokenManagerOptions);
98
+ /**
99
+ * Cross-tab storage-event handler. Arrow-bound so `removeEventListener`
100
+ * with the same reference works if the host ever decides to dispose a
101
+ * TokenManager (the SDK itself does not today).
102
+ */
103
+ private handleStorageEvent;
104
+ /**
105
+ * Update in-memory state from a raw storage value (produced by another
106
+ * tab). Fires `onTokenChange` only when the access token actually
107
+ * differs from what we had, so a listener can map this transition onto
108
+ * `SIGNED_IN` / `SIGNED_OUT` / `TOKEN_REFRESHED` the same way it maps
109
+ * transitions from same-tab mutations.
110
+ */
111
+ private syncFromStorage;
56
112
  saveSession(session: AuthSession): void;
57
113
  getSession(): AuthSession | null;
58
114
  getAccessToken(): string | null;
@@ -63,8 +119,8 @@ declare class TokenManager {
63
119
  setUser(user: User): void;
64
120
  clearSession(): void;
65
121
  /**
66
- * Restore the session from localStorage. Returns true if a persisted
67
- * session was found and loaded into memory.
122
+ * Restore the session from the configured storage. Returns true if a
123
+ * persisted session was found and loaded into memory.
68
124
  */
69
125
  restoreSession(): boolean;
70
126
  private persist;
@@ -479,10 +535,26 @@ interface MitwayBaasConfig {
479
535
  */
480
536
  persistSession?: boolean;
481
537
  /**
482
- * `localStorage` key used to persist the session.
538
+ * Storage key used to persist the session.
483
539
  * @default "mitway_baas_session"
484
540
  */
485
541
  storageKey?: string;
542
+ /**
543
+ * Custom persistence backend for the session. Must implement the
544
+ * synchronous `{ getItem, setItem, removeItem }` contract. Default:
545
+ * browser `localStorage` (SSR-safe). Pass a custom adapter to back
546
+ * sessions with cookies, native secure storage, or an in-memory stub
547
+ * for tests. Ignored when `persistSession: false`.
548
+ */
549
+ storage?: StorageAdapter;
550
+ /**
551
+ * Synchronise session state across browser tabs. When the user signs
552
+ * in, signs out, or refreshes their token in tab A, tabs B, C, D
553
+ * sharing the same origin see the change automatically. Only works
554
+ * when the active storage is (or wraps) `localStorage`. Default:
555
+ * true in a browser, no-op otherwise.
556
+ */
557
+ multiTab?: boolean;
486
558
  }
487
559
  /**
488
560
  * Active user session in memory. Mirrors what the auth endpoints return.
@@ -650,10 +722,59 @@ type AuthResult<T> = {
650
722
  data: T | null;
651
723
  error: MitwayBaasError | null;
652
724
  };
725
+ /**
726
+ * Event names emitted by `auth.onAuthStateChange`. Mirrors
727
+ * `@supabase/supabase-js` event names so consumers that already know that
728
+ * contract do not have to re-learn ours.
729
+ *
730
+ * - `INITIAL_SESSION` — emitted once per `auth.initialize()` call
731
+ * regardless of whether a persisted session was found. `session` is
732
+ * non-null when a valid session was restored, null otherwise.
733
+ * - `SIGNED_IN` — a session transitioned from absent to present
734
+ * (after `signUp`, `signInWithPassword`, or a cross-tab storage sync).
735
+ * - `SIGNED_OUT` — a session transitioned from present to absent
736
+ * (`signOut` or cross-tab storage sync).
737
+ * - `TOKEN_REFRESHED` — the access token changed but the user did not
738
+ * (explicit `refreshSession` or the HttpClient's auto-refresh on 401).
739
+ * - `USER_UPDATED` — the user record changed without a token change
740
+ * (`setProfile` or backend-side profile mutation).
741
+ */
742
+ type AuthChangeEvent = 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED' | 'USER_UPDATED';
743
+ type AuthStateChangeCallback = (event: AuthChangeEvent, session: AuthSession | null) => void;
744
+ /** Return value of `onAuthStateChange` — call `unsubscribe()` to remove the listener. */
745
+ interface Subscription {
746
+ unsubscribe: () => void;
747
+ }
653
748
  declare class Auth {
654
749
  private http;
655
750
  private tokenManager;
751
+ /** Registered `onAuthStateChange` callbacks. */
752
+ private stateChangeListeners;
753
+ /**
754
+ * Last-emitted session snapshot — used by `_handleTokenChange` to decide
755
+ * which event to emit (SIGNED_IN vs TOKEN_REFRESHED vs SIGNED_OUT).
756
+ */
757
+ private lastEmittedUserId;
758
+ private lastEmittedAccessToken;
656
759
  constructor(http: HttpClient, tokenManager: TokenManager);
760
+ /**
761
+ * Register a listener for session state transitions. Returns a
762
+ * `Subscription` whose `unsubscribe()` removes the listener. Safe to
763
+ * register after login — the listener does NOT receive an initial
764
+ * replay of the current state; call `getSession()` separately if you
765
+ * need the current value on mount. `INITIAL_SESSION` is emitted once
766
+ * per `auth.initialize()` call and is the standard hook for the first
767
+ * render path.
768
+ */
769
+ onAuthStateChange(callback: AuthStateChangeCallback): Subscription;
770
+ /** Fan out an event to every registered listener. */
771
+ private emit;
772
+ /**
773
+ * Translate a `TokenManager.onTokenChange` signal into an
774
+ * AuthChangeEvent by diffing previous vs current state. No event is
775
+ * emitted if the net effect is a no-op (defensive — shouldn't happen).
776
+ */
777
+ private _emitFromTokenChange;
657
778
  /**
658
779
  * Persist the session in memory + HttpClient defaults so subsequent
659
780
  * requests carry the new bearer token automatically.
@@ -910,6 +1031,80 @@ declare class Storage {
910
1031
  getConfig(): Promise<StorageResult<StorageConfig>>;
911
1032
  }
912
1033
 
1034
+ /**
1035
+ * Functions module -- thin wrapper over the /api/functions/* and /api/invoke/*
1036
+ * REST endpoints exposed by MITWAY-BaaS.
1037
+ *
1038
+ * Manages edge function CRUD, invocation, and secrets. Function invocation
1039
+ * routes through `HttpClient.rawFetch` since `/api/invoke/:slug` is a
1040
+ * transparent proxy that does NOT use the `{ data, error }` envelope.
1041
+ */
1042
+
1043
+ interface EdgeFunction {
1044
+ id: string;
1045
+ slug: string;
1046
+ name: string;
1047
+ description: string | null;
1048
+ code: string;
1049
+ status: 'draft' | 'active' | 'error';
1050
+ createdAt: string;
1051
+ updatedAt: string;
1052
+ deployedAt: string | null;
1053
+ }
1054
+ interface CreateFunctionRequest {
1055
+ name: string;
1056
+ slug?: string;
1057
+ code: string;
1058
+ description?: string;
1059
+ status?: 'draft' | 'active';
1060
+ }
1061
+ interface UpdateFunctionRequest {
1062
+ name?: string;
1063
+ code?: string;
1064
+ description?: string;
1065
+ status?: 'draft' | 'active';
1066
+ }
1067
+ interface FunctionSecret {
1068
+ key: string;
1069
+ digest: string;
1070
+ updatedAt: string;
1071
+ }
1072
+ interface InvokeOptions {
1073
+ method?: string;
1074
+ headers?: Record<string, string>;
1075
+ body?: BodyInit | Record<string, unknown> | null;
1076
+ }
1077
+ type FunctionsResult<T> = {
1078
+ data: T | null;
1079
+ error: MitwayBaasError | null;
1080
+ };
1081
+ declare class Functions {
1082
+ private readonly http;
1083
+ constructor(http: HttpClient);
1084
+ list(): Promise<FunctionsResult<EdgeFunction[]>>;
1085
+ get(slug: string): Promise<FunctionsResult<EdgeFunction>>;
1086
+ create(req: CreateFunctionRequest): Promise<FunctionsResult<EdgeFunction>>;
1087
+ update(slug: string, req: UpdateFunctionRequest): Promise<FunctionsResult<EdgeFunction>>;
1088
+ remove(slug: string): Promise<FunctionsResult<{
1089
+ deleted: true;
1090
+ }>>;
1091
+ /**
1092
+ * Invoke an edge function. The `/api/invoke/:slug` route is a transparent
1093
+ * proxy — no `{ data, error }` envelope. Returns the raw `Response`.
1094
+ *
1095
+ * If `opts.body` is a plain object it is JSON-stringified and
1096
+ * `Content-Type: application/json` is set automatically.
1097
+ */
1098
+ invoke(slug: string, opts?: InvokeOptions): Promise<FunctionsResult<Response>>;
1099
+ listSecrets(): Promise<FunctionsResult<FunctionSecret[]>>;
1100
+ setSecrets(secrets: Record<string, string>): Promise<FunctionsResult<{
1101
+ saved: true;
1102
+ }>>;
1103
+ deleteSecret(key: string): Promise<FunctionsResult<{
1104
+ deleted: true;
1105
+ }>>;
1106
+ }
1107
+
913
1108
  /**
914
1109
  * MITWAY-BaaS SDK client.
915
1110
  *
@@ -944,6 +1139,7 @@ declare class MitwayBaasClient {
944
1139
  readonly database: Database;
945
1140
  readonly realtime: Realtime;
946
1141
  readonly storage: Storage;
1142
+ readonly functions: Functions;
947
1143
  constructor(config?: MitwayBaasConfig);
948
1144
  /**
949
1145
  * Escape hatch for callers that need to make custom requests against the
@@ -956,13 +1152,13 @@ declare class MitwayBaasClient {
956
1152
  * @mitway-baas/sdk — TypeScript SDK for the MITWAY-BaaS backend.
957
1153
  *
958
1154
  * Currently ships:
959
- * - auth (signUp, signInWithPassword, signOut, refreshSession, getSession, getUser)
960
- * - database (PostgREST-backed query builder via @supabase/postgrest-js)
961
- * - realtime (Socket.IO transport: subscribe / unsubscribe / publish / on)
1155
+ * - auth (signUp, signInWithPassword, signOut, refreshSession, getSession, getUser)
1156
+ * - database (PostgREST-backed query builder via @supabase/postgrest-js)
1157
+ * - realtime (Socket.IO transport: subscribe / unsubscribe / publish / on)
1158
+ * - storage (bucket admin + per-bucket object operations)
1159
+ * - functions (edge function CRUD, invoke, secrets management)
962
1160
  *
963
1161
  * Not yet included (no backend support):
964
- * - storage
965
- * - functions
966
1162
  * - email
967
1163
  * - ai
968
1164
  *
@@ -984,4 +1180,4 @@ declare class MitwayBaasClient {
984
1180
  */
985
1181
  declare function createClient(config: MitwayBaasConfig): MitwayBaasClient;
986
1182
 
987
- export { type ApiError, Auth, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type CreateBucketOptions, Database, type DownloadOptions, HttpClient, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, Storage, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, TokenManager, type UpdateBucketOptions, type UploadBody, type UploadOptions, type User, createClient, MitwayBaasClient as default };
1183
+ export { type ApiError, Auth, type AuthChangeEvent, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type AuthStateChangeCallback, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type CreateBucketOptions, type CreateFunctionRequest, Database, type DownloadOptions, type EdgeFunction, type FunctionSecret, Functions, type FunctionsResult, HttpClient, type InvokeOptions, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, Storage, type StorageAdapter, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, type Subscription, TokenManager, type UpdateBucketOptions, type UpdateFunctionRequest, type UploadBody, type UploadOptions, type User, createClient, createLocalStorageAdapter, MitwayBaasClient as default };
package/dist/index.d.ts CHANGED
@@ -34,15 +34,56 @@ interface User {
34
34
  * Token Manager for the MITWAY-BaaS SDK.
35
35
  *
36
36
  * Stores the access token + user in memory and optionally persists them
37
- * to `localStorage` so sessions survive page reloads (F5). Browser CSRF
38
- * token lives in a cookie for the cookie-based refresh flow.
37
+ * via a pluggable `StorageAdapter`. By default, a browser-`localStorage`-
38
+ * backed adapter is used (with an SSR-safe noop when `localStorage` is not
39
+ * available). Consumers can inject a custom adapter to back the session
40
+ * with something else: cookies, a native secure store, an SSR cache, an
41
+ * in-memory stub for tests, etc. Browser CSRF token lives in a cookie
42
+ * for the cookie-based refresh flow.
39
43
  */
40
44
 
45
+ /**
46
+ * Synchronous key/value contract consumed by the `TokenManager` to read
47
+ * and write persisted sessions. Intentionally narrow: the three methods
48
+ * are the only primitives the SDK calls. Adapters can freely decide
49
+ * where and how the value is stored (localStorage, cookie jar, native
50
+ * secure storage, in-memory, ...). All methods are sync to match what
51
+ * persisted-session consumers expect on the restore path (F5 reload).
52
+ */
53
+ interface StorageAdapter {
54
+ getItem(key: string): string | null;
55
+ setItem(key: string, value: string): void;
56
+ removeItem(key: string): void;
57
+ }
58
+ /**
59
+ * Default adapter that wraps browser `localStorage`. Degrades to a noop
60
+ * when `localStorage` is not available (Node, SSR, sandboxed iframes
61
+ * with storage access disabled). Exposed so consumers that want to
62
+ * compose on top of the default (e.g. dual-write to cookies) can import
63
+ * it rather than re-implement.
64
+ */
65
+ declare function createLocalStorageAdapter(): StorageAdapter;
41
66
  interface TokenManagerOptions {
42
- /** Persist session to localStorage so it survives page reloads. Default: true. */
67
+ /** Persist session so it survives page reloads. Default: true. */
43
68
  persistSession?: boolean;
44
- /** localStorage key. Default: 'mitway_baas_session'. */
69
+ /** Storage key. Default: 'mitway_baas_session'. */
45
70
  storageKey?: string;
71
+ /**
72
+ * Storage backend. Default: browser `localStorage` (SSR-safe). Pass a
73
+ * custom adapter to back the session with cookies, native secure
74
+ * storage, or an in-memory stub for tests.
75
+ */
76
+ storage?: StorageAdapter;
77
+ /**
78
+ * Sync session state across browser tabs via the `storage` event.
79
+ * When enabled, a sign-in / sign-out / token-refresh performed in one
80
+ * tab is reflected in every other tab sharing the same origin. Only
81
+ * useful when the configured storage is (or wraps) `localStorage` —
82
+ * the browser `storage` event only fires on `localStorage` /
83
+ * `sessionStorage` mutations. Default: true in a browser context,
84
+ * no-op otherwise.
85
+ */
86
+ multiTab?: boolean;
46
87
  }
47
88
  declare class TokenManager {
48
89
  private accessToken;
@@ -50,9 +91,24 @@ declare class TokenManager {
50
91
  private user;
51
92
  private readonly persistSession;
52
93
  private readonly storageKey;
94
+ private readonly storage;
53
95
  /** Fired when the access token changes (used by long-lived consumers). */
54
96
  onTokenChange: (() => void) | null;
55
97
  constructor(opts?: TokenManagerOptions);
98
+ /**
99
+ * Cross-tab storage-event handler. Arrow-bound so `removeEventListener`
100
+ * with the same reference works if the host ever decides to dispose a
101
+ * TokenManager (the SDK itself does not today).
102
+ */
103
+ private handleStorageEvent;
104
+ /**
105
+ * Update in-memory state from a raw storage value (produced by another
106
+ * tab). Fires `onTokenChange` only when the access token actually
107
+ * differs from what we had, so a listener can map this transition onto
108
+ * `SIGNED_IN` / `SIGNED_OUT` / `TOKEN_REFRESHED` the same way it maps
109
+ * transitions from same-tab mutations.
110
+ */
111
+ private syncFromStorage;
56
112
  saveSession(session: AuthSession): void;
57
113
  getSession(): AuthSession | null;
58
114
  getAccessToken(): string | null;
@@ -63,8 +119,8 @@ declare class TokenManager {
63
119
  setUser(user: User): void;
64
120
  clearSession(): void;
65
121
  /**
66
- * Restore the session from localStorage. Returns true if a persisted
67
- * session was found and loaded into memory.
122
+ * Restore the session from the configured storage. Returns true if a
123
+ * persisted session was found and loaded into memory.
68
124
  */
69
125
  restoreSession(): boolean;
70
126
  private persist;
@@ -479,10 +535,26 @@ interface MitwayBaasConfig {
479
535
  */
480
536
  persistSession?: boolean;
481
537
  /**
482
- * `localStorage` key used to persist the session.
538
+ * Storage key used to persist the session.
483
539
  * @default "mitway_baas_session"
484
540
  */
485
541
  storageKey?: string;
542
+ /**
543
+ * Custom persistence backend for the session. Must implement the
544
+ * synchronous `{ getItem, setItem, removeItem }` contract. Default:
545
+ * browser `localStorage` (SSR-safe). Pass a custom adapter to back
546
+ * sessions with cookies, native secure storage, or an in-memory stub
547
+ * for tests. Ignored when `persistSession: false`.
548
+ */
549
+ storage?: StorageAdapter;
550
+ /**
551
+ * Synchronise session state across browser tabs. When the user signs
552
+ * in, signs out, or refreshes their token in tab A, tabs B, C, D
553
+ * sharing the same origin see the change automatically. Only works
554
+ * when the active storage is (or wraps) `localStorage`. Default:
555
+ * true in a browser, no-op otherwise.
556
+ */
557
+ multiTab?: boolean;
486
558
  }
487
559
  /**
488
560
  * Active user session in memory. Mirrors what the auth endpoints return.
@@ -650,10 +722,59 @@ type AuthResult<T> = {
650
722
  data: T | null;
651
723
  error: MitwayBaasError | null;
652
724
  };
725
+ /**
726
+ * Event names emitted by `auth.onAuthStateChange`. Mirrors
727
+ * `@supabase/supabase-js` event names so consumers that already know that
728
+ * contract do not have to re-learn ours.
729
+ *
730
+ * - `INITIAL_SESSION` — emitted once per `auth.initialize()` call
731
+ * regardless of whether a persisted session was found. `session` is
732
+ * non-null when a valid session was restored, null otherwise.
733
+ * - `SIGNED_IN` — a session transitioned from absent to present
734
+ * (after `signUp`, `signInWithPassword`, or a cross-tab storage sync).
735
+ * - `SIGNED_OUT` — a session transitioned from present to absent
736
+ * (`signOut` or cross-tab storage sync).
737
+ * - `TOKEN_REFRESHED` — the access token changed but the user did not
738
+ * (explicit `refreshSession` or the HttpClient's auto-refresh on 401).
739
+ * - `USER_UPDATED` — the user record changed without a token change
740
+ * (`setProfile` or backend-side profile mutation).
741
+ */
742
+ type AuthChangeEvent = 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED' | 'USER_UPDATED';
743
+ type AuthStateChangeCallback = (event: AuthChangeEvent, session: AuthSession | null) => void;
744
+ /** Return value of `onAuthStateChange` — call `unsubscribe()` to remove the listener. */
745
+ interface Subscription {
746
+ unsubscribe: () => void;
747
+ }
653
748
  declare class Auth {
654
749
  private http;
655
750
  private tokenManager;
751
+ /** Registered `onAuthStateChange` callbacks. */
752
+ private stateChangeListeners;
753
+ /**
754
+ * Last-emitted session snapshot — used by `_handleTokenChange` to decide
755
+ * which event to emit (SIGNED_IN vs TOKEN_REFRESHED vs SIGNED_OUT).
756
+ */
757
+ private lastEmittedUserId;
758
+ private lastEmittedAccessToken;
656
759
  constructor(http: HttpClient, tokenManager: TokenManager);
760
+ /**
761
+ * Register a listener for session state transitions. Returns a
762
+ * `Subscription` whose `unsubscribe()` removes the listener. Safe to
763
+ * register after login — the listener does NOT receive an initial
764
+ * replay of the current state; call `getSession()` separately if you
765
+ * need the current value on mount. `INITIAL_SESSION` is emitted once
766
+ * per `auth.initialize()` call and is the standard hook for the first
767
+ * render path.
768
+ */
769
+ onAuthStateChange(callback: AuthStateChangeCallback): Subscription;
770
+ /** Fan out an event to every registered listener. */
771
+ private emit;
772
+ /**
773
+ * Translate a `TokenManager.onTokenChange` signal into an
774
+ * AuthChangeEvent by diffing previous vs current state. No event is
775
+ * emitted if the net effect is a no-op (defensive — shouldn't happen).
776
+ */
777
+ private _emitFromTokenChange;
657
778
  /**
658
779
  * Persist the session in memory + HttpClient defaults so subsequent
659
780
  * requests carry the new bearer token automatically.
@@ -910,6 +1031,80 @@ declare class Storage {
910
1031
  getConfig(): Promise<StorageResult<StorageConfig>>;
911
1032
  }
912
1033
 
1034
+ /**
1035
+ * Functions module -- thin wrapper over the /api/functions/* and /api/invoke/*
1036
+ * REST endpoints exposed by MITWAY-BaaS.
1037
+ *
1038
+ * Manages edge function CRUD, invocation, and secrets. Function invocation
1039
+ * routes through `HttpClient.rawFetch` since `/api/invoke/:slug` is a
1040
+ * transparent proxy that does NOT use the `{ data, error }` envelope.
1041
+ */
1042
+
1043
+ interface EdgeFunction {
1044
+ id: string;
1045
+ slug: string;
1046
+ name: string;
1047
+ description: string | null;
1048
+ code: string;
1049
+ status: 'draft' | 'active' | 'error';
1050
+ createdAt: string;
1051
+ updatedAt: string;
1052
+ deployedAt: string | null;
1053
+ }
1054
+ interface CreateFunctionRequest {
1055
+ name: string;
1056
+ slug?: string;
1057
+ code: string;
1058
+ description?: string;
1059
+ status?: 'draft' | 'active';
1060
+ }
1061
+ interface UpdateFunctionRequest {
1062
+ name?: string;
1063
+ code?: string;
1064
+ description?: string;
1065
+ status?: 'draft' | 'active';
1066
+ }
1067
+ interface FunctionSecret {
1068
+ key: string;
1069
+ digest: string;
1070
+ updatedAt: string;
1071
+ }
1072
+ interface InvokeOptions {
1073
+ method?: string;
1074
+ headers?: Record<string, string>;
1075
+ body?: BodyInit | Record<string, unknown> | null;
1076
+ }
1077
+ type FunctionsResult<T> = {
1078
+ data: T | null;
1079
+ error: MitwayBaasError | null;
1080
+ };
1081
+ declare class Functions {
1082
+ private readonly http;
1083
+ constructor(http: HttpClient);
1084
+ list(): Promise<FunctionsResult<EdgeFunction[]>>;
1085
+ get(slug: string): Promise<FunctionsResult<EdgeFunction>>;
1086
+ create(req: CreateFunctionRequest): Promise<FunctionsResult<EdgeFunction>>;
1087
+ update(slug: string, req: UpdateFunctionRequest): Promise<FunctionsResult<EdgeFunction>>;
1088
+ remove(slug: string): Promise<FunctionsResult<{
1089
+ deleted: true;
1090
+ }>>;
1091
+ /**
1092
+ * Invoke an edge function. The `/api/invoke/:slug` route is a transparent
1093
+ * proxy — no `{ data, error }` envelope. Returns the raw `Response`.
1094
+ *
1095
+ * If `opts.body` is a plain object it is JSON-stringified and
1096
+ * `Content-Type: application/json` is set automatically.
1097
+ */
1098
+ invoke(slug: string, opts?: InvokeOptions): Promise<FunctionsResult<Response>>;
1099
+ listSecrets(): Promise<FunctionsResult<FunctionSecret[]>>;
1100
+ setSecrets(secrets: Record<string, string>): Promise<FunctionsResult<{
1101
+ saved: true;
1102
+ }>>;
1103
+ deleteSecret(key: string): Promise<FunctionsResult<{
1104
+ deleted: true;
1105
+ }>>;
1106
+ }
1107
+
913
1108
  /**
914
1109
  * MITWAY-BaaS SDK client.
915
1110
  *
@@ -944,6 +1139,7 @@ declare class MitwayBaasClient {
944
1139
  readonly database: Database;
945
1140
  readonly realtime: Realtime;
946
1141
  readonly storage: Storage;
1142
+ readonly functions: Functions;
947
1143
  constructor(config?: MitwayBaasConfig);
948
1144
  /**
949
1145
  * Escape hatch for callers that need to make custom requests against the
@@ -956,13 +1152,13 @@ declare class MitwayBaasClient {
956
1152
  * @mitway-baas/sdk — TypeScript SDK for the MITWAY-BaaS backend.
957
1153
  *
958
1154
  * Currently ships:
959
- * - auth (signUp, signInWithPassword, signOut, refreshSession, getSession, getUser)
960
- * - database (PostgREST-backed query builder via @supabase/postgrest-js)
961
- * - realtime (Socket.IO transport: subscribe / unsubscribe / publish / on)
1155
+ * - auth (signUp, signInWithPassword, signOut, refreshSession, getSession, getUser)
1156
+ * - database (PostgREST-backed query builder via @supabase/postgrest-js)
1157
+ * - realtime (Socket.IO transport: subscribe / unsubscribe / publish / on)
1158
+ * - storage (bucket admin + per-bucket object operations)
1159
+ * - functions (edge function CRUD, invoke, secrets management)
962
1160
  *
963
1161
  * Not yet included (no backend support):
964
- * - storage
965
- * - functions
966
1162
  * - email
967
1163
  * - ai
968
1164
  *
@@ -984,4 +1180,4 @@ declare class MitwayBaasClient {
984
1180
  */
985
1181
  declare function createClient(config: MitwayBaasConfig): MitwayBaasClient;
986
1182
 
987
- export { type ApiError, Auth, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type CreateBucketOptions, Database, type DownloadOptions, HttpClient, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, Storage, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, TokenManager, type UpdateBucketOptions, type UploadBody, type UploadOptions, type User, createClient, MitwayBaasClient as default };
1183
+ export { type ApiError, Auth, type AuthChangeEvent, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type AuthStateChangeCallback, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type CreateBucketOptions, type CreateFunctionRequest, Database, type DownloadOptions, type EdgeFunction, type FunctionSecret, Functions, type FunctionsResult, HttpClient, type InvokeOptions, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, Storage, type StorageAdapter, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, type Subscription, TokenManager, type UpdateBucketOptions, type UpdateFunctionRequest, type UploadBody, type UploadOptions, type User, createClient, createLocalStorageAdapter, MitwayBaasClient as default };