@phibac/sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +53 -2
- package/dist/auth.d.ts +104 -0
- package/dist/auth.js +343 -0
- package/dist/auth.js.map +1 -0
- package/dist/brand.d.ts +7 -0
- package/dist/brand.js +8 -0
- package/dist/brand.js.map +1 -0
- package/dist/cache.d.ts +170 -0
- package/dist/cache.js +293 -0
- package/dist/cache.js.map +1 -0
- package/dist/collection.d.ts +119 -0
- package/dist/collection.js +511 -0
- package/dist/collection.js.map +1 -0
- package/dist/dpop.d.ts +50 -0
- package/dist/dpop.js +105 -0
- package/dist/dpop.js.map +1 -0
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +55 -0
- package/dist/errors.js.map +1 -0
- package/dist/files.d.ts +25 -0
- package/dist/files.js +65 -0
- package/dist/files.js.map +1 -0
- package/dist/http.d.ts +53 -0
- package/dist/http.js +130 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +90 -0
- package/dist/index.js +209 -0
- package/dist/index.js.map +1 -0
- package/dist/live.d.ts +116 -0
- package/dist/live.js +448 -0
- package/dist/live.js.map +1 -0
- package/dist/queue.d.ts +103 -0
- package/dist/queue.js +397 -0
- package/dist/queue.js.map +1 -0
- package/package.json +45 -4
- package/src/auth.ts +371 -0
- package/src/brand.ts +8 -0
- package/src/cache.ts +379 -0
- package/src/collection.ts +533 -0
- package/src/dpop.ts +132 -0
- package/src/errors.ts +61 -0
- package/src/files.ts +60 -0
- package/src/http.ts +154 -0
- package/src/index.ts +238 -0
- package/src/live.ts +434 -0
- package/src/queue.ts +419 -0
package/src/errors.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { BRAND } from "./brand.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* PbError is every error the SDK throws. code is a server error code (see
|
|
5
|
+
* the errors section of the agent docs) or one of the SDK's own: network,
|
|
6
|
+
* popup_blocked, sign_in_cancelled, access_denied. message says what went
|
|
7
|
+
* wrong, hint how to fix it, and extra holds every other field of the
|
|
8
|
+
* server's error body (for example reason, serverTime, consentUrl) plus
|
|
9
|
+
* retryAfter (seconds) on rate_limited.
|
|
10
|
+
*/
|
|
11
|
+
export class PbError extends Error {
|
|
12
|
+
code: string;
|
|
13
|
+
hint: string;
|
|
14
|
+
extra: Record<string, unknown>;
|
|
15
|
+
|
|
16
|
+
constructor(code: string, message: string, hint = "", extra: Record<string, unknown> = {}) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "PbError";
|
|
19
|
+
this.code = code;
|
|
20
|
+
this.hint = hint;
|
|
21
|
+
this.extra = extra;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The hint for every "sign in again" situation. */
|
|
26
|
+
export const SIGN_IN_HINT = `Call connect() (or signIn()) again from a click or key handler so the user can sign in to ${BRAND}.`;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* errorFromResponse turns a failed response into a PbError. The server's
|
|
30
|
+
* body is {"error": {"code", "message", "hint", ...extra}}; a body that is
|
|
31
|
+
* not of that form becomes code "internal" with the HTTP status in extra.
|
|
32
|
+
*/
|
|
33
|
+
export async function errorFromResponse(res: Response): Promise<PbError> {
|
|
34
|
+
let body: unknown;
|
|
35
|
+
try {
|
|
36
|
+
body = await res.json();
|
|
37
|
+
} catch {
|
|
38
|
+
body = undefined;
|
|
39
|
+
}
|
|
40
|
+
const extra: Record<string, unknown> = {};
|
|
41
|
+
let err: PbError;
|
|
42
|
+
const e = (body as { error?: unknown } | undefined)?.error;
|
|
43
|
+
if (e && typeof e === "object" && typeof (e as { code?: unknown }).code === "string") {
|
|
44
|
+
const { code, message, hint, ...rest } = e as Record<string, unknown>;
|
|
45
|
+
Object.assign(extra, rest);
|
|
46
|
+
err = new PbError(code as string, typeof message === "string" ? message : "", typeof hint === "string" ? hint : "", extra);
|
|
47
|
+
} else {
|
|
48
|
+
extra.status = res.status;
|
|
49
|
+
err = new PbError(
|
|
50
|
+
"internal",
|
|
51
|
+
`${BRAND} answered with HTTP ${res.status} and no error details.`,
|
|
52
|
+
"Retry later; if it keeps failing, check the server's base URL.",
|
|
53
|
+
extra,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
const retryAfter = Number(res.headers.get("Retry-After"));
|
|
57
|
+
if (res.status === 429 && res.headers.has("Retry-After") && Number.isFinite(retryAfter)) {
|
|
58
|
+
extra.retryAfter = retryAfter;
|
|
59
|
+
}
|
|
60
|
+
return err;
|
|
61
|
+
}
|
package/src/files.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Files: upload a blob (request an upload URL, PUT the bytes to it, mark
|
|
2
|
+
// it complete), get a short-lived download URL, and delete a file. Uploads
|
|
3
|
+
// and deletes are never queued: offline, or on any failure, they reject
|
|
4
|
+
// with a PbError.
|
|
5
|
+
import { BRAND } from "./brand.js";
|
|
6
|
+
import { PbError, errorFromResponse } from "./errors.js";
|
|
7
|
+
import type { Net } from "./queue.js";
|
|
8
|
+
|
|
9
|
+
const offline = () => new PbError("network", `Cannot upload a file to ${BRAND} while offline.`, "Upload again once the device is back online; uploads are not queued.");
|
|
10
|
+
const offlineDelete = () => new PbError("network", `Cannot delete a file on ${BRAND} while offline.`, "Delete it again once the device is back online; file deletes are not queued.");
|
|
11
|
+
|
|
12
|
+
export class Files {
|
|
13
|
+
constructor(private readonly net: Net) {}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* upload stores blob as a file of a record in collection and resolves with
|
|
17
|
+
* its file ID (f_...), to be kept in a fileRef field. The bytes go
|
|
18
|
+
* straight to the signed upload URL with Content-Type and no
|
|
19
|
+
* Authorization or DPoP header.
|
|
20
|
+
*/
|
|
21
|
+
async upload(blob: Blob, opts: { collection: string; rkey?: string }): Promise<string> {
|
|
22
|
+
if (!(blob instanceof Blob)) throw new PbError("invalid_request", "files.upload needs a Blob or File.", "Pass the file from an <input type=file> or a Blob.");
|
|
23
|
+
if (!this.net.deviceOnline) throw offline();
|
|
24
|
+
const mime = blob.type || "application/octet-stream";
|
|
25
|
+
const body: Record<string, unknown> = { size: blob.size, mime, collection: opts.collection };
|
|
26
|
+
if (opts.rkey !== undefined) body.rkey = opts.rkey;
|
|
27
|
+
const res = await this.net.request<{ fileId?: unknown; uploadUrl?: unknown }>("POST", "/v1/files", body);
|
|
28
|
+
if (typeof res?.fileId !== "string" || typeof res.uploadUrl !== "string") {
|
|
29
|
+
throw new PbError("invalid_response", `${BRAND} returned no upload URL.`, "Check that baseUrl points at the server.");
|
|
30
|
+
}
|
|
31
|
+
let put: Response;
|
|
32
|
+
try {
|
|
33
|
+
put = await fetch(res.uploadUrl, { method: "PUT", headers: { "Content-Type": mime }, body: blob });
|
|
34
|
+
} catch {
|
|
35
|
+
throw new PbError("network", `The file upload to ${BRAND} failed.`, "Check the network connection, then upload again.");
|
|
36
|
+
}
|
|
37
|
+
if (!put.ok) throw await errorFromResponse(put);
|
|
38
|
+
await this.net.request("POST", `/v1/files/${encodeURIComponent(res.fileId)}/complete`);
|
|
39
|
+
return res.fileId;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** url resolves with a short-lived download URL for the file. */
|
|
43
|
+
async url(fileId: string): Promise<string> {
|
|
44
|
+
const res = await this.net.request<{ url?: unknown }>("GET", `/v1/files/${encodeURIComponent(fileId)}`, undefined, { Accept: "application/json" });
|
|
45
|
+
if (typeof res?.url !== "string") throw new PbError("invalid_response", `${BRAND} returned no download URL.`, "Check that baseUrl points at the server.");
|
|
46
|
+
return res.url;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* delete removes the file at once and frees its storage. Only the app
|
|
51
|
+
* that owns the file's collection may delete it (forbidden otherwise); an
|
|
52
|
+
* unknown or already deleted file is not_found. Records whose fields name
|
|
53
|
+
* the file are not changed: clear those fields yourself. It works when the
|
|
54
|
+
* account is full or read-only. Not queued: offline it rejects.
|
|
55
|
+
*/
|
|
56
|
+
async delete(fileId: string): Promise<void> {
|
|
57
|
+
if (!this.net.deviceOnline) throw offlineDelete();
|
|
58
|
+
await this.net.request("DELETE", `/v1/files/${encodeURIComponent(fileId)}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/http.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// The HTTP client: every request carries the DPoP-bound access token and a
|
|
2
|
+
// fresh proof, and a failed request is retried at most once (wrong device
|
|
3
|
+
// clock, or an access token that needs refreshing).
|
|
4
|
+
import type { Auth } from "./auth.js";
|
|
5
|
+
import { BRAND } from "./brand.js";
|
|
6
|
+
import { PbError, errorFromResponse } from "./errors.js";
|
|
7
|
+
|
|
8
|
+
/** What attempt needs from Auth: proofs, and the clock correction. */
|
|
9
|
+
export interface ProofSigner {
|
|
10
|
+
proof(method: string, url: string, accessToken?: string): Promise<string>;
|
|
11
|
+
setServerTime(serverTime: string): void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* REQUEST_TIMEOUT_MS bounds every API request (sending it and reading the
|
|
16
|
+
* whole response). A request that takes longer is abandoned and fails as
|
|
17
|
+
* PbError "network", which the queue and catch-up retry.
|
|
18
|
+
*/
|
|
19
|
+
export const REQUEST_TIMEOUT_MS = 30_000;
|
|
20
|
+
|
|
21
|
+
export type Outcome = { ok: true; res: Response } | { ok: false; err: PbError };
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* attempt sends one request with a new DPoP proof for exactly this method
|
|
25
|
+
* and URL, plus "Authorization: DPoP <token>" when accessToken is given and
|
|
26
|
+
* a JSON body when body is not undefined. A failed response comes back as
|
|
27
|
+
* a PbError; a network failure is thrown as PbError "network".
|
|
28
|
+
*/
|
|
29
|
+
export async function attempt(
|
|
30
|
+
signer: ProofSigner,
|
|
31
|
+
method: string,
|
|
32
|
+
url: string,
|
|
33
|
+
body?: unknown,
|
|
34
|
+
accessToken?: string,
|
|
35
|
+
extraHeaders: Record<string, string> = {},
|
|
36
|
+
signal?: AbortSignal,
|
|
37
|
+
): Promise<Outcome> {
|
|
38
|
+
method = method.toUpperCase();
|
|
39
|
+
const headers: Record<string, string> = { ...extraHeaders, DPoP: await signer.proof(method, url, accessToken) };
|
|
40
|
+
if (accessToken !== undefined) headers.Authorization = `DPoP ${accessToken}`;
|
|
41
|
+
const init: RequestInit = { method, headers };
|
|
42
|
+
if (body !== undefined) {
|
|
43
|
+
headers["Content-Type"] = "application/json";
|
|
44
|
+
init.body = JSON.stringify(body);
|
|
45
|
+
}
|
|
46
|
+
// One controller per request: aborted by the timeout or by the caller's signal.
|
|
47
|
+
const ac = new AbortController();
|
|
48
|
+
let timedOut = false;
|
|
49
|
+
const timer = setTimeout(() => {
|
|
50
|
+
timedOut = true;
|
|
51
|
+
ac.abort();
|
|
52
|
+
}, REQUEST_TIMEOUT_MS);
|
|
53
|
+
const cancel = () => ac.abort();
|
|
54
|
+
if (signal?.aborted) ac.abort();
|
|
55
|
+
else signal?.addEventListener("abort", cancel, { once: true });
|
|
56
|
+
init.signal = ac.signal;
|
|
57
|
+
let res: Response;
|
|
58
|
+
try {
|
|
59
|
+
const sent = await fetch(url, init);
|
|
60
|
+
// Read the body inside the timeout too, then hand on a complete response.
|
|
61
|
+
const text = await sent.text();
|
|
62
|
+
res = new Response(text === "" && (sent.status === 204 || sent.status === 304) ? null : text, {
|
|
63
|
+
status: sent.status,
|
|
64
|
+
statusText: sent.statusText,
|
|
65
|
+
headers: sent.headers,
|
|
66
|
+
});
|
|
67
|
+
} catch {
|
|
68
|
+
throw new PbError(
|
|
69
|
+
"network",
|
|
70
|
+
timedOut
|
|
71
|
+
? `${BRAND} at ${new URL(url).origin} did not answer within ${REQUEST_TIMEOUT_MS / 1000} seconds.`
|
|
72
|
+
: ac.signal.aborted
|
|
73
|
+
? `The request to ${BRAND} was cancelled.`
|
|
74
|
+
: `Could not reach ${BRAND} at ${new URL(url).origin}.`,
|
|
75
|
+
"Check the network connection and the base URL, then retry.",
|
|
76
|
+
);
|
|
77
|
+
} finally {
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
signal?.removeEventListener("abort", cancel);
|
|
80
|
+
}
|
|
81
|
+
if (res.ok) return { ok: true, res };
|
|
82
|
+
return { ok: false, err: await errorFromResponse(res) };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* readJSON returns the parsed JSON body of a successful response, or
|
|
87
|
+
* undefined for an empty body. A body that is not JSON (for example a proxy's
|
|
88
|
+
* HTML page) is PbError invalid_response, never a raw SyntaxError.
|
|
89
|
+
*/
|
|
90
|
+
export async function readJSON(res: Response): Promise<unknown> {
|
|
91
|
+
let text: string;
|
|
92
|
+
try {
|
|
93
|
+
text = await res.text();
|
|
94
|
+
} catch {
|
|
95
|
+
throw new PbError("network", `The response from ${BRAND} was cut off.`, "Check the network connection, then retry.");
|
|
96
|
+
}
|
|
97
|
+
if (text === "") return undefined;
|
|
98
|
+
try {
|
|
99
|
+
return JSON.parse(text) as unknown;
|
|
100
|
+
} catch {
|
|
101
|
+
throw new PbError(
|
|
102
|
+
"invalid_response",
|
|
103
|
+
`${BRAND} answered with a body that is not JSON (HTTP ${res.status}).`,
|
|
104
|
+
"Check that baseUrl points at the server and not at a proxy or web page.",
|
|
105
|
+
{ status: res.status },
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* clockError returns the server's time when err rejected a DPoP proof
|
|
112
|
+
* because the device clock is wrong (reason dpop_iat), else undefined.
|
|
113
|
+
*/
|
|
114
|
+
export function clockError(err: PbError): string | undefined {
|
|
115
|
+
const t = err.extra.serverTime;
|
|
116
|
+
if (err.code === "unauthorized" && err.extra.reason === "dpop_iat" && typeof t === "string" && !Number.isNaN(Date.parse(t))) {
|
|
117
|
+
return t;
|
|
118
|
+
}
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export class Http {
|
|
123
|
+
private readonly base: string;
|
|
124
|
+
|
|
125
|
+
constructor(
|
|
126
|
+
private readonly auth: Auth,
|
|
127
|
+
baseUrl: string,
|
|
128
|
+
) {
|
|
129
|
+
this.base = baseUrl.replace(/\/+$/, "");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* request calls path (e.g. "/v1/records") on the server and returns the
|
|
134
|
+
* parsed JSON response (undefined for an empty body). On 401 it retries
|
|
135
|
+
* exactly once: with the server's time when the proof's iat was refused
|
|
136
|
+
* (dpop_iat), otherwise after refreshing the access token. A second
|
|
137
|
+
* failure, and every other error, is thrown as a PbError. headers are
|
|
138
|
+
* added to the request (e.g. Accept). Each attempt times out after
|
|
139
|
+
* REQUEST_TIMEOUT_MS; signal cancels the request (both fail as network).
|
|
140
|
+
*/
|
|
141
|
+
async request<T>(method: string, path: string, body?: unknown, headers?: Record<string, string>, signal?: AbortSignal): Promise<T> {
|
|
142
|
+
const url = this.base + path;
|
|
143
|
+
let token = await this.auth.accessToken();
|
|
144
|
+
let out = await attempt(this.auth, method, url, body, token, headers, signal);
|
|
145
|
+
if (!out.ok && out.err.code === "unauthorized") {
|
|
146
|
+
const serverTime = clockError(out.err);
|
|
147
|
+
if (serverTime) this.auth.setServerTime(serverTime);
|
|
148
|
+
else token = await this.auth.refresh(token);
|
|
149
|
+
out = await attempt(this.auth, method, url, body, token, headers, signal);
|
|
150
|
+
}
|
|
151
|
+
if (!out.ok) throw out.err;
|
|
152
|
+
return (await readJSON(out.res)) as T;
|
|
153
|
+
}
|
|
154
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
// The SDK's public entry point (the package's only export): connect()
|
|
2
|
+
// signs in and returns a Backend with typed collections, a local cache in
|
|
3
|
+
// IndexedDB, an offline write queue, live updates and files.
|
|
4
|
+
import { Auth, POPUP_FEATURES, POPUP_NAME, popupBlocked } from "./auth.js";
|
|
5
|
+
import { DEFAULT_BASE_URL } from "./brand.js";
|
|
6
|
+
import { Cache } from "./cache.js";
|
|
7
|
+
import { Bus, CollectionImpl, signedOut, type Ctx } from "./collection.js";
|
|
8
|
+
import { PbError } from "./errors.js";
|
|
9
|
+
import { Files } from "./files.js";
|
|
10
|
+
import { Http } from "./http.js";
|
|
11
|
+
import { Live } from "./live.js";
|
|
12
|
+
import { Flusher, Net, asPbError, type ConflictEvent } from "./queue.js";
|
|
13
|
+
|
|
14
|
+
export { PbError };
|
|
15
|
+
|
|
16
|
+
export interface Backend {
|
|
17
|
+
collection<T>(name: string, opts?: { versions?: number[]; schemaMajor?: number }): Collection<T>;
|
|
18
|
+
files: { upload(blob: Blob, opts: { collection: string; rkey?: string }): Promise<string>; url(fileId: string): Promise<string>;
|
|
19
|
+
delete(fileId: string): Promise<void> };
|
|
20
|
+
onConflict(cb: (e: { op: QueuedOp; error: PbError; localData: unknown }) => void): () => void;
|
|
21
|
+
/**
|
|
22
|
+
* online: the device is online and the last request reached the server.
|
|
23
|
+
* pending: the number of queued writes. problem: set while something the
|
|
24
|
+
* user must fix stops the queue or the live connection (storage_full,
|
|
25
|
+
* trial_ended, app_suspended, account_closed, or consent_required for a
|
|
26
|
+
* subscribed collection the app may not read); undefined otherwise.
|
|
27
|
+
*/
|
|
28
|
+
status(): { online: boolean; pending: number; problem?: PbError };
|
|
29
|
+
signOut(): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
export interface PbRecord<T> { id: string; collection: string; rkey: string; data: T; rev: number;
|
|
32
|
+
status: "pending" | "synced"; createdAt: string; updatedAt: string }
|
|
33
|
+
export interface Collection<T> {
|
|
34
|
+
create(data: T): Promise<PbRecord<T>>; update(rkey: string, patch: Partial<T>): Promise<PbRecord<T>>;
|
|
35
|
+
delete(rkey: string): Promise<void>; get(rkey: string): Promise<PbRecord<T> | null>; list(): Promise<PbRecord<T>[]>;
|
|
36
|
+
where(field: string, op: "==" | "!=" | "<" | "<=" | ">" | ">=" | "in", value: unknown): Query<T>;
|
|
37
|
+
orderBy(field: string, dir?: "asc" | "desc"): Query<T>;
|
|
38
|
+
subscribe(cb: (records: PbRecord<T>[]) => void): () => void;
|
|
39
|
+
requestAccess(): Promise<boolean>;
|
|
40
|
+
}
|
|
41
|
+
export interface Query<T> { where: Collection<T>["where"]; orderBy: Collection<T>["orderBy"]; limit(n: number): Query<T>;
|
|
42
|
+
get(): Promise<PbRecord<T>[]>; subscribe(cb: (records: PbRecord<T>[]) => void): () => void }
|
|
43
|
+
export interface QueuedOp { opId: string; kind: "create" | "update" | "delete"; collection: string; rkey: string;
|
|
44
|
+
input: { schemaMajor?: number; baseRev?: number; data?: unknown } }
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* connect signs the user in if needed and returns their backend for the
|
|
49
|
+
* app. Call it from a click or key handler: when no sign-in is stored it
|
|
50
|
+
* opens the sign-in popup, which browsers allow only inside a user gesture.
|
|
51
|
+
*
|
|
52
|
+
* Whether a sign-in is stored is known only after an IndexedDB read, so a
|
|
53
|
+
* blank popup is opened first, synchronously, and then either sent to the
|
|
54
|
+
* sign-in page or closed again. Outside a gesture (navigator.userActivation
|
|
55
|
+
* says so) no popup is opened: a stored sign-in still works, and a missing
|
|
56
|
+
* one rejects with popup_blocked. No network request is needed when a
|
|
57
|
+
* sign-in is stored, so connect() works offline.
|
|
58
|
+
*/
|
|
59
|
+
export function connect(opts: { app: string; baseUrl?: string; schemaMajors?: Record<string, number> }): Promise<Backend> {
|
|
60
|
+
let popup: Window | null = null;
|
|
61
|
+
try {
|
|
62
|
+
const activation = (navigator as Navigator & { userActivation?: { isActive: boolean } }).userActivation;
|
|
63
|
+
if (!activation || activation.isActive) popup = window.open("", POPUP_NAME, POPUP_FEATURES);
|
|
64
|
+
} catch {
|
|
65
|
+
popup = null;
|
|
66
|
+
}
|
|
67
|
+
return start(opts, popup);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function start(opts: { app: string; baseUrl?: string; schemaMajors?: Record<string, number> }, opened: Window | null): Promise<Backend> {
|
|
71
|
+
let popup = opened;
|
|
72
|
+
try {
|
|
73
|
+
const base = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
74
|
+
const auth = new Auth({ app: opts.app, baseUrl: base });
|
|
75
|
+
await auth.ready;
|
|
76
|
+
if (!auth.signedIn) {
|
|
77
|
+
if (!popup || popup.closed) throw popupBlocked();
|
|
78
|
+
const p = popup;
|
|
79
|
+
popup = null; // signIn owns it now and closes it on failure
|
|
80
|
+
await auth.signIn(p);
|
|
81
|
+
}
|
|
82
|
+
const origin = new URL(base).origin;
|
|
83
|
+
const userId = auth.userId!;
|
|
84
|
+
const part = `${origin} ${opts.app} ${userId}`;
|
|
85
|
+
const cache = await Cache.open(part);
|
|
86
|
+
return new BackendImpl(auth, cache, base, origin, userId, part, opts.schemaMajors ?? {});
|
|
87
|
+
} catch (e) {
|
|
88
|
+
throw asPbError(e);
|
|
89
|
+
} finally {
|
|
90
|
+
// Every path that did not hand the popup to signIn closes it here, so
|
|
91
|
+
// no blank window is left open (already signed in, or a failure).
|
|
92
|
+
if (popup && !popup.closed) popup.close();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The longest signOut() waits for work in flight before clearing the cache. */
|
|
97
|
+
const SIGN_OUT_WAIT_MS = 2000;
|
|
98
|
+
|
|
99
|
+
class BackendImpl implements Backend {
|
|
100
|
+
readonly files: Files;
|
|
101
|
+
private readonly ctx: Ctx;
|
|
102
|
+
private readonly conflicts = new Set<(e: ConflictEvent) => void>();
|
|
103
|
+
/** The union of the majors every handle of a collection reads. */
|
|
104
|
+
private readonly versions = new Map<string, Set<number>>();
|
|
105
|
+
private readonly channel: BroadcastChannel | null;
|
|
106
|
+
private readonly onOnline = () => {
|
|
107
|
+
this.ctx.net.online = true;
|
|
108
|
+
this.ctx.flusher.kick(true);
|
|
109
|
+
this.ctx.live.refresh();
|
|
110
|
+
};
|
|
111
|
+
private readonly onOffline = () => {
|
|
112
|
+
this.ctx.net.online = false;
|
|
113
|
+
};
|
|
114
|
+
private closed = false;
|
|
115
|
+
|
|
116
|
+
constructor(
|
|
117
|
+
private readonly auth: Auth,
|
|
118
|
+
private readonly cache: Cache,
|
|
119
|
+
base: string,
|
|
120
|
+
origin: string,
|
|
121
|
+
userId: string,
|
|
122
|
+
part: string,
|
|
123
|
+
schemaMajors: Record<string, number>,
|
|
124
|
+
) {
|
|
125
|
+
const net = new Net(new Http(auth, base));
|
|
126
|
+
const bus = new Bus();
|
|
127
|
+
// Other tabs of this app and user share the cache: tell them what changed.
|
|
128
|
+
this.channel = typeof BroadcastChannel === "undefined" ? null : new BroadcastChannel(`pb-cache ${part}`);
|
|
129
|
+
(this.channel as unknown as { unref?: () => void } | null)?.unref?.();
|
|
130
|
+
const flusher = new Flusher({
|
|
131
|
+
cache,
|
|
132
|
+
net,
|
|
133
|
+
lockName: `pb-queue ${part}`,
|
|
134
|
+
conflict: (e) => {
|
|
135
|
+
for (const cb of [...this.conflicts]) cb(e);
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
const live = new Live({ net, cache, base, versionsOf: (c) => { const v = this.versions.get(c); return v ? [...v] : undefined; } });
|
|
139
|
+
cache.onChange = (cols) => {
|
|
140
|
+
bus.emit(cols);
|
|
141
|
+
if (!this.closed) this.channel?.postMessage({ collections: [...cols] });
|
|
142
|
+
};
|
|
143
|
+
if (this.channel) {
|
|
144
|
+
this.channel.onmessage = (ev: MessageEvent) => {
|
|
145
|
+
const cols = (ev.data as { collections?: unknown } | null)?.collections;
|
|
146
|
+
if (Array.isArray(cols)) bus.emit(cols.filter((c): c is string => typeof c === "string"));
|
|
147
|
+
void flusher.count().catch(() => undefined);
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
this.ctx = {
|
|
151
|
+
userId,
|
|
152
|
+
origin,
|
|
153
|
+
cache,
|
|
154
|
+
net,
|
|
155
|
+
flusher,
|
|
156
|
+
live,
|
|
157
|
+
bus,
|
|
158
|
+
schemaMajors,
|
|
159
|
+
consent: { current: null },
|
|
160
|
+
check: () => {
|
|
161
|
+
if (this.closed) throw signedOut();
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
this.files = new Files(net);
|
|
165
|
+
window.addEventListener("online", this.onOnline);
|
|
166
|
+
window.addEventListener("offline", this.onOffline);
|
|
167
|
+
void flusher.count().then(
|
|
168
|
+
() => {
|
|
169
|
+
if (flusher.pending > 0) flusher.kick();
|
|
170
|
+
},
|
|
171
|
+
() => undefined,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
collection<T>(name: string, opts: { versions?: number[]; schemaMajor?: number } = {}): CollectionImpl<T> {
|
|
176
|
+
this.ctx.check();
|
|
177
|
+
if (opts.versions) {
|
|
178
|
+
// The changes feed and live updates keep the union of every handle's
|
|
179
|
+
// majors; each handle shows only its own (CollectionImpl.visible).
|
|
180
|
+
let set = this.versions.get(name);
|
|
181
|
+
const widened = set !== undefined && opts.versions.some((v) => !set!.has(v));
|
|
182
|
+
if (!set) this.versions.set(name, (set = new Set()));
|
|
183
|
+
for (const v of opts.versions) set.add(v);
|
|
184
|
+
// Records of the new majors were dropped before: fetch them again.
|
|
185
|
+
if (widened) this.ctx.live.granted(name);
|
|
186
|
+
}
|
|
187
|
+
return new CollectionImpl<T>(this.ctx, name, opts);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
onConflict(cb: (e: { op: QueuedOp; error: PbError; localData: unknown }) => void): () => void {
|
|
191
|
+
this.conflicts.add(cb);
|
|
192
|
+
return () => {
|
|
193
|
+
this.conflicts.delete(cb);
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
status(): { online: boolean; pending: number; problem?: PbError } {
|
|
198
|
+
const out: { online: boolean; pending: number; problem?: PbError } = { online: this.ctx.net.online, pending: this.ctx.flusher.pending };
|
|
199
|
+
const problem = this.ctx.net.problem();
|
|
200
|
+
if (problem) out.problem = problem;
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* signOut stops the queue and the live connection, deletes this user's
|
|
206
|
+
* cached records and queued writes for this app, and forgets the
|
|
207
|
+
* sign-in. The backend cannot be used afterwards.
|
|
208
|
+
*/
|
|
209
|
+
async signOut(): Promise<void> {
|
|
210
|
+
if (this.closed) return;
|
|
211
|
+
this.closed = true;
|
|
212
|
+
this.ctx.flusher.stop();
|
|
213
|
+
this.ctx.live.stop();
|
|
214
|
+
// Cancel this tab's requests in flight, then give the work in flight a
|
|
215
|
+
// short while to settle. Once stopped, nothing writes to the cache
|
|
216
|
+
// (every writer checks before opening its transaction), so the wait is
|
|
217
|
+
// only politeness and never needed for correctness; it is bounded
|
|
218
|
+
// because a flush may be waiting on another tab's lock.
|
|
219
|
+
this.ctx.net.abort();
|
|
220
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
221
|
+
await Promise.race([
|
|
222
|
+
Promise.all([this.ctx.flusher.idle(), this.ctx.live.idle()]),
|
|
223
|
+
new Promise<void>((r) => (timer = setTimeout(r, SIGN_OUT_WAIT_MS))),
|
|
224
|
+
]);
|
|
225
|
+
clearTimeout(timer);
|
|
226
|
+
window.removeEventListener("online", this.onOnline);
|
|
227
|
+
window.removeEventListener("offline", this.onOffline);
|
|
228
|
+
try {
|
|
229
|
+
await this.cache.clear();
|
|
230
|
+
this.cache.close();
|
|
231
|
+
await this.auth.signOut();
|
|
232
|
+
} catch (e) {
|
|
233
|
+
throw asPbError(e);
|
|
234
|
+
} finally {
|
|
235
|
+
this.channel?.close();
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|