usebecky 0.0.0-stage → 0.2.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 +701 -2
- package/dist/analytics/client.d.ts +219 -0
- package/dist/analytics/client.js +923 -0
- package/dist/analytics/cmp.d.ts +20 -0
- package/dist/analytics/cmp.js +166 -0
- package/dist/analytics/context.d.ts +29 -0
- package/dist/analytics/context.js +97 -0
- package/dist/auth/client.d.ts +401 -0
- package/dist/auth/client.js +1081 -0
- package/dist/auth/webauthn.d.ts +18 -0
- package/dist/auth/webauthn.js +138 -0
- package/dist/cli/ai.d.ts +54 -0
- package/dist/cli/ai.js +202 -0
- package/dist/cli/analytics.d.ts +53 -0
- package/dist/cli/analytics.js +357 -0
- package/dist/cli/config.d.ts +75 -0
- package/dist/cli/config.js +718 -0
- package/dist/cli/db.d.ts +48 -0
- package/dist/cli/db.js +215 -0
- package/dist/cli/deploy-api.d.ts +168 -0
- package/dist/cli/deploy-api.js +177 -0
- package/dist/cli/deploy-ci.d.ts +15 -0
- package/dist/cli/deploy-ci.js +54 -0
- package/dist/cli/deploy-detect.d.ts +64 -0
- package/dist/cli/deploy-detect.js +249 -0
- package/dist/cli/deploy-files.d.ts +112 -0
- package/dist/cli/deploy-files.js +778 -0
- package/dist/cli/deploy.d.ts +10 -0
- package/dist/cli/deploy.js +430 -0
- package/dist/cli/emails.d.ts +29 -0
- package/dist/cli/emails.js +122 -0
- package/dist/cli/framework.d.ts +135 -0
- package/dist/cli/framework.js +459 -0
- package/dist/cli/functions.d.ts +59 -0
- package/dist/cli/functions.js +426 -0
- package/dist/cli/hosting.d.ts +4 -0
- package/dist/cli/hosting.js +532 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/payments.d.ts +35 -0
- package/dist/cli/payments.js +176 -0
- package/dist/cli/push.d.ts +36 -0
- package/dist/cli/push.js +172 -0
- package/dist/cli/run.d.ts +65 -0
- package/dist/cli/run.js +850 -0
- package/dist/cli/social.d.ts +52 -0
- package/dist/cli/social.js +532 -0
- package/dist/cli/tokens.d.ts +28 -0
- package/dist/cli/tokens.js +114 -0
- package/dist/cli/ui.d.ts +38 -0
- package/dist/cli/ui.js +140 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +156 -0
- package/dist/db/query.d.ts +162 -0
- package/dist/db/query.js +336 -0
- package/dist/db/types.d.ts +93 -0
- package/dist/db/types.js +4 -0
- package/dist/forms/client.d.ts +65 -0
- package/dist/forms/client.js +106 -0
- package/dist/functions/client.d.ts +37 -0
- package/dist/functions/client.js +76 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +16 -0
- package/dist/lib/dashboard-paths.d.ts +4 -0
- package/dist/lib/dashboard-paths.js +8 -0
- package/dist/lib/env.d.ts +9 -0
- package/dist/lib/env.js +55 -0
- package/dist/lib/errors.d.ts +22 -0
- package/dist/lib/errors.js +90 -0
- package/dist/lib/hosted.d.ts +2 -0
- package/dist/lib/hosted.js +7 -0
- package/dist/lib/http.d.ts +59 -0
- package/dist/lib/http.js +172 -0
- package/dist/lib/jwt.d.ts +1 -0
- package/dist/lib/jwt.js +31 -0
- package/dist/lib/locale.d.ts +12 -0
- package/dist/lib/locale.js +51 -0
- package/dist/lib/pkce.d.ts +20 -0
- package/dist/lib/pkce.js +124 -0
- package/dist/lib/storage-adapter.d.ts +15 -0
- package/dist/lib/storage-adapter.js +91 -0
- package/dist/lib/types.d.ts +339 -0
- package/dist/lib/types.js +1 -0
- package/dist/newsletter/client.d.ts +140 -0
- package/dist/newsletter/client.js +85 -0
- package/dist/payments/client.d.ts +352 -0
- package/dist/payments/client.js +323 -0
- package/dist/push/client.d.ts +110 -0
- package/dist/push/client.js +179 -0
- package/dist/realtime/client.d.ts +131 -0
- package/dist/realtime/client.js +513 -0
- package/dist/server/analytics.d.ts +176 -0
- package/dist/server/analytics.js +49 -0
- package/dist/server/cache.d.ts +74 -0
- package/dist/server/cache.js +154 -0
- package/dist/server/emails.d.ts +142 -0
- package/dist/server/emails.js +123 -0
- package/dist/server/events.d.ts +357 -0
- package/dist/server/events.js +219 -0
- package/dist/server/functions.d.ts +40 -0
- package/dist/server/functions.js +1 -0
- package/dist/server/http-utils.d.ts +10 -0
- package/dist/server/http-utils.js +115 -0
- package/dist/server/index.d.ts +195 -0
- package/dist/server/index.js +314 -0
- package/dist/server/payments.d.ts +218 -0
- package/dist/server/payments.js +150 -0
- package/dist/server/push.d.ts +85 -0
- package/dist/server/push.js +37 -0
- package/dist/server/usage.d.ts +43 -0
- package/dist/server/usage.js +8 -0
- package/dist/storage/client.d.ts +143 -0
- package/dist/storage/client.js +224 -0
- package/package.json +52 -4
- package/skill/usebecky/SKILL.md +339 -0
- package/skill/usebecky/references/access-rules.md +307 -0
- package/skill/usebecky/references/addons.md +68 -0
- package/skill/usebecky/references/analytics.md +166 -0
- package/skill/usebecky/references/android.md +434 -0
- package/skill/usebecky/references/auth.md +379 -0
- package/skill/usebecky/references/cache.md +51 -0
- package/skill/usebecky/references/components.md +127 -0
- package/skill/usebecky/references/emails.md +105 -0
- package/skill/usebecky/references/expo.md +147 -0
- package/skill/usebecky/references/functions.md +99 -0
- package/skill/usebecky/references/hosting.md +119 -0
- package/skill/usebecky/references/http-api.md +233 -0
- package/skill/usebecky/references/ios.md +355 -0
- package/skill/usebecky/references/payments.md +493 -0
- package/skill/usebecky/references/realtime.md +143 -0
- package/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/skill/usebecky/references/sdk.md +838 -0
- package/skill/usebecky/references/storage.md +210 -0
- package/skill/usebecky/references/templates.md +191 -0
- package/skill/usebecky/references/wordpress.md +87 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { HttpClient } from '../lib/http.ts';
|
|
2
|
+
import type { StorageAdapter } from '../lib/storage-adapter.ts';
|
|
3
|
+
import type { AuthChangeEvent, Result } from '../lib/types.ts';
|
|
4
|
+
export type PushPlatform = 'ios' | 'android' | 'web';
|
|
5
|
+
/** The JSON form of a browser PushSubscription (`subscription.toJSON()`). */
|
|
6
|
+
export interface WebPushSubscriptionJSON {
|
|
7
|
+
endpoint: string;
|
|
8
|
+
expirationTime?: number | null;
|
|
9
|
+
keys: {
|
|
10
|
+
p256dh: string;
|
|
11
|
+
auth: string;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export interface PushRegisterOptions {
|
|
15
|
+
/** 'ios' (APNs device token), 'android' (FCM registration token) or 'web' (a PushSubscription). */
|
|
16
|
+
platform: PushPlatform;
|
|
17
|
+
/** iOS: the device token as hex text. Android: the FCM token. Web: the PushSubscription (or its JSON). */
|
|
18
|
+
token: string | WebPushSubscriptionJSON;
|
|
19
|
+
/** Your app's id or bundle id, e.g. 'com.example.app' (shown in the dashboard). */
|
|
20
|
+
appId?: string;
|
|
21
|
+
/** The user's language, e.g. 'en-US'. */
|
|
22
|
+
locale?: string;
|
|
23
|
+
/** Up to 10 labels to send to groups later, e.g. ['news']. Leave out to keep the current tags. */
|
|
24
|
+
tags?: string[];
|
|
25
|
+
}
|
|
26
|
+
/** A registered device as the API returns it. The full token is never sent back. */
|
|
27
|
+
export interface PushDevice {
|
|
28
|
+
id: string;
|
|
29
|
+
user_id: string;
|
|
30
|
+
platform: PushPlatform;
|
|
31
|
+
/** A short piece of the token, to recognize the device. */
|
|
32
|
+
token_preview: string;
|
|
33
|
+
app_id: string | null;
|
|
34
|
+
locale: string | null;
|
|
35
|
+
tags: string[];
|
|
36
|
+
created_at: string;
|
|
37
|
+
last_seen_at: string;
|
|
38
|
+
/** true the first time this token was registered, false when it was updated. */
|
|
39
|
+
created: boolean;
|
|
40
|
+
}
|
|
41
|
+
export interface PushConfig {
|
|
42
|
+
web: {
|
|
43
|
+
vapid_public_key: string | null;
|
|
44
|
+
};
|
|
45
|
+
/** Which platforms are set up in Dashboard → Push notifications → Setup. */
|
|
46
|
+
platforms: {
|
|
47
|
+
ios: boolean;
|
|
48
|
+
android: boolean;
|
|
49
|
+
web: boolean;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export interface WebPushOptions {
|
|
53
|
+
/** Labels for this browser, e.g. ['news']. */
|
|
54
|
+
tags?: string[];
|
|
55
|
+
/** The user's language, e.g. navigator.language (the default). */
|
|
56
|
+
locale?: string;
|
|
57
|
+
}
|
|
58
|
+
/** The parts of a ServiceWorkerRegistration we use (works without DOM types; `await navigator.serviceWorker.ready` fits). */
|
|
59
|
+
export interface PushServiceWorkerRegistration {
|
|
60
|
+
pushManager: {
|
|
61
|
+
getSubscription(): Promise<any>;
|
|
62
|
+
subscribe(options: {
|
|
63
|
+
userVisibleOnly: boolean;
|
|
64
|
+
applicationServerKey: Uint8Array<ArrayBuffer> | ArrayBuffer | string;
|
|
65
|
+
}): Promise<any>;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
interface AuthEvents {
|
|
69
|
+
onAuthStateChange(cb: (event: AuthChangeEvent, session: unknown) => void): () => void;
|
|
70
|
+
}
|
|
71
|
+
/** VAPID public key (base64url) → the bytes pushManager.subscribe() wants. */
|
|
72
|
+
export declare function vapidKeyToBytes(key: string): Uint8Array<ArrayBuffer>;
|
|
73
|
+
export declare class PushClient {
|
|
74
|
+
private http;
|
|
75
|
+
private storage;
|
|
76
|
+
private storageKey;
|
|
77
|
+
constructor(http: HttpClient, storage: StorageAdapter, storageKey: string, auth?: AuthEvents);
|
|
78
|
+
/**
|
|
79
|
+
* Register this device's push token for the signed-in user. Call it after sign-in and whenever the
|
|
80
|
+
* token changes (Firebase's onNewToken, Apple's didRegisterForRemoteNotificationsWithDeviceToken).
|
|
81
|
+
*
|
|
82
|
+
* const { data, error } = await baas.push.register({ platform: 'android', token })
|
|
83
|
+
*/
|
|
84
|
+
register(options: PushRegisterOptions): Promise<Result<PushDevice>>;
|
|
85
|
+
/**
|
|
86
|
+
* Stop sending notifications to this device. Without arguments it removes the token registered
|
|
87
|
+
* last on this device. Signing out does this for you.
|
|
88
|
+
*/
|
|
89
|
+
unregister(token?: string | WebPushSubscriptionJSON): Promise<Result<{
|
|
90
|
+
removed: number;
|
|
91
|
+
}>>;
|
|
92
|
+
private isSaved;
|
|
93
|
+
/** The project's Web Push public key and which platforms are set up. */
|
|
94
|
+
getConfig(): Promise<Result<PushConfig>>;
|
|
95
|
+
/**
|
|
96
|
+
* Websites: ask for permission, subscribe this browser with your project's Web Push key and
|
|
97
|
+
* register it for the signed-in user.
|
|
98
|
+
*
|
|
99
|
+
* const registration = await navigator.serviceWorker.register('/sw.js')
|
|
100
|
+
* const { data, error } = await baas.push.subscribeWebPush(registration)
|
|
101
|
+
*
|
|
102
|
+
* Call it from a click (browsers only show the permission prompt after a user action).
|
|
103
|
+
*/
|
|
104
|
+
subscribeWebPush(registration: PushServiceWorkerRegistration, options?: WebPushOptions): Promise<Result<PushDevice>>;
|
|
105
|
+
/** Websites: unsubscribe this browser and remove it from your project. */
|
|
106
|
+
unsubscribeWebPush(registration: PushServiceWorkerRegistration): Promise<Result<{
|
|
107
|
+
removed: number;
|
|
108
|
+
}>>;
|
|
109
|
+
}
|
|
110
|
+
export {};
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// Push notifications: register this device (or browser) so your server and the dashboard can send it
|
|
2
|
+
// notifications. API: POST/DELETE /push/v1/devices, GET /push/v1/config.
|
|
3
|
+
//
|
|
4
|
+
// // After sign-in, with the token your app got from Apple / Firebase:
|
|
5
|
+
// await baas.push.register({ platform: 'android', token })
|
|
6
|
+
//
|
|
7
|
+
// // Websites (Web Push): ask permission, subscribe and register in one call.
|
|
8
|
+
// const registration = await navigator.serviceWorker.register('/sw.js')
|
|
9
|
+
// const { data, error } = await baas.push.subscribeWebPush(registration)
|
|
10
|
+
//
|
|
11
|
+
// Signing out unregisters the device automatically, so the next person who signs in on it doesn't
|
|
12
|
+
// get the previous person's notifications. Sending happens on your server (`usebecky/server` →
|
|
13
|
+
// baas.push.send) or in Dashboard → Push notifications.
|
|
14
|
+
import { UseBeckyError } from "../lib/errors.js";
|
|
15
|
+
function err(code, message, hint) {
|
|
16
|
+
return new UseBeckyError({ code, message, hint, status: 0 });
|
|
17
|
+
}
|
|
18
|
+
/** VAPID public key (base64url) → the bytes pushManager.subscribe() wants. */
|
|
19
|
+
export function vapidKeyToBytes(key) {
|
|
20
|
+
const b64 = key.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (key.length % 4)) % 4);
|
|
21
|
+
const g = globalThis;
|
|
22
|
+
const bin = typeof g.atob === 'function' ? g.atob(b64) : g.Buffer.from(b64, 'base64').toString('binary');
|
|
23
|
+
const out = new Uint8Array(bin.length);
|
|
24
|
+
for (let i = 0; i < bin.length; i++)
|
|
25
|
+
out[i] = bin.charCodeAt(i);
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
function subscriptionJson(sub) {
|
|
29
|
+
return typeof sub?.toJSON === 'function' ? sub.toJSON() : sub;
|
|
30
|
+
}
|
|
31
|
+
export class PushClient {
|
|
32
|
+
http;
|
|
33
|
+
storage;
|
|
34
|
+
storageKey;
|
|
35
|
+
constructor(http, storage, storageKey, auth) {
|
|
36
|
+
this.http = http;
|
|
37
|
+
this.storage = storage;
|
|
38
|
+
this.storageKey = storageKey;
|
|
39
|
+
// Sign-out: stop sending this person's notifications to this device.
|
|
40
|
+
auth?.onAuthStateChange((event) => {
|
|
41
|
+
if (event === 'SIGNED_OUT')
|
|
42
|
+
void this.unregister().catch(() => { });
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Register this device's push token for the signed-in user. Call it after sign-in and whenever the
|
|
47
|
+
* token changes (Firebase's onNewToken, Apple's didRegisterForRemoteNotificationsWithDeviceToken).
|
|
48
|
+
*
|
|
49
|
+
* const { data, error } = await baas.push.register({ platform: 'android', token })
|
|
50
|
+
*/
|
|
51
|
+
async register(options) {
|
|
52
|
+
if (!options || typeof options !== 'object' || !options.platform || !options.token) {
|
|
53
|
+
return { data: null, error: err('invalid_input', 'Pass the platform and the token, like { platform: "android", token }.', 'iOS tokens come from didRegisterForRemoteNotificationsWithDeviceToken, Android tokens from FirebaseMessaging, web subscriptions from baas.push.subscribeWebPush().') };
|
|
54
|
+
}
|
|
55
|
+
const token = options.platform === 'web' && typeof options.token === 'object' ? subscriptionJson(options.token) : options.token;
|
|
56
|
+
const res = await this.http.request('/push/v1/devices', {
|
|
57
|
+
method: 'POST',
|
|
58
|
+
body: { platform: options.platform, token, app_id: options.appId, locale: options.locale, tags: options.tags },
|
|
59
|
+
});
|
|
60
|
+
if (res.error)
|
|
61
|
+
return { data: null, error: res.error };
|
|
62
|
+
try {
|
|
63
|
+
await this.storage.setItem(this.storageKey, JSON.stringify({ platform: options.platform, token }));
|
|
64
|
+
}
|
|
65
|
+
catch { }
|
|
66
|
+
return { data: res.data, error: null };
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Stop sending notifications to this device. Without arguments it removes the token registered
|
|
70
|
+
* last on this device. Signing out does this for you.
|
|
71
|
+
*/
|
|
72
|
+
async unregister(token) {
|
|
73
|
+
let platform;
|
|
74
|
+
let value = token;
|
|
75
|
+
if (value === undefined) {
|
|
76
|
+
try {
|
|
77
|
+
const saved = await this.storage.getItem(this.storageKey);
|
|
78
|
+
if (saved)
|
|
79
|
+
({ platform, token: value } = JSON.parse(saved));
|
|
80
|
+
}
|
|
81
|
+
catch { }
|
|
82
|
+
if (value === undefined)
|
|
83
|
+
return { data: { removed: 0 }, error: null };
|
|
84
|
+
}
|
|
85
|
+
// No user token needed (the device token itself identifies the device), so this also works
|
|
86
|
+
// right after the session ended.
|
|
87
|
+
const res = await this.http.request('/push/v1/devices', { method: 'DELETE', token: null, body: { token: value, platform } });
|
|
88
|
+
if (res.error)
|
|
89
|
+
return { data: null, error: res.error };
|
|
90
|
+
if (token === undefined || (await this.isSaved(value))) {
|
|
91
|
+
try {
|
|
92
|
+
await this.storage.removeItem(this.storageKey);
|
|
93
|
+
}
|
|
94
|
+
catch { }
|
|
95
|
+
}
|
|
96
|
+
return { data: { removed: res.data?.removed ?? 0 }, error: null };
|
|
97
|
+
}
|
|
98
|
+
async isSaved(value) {
|
|
99
|
+
try {
|
|
100
|
+
const saved = await this.storage.getItem(this.storageKey);
|
|
101
|
+
return !!saved && JSON.stringify(JSON.parse(saved).token) === JSON.stringify(value);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** The project's Web Push public key and which platforms are set up. */
|
|
108
|
+
async getConfig() {
|
|
109
|
+
const res = await this.http.request('/push/v1/config', { token: null });
|
|
110
|
+
return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Websites: ask for permission, subscribe this browser with your project's Web Push key and
|
|
114
|
+
* register it for the signed-in user.
|
|
115
|
+
*
|
|
116
|
+
* const registration = await navigator.serviceWorker.register('/sw.js')
|
|
117
|
+
* const { data, error } = await baas.push.subscribeWebPush(registration)
|
|
118
|
+
*
|
|
119
|
+
* Call it from a click (browsers only show the permission prompt after a user action).
|
|
120
|
+
*/
|
|
121
|
+
async subscribeWebPush(registration, options = {}) {
|
|
122
|
+
const g = globalThis;
|
|
123
|
+
if (!registration?.pushManager) {
|
|
124
|
+
return { data: null, error: err('push_not_supported', 'This browser does not support Web Push here.', 'Pass the result of navigator.serviceWorker.register("/sw.js"). Web Push needs https:// (or localhost); on iPhone it works in web apps added to the Home Screen (iOS 16.4+).') };
|
|
125
|
+
}
|
|
126
|
+
if (g.Notification && typeof g.Notification.requestPermission === 'function' && g.Notification.permission !== 'granted') {
|
|
127
|
+
const permission = g.Notification.permission === 'denied' ? 'denied' : await g.Notification.requestPermission();
|
|
128
|
+
if (permission !== 'granted') {
|
|
129
|
+
return { data: null, error: err('permission_denied', 'Notifications are blocked for this site.', 'The visitor said no (or blocked notifications). They can allow them again in the browser\'s site settings (the icon left of the address bar).') };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const config = await this.getConfig();
|
|
133
|
+
if (config.error)
|
|
134
|
+
return { data: null, error: config.error };
|
|
135
|
+
const key = config.data.web.vapid_public_key;
|
|
136
|
+
if (!key)
|
|
137
|
+
return { data: null, error: err('push_not_configured', 'Web Push is not set up for this project.', 'Open Dashboard → Push notifications → Setup → Web Push.') };
|
|
138
|
+
let sub;
|
|
139
|
+
try {
|
|
140
|
+
sub = await registration.pushManager.getSubscription();
|
|
141
|
+
// A subscription made with another key (e.g. after "Generate new keys") can't be used: renew it.
|
|
142
|
+
const current = sub?.options?.applicationServerKey;
|
|
143
|
+
if (sub && current && toBase64Url(current) !== key.replace(/=+$/, '')) {
|
|
144
|
+
await sub.unsubscribe();
|
|
145
|
+
sub = null;
|
|
146
|
+
}
|
|
147
|
+
sub ??= await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: vapidKeyToBytes(key) });
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
return { data: null, error: err('push_subscribe_failed', `The browser could not subscribe: ${e?.message ?? e}`, 'Check that the page is served over https:// (or localhost) and that notifications are allowed.') };
|
|
151
|
+
}
|
|
152
|
+
return this.register({ platform: 'web', token: subscriptionJson(sub), locale: options.locale ?? g.navigator?.language, tags: options.tags });
|
|
153
|
+
}
|
|
154
|
+
/** Websites: unsubscribe this browser and remove it from your project. */
|
|
155
|
+
async unsubscribeWebPush(registration) {
|
|
156
|
+
let sub = null;
|
|
157
|
+
try {
|
|
158
|
+
sub = await registration?.pushManager?.getSubscription();
|
|
159
|
+
}
|
|
160
|
+
catch { }
|
|
161
|
+
if (!sub)
|
|
162
|
+
return { data: { removed: 0 }, error: null };
|
|
163
|
+
const res = await this.unregister(subscriptionJson(sub));
|
|
164
|
+
try {
|
|
165
|
+
await sub.unsubscribe();
|
|
166
|
+
}
|
|
167
|
+
catch { }
|
|
168
|
+
return res;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function toBase64Url(buf) {
|
|
172
|
+
const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
|
|
173
|
+
let bin = '';
|
|
174
|
+
for (const b of bytes)
|
|
175
|
+
bin += String.fromCharCode(b);
|
|
176
|
+
const g = globalThis;
|
|
177
|
+
const b64 = typeof g.btoa === 'function' ? g.btoa(bin) : g.Buffer.from(bin, 'binary').toString('base64');
|
|
178
|
+
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
179
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { RowOf, SchemaOf, TableName } from '../db/types.ts';
|
|
2
|
+
import { UseBeckyError } from '../lib/errors.ts';
|
|
3
|
+
import type { Change, ChangeEvent, PresenceState } from '../lib/types.ts';
|
|
4
|
+
export interface RealtimeOptions {
|
|
5
|
+
/** WebSocket implementation (default: the global WebSocket; pass one on older runtimes). */
|
|
6
|
+
WebSocket?: any;
|
|
7
|
+
/** How often to ping the server (ms). Default 25000. */
|
|
8
|
+
heartbeatIntervalMs?: number;
|
|
9
|
+
/** Close and reconnect if no pong arrives within this time (ms). Default 10000. */
|
|
10
|
+
heartbeatTimeoutMs?: number;
|
|
11
|
+
/** Backoff delays between reconnect attempts (ms). */
|
|
12
|
+
reconnectDelaysMs?: number[];
|
|
13
|
+
/** Keep the socket open this long after the last subscription stops (ms). Default 1000. */
|
|
14
|
+
idleTimeoutMs?: number;
|
|
15
|
+
}
|
|
16
|
+
export interface SubscribeOptions {
|
|
17
|
+
/** 'INSERT', 'UPDATE', 'DELETE' or '*' (default). */
|
|
18
|
+
event?: ChangeEvent | '*';
|
|
19
|
+
/** Only rows matching this filter, e.g. `room_id=eq.42`. */
|
|
20
|
+
filter?: string;
|
|
21
|
+
/** Called once the server confirms the subscription. */
|
|
22
|
+
onSubscribed?: () => void;
|
|
23
|
+
/** Called if the server rejects the subscription (e.g. realtime not enabled for the table). */
|
|
24
|
+
onError?: (error: UseBeckyError) => void;
|
|
25
|
+
}
|
|
26
|
+
export type RealtimeStatus = 'idle' | 'connecting' | 'open' | 'reconnecting';
|
|
27
|
+
export declare class RealtimeClient<DB = any> {
|
|
28
|
+
private baseUrl;
|
|
29
|
+
private key;
|
|
30
|
+
private getToken;
|
|
31
|
+
private WS;
|
|
32
|
+
private heartbeatMs;
|
|
33
|
+
private heartbeatTimeoutMs;
|
|
34
|
+
private delays;
|
|
35
|
+
private idleMs;
|
|
36
|
+
private ws;
|
|
37
|
+
private connecting;
|
|
38
|
+
private token;
|
|
39
|
+
private attempts;
|
|
40
|
+
private reconnectTimer;
|
|
41
|
+
private heartbeatTimer;
|
|
42
|
+
private pongTimer;
|
|
43
|
+
private idleTimer;
|
|
44
|
+
private nextId;
|
|
45
|
+
private subs;
|
|
46
|
+
private channelMap;
|
|
47
|
+
private _status;
|
|
48
|
+
private warnedNoWs;
|
|
49
|
+
constructor(init: {
|
|
50
|
+
url: string;
|
|
51
|
+
key: string;
|
|
52
|
+
getToken: () => Promise<string | null>;
|
|
53
|
+
options?: RealtimeOptions;
|
|
54
|
+
});
|
|
55
|
+
/** Connection status. */
|
|
56
|
+
get status(): RealtimeStatus;
|
|
57
|
+
/**
|
|
58
|
+
* Get notified when rows change.
|
|
59
|
+
* const stop = baas.realtime.subscribe('messages', { filter: 'room_id=eq.42' }, (change) => {...})
|
|
60
|
+
* Rows you can't SELECT (RLS) are never sent to you. Call `stop()` to unsubscribe.
|
|
61
|
+
*/
|
|
62
|
+
subscribe<T extends TableName<SchemaOf<DB>>>(table: T, callback: (change: Change<RowOf<SchemaOf<DB>, T>>) => void): () => void;
|
|
63
|
+
subscribe<T extends TableName<SchemaOf<DB>>>(table: T, options: SubscribeOptions, callback: (change: Change<RowOf<SchemaOf<DB>, T>>) => void): () => void;
|
|
64
|
+
/** A broadcast + presence channel (chat rooms, cursors, "who's online"). */
|
|
65
|
+
channel(name: string): RealtimeChannel;
|
|
66
|
+
/** Close the connection and drop every subscription and channel. */
|
|
67
|
+
disconnect(): void;
|
|
68
|
+
/** Called by the auth client when the user signs in/out or the token is refreshed. */
|
|
69
|
+
setAuth(token: string | null): void;
|
|
70
|
+
/** @internal */
|
|
71
|
+
_channelLeft(name: string): void;
|
|
72
|
+
/** @internal */
|
|
73
|
+
send(msg: Record<string, unknown>): boolean;
|
|
74
|
+
private sendSubscribe;
|
|
75
|
+
private hasWork;
|
|
76
|
+
private ensureConnected;
|
|
77
|
+
private maybeIdle;
|
|
78
|
+
private connectNow;
|
|
79
|
+
private open;
|
|
80
|
+
private onMessage;
|
|
81
|
+
private startHeartbeat;
|
|
82
|
+
private stopHeartbeat;
|
|
83
|
+
/** Forget the current socket (without reconnecting). */
|
|
84
|
+
private dropSocket;
|
|
85
|
+
private scheduleReconnect;
|
|
86
|
+
private close;
|
|
87
|
+
}
|
|
88
|
+
export declare class RealtimeChannel {
|
|
89
|
+
readonly name: string;
|
|
90
|
+
private client;
|
|
91
|
+
private handlers;
|
|
92
|
+
private presenceHandlers;
|
|
93
|
+
private errorHandlers;
|
|
94
|
+
private state;
|
|
95
|
+
private tracked;
|
|
96
|
+
private queue;
|
|
97
|
+
private isJoined;
|
|
98
|
+
private left;
|
|
99
|
+
private key;
|
|
100
|
+
constructor(client: RealtimeClient<any>, name: string);
|
|
101
|
+
/** Your key in the presence state (set once joined). */
|
|
102
|
+
get presenceKey(): string | null;
|
|
103
|
+
/** True once the server confirmed the join. */
|
|
104
|
+
get joined(): boolean;
|
|
105
|
+
/** Listen for a broadcast event (`'*'` for all). Returns a function that stops listening. */
|
|
106
|
+
on<T = any>(event: string, callback: (payload: T, event: string) => void): () => void;
|
|
107
|
+
/** Send a message to everyone else in the channel. */
|
|
108
|
+
send(event: string, payload?: unknown): void;
|
|
109
|
+
/** Share your presence state (e.g. `{ name: 'Ada' }`). Re-sent automatically after reconnects. */
|
|
110
|
+
track(state: Record<string, unknown>): void;
|
|
111
|
+
/** Stop sharing your presence. */
|
|
112
|
+
untrack(): void;
|
|
113
|
+
/** Called with everyone's presence (`{ [key]: state }`) whenever it changes. */
|
|
114
|
+
onPresence<T = Record<string, any>>(callback: (state: PresenceState<T>) => void): () => void;
|
|
115
|
+
/** Called if the server reports an error for this channel. */
|
|
116
|
+
onError(callback: (error: UseBeckyError) => void): () => void;
|
|
117
|
+
/** Current presence state. */
|
|
118
|
+
presence<T = Record<string, any>>(): PresenceState<T>;
|
|
119
|
+
/** Leave the channel and stop all its listeners. */
|
|
120
|
+
leave(): void;
|
|
121
|
+
/** @internal */
|
|
122
|
+
_reset(): void;
|
|
123
|
+
/** @internal */
|
|
124
|
+
_joined(presenceKey?: string | null): void;
|
|
125
|
+
/** @internal */
|
|
126
|
+
_broadcast(event: string, payload: unknown): void;
|
|
127
|
+
/** @internal */
|
|
128
|
+
_presence(state: PresenceState): void;
|
|
129
|
+
/** @internal */
|
|
130
|
+
_error(err: UseBeckyError): void;
|
|
131
|
+
}
|