@biltme/backend 0.7.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -0
- package/dist/index.d.ts +16 -5
- package/dist/index.js +60 -1
- package/dist/notifications.d.ts +78 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -169,6 +169,61 @@ picked file passes a bucket's MIME allowlist. Pass `contentType` for such
|
|
|
169
169
|
files: a React Native Blob has no type of its own, and without one the upload
|
|
170
170
|
is labelled `application/octet-stream`.
|
|
171
171
|
|
|
172
|
+
## Push notifications
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
const { data, error } = await bilt.notifications.send({
|
|
176
|
+
to: otherUser.id, // the recipient's user id
|
|
177
|
+
id: `chat-${chat.id}`, // optional: a later send with the same id replaces this one
|
|
178
|
+
title: 'Ana',
|
|
179
|
+
body: 'See you at 8',
|
|
180
|
+
data: { chatId: chat.id }, // optional, passed to the app on open
|
|
181
|
+
url: `/chat/${chat.id}`, // optional in-app path a tap opens
|
|
182
|
+
})
|
|
183
|
+
// data.outcome: 'accepted' | 'no_devices' | 'notifications_off' | 'platform_off'
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
A `to` typed as `string` could hold `'all'`, so its answer is typed as either
|
|
187
|
+
shape: `data.outcome` is set for one user and `data.counts` for all.
|
|
188
|
+
|
|
189
|
+
Sends to the recipient's devices as the signed-in user, authenticated
|
|
190
|
+
the way the client's other calls are: a `global.headers` Authorization header,
|
|
191
|
+
else `accessToken`, else the session, else the client's key. The client's other
|
|
192
|
+
`global.headers` go along. Bilt Cloud accepts the key only from an edge
|
|
193
|
+
function, so an app without a session gets a 403 `auth_role_denied`. `accepted` means
|
|
194
|
+
Apple or Google took the notification, not that it arrived. `url` must be an in-app path
|
|
195
|
+
starting with a single `/`, `data` may not have its own `url` key, and the two
|
|
196
|
+
together stay under 2 KB. A user may send 10 a minute
|
|
197
|
+
and 200 a day, and a recipient receives at most 30 a minute; over that, `error`
|
|
198
|
+
is a `NotificationsError` with `code` `rate_limited` and `status` 429. The
|
|
199
|
+
method never throws. The app registers devices and handles taps through
|
|
200
|
+
`@biltme/notifications-expo`.
|
|
201
|
+
|
|
202
|
+
### From an edge function
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
import { createClient } from 'npm:@biltme/backend'
|
|
206
|
+
|
|
207
|
+
const bilt = createClient(Deno.env.get('EXPO_PUBLIC_BILT_URL')!, Deno.env.get('BILT_SERVICE_KEY')!)
|
|
208
|
+
await bilt.notifications.send({ to: userId, title: 'Order shipped', body: 'It arrives Friday' })
|
|
209
|
+
const { data } = await bilt.notifications.send({ to: 'all', title: 'We are back', body: 'Service is restored' })
|
|
210
|
+
// data.counts: { accepted, notifications_off, platform_off, error, rate_limited }, in devices
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
A function sends with its `BILT_SERVICE_KEY` and needs no session. Only a
|
|
214
|
+
function may send `to: 'all'`, which reaches every registered device of the app
|
|
215
|
+
and answers how many devices had each outcome instead of one outcome. A function
|
|
216
|
+
has no per-user limit, but each recipient still receives at most 30 a minute: a
|
|
217
|
+
send to `'all'` skips a recipient over that and counts its devices as
|
|
218
|
+
`rate_limited`, and a device Apple or Google failed for counts as `error` rather
|
|
219
|
+
than failing the send. A send to `'all'` has the request's 10 seconds, which
|
|
220
|
+
reaches roughly 800 devices per platform; devices past the deadline count as
|
|
221
|
+
`error`.
|
|
222
|
+
|
|
223
|
+
`bilt.notifications` is typed on the client a bare `createClient(url, key, options)`
|
|
224
|
+
returns. It exists at runtime with explicit type arguments too, but isn't in that
|
|
225
|
+
client's type.
|
|
226
|
+
|
|
172
227
|
## Web
|
|
173
228
|
|
|
174
229
|
```ts
|
|
@@ -195,6 +250,7 @@ const bilt = createClient(url, key, {
|
|
|
195
250
|
arguments defaults its schema to the augmentable `Database` interface above instead of `any`.
|
|
196
251
|
- `Database`, the empty interface a project augments to type its schema.
|
|
197
252
|
- On React Native, storage uploads send a `Blob` as bytes so `contentType` reaches the bucket (see Storage).
|
|
253
|
+
- `bilt.notifications.send` sends a push notification to one end user, or from an edge function to every device (see Push notifications).
|
|
198
254
|
- Realtime is not available: `bilt.channel()` throws `REALTIME_NOT_SUPPORTED`. Refetch with `bilt.from(...)` on an interval or on screen focus instead.
|
|
199
255
|
- `asyncStorage(impl)` factory wrapping `@react-native-async-storage/async-storage` to the supabase-js storage shape.
|
|
200
256
|
- `webStorage()` and `memoryStorage()` for completeness.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createClient as createSupabaseClient } from '@supabase/supabase-js';
|
|
2
|
+
import { type Notifications } from './notifications';
|
|
2
3
|
/**
|
|
3
4
|
* Schema of the project's database, in postgrest-js's `Database` shape.
|
|
4
5
|
*
|
|
@@ -82,21 +83,31 @@ export type TablesUpdate<Name extends keyof PublicTables> = PublicTables[Name] e
|
|
|
82
83
|
Update: infer U;
|
|
83
84
|
} ? U : never;
|
|
84
85
|
/**
|
|
85
|
-
* Creates a Bilt client. supabase-js's `createClient` with
|
|
86
|
+
* Creates a Bilt client. supabase-js's `createClient` with five changes: called
|
|
86
87
|
* with no type arguments, the schema is {@link BiltDatabase} instead of `any`,
|
|
87
88
|
* a missing or malformed URL or key names Bilt Cloud rather than Supabase, on
|
|
88
89
|
* React Native a Blob upload is sent as bytes so `contentType` reaches the
|
|
89
|
-
* bucket's MIME allowlist (see {@link sendNativeBlobsAsBytes}),
|
|
90
|
-
* realtime channel throws because Bilt Cloud has no realtime (see {@link blockRealtime})
|
|
90
|
+
* bucket's MIME allowlist (see {@link sendNativeBlobsAsBytes}), opening a
|
|
91
|
+
* realtime channel throws because Bilt Cloud has no realtime (see {@link blockRealtime}),
|
|
92
|
+
* and the client has `notifications` (see {@link Notifications}).
|
|
91
93
|
*
|
|
92
94
|
* The second member of the intersection is supabase-js's own signature. An
|
|
93
95
|
* intersection of function types is an overload set, so a bare call takes the
|
|
94
96
|
* first member and any call with explicit type arguments falls through to the
|
|
95
97
|
* second. Restating the parameter list here instead would have to track
|
|
96
|
-
* supabase-js's defaults by hand across a caret range.
|
|
98
|
+
* supabase-js's defaults by hand across a caret range. For the same reason only
|
|
99
|
+
* the bare call's type carries `notifications`; it is there at runtime either way.
|
|
97
100
|
*/
|
|
98
|
-
export declare const createClient:
|
|
101
|
+
export declare const createClient: BareCreateClient & typeof createSupabaseClient;
|
|
102
|
+
type BareCall = typeof createSupabaseClient<BiltDatabase>;
|
|
103
|
+
/** What a bare `createClient(url, key, options?)` returns: supabase-js's client plus Bilt's additions. */
|
|
104
|
+
export type BiltClient = ReturnType<BareCall> & {
|
|
105
|
+
notifications: Notifications;
|
|
106
|
+
};
|
|
107
|
+
type BareCreateClient = (...args: Parameters<BareCall>) => BiltClient;
|
|
99
108
|
export { REALTIME_NOT_SUPPORTED } from './realtime';
|
|
109
|
+
export { NotificationsError } from './notifications';
|
|
110
|
+
export type { Notifications, NotificationMessage, NotificationOutcome, NotificationSendResult, NotificationCounts, NotificationSendAllResult, } from './notifications';
|
|
100
111
|
export { webStorage, memoryStorage, asyncStorage } from './storage';
|
|
101
112
|
export type { StorageAdapter } from './storage';
|
|
102
113
|
export { FunctionsHttpError, FunctionsRelayError, FunctionsFetchError, FunctionRegion } from '@supabase/supabase-js';
|
package/dist/index.js
CHANGED
|
@@ -11796,6 +11796,64 @@ function shouldShowDeprecationWarning() {
|
|
|
11796
11796
|
if (shouldShowDeprecationWarning())
|
|
11797
11797
|
console.warn("⚠️ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");
|
|
11798
11798
|
|
|
11799
|
+
// src/notifications.ts
|
|
11800
|
+
class NotificationsError extends Error {
|
|
11801
|
+
status;
|
|
11802
|
+
code;
|
|
11803
|
+
constructor(message, status, code) {
|
|
11804
|
+
super(message);
|
|
11805
|
+
this.name = "NotificationsError";
|
|
11806
|
+
this.status = status;
|
|
11807
|
+
this.code = code;
|
|
11808
|
+
}
|
|
11809
|
+
}
|
|
11810
|
+
function notifications(client, url, key, options = {}) {
|
|
11811
|
+
const endpoint = `${url.trim().replace(/\/+$/, "")}/notifications/v1/send`;
|
|
11812
|
+
const fetchImpl = options.global?.fetch ?? fetch;
|
|
11813
|
+
const userToken = async () => {
|
|
11814
|
+
if (options.accessToken)
|
|
11815
|
+
return options.accessToken();
|
|
11816
|
+
const { data, error } = await client.auth.getSession();
|
|
11817
|
+
if (error)
|
|
11818
|
+
throw error;
|
|
11819
|
+
return data.session?.access_token ?? null;
|
|
11820
|
+
};
|
|
11821
|
+
async function send(message) {
|
|
11822
|
+
const headers = new Headers(options.global?.headers);
|
|
11823
|
+
if (!headers.has("Authorization")) {
|
|
11824
|
+
let token;
|
|
11825
|
+
try {
|
|
11826
|
+
token = await userToken();
|
|
11827
|
+
} catch (err) {
|
|
11828
|
+
return {
|
|
11829
|
+
data: null,
|
|
11830
|
+
error: new NotificationsError(`Couldn't read the session: ${String(err)}`, 0, "session_unavailable")
|
|
11831
|
+
};
|
|
11832
|
+
}
|
|
11833
|
+
headers.set("Authorization", `Bearer ${token ?? key}`);
|
|
11834
|
+
}
|
|
11835
|
+
if (!headers.has("apikey"))
|
|
11836
|
+
headers.set("apikey", key);
|
|
11837
|
+
headers.set("Content-Type", "application/json");
|
|
11838
|
+
let res;
|
|
11839
|
+
try {
|
|
11840
|
+
res = await fetchImpl(endpoint, { method: "POST", headers, body: JSON.stringify(message) });
|
|
11841
|
+
} catch (err) {
|
|
11842
|
+
return { data: null, error: new NotificationsError(`Bilt Cloud didn't answer: ${String(err)}`, 0, "network") };
|
|
11843
|
+
}
|
|
11844
|
+
const body = await res.json().catch(() => null);
|
|
11845
|
+
if (res.ok && body?.outcome) {
|
|
11846
|
+
return { data: { outcome: body.outcome }, error: null };
|
|
11847
|
+
}
|
|
11848
|
+
if (res.ok && body?.counts) {
|
|
11849
|
+
return { data: { counts: body.counts }, error: null };
|
|
11850
|
+
}
|
|
11851
|
+
const detail = body?.error?.message ?? `Bilt Cloud answered ${res.status}`;
|
|
11852
|
+
return { data: null, error: new NotificationsError(detail, res.status, body?.error?.code ?? "unknown") };
|
|
11853
|
+
}
|
|
11854
|
+
return { send };
|
|
11855
|
+
}
|
|
11856
|
+
|
|
11799
11857
|
// src/realtime.ts
|
|
11800
11858
|
var REALTIME_NOT_SUPPORTED = "Realtime is not supported by Bilt Cloud yet. Refetch with bilt.from(...) on an interval or when the screen regains focus instead.";
|
|
11801
11859
|
function notSupported() {
|
|
@@ -11927,7 +11985,7 @@ var createClient2 = (url, key, options) => {
|
|
|
11927
11985
|
const client = createClient(url, key, options);
|
|
11928
11986
|
sendNativeBlobsAsBytes(client);
|
|
11929
11987
|
blockRealtime(client);
|
|
11930
|
-
return client;
|
|
11988
|
+
return Object.assign(client, { notifications: notifications(client, url, key, options) });
|
|
11931
11989
|
};
|
|
11932
11990
|
var export_FunctionsRelayError = import_functions_js.FunctionsRelayError;
|
|
11933
11991
|
var export_FunctionsHttpError = import_functions_js.FunctionsHttpError;
|
|
@@ -11941,6 +11999,7 @@ export {
|
|
|
11941
11999
|
asyncStorage,
|
|
11942
12000
|
StorageApiError,
|
|
11943
12001
|
REALTIME_NOT_SUPPORTED,
|
|
12002
|
+
NotificationsError,
|
|
11944
12003
|
export_FunctionsRelayError as FunctionsRelayError,
|
|
11945
12004
|
export_FunctionsHttpError as FunctionsHttpError,
|
|
11946
12005
|
export_FunctionsFetchError as FunctionsFetchError,
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
2
|
+
/** The push notification {@link Notifications.send} delivers to one end user, or from an edge function to all. */
|
|
3
|
+
export type NotificationMessage = {
|
|
4
|
+
/** The recipient's user id, or `'all'` for every registered device of the app, which only an edge function may send. */
|
|
5
|
+
to: string;
|
|
6
|
+
/** A later send with the same id replaces the earlier notification on the device. */
|
|
7
|
+
id?: string;
|
|
8
|
+
title: string;
|
|
9
|
+
body: string;
|
|
10
|
+
/** Passed to the app as is when the notification is opened. With `url`, at most 2 KB of JSON. */
|
|
11
|
+
data?: Record<string, unknown>;
|
|
12
|
+
/** An in-app path such as `/chat/123`, opened on tap. */
|
|
13
|
+
url?: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* What happened for the recipient. `accepted` means Google or Apple took the
|
|
17
|
+
* notification, not that it arrived.
|
|
18
|
+
*/
|
|
19
|
+
export type NotificationOutcome = 'accepted' | 'no_devices' | 'notifications_off' | 'platform_off';
|
|
20
|
+
/** A send bilt-cloud refused or never answered, with its error code, such as `rate_limited`. */
|
|
21
|
+
export declare class NotificationsError extends Error {
|
|
22
|
+
readonly status: number;
|
|
23
|
+
readonly code: string;
|
|
24
|
+
constructor(message: string, status: number, code: string);
|
|
25
|
+
}
|
|
26
|
+
export type NotificationSendResult = {
|
|
27
|
+
data: {
|
|
28
|
+
outcome: NotificationOutcome;
|
|
29
|
+
counts?: undefined;
|
|
30
|
+
};
|
|
31
|
+
error: null;
|
|
32
|
+
} | {
|
|
33
|
+
data: null;
|
|
34
|
+
error: NotificationsError;
|
|
35
|
+
};
|
|
36
|
+
export type NotificationCounts = {
|
|
37
|
+
accepted: number;
|
|
38
|
+
notifications_off: number;
|
|
39
|
+
platform_off: number;
|
|
40
|
+
error: number;
|
|
41
|
+
rate_limited: number;
|
|
42
|
+
};
|
|
43
|
+
export type NotificationSendAllResult = {
|
|
44
|
+
data: {
|
|
45
|
+
counts: NotificationCounts;
|
|
46
|
+
outcome?: undefined;
|
|
47
|
+
};
|
|
48
|
+
error: null;
|
|
49
|
+
} | {
|
|
50
|
+
data: null;
|
|
51
|
+
error: NotificationsError;
|
|
52
|
+
};
|
|
53
|
+
export type Notifications = {
|
|
54
|
+
/**
|
|
55
|
+
* Sends a push notification to every registered device of the app and
|
|
56
|
+
* returns how many devices had each outcome. Only an edge function may send it.
|
|
57
|
+
*/
|
|
58
|
+
send(message: NotificationMessage & {
|
|
59
|
+
to: 'all';
|
|
60
|
+
}): Promise<NotificationSendAllResult>;
|
|
61
|
+
/**
|
|
62
|
+
* Sends a push notification to one end user's devices, as the signed-in user.
|
|
63
|
+
* Without a session it sends with the client's key, which bilt-cloud accepts
|
|
64
|
+
* only from an edge function's `BILT_SERVICE_KEY`. A `to` typed as `string`
|
|
65
|
+
* may hold `'all'`, so the answer is either shape: read `data.outcome` for
|
|
66
|
+
* one user and `data.counts` for all.
|
|
67
|
+
*/
|
|
68
|
+
send(message: NotificationMessage): Promise<NotificationSendResult | NotificationSendAllResult>;
|
|
69
|
+
};
|
|
70
|
+
/** The supabase-js options `send` honours, so it authenticates the way the client's own calls do. */
|
|
71
|
+
export type NotificationsOptions = {
|
|
72
|
+
global?: {
|
|
73
|
+
fetch?: typeof fetch;
|
|
74
|
+
headers?: Record<string, string>;
|
|
75
|
+
};
|
|
76
|
+
accessToken?: () => Promise<string | null>;
|
|
77
|
+
};
|
|
78
|
+
export declare function notifications(client: SupabaseClient<any, any, any>, url: string, key: string, options?: NotificationsOptions): Notifications;
|