@persql/sdk 1.2.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -167,7 +167,104 @@ function runOne(db, sql, params) {
167
167
  return { columns: cols, rows, rowsRead: rows.length, rowsWritten: 0 };
168
168
  }
169
169
  const info = stmt.run(...params);
170
- return { columns: [], rows: [], rowsRead: 0, rowsWritten: info.changes ?? 0 };
170
+ return {
171
+ columns: [],
172
+ rows: [],
173
+ rowsRead: 0,
174
+ rowsWritten: info.changes ?? 0,
175
+ changes: info.changes ?? 0,
176
+ lastInsertRowid: Number(info.lastInsertRowid ?? 0)
177
+ };
178
+ }
179
+
180
+ // src/connect.ts
181
+ async function createAuthorizeUrl(opts) {
182
+ const base = (opts.baseURL ?? "https://api.persql.com").replace(/\/$/, "");
183
+ const codeVerifier = opts.codeVerifier ?? randomUrlBytes(32);
184
+ const state = opts.state ?? randomUrlBytes(16);
185
+ const challenge = await sha256Base64Url(codeVerifier);
186
+ const params = new URLSearchParams({
187
+ response_type: "code",
188
+ client_id: opts.clientId,
189
+ redirect_uri: opts.redirectUri,
190
+ scope: opts.scope ?? "database",
191
+ code_challenge: challenge,
192
+ code_challenge_method: "S256",
193
+ state
194
+ });
195
+ return { url: `${base}/oauth/authorize?${params.toString()}`, codeVerifier, state };
196
+ }
197
+ async function exchangeAuthorizationCode(opts) {
198
+ const base = (opts.baseURL ?? "https://api.persql.com").replace(/\/$/, "");
199
+ const fetcher = opts.fetch ?? globalThis.fetch?.bind(globalThis);
200
+ if (!fetcher) throw new Error("PerSQL connect: no fetch available \u2014 pass { fetch }.");
201
+ const body = new URLSearchParams({
202
+ grant_type: "authorization_code",
203
+ code: opts.code,
204
+ client_id: opts.clientId,
205
+ redirect_uri: opts.redirectUri,
206
+ code_verifier: opts.codeVerifier
207
+ });
208
+ if (opts.clientSecret) body.set("client_secret", opts.clientSecret);
209
+ const res = await fetcher(`${base}/oauth/token`, {
210
+ method: "POST",
211
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
212
+ body: body.toString()
213
+ });
214
+ const json = await res.json().catch(() => null);
215
+ if (!res.ok || !json?.access_token || !json.database) {
216
+ throw new Error(
217
+ json?.error_description ?? json?.error ?? `PerSQL connect: token exchange failed (${res.status})`
218
+ );
219
+ }
220
+ return {
221
+ accessToken: json.access_token,
222
+ database: json.database,
223
+ apiUrl: json.api_url ?? base,
224
+ scope: json.scope ?? "",
225
+ idToken: json.id_token,
226
+ userEmail: json.user_email
227
+ };
228
+ }
229
+ function getCrypto() {
230
+ const c = globalThis.crypto;
231
+ if (!c?.getRandomValues) {
232
+ throw new Error(
233
+ 'PerSQL connect: Web Crypto is unavailable. In bare React Native, import "react-native-get-random-values" and a Web Crypto SHA-256 polyfill, or exchange the code on your server.'
234
+ );
235
+ }
236
+ return c;
237
+ }
238
+ function randomUrlBytes(n) {
239
+ const bytes = new Uint8Array(n);
240
+ getCrypto().getRandomValues(bytes);
241
+ return base64url(bytes);
242
+ }
243
+ async function sha256Base64Url(input) {
244
+ const c = getCrypto();
245
+ if (!c.subtle) {
246
+ throw new Error(
247
+ "PerSQL connect: crypto.subtle is unavailable (needed for PKCE S256). Polyfill Web Crypto, or exchange the code on your server."
248
+ );
249
+ }
250
+ const digest = await c.subtle.digest("SHA-256", new TextEncoder().encode(input));
251
+ return base64url(new Uint8Array(digest));
252
+ }
253
+ var B64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
254
+ function base64url(bytes) {
255
+ let out = "";
256
+ for (let i = 0; i < bytes.length; i += 3) {
257
+ const b0 = bytes[i];
258
+ const b1 = bytes[i + 1];
259
+ const b2 = bytes[i + 2];
260
+ out += B64URL[b0 >> 2];
261
+ out += B64URL[(b0 & 3) << 4 | (b1 ?? 0) >> 4];
262
+ if (b1 === void 0) break;
263
+ out += B64URL[(b1 & 15) << 2 | (b2 ?? 0) >> 6];
264
+ if (b2 === void 0) break;
265
+ out += B64URL[b2 & 63];
266
+ }
267
+ return out;
171
268
  }
172
269
 
173
270
  // src/index.ts
@@ -279,6 +376,38 @@ var PerSQL = class _PerSQL {
279
376
  const client = new _PerSQL({ token: plaintext, baseURL, fetch: opts.fetch });
280
377
  return Object.assign(client, { handedOff });
281
378
  }
379
+ /**
380
+ * Step 1 of the `database`-scope sign-in (user-owned app databases):
381
+ * build the `/oauth/authorize` URL plus the PKCE verifier + state to
382
+ * keep. Open `url` in a browser / in-app browser / Expo AuthSession,
383
+ * then call {@link PerSQL.completeConnect} with the returned `code`.
384
+ *
385
+ * const req = await PerSQL.beginConnect({
386
+ * clientId, redirectUri, scope: "openid database",
387
+ * });
388
+ * // open req.url, capture { code, state }; verify state === req.state
389
+ */
390
+ static beginConnect(opts) {
391
+ return createAuthorizeUrl(opts);
392
+ }
393
+ /**
394
+ * Step 2: exchange the redirect's `code` for a scoped database token and
395
+ * get back a ready client. The granted database is on `.grant.database`.
396
+ *
397
+ * const persql = await PerSQL.completeConnect({
398
+ * clientId, redirectUri, code, codeVerifier: req.codeVerifier,
399
+ * });
400
+ * const db = persql.database(persql.grant.database);
401
+ */
402
+ static async completeConnect(opts) {
403
+ const grant = await exchangeAuthorizationCode(opts);
404
+ const client = new _PerSQL({
405
+ token: grant.accessToken,
406
+ baseURL: grant.apiUrl,
407
+ fetch: opts.fetch
408
+ });
409
+ return Object.assign(client, { grant });
410
+ }
282
411
  database(a, b) {
283
412
  if (b !== void 0) return new PerSQLDatabase(this, a, b);
284
413
  const [ns, slug] = a.split("/");