@protobase/client 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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ //#region src/auth.d.ts
2
+ export type AuthUser = {
3
+ id: string;
4
+ email: string;
5
+ name: string;
6
+ role?: string | null;
7
+ };
8
+ /** A failed sign-in or sign-out, with Better Auth's status and code (for example `INVALID_EMAIL_OR_PASSWORD`). */
9
+ export declare class AuthError extends Error {
10
+ readonly status: number;
11
+ readonly code?: string | undefined;
12
+ constructor(message: string, status: number, code?: string | undefined);
13
+ }
14
+ export type AuthSessionOptions = {
15
+ /** Origin of the server; defaults to the page's own. */
16
+ origin?: string;
17
+ /** Where Better Auth is mounted. */
18
+ basePath?: string;
19
+ fetch?: typeof fetch;
20
+ /** Refresh this long before the token expires. */
21
+ refreshMarginMs?: number;
22
+ /** Called when a background refresh finds the session gone. */
23
+ onSignedOut?: () => void;
24
+ };
25
+ /** The expiry of a JWT in milliseconds, read from its payload (the signature is the server's business). */
26
+ export declare const tokenExpiry: (token: string) => number;
27
+ /** `needsAdmin` while no user exists yet; `passwordReset` when the server can email reset links. */
28
+ export type SetupStatus = {
29
+ needsAdmin: boolean;
30
+ passwordReset: boolean;
31
+ };
32
+ /**
33
+ * The browser side of Better Auth: sign in with email and password, and a short-lived JWT held in memory only
34
+ * (never in storage), fetched with the session cookie and refreshed before it expires.
35
+ */
36
+ export declare const createAuthSession: (options?: AuthSessionOptions) => {
37
+ token: ({ refresh }?: {
38
+ refresh?: boolean;
39
+ }) => Promise<string | undefined>;
40
+ /** Whether the first admin is still missing. Every server has a login, so a 404 means the URL is not a Protobase server. */
41
+ status: () => Promise<SetupStatus>;
42
+ /** The signed-in user from the session cookie, or `undefined`. */
43
+ session: () => Promise<AuthUser | undefined>;
44
+ signIn: (email: string, password: string) => Promise<AuthUser>;
45
+ signOut: () => Promise<void>;
46
+ /**
47
+ * Emails a reset link when an account has this address; the answer is the same either way. The link leads back to
48
+ * `redirectTo`, with `token` (or `error=INVALID_TOKEN`) added to its query.
49
+ */
50
+ requestPasswordReset: (email: string, redirectTo: string) => Promise<void>;
51
+ /** Sets a new password with the token from a reset link; the link works once. */
52
+ resetPassword: (token: string, newPassword: string) => Promise<void>;
53
+ };
54
+ export type AuthSession = ReturnType<typeof createAuthSession>;
55
+ /**
56
+ * A session that is already signed in with a token you hold, for stories and scripts (`protobase token <email>`).
57
+ * It never refreshes, so use a token that outlives the run.
58
+ */
59
+ export declare const createStaticSession: (token: string, user?: AuthUser) => AuthSession;
60
+ //#endregion
package/dist/auth.js ADDED
@@ -0,0 +1,141 @@
1
+ import { createAuthClient } from "better-auth/client";
2
+ import { jwtClient } from "better-auth/client/plugins";
3
+ //#region src/auth.ts
4
+ /** A failed sign-in or sign-out, with Better Auth's status and code (for example `INVALID_EMAIL_OR_PASSWORD`). */
5
+ var AuthError = class extends Error {
6
+ status;
7
+ code;
8
+ constructor(message, status, code) {
9
+ super(message);
10
+ this.status = status;
11
+ this.code = code;
12
+ this.name = "AuthError";
13
+ }
14
+ };
15
+ /** The expiry of a JWT in milliseconds, read from its payload (the signature is the server's business). */
16
+ const tokenExpiry = (token) => {
17
+ const payload = token.split(".")[1];
18
+ if (!payload) throw new Error("Not a JWT");
19
+ const json = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
20
+ if (typeof json.exp !== "number") throw new Error("The token has no expiry");
21
+ return json.exp * 1e3;
22
+ };
23
+ /**
24
+ * The browser side of Better Auth: sign in with email and password, and a short-lived JWT held in memory only
25
+ * (never in storage), fetched with the session cookie and refreshed before it expires.
26
+ */
27
+ const createAuthSession = (options = {}) => {
28
+ const origin = options.origin ?? globalThis.location?.origin ?? "http://localhost";
29
+ const basePath = options.basePath ?? "/api/auth";
30
+ const margin = options.refreshMarginMs ?? 6e4;
31
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
32
+ const client = createAuthClient({
33
+ baseURL: origin,
34
+ basePath,
35
+ plugins: [jwtClient()],
36
+ fetchOptions: { customFetchImpl: doFetch }
37
+ });
38
+ let cached;
39
+ let pending;
40
+ let timer;
41
+ const forget = () => {
42
+ cached = void 0;
43
+ clearTimeout(timer);
44
+ };
45
+ const load = async () => {
46
+ const { data } = await client.$fetch("/token");
47
+ if (!data?.token) {
48
+ forget();
49
+ return;
50
+ }
51
+ cached = {
52
+ token: data.token,
53
+ expiresAt: tokenExpiry(data.token)
54
+ };
55
+ clearTimeout(timer);
56
+ timer = setTimeout(() => void token({ refresh: true }).then((fresh) => fresh || options.onSignedOut?.()), Math.max(1e3, cached.expiresAt - Date.now() - margin));
57
+ return cached.token;
58
+ };
59
+ /** The bearer token; a cached one is reused until it is within the margin of expiring. `undefined` when signed out. */
60
+ const token = async ({ refresh = false } = {}) => {
61
+ if (!refresh && cached && cached.expiresAt - Date.now() > margin) return cached.token;
62
+ pending ??= load().finally(() => {
63
+ pending = void 0;
64
+ });
65
+ return pending;
66
+ };
67
+ return {
68
+ token,
69
+ /** Whether the first admin is still missing. Every server has a login, so a 404 means the URL is not a Protobase server. */
70
+ status: async () => {
71
+ const response = await doFetch(`${origin}${basePath}/status`);
72
+ if (response.status === 404) throw new AuthError("This server has no sign-in. Is the API URL right?", 404);
73
+ if (!response.ok) throw new AuthError("Could not read the sign-in status", response.status);
74
+ const body = await response.json();
75
+ return {
76
+ needsAdmin: Boolean(body.needsAdmin),
77
+ passwordReset: Boolean(body.passwordReset)
78
+ };
79
+ },
80
+ /** The signed-in user from the session cookie, or `undefined`. */
81
+ session: async () => {
82
+ const { data } = await client.getSession();
83
+ return data?.user;
84
+ },
85
+ signIn: async (email, password) => {
86
+ const { data, error } = await client.signIn.email({
87
+ email,
88
+ password
89
+ });
90
+ if (error || !data) throw new AuthError(error?.message || "Sign-in failed", error?.status ?? 500, error?.code);
91
+ await token({ refresh: true });
92
+ return data.user;
93
+ },
94
+ signOut: async () => {
95
+ forget();
96
+ await client.signOut();
97
+ },
98
+ /**
99
+ * Emails a reset link when an account has this address; the answer is the same either way. The link leads back to
100
+ * `redirectTo`, with `token` (or `error=INVALID_TOKEN`) added to its query.
101
+ */
102
+ requestPasswordReset: async (email, redirectTo) => {
103
+ const { error } = await client.requestPasswordReset({
104
+ email,
105
+ redirectTo
106
+ });
107
+ if (error) throw new AuthError(error.message || "Could not send the reset link", error.status, error.code);
108
+ },
109
+ /** Sets a new password with the token from a reset link; the link works once. */
110
+ resetPassword: async (token, newPassword) => {
111
+ const { error } = await client.resetPassword({
112
+ token,
113
+ newPassword
114
+ });
115
+ if (error) throw new AuthError(error.message || "Could not set the password", error.status, error.code);
116
+ }
117
+ };
118
+ };
119
+ /**
120
+ * A session that is already signed in with a token you hold, for stories and scripts (`protobase token <email>`).
121
+ * It never refreshes, so use a token that outlives the run.
122
+ */
123
+ const createStaticSession = (token, user = {
124
+ id: "token",
125
+ email: "token",
126
+ name: "API token",
127
+ role: null
128
+ }) => ({
129
+ token: async () => token,
130
+ status: async () => ({
131
+ needsAdmin: false,
132
+ passwordReset: false
133
+ }),
134
+ session: async () => user,
135
+ signIn: async () => user,
136
+ signOut: async () => void 0,
137
+ requestPasswordReset: async () => void 0,
138
+ resetPassword: async () => void 0
139
+ });
140
+ //#endregion
141
+ export { AuthError, createAuthSession, createStaticSession, tokenExpiry };
@@ -0,0 +1,37 @@
1
+ import { FilterInput, ListParams } from "./query-string.js";
2
+ import { ClientOptions } from "./transport.js";
3
+ import { BatchOp, BatchResult, Facet, Histogram, ListPage, MetaResult, RecordOf, ResourceRef, Series, SeriesParams, Stored } from "./types.js";
4
+ import { KeyValue } from "@protobase/schema";
5
+ //#region src/client.d.ts
6
+ export declare const createClient: (options?: ClientOptions) => {
7
+ list: <R extends ResourceRef>(resource: R, params?: ListParams) => Promise<ListPage<RecordOf<R>>>;
8
+ search: <R extends ResourceRef>(resource: R, params?: ListParams) => Promise<ListPage<RecordOf<R>>>;
9
+ get: <R extends ResourceRef>(resource: R, key: KeyValue | readonly KeyValue[]) => Promise<Stored<RecordOf<R>>>;
10
+ create: <R extends ResourceRef>(resource: R, body: Partial<RecordOf<R>>) => Promise<Stored<RecordOf<R>> & {
11
+ location: string;
12
+ }>;
13
+ update: <R extends ResourceRef>(resource: R, key: KeyValue | readonly KeyValue[], patch: Partial<RecordOf<R>>, etag: string) => Promise<Stored<RecordOf<R>>>;
14
+ remove: (resource: ResourceRef, key: KeyValue | readonly KeyValue[], { etag }?: {
15
+ etag?: string;
16
+ }) => Promise<void>;
17
+ undelete: <R extends ResourceRef>(resource: R, key: KeyValue | readonly KeyValue[]) => Promise<Stored<RecordOf<R>>>;
18
+ reveal: (resource: ResourceRef, key: KeyValue | readonly KeyValue[], field: string) => Promise<unknown>;
19
+ batchWrite: (ops: BatchOp[]) => Promise<BatchResult>;
20
+ facets: (resource: ResourceRef, field: string, o?: {
21
+ filter?: FilterInput;
22
+ limit?: number;
23
+ }) => Promise<Facet[]>;
24
+ series: (resource: ResourceRef, params: SeriesParams & {
25
+ filter?: FilterInput;
26
+ }) => Promise<Series>;
27
+ histogram: (resource: ResourceRef, field: string, o?: {
28
+ filter?: FilterInput;
29
+ buckets?: number;
30
+ }) => Promise<Histogram>;
31
+ seek: <R extends ResourceRef>(resource: R, params: ListParams & {
32
+ position: number;
33
+ }) => Promise<ListPage<RecordOf<R>>>;
34
+ meta: (etag?: string) => Promise<MetaResult>;
35
+ };
36
+ export type Client = ReturnType<typeof createClient>;
37
+ //#endregion
package/dist/client.js ADDED
@@ -0,0 +1,206 @@
1
+ import { filterText, listWire, queryString } from "./query-string.js";
2
+ import { createTransport } from "./transport.js";
3
+ import { encodeKey } from "@protobase/schema";
4
+ //#region src/client.ts
5
+ const nameOf = (resource) => typeof resource === "string" ? resource : resource.toModel().name;
6
+ const keyPath = (resource, key) => `/${nameOf(resource)}/${encodeKey(key)}`;
7
+ const toPage = (body, response) => ({
8
+ items: body.items,
9
+ nextPageToken: body.next_page_token,
10
+ totalSizeEstimate: body.total_size_estimate,
11
+ ...body.prev_page_token !== void 0 && { prevPageToken: body.prev_page_token },
12
+ ...body.total_size !== void 0 && { totalSize: body.total_size },
13
+ ...response.headers.get("x-protobase-warning") && { warning: response.headers.get("x-protobase-warning") }
14
+ });
15
+ const etagOf = (response) => response.headers.get("etag") ?? "";
16
+ /** A single-record response: the record without its `permissions` member, which travels beside it. */
17
+ const storedOf = async (response) => {
18
+ const { permissions, ...record } = await response.json();
19
+ return {
20
+ record,
21
+ etag: etagOf(response),
22
+ ...permissions && { permissions }
23
+ };
24
+ };
25
+ const createClient = (options = {}) => {
26
+ const send = createTransport(options);
27
+ const list = async (resource, params) => {
28
+ const response = await send({
29
+ method: "GET",
30
+ path: `/${nameOf(resource)}`,
31
+ query: queryString(listWire(params))
32
+ });
33
+ return toPage(await response.json(), response);
34
+ };
35
+ /** Same as `list`, with the parameters in a JSON body, for long filters. */
36
+ const search = async (resource, params) => {
37
+ const wire = listWire(params);
38
+ const response = await send({
39
+ method: "POST",
40
+ path: `/${nameOf(resource)}:search`,
41
+ body: {
42
+ ...wire,
43
+ fields: params?.fields
44
+ }
45
+ });
46
+ return toPage(await response.json(), response);
47
+ };
48
+ const get = async (resource, key) => {
49
+ return storedOf(await send({
50
+ method: "GET",
51
+ path: keyPath(resource, key)
52
+ }));
53
+ };
54
+ const create = async (resource, body) => {
55
+ const response = await send({
56
+ method: "POST",
57
+ path: `/${nameOf(resource)}`,
58
+ body
59
+ });
60
+ return {
61
+ record: await response.json(),
62
+ etag: etagOf(response),
63
+ location: response.headers.get("location") ?? ""
64
+ };
65
+ };
66
+ /** `etag` is what `get` returned; a stale one rejects with `PreconditionFailedError`. */
67
+ const update = async (resource, key, patch, etag) => {
68
+ return storedOf(await send({
69
+ method: "PATCH",
70
+ path: keyPath(resource, key),
71
+ body: patch,
72
+ headers: { "if-match": etag }
73
+ }));
74
+ };
75
+ /** `etag` is the version the user saw (`*` for any); a stale one rejects with `PreconditionFailedError`. */
76
+ const remove = async (resource, key, { etag } = {}) => {
77
+ await send({
78
+ method: "DELETE",
79
+ path: keyPath(resource, key),
80
+ headers: etag ? { "if-match": etag } : void 0
81
+ });
82
+ };
83
+ /** AIP-164: brings a soft-deleted record back. A record that is not deleted answers 409. */
84
+ const undelete = async (resource, key) => {
85
+ const response = await send({
86
+ method: "POST",
87
+ path: `${keyPath(resource, key)}:undelete`
88
+ });
89
+ return {
90
+ record: await response.json(),
91
+ etag: etagOf(response)
92
+ };
93
+ };
94
+ /** The value of a sensitive field of one record, which the record itself never carries. The server audits every call. */
95
+ const reveal = async (resource, key, field) => {
96
+ return (await (await send({
97
+ method: "POST",
98
+ path: `${keyPath(resource, key)}:reveal`,
99
+ body: { field }
100
+ })).json()).value;
101
+ };
102
+ /** Applies several writes atomically (`POST /api/v1:batchWrite`), for example a record and its lines on Save. */
103
+ const batchWrite = async (ops) => {
104
+ const keyText = (key) => typeof key === "object" && key !== null && "$ref" in key ? key : encodeKey(key);
105
+ const wireOps = ops.map((operation) => ({
106
+ ...operation,
107
+ resource: nameOf(operation.resource),
108
+ ..."key" in operation && { key: keyText(operation.key) },
109
+ ...operation.op === "reorder" && { keys: operation.keys.map(keyText) }
110
+ }));
111
+ return { results: (await (await send({
112
+ method: "POST",
113
+ path: ":batchWrite",
114
+ body: { ops: wireOps }
115
+ })).json()).results ?? [] };
116
+ };
117
+ const facets = async (resource, field, o = {}) => {
118
+ return (await (await send({
119
+ method: "GET",
120
+ path: `/${nameOf(resource)}:facets`,
121
+ query: queryString({
122
+ field,
123
+ filter: filterText(o.filter) || void 0,
124
+ limit: o.limit
125
+ })
126
+ })).json()).facets;
127
+ };
128
+ const series = async (resource, params) => {
129
+ const body = await (await send({
130
+ method: "GET",
131
+ path: `/${nameOf(resource)}:series`,
132
+ query: queryString({
133
+ field: params.field,
134
+ range: params.range,
135
+ from: params.from,
136
+ to: params.to,
137
+ granularity: params.granularity,
138
+ time_zone: params.timeZone,
139
+ filter: filterText(params.filter) || void 0
140
+ })
141
+ })).json();
142
+ return {
143
+ field: body.field,
144
+ granularity: body.granularity,
145
+ timeZone: body.time_zone,
146
+ points: body.points
147
+ };
148
+ };
149
+ const histogram = async (resource, field, o = {}) => {
150
+ return (await send({
151
+ method: "GET",
152
+ path: `/${nameOf(resource)}:histogram`,
153
+ query: queryString({
154
+ field,
155
+ buckets: o.buckets,
156
+ filter: filterText(o.filter) || void 0
157
+ })
158
+ })).json();
159
+ };
160
+ /** The page that starts at row `position` of a sort (scrollbar jumps), with the tokens of its own neighbours. Past the end it is empty. */
161
+ const seek = async (resource, params) => {
162
+ const response = await send({
163
+ method: "GET",
164
+ path: `/${nameOf(resource)}:seek`,
165
+ query: queryString({
166
+ ...listWire(params),
167
+ position: params.position
168
+ })
169
+ });
170
+ return toPage(await response.json(), response);
171
+ };
172
+ /** Pass the `etag` of the last result to get `{ status: 'unchanged' }` on a `304`. */
173
+ const meta = async (etag) => {
174
+ const response = await send({
175
+ method: "GET",
176
+ path: "/meta",
177
+ system: true,
178
+ headers: etag ? { "if-none-match": etag } : void 0,
179
+ accept: [304]
180
+ });
181
+ if (response.status === 304) return { status: "unchanged" };
182
+ return {
183
+ status: "modified",
184
+ meta: await response.json(),
185
+ etag: etagOf(response)
186
+ };
187
+ };
188
+ return {
189
+ list,
190
+ search,
191
+ get,
192
+ create,
193
+ update,
194
+ remove,
195
+ undelete,
196
+ reveal,
197
+ batchWrite,
198
+ facets,
199
+ series,
200
+ histogram,
201
+ seek,
202
+ meta
203
+ };
204
+ };
205
+ //#endregion
206
+ export { createClient };
@@ -0,0 +1,7 @@
1
+ import { FilterInput, ListParams, filterText, listWire } from "./query-string.js";
2
+ import { ClientOptions } from "./transport.js";
3
+ import { BatchOp, BatchRef, BatchResult, Facet, Histogram, HistogramBucket, ListPage, Meta, MetaResult, RecordOf, RecordPermissions, ResourcePermissions, ResourceRef, Series, SeriesParams, SeriesPoint, Stored } from "./types.js";
4
+ import { Client, createClient } from "./client.js";
5
+ import { ApiError, PreconditionFailedError, ProblemDetails, ProblemError, isApiError } from "./problem.js";
6
+ import { AuthError, AuthSession, AuthSessionOptions, AuthUser, SetupStatus, createAuthSession, createStaticSession, tokenExpiry } from "./auth.js";
7
+ export { ApiError, AuthError, type AuthSession, type AuthSessionOptions, type AuthUser, type BatchOp, type BatchRef, type BatchResult, type Client, type ClientOptions, type Facet, type FilterInput, type Histogram, type HistogramBucket, type ListPage, type ListParams, type Meta, type MetaResult, PreconditionFailedError, type ProblemDetails, type ProblemError, type RecordOf, type RecordPermissions, type ResourcePermissions, type ResourceRef, type Series, type SeriesParams, type SeriesPoint, type SetupStatus, type Stored, createAuthSession, createClient, createStaticSession, filterText, isApiError, listWire, tokenExpiry };
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ import { filterText, listWire } from "./query-string.js";
2
+ import { ApiError, PreconditionFailedError, isApiError } from "./problem.js";
3
+ import { createClient } from "./client.js";
4
+ import { AuthError, createAuthSession, createStaticSession, tokenExpiry } from "./auth.js";
5
+ export { ApiError, AuthError, PreconditionFailedError, createAuthSession, createClient, createStaticSession, filterText, isApiError, listWire, tokenExpiry };
@@ -0,0 +1,45 @@
1
+ //#region src/problem.d.ts
2
+ export type ProblemError = {
3
+ code?: string;
4
+ message: string;
5
+ hint?: string;
6
+ span?: {
7
+ start: number;
8
+ end: number;
9
+ };
10
+ field?: string;
11
+ parameter?: string;
12
+ /** The index of the operation in a batch that this error belongs to. */
13
+ operation?: number;
14
+ };
15
+ export type ProblemDetails = {
16
+ type: string;
17
+ title: string;
18
+ status: number;
19
+ detail?: string;
20
+ instance?: string;
21
+ /** The query parameter a filter or `order_by` error refers to. */
22
+ parameter?: string;
23
+ errors?: ProblemError[];
24
+ /** The index of the operation that failed, when the request was a batch. */
25
+ operation?: number;
26
+ };
27
+ /** A non-2xx response, parsed from `application/problem+json`. */
28
+ export declare class ApiError extends Error {
29
+ readonly problem: ProblemDetails;
30
+ constructor(problem: ProblemDetails);
31
+ get status(): number;
32
+ /** The problem slug, for example `invalid-filter` or `precondition-failed`. */
33
+ get slug(): string;
34
+ /** For a batch: the index of the operation that failed, so the UI can name it. */
35
+ get operation(): number | undefined;
36
+ get errors(): ProblemError[];
37
+ /** Filter errors carry the span of the offending text, so the UI can underline it. */
38
+ get filterErrors(): ProblemError[];
39
+ }
40
+ /** `412`: the record changed since it was read. */
41
+ export declare class PreconditionFailedError extends ApiError {
42
+ constructor(problem: ProblemDetails);
43
+ }
44
+ export declare const isApiError: (error: unknown) => error is ApiError;
45
+ //#endregion
@@ -0,0 +1,49 @@
1
+ //#region src/problem.ts
2
+ /** A non-2xx response, parsed from `application/problem+json`. */
3
+ var ApiError = class extends Error {
4
+ problem;
5
+ constructor(problem) {
6
+ super(problem.detail ?? problem.title);
7
+ this.problem = problem;
8
+ this.name = "ApiError";
9
+ }
10
+ get status() {
11
+ return this.problem.status;
12
+ }
13
+ /** The problem slug, for example `invalid-filter` or `precondition-failed`. */
14
+ get slug() {
15
+ return this.problem.type.split(":").at(-1) ?? "";
16
+ }
17
+ /** For a batch: the index of the operation that failed, so the UI can name it. */
18
+ get operation() {
19
+ return this.problem.operation ?? this.errors.find((entry) => entry.operation !== void 0)?.operation;
20
+ }
21
+ get errors() {
22
+ return this.problem.errors ?? [];
23
+ }
24
+ /** Filter errors carry the span of the offending text, so the UI can underline it. */
25
+ get filterErrors() {
26
+ return this.slug === "invalid-filter" ? this.errors : [];
27
+ }
28
+ };
29
+ /** `412`: the record changed since it was read. */
30
+ var PreconditionFailedError = class extends ApiError {
31
+ constructor(problem) {
32
+ super(problem);
33
+ this.name = "PreconditionFailedError";
34
+ }
35
+ };
36
+ const isApiError = (error) => error instanceof ApiError;
37
+ const isProblem = (body) => typeof body === "object" && body !== null && "type" in body && "status" in body;
38
+ /** Turns a failed response into a typed error; bodies that are not problem+json become a generic problem. */
39
+ const readProblem = async (response) => {
40
+ const body = response.headers.get("content-type")?.includes("json") ?? false ? await response.json() : void 0;
41
+ const problem = isProblem(body) ? body : {
42
+ type: "urn:protobase:problem:unknown",
43
+ title: response.statusText || "Request failed",
44
+ status: response.status
45
+ };
46
+ return problem.status === 412 ? new PreconditionFailedError(problem) : new ApiError(problem);
47
+ };
48
+ //#endregion
49
+ export { ApiError, PreconditionFailedError, isApiError, readProblem };
@@ -0,0 +1,23 @@
1
+ import { FilterExpr } from "@protobase/schema";
2
+ //#region src/query-string.d.ts
3
+ export type FilterInput = string | FilterExpr;
4
+ export type ListParams = {
5
+ filter?: FilterInput;
6
+ /** AIP-132 text, for example `createdAt desc`. */
7
+ orderBy?: string;
8
+ pageSize?: number;
9
+ pageToken?: string;
10
+ fields?: string[];
11
+ count?: 'exact';
12
+ };
13
+ export declare const filterText: (filter: FilterInput | undefined) => string | undefined;
14
+ /** The snake_case parameters of `GET /{resource}` and the body of `POST /{resource}:search`. */
15
+ export declare const listWire: (params?: ListParams) => {
16
+ filter: string | undefined;
17
+ order_by: string | undefined;
18
+ page_size: number | undefined;
19
+ page_token: string | undefined;
20
+ fields: string | undefined;
21
+ count: "exact" | undefined;
22
+ };
23
+ //#endregion
@@ -0,0 +1,20 @@
1
+ import { printFilter } from "@protobase/schema";
2
+ //#region src/query-string.ts
3
+ const filterText = (filter) => typeof filter === "string" ? filter : filter && printFilter(filter);
4
+ /** The snake_case parameters of `GET /{resource}` and the body of `POST /{resource}:search`. */
5
+ const listWire = (params = {}) => ({
6
+ filter: filterText(params.filter) || void 0,
7
+ order_by: params.orderBy,
8
+ page_size: params.pageSize,
9
+ page_token: params.pageToken || void 0,
10
+ fields: params.fields?.join(","),
11
+ count: params.count
12
+ });
13
+ const queryString = (wire) => {
14
+ const search = new URLSearchParams();
15
+ for (const [name, value] of Object.entries(wire)) if (value !== void 0) search.set(name, String(value));
16
+ const text = search.toString();
17
+ return text ? `?${text}` : "";
18
+ };
19
+ //#endregion
20
+ export { filterText, listWire, queryString };
@@ -0,0 +1,19 @@
1
+ //#region src/transport.d.ts
2
+ export type ClientOptions = {
3
+ /** Where `/api/v1` lives, without a trailing slash. Defaults to `/api/v1` on the current origin. */
4
+ baseUrl?: string;
5
+ fetch?: typeof fetch;
6
+ headers?: () => Record<string, string>;
7
+ /** Called with the `X-Meta-Version` of every response; a change means `/meta` should be refetched. */
8
+ onMetaVersion?: (version: string) => void;
9
+ /**
10
+ * The bearer token for a request. Called with `refresh: true` when the server answered 401, so the
11
+ * caller can fetch a new one; the request is then retried once.
12
+ */
13
+ token?: (options: {
14
+ refresh: boolean;
15
+ }) => Promise<string | undefined>;
16
+ /** Called when a request is still 401 after the retry: the session is over. */
17
+ onUnauthenticated?: () => void;
18
+ };
19
+ //#endregion
@@ -0,0 +1,33 @@
1
+ import { readProblem } from "./problem.js";
2
+ //#region src/transport.ts
3
+ const createTransport = (options = {}) => {
4
+ const baseUrl = options.baseUrl ?? "/api/v1";
5
+ const systemUrl = baseUrl.replace(/\/[^/]*$/, "");
6
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
7
+ return async ({ method, path, query = "", body, headers, accept = [], system }) => {
8
+ const attempt = async (refresh) => {
9
+ const token = await options.token?.({ refresh });
10
+ return doFetch(`${system ? systemUrl : baseUrl}${path}${query}`, {
11
+ method,
12
+ headers: {
13
+ ...body !== void 0 && { "content-type": "application/json" },
14
+ ...token && { authorization: `Bearer ${token}` },
15
+ ...options.headers?.(),
16
+ ...headers
17
+ },
18
+ body: body === void 0 ? void 0 : JSON.stringify(body)
19
+ });
20
+ };
21
+ let response = await attempt(false);
22
+ if (response.status === 401 && options.token) {
23
+ response = await attempt(true);
24
+ if (response.status === 401) options.onUnauthenticated?.();
25
+ }
26
+ const metaVersion = response.headers.get("x-meta-version");
27
+ if (metaVersion) options.onMetaVersion?.(metaVersion);
28
+ if (!response.ok && !accept.includes(response.status)) throw await readProblem(response);
29
+ return response;
30
+ };
31
+ };
32
+ //#endregion
33
+ export { createTransport };
@@ -0,0 +1,152 @@
1
+ import { InferRecord, ResourceModel, UserMenuModel, ViewModel } from "@protobase/schema";
2
+ import { PageModel } from "@protobase/layout";
3
+ //#region src/types.d.ts
4
+ /** A resource by name, or the builder from `resource(...)`, which carries its record type. */
5
+ export type ResourceRef = string | {
6
+ readonly $fields: unknown;
7
+ toModel(): ResourceModel;
8
+ };
9
+ /** Records as they travel: dates are ISO text, 64-bit integers and decimals are strings. */
10
+ export type RecordOf<R extends ResourceRef> = R extends {
11
+ readonly $fields: unknown;
12
+ } ? InferRecord<R> : Record<string, unknown>;
13
+ export type ListPage<T> = {
14
+ items: T[];
15
+ /** `""` on the last page. */
16
+ nextPageToken: string;
17
+ /** Only from `seek`; `""` on the first page. */
18
+ prevPageToken?: string;
19
+ totalSizeEstimate: number;
20
+ /** Only with `count: 'exact'`. */
21
+ totalSize?: number;
22
+ /** `X-Protobase-Warning`, for example a scan-guard notice. */
23
+ warning?: string;
24
+ };
25
+ export type Facet = {
26
+ value: string | number | boolean | null;
27
+ count: number;
28
+ };
29
+ export type SeriesPoint = {
30
+ bucket: string;
31
+ count: number;
32
+ };
33
+ export type Series = {
34
+ field: string;
35
+ granularity: string;
36
+ timeZone: string;
37
+ points: SeriesPoint[];
38
+ };
39
+ export type SeriesParams = {
40
+ field: string;
41
+ range?: '7d' | '30d' | '90d' | '1y' | 'all';
42
+ from?: string;
43
+ to?: string;
44
+ granularity?: 'hour' | 'day' | 'week' | 'month';
45
+ timeZone?: string;
46
+ };
47
+ export type HistogramBucket = {
48
+ from: number;
49
+ to: number;
50
+ count: number;
51
+ };
52
+ export type Histogram = {
53
+ min: number | null;
54
+ max: number | null;
55
+ buckets: HistogramBucket[];
56
+ };
57
+ /** What the signed-in user may do with a resource; `conditional` operations are decided per record by the server. */
58
+ export type ResourcePermissions = {
59
+ read?: boolean;
60
+ create: boolean;
61
+ update: boolean;
62
+ delete: boolean;
63
+ conditional: Array<'create' | 'update' | 'delete'>;
64
+ };
65
+ export type Meta = {
66
+ resources: ResourceModel[];
67
+ views: ViewModel[];
68
+ pages?: PageModel[];
69
+ permissions?: Record<string, ResourcePermissions>;
70
+ userMenu?: UserMenuModel;
71
+ };
72
+ export type MetaResult = {
73
+ status: 'modified';
74
+ meta: Meta;
75
+ etag: string;
76
+ } | {
77
+ status: 'unchanged';
78
+ };
79
+ /** What the caller may do with one record; `fields` maps each readable field to `edit` or `read`, hidden ones are absent. */
80
+ export type RecordPermissions = {
81
+ update: boolean;
82
+ delete: boolean;
83
+ fields?: Record<string, 'edit' | 'read'>;
84
+ };
85
+ export type Stored<T> = {
86
+ record: T;
87
+ etag: string;
88
+ permissions?: RecordPermissions;
89
+ };
90
+ /** A reference to a record created earlier in the same batch (`ref` on its `create`). */
91
+ export type BatchRef = {
92
+ $ref: string;
93
+ field?: string;
94
+ };
95
+ type Key = string | number | readonly (string | number)[] | BatchRef;
96
+ /**
97
+ * One operation of `POST /api/v1:batchWrite`. The batch runs in a single transaction: either every operation is
98
+ * applied or none is, and a failure names the operation that caused it.
99
+ */
100
+ export type BatchOp = {
101
+ op: 'create';
102
+ resource: ResourceRef;
103
+ data: Record<string, unknown>;
104
+ ref?: string;
105
+ } | {
106
+ op: 'update';
107
+ resource: ResourceRef;
108
+ key: Key;
109
+ data: Record<string, unknown>;
110
+ etag?: string;
111
+ } | {
112
+ op: 'delete';
113
+ resource: ResourceRef;
114
+ key: Key;
115
+ etag?: string;
116
+ } |
117
+ /** Renumbers `field` of the records so they sort in the order of `keys`; `etags` maps each key (as URL text) to its ETag. */
118
+ {
119
+ op: 'reorder';
120
+ resource: ResourceRef;
121
+ field: string;
122
+ keys: Key[];
123
+ etags?: Record<string, string>;
124
+ };
125
+ /** One entry per operation, in order. A `reorder` lists every key in its final order with its new ETag. */
126
+ export type BatchOpResult = {
127
+ op: 'create';
128
+ resource: string;
129
+ ref?: string;
130
+ record: Record<string, unknown>;
131
+ etag: string;
132
+ } | {
133
+ op: 'update';
134
+ resource: string;
135
+ record: Record<string, unknown>;
136
+ etag: string;
137
+ } | {
138
+ op: 'delete';
139
+ resource: string;
140
+ deleted: true;
141
+ } | {
142
+ op: 'reorder';
143
+ resource: string;
144
+ records: Array<{
145
+ record: Record<string, unknown>;
146
+ etag: string;
147
+ }>;
148
+ };
149
+ export type BatchResult = {
150
+ results: BatchOpResult[];
151
+ };
152
+ //#endregion
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@protobase/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Typed fetch client for the Protobase REST API.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/PrototeamHQ/protobase.git",
9
+ "directory": "packages/client"
10
+ },
11
+ "homepage": "https://docs.protobase.net",
12
+ "type": "module",
13
+ "sideEffects": false,
14
+ "engines": {
15
+ "node": ">=22.12.0"
16
+ },
17
+ "exports": {
18
+ ".": "./dist/index.js"
19
+ },
20
+ "types": "./dist/index.d.ts",
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "dependencies": {
28
+ "better-auth": "^1.7.7",
29
+ "@protobase/layout": "0.1.0",
30
+ "@protobase/schema": "0.1.0"
31
+ },
32
+ "scripts": {
33
+ "build": "tsdown"
34
+ }
6
35
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.