@xata.io/client 0.0.0-alpha.vec0bff6 → 0.0.0-alpha.vec26c56

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/index.mjs CHANGED
@@ -1,3 +1,25 @@
1
+ const defaultTrace = async (_name, fn, _options) => {
2
+ return await fn({
3
+ setAttributes: () => {
4
+ return;
5
+ }
6
+ });
7
+ };
8
+ const TraceAttributes = {
9
+ KIND: "xata.trace.kind",
10
+ VERSION: "xata.sdk.version",
11
+ TABLE: "xata.table",
12
+ HTTP_REQUEST_ID: "http.request_id",
13
+ HTTP_STATUS_CODE: "http.status_code",
14
+ HTTP_HOST: "http.host",
15
+ HTTP_SCHEME: "http.scheme",
16
+ HTTP_USER_AGENT: "http.user_agent",
17
+ HTTP_METHOD: "http.method",
18
+ HTTP_URL: "http.url",
19
+ HTTP_ROUTE: "http.route",
20
+ HTTP_TARGET: "http.target"
21
+ };
22
+
1
23
  function notEmpty(value) {
2
24
  return value !== null && value !== void 0;
3
25
  }
@@ -122,13 +144,13 @@ function getFetchImplementation(userFetch) {
122
144
  const fetchImpl = userFetch ?? globalFetch;
123
145
  if (!fetchImpl) {
124
146
  throw new Error(
125
- `The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`
147
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
126
148
  );
127
149
  }
128
150
  return fetchImpl;
129
151
  }
130
152
 
131
- const VERSION = "0.0.0-alpha.vec0bff6";
153
+ const VERSION = "0.0.0-alpha.vec26c56";
132
154
 
133
155
  class ErrorWithCause extends Error {
134
156
  constructor(message, options) {
@@ -179,7 +201,10 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
179
201
  }, {});
180
202
  const query = new URLSearchParams(cleanQueryParams).toString();
181
203
  const queryString = query.length > 0 ? `?${query}` : "";
182
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
204
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
205
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
206
+ }, {});
207
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
183
208
  };
184
209
  function buildBaseUrl({
185
210
  path,
@@ -187,10 +212,10 @@ function buildBaseUrl({
187
212
  apiUrl,
188
213
  pathParams
189
214
  }) {
190
- if (!pathParams?.workspace)
215
+ if (pathParams?.workspace === void 0 || !path.startsWith("/db"))
191
216
  return `${apiUrl}${path}`;
192
217
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
193
- return url.replace("{workspaceId}", pathParams.workspace);
218
+ return url.replace("{workspaceId}", String(pathParams.workspace));
194
219
  }
195
220
  function hostHeader(url) {
196
221
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -207,245 +232,386 @@ async function fetch$1({
207
232
  fetchImpl,
208
233
  apiKey,
209
234
  apiUrl,
210
- workspacesApiUrl
235
+ workspacesApiUrl,
236
+ trace,
237
+ signal,
238
+ clientID,
239
+ sessionID
211
240
  }) {
212
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
213
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
214
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
215
- const response = await fetchImpl(url, {
216
- method: method.toUpperCase(),
217
- body: body ? JSON.stringify(body) : void 0,
218
- headers: {
219
- "Content-Type": "application/json",
220
- "User-Agent": `Xata client-ts/${VERSION}`,
221
- ...headers,
222
- ...hostHeader(fullUrl),
223
- Authorization: `Bearer ${apiKey}`
224
- }
225
- });
226
- if (response.status === 204) {
227
- return {};
228
- }
229
- const requestId = response.headers?.get("x-request-id") ?? void 0;
241
+ return trace(
242
+ `${method.toUpperCase()} ${path}`,
243
+ async ({ setAttributes }) => {
244
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
245
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
246
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
247
+ setAttributes({
248
+ [TraceAttributes.HTTP_URL]: url,
249
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
250
+ });
251
+ const response = await fetchImpl(url, {
252
+ method: method.toUpperCase(),
253
+ body: body ? JSON.stringify(body) : void 0,
254
+ headers: {
255
+ "Content-Type": "application/json",
256
+ "User-Agent": `Xata client-ts/${VERSION}`,
257
+ "X-Xata-Client-ID": clientID ?? "",
258
+ "X-Xata-Session-ID": sessionID ?? "",
259
+ ...headers,
260
+ ...hostHeader(fullUrl),
261
+ Authorization: `Bearer ${apiKey}`
262
+ },
263
+ signal
264
+ });
265
+ if (response.status === 204) {
266
+ return {};
267
+ }
268
+ const { host, protocol } = parseUrl(response.url);
269
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
270
+ setAttributes({
271
+ [TraceAttributes.KIND]: "http",
272
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
273
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
274
+ [TraceAttributes.HTTP_HOST]: host,
275
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
276
+ });
277
+ try {
278
+ const jsonResponse = await response.json();
279
+ if (response.ok) {
280
+ return jsonResponse;
281
+ }
282
+ throw new FetcherError(response.status, jsonResponse, requestId);
283
+ } catch (error) {
284
+ throw new FetcherError(response.status, error, requestId);
285
+ }
286
+ },
287
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
288
+ );
289
+ }
290
+ function parseUrl(url) {
230
291
  try {
231
- const jsonResponse = await response.json();
232
- if (response.ok) {
233
- return jsonResponse;
234
- }
235
- throw new FetcherError(response.status, jsonResponse, requestId);
292
+ const { host, protocol } = new URL(url);
293
+ return { host, protocol };
236
294
  } catch (error) {
237
- throw new FetcherError(response.status, error, requestId);
295
+ return {};
238
296
  }
239
297
  }
240
298
 
241
- const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
242
- const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
243
- const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
244
- const getUserAPIKeys = (variables) => fetch$1({
299
+ const getUser = (variables, signal) => fetch$1({ url: "/user", method: "get", ...variables, signal });
300
+ const updateUser = (variables, signal) => fetch$1({
301
+ url: "/user",
302
+ method: "put",
303
+ ...variables,
304
+ signal
305
+ });
306
+ const deleteUser = (variables, signal) => fetch$1({ url: "/user", method: "delete", ...variables, signal });
307
+ const getUserAPIKeys = (variables, signal) => fetch$1({
245
308
  url: "/user/keys",
246
309
  method: "get",
247
- ...variables
310
+ ...variables,
311
+ signal
248
312
  });
249
- const createUserAPIKey = (variables) => fetch$1({
313
+ const createUserAPIKey = (variables, signal) => fetch$1({
250
314
  url: "/user/keys/{keyName}",
251
315
  method: "post",
252
- ...variables
316
+ ...variables,
317
+ signal
253
318
  });
254
- const deleteUserAPIKey = (variables) => fetch$1({
319
+ const deleteUserAPIKey = (variables, signal) => fetch$1({
255
320
  url: "/user/keys/{keyName}",
256
321
  method: "delete",
257
- ...variables
322
+ ...variables,
323
+ signal
258
324
  });
259
- const createWorkspace = (variables) => fetch$1({
325
+ const createWorkspace = (variables, signal) => fetch$1({
260
326
  url: "/workspaces",
261
327
  method: "post",
262
- ...variables
328
+ ...variables,
329
+ signal
263
330
  });
264
- const getWorkspacesList = (variables) => fetch$1({
331
+ const getWorkspacesList = (variables, signal) => fetch$1({
265
332
  url: "/workspaces",
266
333
  method: "get",
267
- ...variables
334
+ ...variables,
335
+ signal
268
336
  });
269
- const getWorkspace = (variables) => fetch$1({
337
+ const getWorkspace = (variables, signal) => fetch$1({
270
338
  url: "/workspaces/{workspaceId}",
271
339
  method: "get",
272
- ...variables
340
+ ...variables,
341
+ signal
273
342
  });
274
- const updateWorkspace = (variables) => fetch$1({
343
+ const updateWorkspace = (variables, signal) => fetch$1({
275
344
  url: "/workspaces/{workspaceId}",
276
345
  method: "put",
277
- ...variables
346
+ ...variables,
347
+ signal
278
348
  });
279
- const deleteWorkspace = (variables) => fetch$1({
349
+ const deleteWorkspace = (variables, signal) => fetch$1({
280
350
  url: "/workspaces/{workspaceId}",
281
351
  method: "delete",
282
- ...variables
352
+ ...variables,
353
+ signal
283
354
  });
284
- const getWorkspaceMembersList = (variables) => fetch$1({
355
+ const getWorkspaceMembersList = (variables, signal) => fetch$1({
285
356
  url: "/workspaces/{workspaceId}/members",
286
357
  method: "get",
287
- ...variables
358
+ ...variables,
359
+ signal
288
360
  });
289
- const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
290
- const removeWorkspaceMember = (variables) => fetch$1({
361
+ const updateWorkspaceMemberRole = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
362
+ const removeWorkspaceMember = (variables, signal) => fetch$1({
291
363
  url: "/workspaces/{workspaceId}/members/{userId}",
292
364
  method: "delete",
293
- ...variables
365
+ ...variables,
366
+ signal
294
367
  });
295
- const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
296
- const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
297
- const cancelWorkspaceMemberInvite = (variables) => fetch$1({
368
+ const inviteWorkspaceMember = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
369
+ const updateWorkspaceMemberInvite = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
370
+ const cancelWorkspaceMemberInvite = (variables, signal) => fetch$1({
298
371
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
299
372
  method: "delete",
300
- ...variables
373
+ ...variables,
374
+ signal
301
375
  });
302
- const resendWorkspaceMemberInvite = (variables) => fetch$1({
376
+ const resendWorkspaceMemberInvite = (variables, signal) => fetch$1({
303
377
  url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
304
378
  method: "post",
305
- ...variables
379
+ ...variables,
380
+ signal
306
381
  });
307
- const acceptWorkspaceMemberInvite = (variables) => fetch$1({
382
+ const acceptWorkspaceMemberInvite = (variables, signal) => fetch$1({
308
383
  url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
309
384
  method: "post",
310
- ...variables
385
+ ...variables,
386
+ signal
311
387
  });
312
- const getDatabaseList = (variables) => fetch$1({
388
+ const getDatabaseList = (variables, signal) => fetch$1({
313
389
  url: "/dbs",
314
390
  method: "get",
315
- ...variables
391
+ ...variables,
392
+ signal
316
393
  });
317
- const getBranchList = (variables) => fetch$1({
394
+ const getBranchList = (variables, signal) => fetch$1({
318
395
  url: "/dbs/{dbName}",
319
396
  method: "get",
320
- ...variables
397
+ ...variables,
398
+ signal
321
399
  });
322
- const createDatabase = (variables) => fetch$1({
400
+ const createDatabase = (variables, signal) => fetch$1({
323
401
  url: "/dbs/{dbName}",
324
402
  method: "put",
325
- ...variables
403
+ ...variables,
404
+ signal
326
405
  });
327
- const deleteDatabase = (variables) => fetch$1({
406
+ const deleteDatabase = (variables, signal) => fetch$1({
328
407
  url: "/dbs/{dbName}",
329
408
  method: "delete",
330
- ...variables
409
+ ...variables,
410
+ signal
411
+ });
412
+ const getDatabaseMetadata = (variables, signal) => fetch$1({
413
+ url: "/dbs/{dbName}/metadata",
414
+ method: "get",
415
+ ...variables,
416
+ signal
331
417
  });
332
- const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
333
- const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
334
- const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
335
- const resolveBranch = (variables) => fetch$1({
418
+ const updateDatabaseMetadata = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
419
+ const getGitBranchesMapping = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
420
+ const addGitBranchesEntry = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
421
+ const removeGitBranchesEntry = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
422
+ const resolveBranch = (variables, signal) => fetch$1({
336
423
  url: "/dbs/{dbName}/resolveBranch",
337
424
  method: "get",
338
- ...variables
425
+ ...variables,
426
+ signal
339
427
  });
340
- const getBranchDetails = (variables) => fetch$1({
428
+ const queryMigrationRequests = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
429
+ const createMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
430
+ const getMigrationRequest = (variables, signal) => fetch$1({
431
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
432
+ method: "get",
433
+ ...variables,
434
+ signal
435
+ });
436
+ const updateMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
437
+ const listMigrationRequestsCommits = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
438
+ const compareMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
439
+ const getMigrationRequestIsMerged = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
440
+ const mergeMigrationRequest = (variables, signal) => fetch$1({
441
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
442
+ method: "post",
443
+ ...variables,
444
+ signal
445
+ });
446
+ const getBranchDetails = (variables, signal) => fetch$1({
341
447
  url: "/db/{dbBranchName}",
342
448
  method: "get",
343
- ...variables
449
+ ...variables,
450
+ signal
344
451
  });
345
- const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
346
- const deleteBranch = (variables) => fetch$1({
452
+ const createBranch = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
453
+ const deleteBranch = (variables, signal) => fetch$1({
347
454
  url: "/db/{dbBranchName}",
348
455
  method: "delete",
349
- ...variables
456
+ ...variables,
457
+ signal
350
458
  });
351
- const updateBranchMetadata = (variables) => fetch$1({
459
+ const updateBranchMetadata = (variables, signal) => fetch$1({
352
460
  url: "/db/{dbBranchName}/metadata",
353
461
  method: "put",
354
- ...variables
462
+ ...variables,
463
+ signal
355
464
  });
356
- const getBranchMetadata = (variables) => fetch$1({
465
+ const getBranchMetadata = (variables, signal) => fetch$1({
357
466
  url: "/db/{dbBranchName}/metadata",
358
467
  method: "get",
359
- ...variables
468
+ ...variables,
469
+ signal
360
470
  });
361
- const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
362
- const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
363
- const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
364
- const getBranchStats = (variables) => fetch$1({
471
+ const getBranchMigrationHistory = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
472
+ const executeBranchMigrationPlan = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
473
+ const getBranchMigrationPlan = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
474
+ const compareBranchWithUserSchema = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
475
+ const compareBranchSchemas = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
476
+ const updateBranchSchema = (variables, signal) => fetch$1({
477
+ url: "/db/{dbBranchName}/schema/update",
478
+ method: "post",
479
+ ...variables,
480
+ signal
481
+ });
482
+ const previewBranchSchemaEdit = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
483
+ const applyBranchSchemaEdit = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
484
+ const getBranchSchemaHistory = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
485
+ const getBranchStats = (variables, signal) => fetch$1({
365
486
  url: "/db/{dbBranchName}/stats",
366
487
  method: "get",
367
- ...variables
488
+ ...variables,
489
+ signal
368
490
  });
369
- const createTable = (variables) => fetch$1({
491
+ const createTable = (variables, signal) => fetch$1({
370
492
  url: "/db/{dbBranchName}/tables/{tableName}",
371
493
  method: "put",
372
- ...variables
494
+ ...variables,
495
+ signal
373
496
  });
374
- const deleteTable = (variables) => fetch$1({
497
+ const deleteTable = (variables, signal) => fetch$1({
375
498
  url: "/db/{dbBranchName}/tables/{tableName}",
376
499
  method: "delete",
377
- ...variables
500
+ ...variables,
501
+ signal
378
502
  });
379
- const updateTable = (variables) => fetch$1({
503
+ const updateTable = (variables, signal) => fetch$1({
380
504
  url: "/db/{dbBranchName}/tables/{tableName}",
381
505
  method: "patch",
382
- ...variables
506
+ ...variables,
507
+ signal
383
508
  });
384
- const getTableSchema = (variables) => fetch$1({
509
+ const getTableSchema = (variables, signal) => fetch$1({
385
510
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
386
511
  method: "get",
387
- ...variables
512
+ ...variables,
513
+ signal
388
514
  });
389
- const setTableSchema = (variables) => fetch$1({
515
+ const setTableSchema = (variables, signal) => fetch$1({
390
516
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
391
517
  method: "put",
392
- ...variables
518
+ ...variables,
519
+ signal
393
520
  });
394
- const getTableColumns = (variables) => fetch$1({
521
+ const getTableColumns = (variables, signal) => fetch$1({
395
522
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
396
523
  method: "get",
397
- ...variables
524
+ ...variables,
525
+ signal
398
526
  });
399
- const addTableColumn = (variables) => fetch$1({
527
+ const addTableColumn = (variables, signal) => fetch$1({
400
528
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
401
529
  method: "post",
402
- ...variables
530
+ ...variables,
531
+ signal
403
532
  });
404
- const getColumn = (variables) => fetch$1({
533
+ const getColumn = (variables, signal) => fetch$1({
405
534
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
406
535
  method: "get",
407
- ...variables
536
+ ...variables,
537
+ signal
408
538
  });
409
- const deleteColumn = (variables) => fetch$1({
539
+ const deleteColumn = (variables, signal) => fetch$1({
410
540
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
411
541
  method: "delete",
412
- ...variables
542
+ ...variables,
543
+ signal
413
544
  });
414
- const updateColumn = (variables) => fetch$1({
545
+ const updateColumn = (variables, signal) => fetch$1({
415
546
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
416
547
  method: "patch",
417
- ...variables
548
+ ...variables,
549
+ signal
418
550
  });
419
- const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
420
- const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
421
- const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
422
- const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
423
- const deleteRecord = (variables) => fetch$1({
551
+ const insertRecord = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
552
+ const insertRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
553
+ const updateRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
554
+ const upsertRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
555
+ const deleteRecord = (variables, signal) => fetch$1({
424
556
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
425
557
  method: "delete",
426
- ...variables
558
+ ...variables,
559
+ signal
427
560
  });
428
- const getRecord = (variables) => fetch$1({
561
+ const getRecord = (variables, signal) => fetch$1({
429
562
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
430
563
  method: "get",
431
- ...variables
564
+ ...variables,
565
+ signal
432
566
  });
433
- const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
434
- const queryTable = (variables) => fetch$1({
567
+ const bulkInsertTableRecords = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
568
+ const queryTable = (variables, signal) => fetch$1({
435
569
  url: "/db/{dbBranchName}/tables/{tableName}/query",
436
570
  method: "post",
437
- ...variables
571
+ ...variables,
572
+ signal
438
573
  });
439
- const searchTable = (variables) => fetch$1({
574
+ const searchTable = (variables, signal) => fetch$1({
440
575
  url: "/db/{dbBranchName}/tables/{tableName}/search",
441
576
  method: "post",
442
- ...variables
577
+ ...variables,
578
+ signal
443
579
  });
444
- const searchBranch = (variables) => fetch$1({
580
+ const searchBranch = (variables, signal) => fetch$1({
445
581
  url: "/db/{dbBranchName}/search",
446
582
  method: "post",
447
- ...variables
583
+ ...variables,
584
+ signal
585
+ });
586
+ const summarizeTable = (variables, signal) => fetch$1({
587
+ url: "/db/{dbBranchName}/tables/{tableName}/summarize",
588
+ method: "post",
589
+ ...variables,
590
+ signal
591
+ });
592
+ const aggregateTable = (variables, signal) => fetch$1({
593
+ url: "/db/{dbBranchName}/tables/{tableName}/aggregate",
594
+ method: "post",
595
+ ...variables,
596
+ signal
597
+ });
598
+ const cPGetDatabaseList = (variables, signal) => fetch$1({
599
+ url: "/workspaces/{workspaceId}/dbs",
600
+ method: "get",
601
+ ...variables,
602
+ signal
603
+ });
604
+ const cPCreateDatabase = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
605
+ const cPDeleteDatabase = (variables, signal) => fetch$1({
606
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
607
+ method: "delete",
608
+ ...variables,
609
+ signal
448
610
  });
611
+ const cPGetCPDatabaseMetadata = (variables, signal) => fetch$1(
612
+ { url: "/workspaces/{workspaceId}/dbs/{dbName}/metadata", method: "get", ...variables, signal }
613
+ );
614
+ const cPUpdateCPDatabaseMetadata = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
449
615
  const operationsByTag = {
450
616
  users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
451
617
  workspaces: {
@@ -467,6 +633,8 @@ const operationsByTag = {
467
633
  getDatabaseList,
468
634
  createDatabase,
469
635
  deleteDatabase,
636
+ getDatabaseMetadata,
637
+ updateDatabaseMetadata,
470
638
  getGitBranchesMapping,
471
639
  addGitBranchesEntry,
472
640
  removeGitBranchesEntry,
@@ -479,10 +647,28 @@ const operationsByTag = {
479
647
  deleteBranch,
480
648
  updateBranchMetadata,
481
649
  getBranchMetadata,
650
+ getBranchStats
651
+ },
652
+ migrationRequests: {
653
+ queryMigrationRequests,
654
+ createMigrationRequest,
655
+ getMigrationRequest,
656
+ updateMigrationRequest,
657
+ listMigrationRequestsCommits,
658
+ compareMigrationRequest,
659
+ getMigrationRequestIsMerged,
660
+ mergeMigrationRequest
661
+ },
662
+ branchSchema: {
482
663
  getBranchMigrationHistory,
483
664
  executeBranchMigrationPlan,
484
665
  getBranchMigrationPlan,
485
- getBranchStats
666
+ compareBranchWithUserSchema,
667
+ compareBranchSchemas,
668
+ updateBranchSchema,
669
+ previewBranchSchemaEdit,
670
+ applyBranchSchemaEdit,
671
+ getBranchSchemaHistory
486
672
  },
487
673
  table: {
488
674
  createTable,
@@ -506,14 +692,23 @@ const operationsByTag = {
506
692
  bulkInsertTableRecords,
507
693
  queryTable,
508
694
  searchTable,
509
- searchBranch
695
+ searchBranch,
696
+ summarizeTable,
697
+ aggregateTable
698
+ },
699
+ databases: {
700
+ cPGetDatabaseList,
701
+ cPCreateDatabase,
702
+ cPDeleteDatabase,
703
+ cPGetCPDatabaseMetadata,
704
+ cPUpdateCPDatabaseMetadata
510
705
  }
511
706
  };
512
707
 
513
708
  function getHostUrl(provider, type) {
514
- if (isValidAlias(provider)) {
709
+ if (isHostProviderAlias(provider)) {
515
710
  return providers[provider][type];
516
- } else if (isValidBuilder(provider)) {
711
+ } else if (isHostProviderBuilder(provider)) {
517
712
  return provider[type];
518
713
  }
519
714
  throw new Error("Invalid API provider");
@@ -528,12 +723,21 @@ const providers = {
528
723
  workspaces: "https://{workspaceId}.staging.xatabase.co"
529
724
  }
530
725
  };
531
- function isValidAlias(alias) {
726
+ function isHostProviderAlias(alias) {
532
727
  return isString(alias) && Object.keys(providers).includes(alias);
533
728
  }
534
- function isValidBuilder(builder) {
729
+ function isHostProviderBuilder(builder) {
535
730
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
536
731
  }
732
+ function parseProviderString(provider = "production") {
733
+ if (isHostProviderAlias(provider)) {
734
+ return provider;
735
+ }
736
+ const [main, workspaces] = provider.split(",");
737
+ if (!main || !workspaces)
738
+ return null;
739
+ return { main, workspaces };
740
+ }
537
741
 
538
742
  var __accessCheck$7 = (obj, member, msg) => {
539
743
  if (!member.has(obj))
@@ -559,7 +763,8 @@ class XataApiClient {
559
763
  __privateAdd$7(this, _extraProps, void 0);
560
764
  __privateAdd$7(this, _namespaces, {});
561
765
  const provider = options.host ?? "production";
562
- const apiKey = options?.apiKey ?? getAPIKey();
766
+ const apiKey = options.apiKey ?? getAPIKey();
767
+ const trace = options.trace ?? defaultTrace;
563
768
  if (!apiKey) {
564
769
  throw new Error("Could not resolve a valid apiKey");
565
770
  }
@@ -567,7 +772,8 @@ class XataApiClient {
567
772
  apiUrl: getHostUrl(provider, "main"),
568
773
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
569
774
  fetchImpl: getFetchImplementation(options.fetch),
570
- apiKey
775
+ apiKey,
776
+ trace
571
777
  });
572
778
  }
573
779
  get user() {
@@ -600,6 +806,16 @@ class XataApiClient {
600
806
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
601
807
  return __privateGet$7(this, _namespaces).records;
602
808
  }
809
+ get migrationRequests() {
810
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
811
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
812
+ return __privateGet$7(this, _namespaces).migrationRequests;
813
+ }
814
+ get branchSchema() {
815
+ if (!__privateGet$7(this, _namespaces).branchSchema)
816
+ __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
817
+ return __privateGet$7(this, _namespaces).branchSchema;
818
+ }
603
819
  }
604
820
  _extraProps = new WeakMap();
605
821
  _namespaces = new WeakMap();
@@ -739,6 +955,19 @@ class DatabaseApi {
739
955
  ...this.extraProps
740
956
  });
741
957
  }
958
+ getDatabaseMetadata(workspace, dbName) {
959
+ return operationsByTag.database.getDatabaseMetadata({
960
+ pathParams: { workspace, dbName },
961
+ ...this.extraProps
962
+ });
963
+ }
964
+ updateDatabaseMetadata(workspace, dbName, options = {}) {
965
+ return operationsByTag.database.updateDatabaseMetadata({
966
+ pathParams: { workspace, dbName },
967
+ body: options,
968
+ ...this.extraProps
969
+ });
970
+ }
742
971
  getGitBranchesMapping(workspace, dbName) {
743
972
  return operationsByTag.database.getGitBranchesMapping({
744
973
  pathParams: { workspace, dbName },
@@ -810,27 +1039,6 @@ class BranchApi {
810
1039
  ...this.extraProps
811
1040
  });
812
1041
  }
813
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
814
- return operationsByTag.branch.getBranchMigrationHistory({
815
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
816
- body: options,
817
- ...this.extraProps
818
- });
819
- }
820
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
821
- return operationsByTag.branch.executeBranchMigrationPlan({
822
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
823
- body: migrationPlan,
824
- ...this.extraProps
825
- });
826
- }
827
- getBranchMigrationPlan(workspace, database, branch, schema) {
828
- return operationsByTag.branch.getBranchMigrationPlan({
829
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
830
- body: schema,
831
- ...this.extraProps
832
- });
833
- }
834
1042
  getBranchStats(workspace, database, branch) {
835
1043
  return operationsByTag.branch.getBranchStats({
836
1044
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -986,6 +1194,138 @@ class RecordsApi {
986
1194
  ...this.extraProps
987
1195
  });
988
1196
  }
1197
+ summarizeTable(workspace, database, branch, tableName, query) {
1198
+ return operationsByTag.records.summarizeTable({
1199
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1200
+ body: query,
1201
+ ...this.extraProps
1202
+ });
1203
+ }
1204
+ }
1205
+ class MigrationRequestsApi {
1206
+ constructor(extraProps) {
1207
+ this.extraProps = extraProps;
1208
+ }
1209
+ queryMigrationRequests(workspace, database, options = {}) {
1210
+ return operationsByTag.migrationRequests.queryMigrationRequests({
1211
+ pathParams: { workspace, dbName: database },
1212
+ body: options,
1213
+ ...this.extraProps
1214
+ });
1215
+ }
1216
+ createMigrationRequest(workspace, database, options) {
1217
+ return operationsByTag.migrationRequests.createMigrationRequest({
1218
+ pathParams: { workspace, dbName: database },
1219
+ body: options,
1220
+ ...this.extraProps
1221
+ });
1222
+ }
1223
+ getMigrationRequest(workspace, database, migrationRequest) {
1224
+ return operationsByTag.migrationRequests.getMigrationRequest({
1225
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1226
+ ...this.extraProps
1227
+ });
1228
+ }
1229
+ updateMigrationRequest(workspace, database, migrationRequest, options) {
1230
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1231
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1232
+ body: options,
1233
+ ...this.extraProps
1234
+ });
1235
+ }
1236
+ listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1237
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1238
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1239
+ body: options,
1240
+ ...this.extraProps
1241
+ });
1242
+ }
1243
+ compareMigrationRequest(workspace, database, migrationRequest) {
1244
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1245
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1246
+ ...this.extraProps
1247
+ });
1248
+ }
1249
+ getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1250
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1251
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1252
+ ...this.extraProps
1253
+ });
1254
+ }
1255
+ mergeMigrationRequest(workspace, database, migrationRequest) {
1256
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1257
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1258
+ ...this.extraProps
1259
+ });
1260
+ }
1261
+ }
1262
+ class BranchSchemaApi {
1263
+ constructor(extraProps) {
1264
+ this.extraProps = extraProps;
1265
+ }
1266
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
1267
+ return operationsByTag.branchSchema.getBranchMigrationHistory({
1268
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1269
+ body: options,
1270
+ ...this.extraProps
1271
+ });
1272
+ }
1273
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1274
+ return operationsByTag.branchSchema.executeBranchMigrationPlan({
1275
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1276
+ body: migrationPlan,
1277
+ ...this.extraProps
1278
+ });
1279
+ }
1280
+ getBranchMigrationPlan(workspace, database, branch, schema) {
1281
+ return operationsByTag.branchSchema.getBranchMigrationPlan({
1282
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1283
+ body: schema,
1284
+ ...this.extraProps
1285
+ });
1286
+ }
1287
+ compareBranchWithUserSchema(workspace, database, branch, schema) {
1288
+ return operationsByTag.branchSchema.compareBranchWithUserSchema({
1289
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1290
+ body: { schema },
1291
+ ...this.extraProps
1292
+ });
1293
+ }
1294
+ compareBranchSchemas(workspace, database, branch, branchName, schema) {
1295
+ return operationsByTag.branchSchema.compareBranchSchemas({
1296
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1297
+ body: { schema },
1298
+ ...this.extraProps
1299
+ });
1300
+ }
1301
+ updateBranchSchema(workspace, database, branch, migration) {
1302
+ return operationsByTag.branchSchema.updateBranchSchema({
1303
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1304
+ body: migration,
1305
+ ...this.extraProps
1306
+ });
1307
+ }
1308
+ previewBranchSchemaEdit(workspace, database, branch, migration) {
1309
+ return operationsByTag.branchSchema.previewBranchSchemaEdit({
1310
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1311
+ body: migration,
1312
+ ...this.extraProps
1313
+ });
1314
+ }
1315
+ applyBranchSchemaEdit(workspace, database, branch, edits) {
1316
+ return operationsByTag.branchSchema.applyBranchSchemaEdit({
1317
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1318
+ body: { edits },
1319
+ ...this.extraProps
1320
+ });
1321
+ }
1322
+ getBranchSchemaHistory(workspace, database, branch, options = {}) {
1323
+ return operationsByTag.branchSchema.getBranchSchemaHistory({
1324
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1325
+ body: options,
1326
+ ...this.extraProps
1327
+ });
1328
+ }
989
1329
  }
990
1330
 
991
1331
  class XataApiPlugin {
@@ -998,6 +1338,13 @@ class XataApiPlugin {
998
1338
  class XataPlugin {
999
1339
  }
1000
1340
 
1341
+ function generateUUID() {
1342
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1343
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1344
+ return v.toString(16);
1345
+ });
1346
+ }
1347
+
1001
1348
  var __accessCheck$6 = (obj, member, msg) => {
1002
1349
  if (!member.has(obj))
1003
1350
  throw TypeError("Cannot " + msg);
@@ -1111,9 +1458,14 @@ var __privateSet$5 = (obj, member, value, setter) => {
1111
1458
  setter ? setter.call(obj, value) : member.set(obj, value);
1112
1459
  return value;
1113
1460
  };
1114
- var _table$1, _repository, _data;
1461
+ var __privateMethod$3 = (obj, member, method) => {
1462
+ __accessCheck$5(obj, member, "access private method");
1463
+ return method;
1464
+ };
1465
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1115
1466
  const _Query = class {
1116
1467
  constructor(repository, table, data, rawParent) {
1468
+ __privateAdd$5(this, _cleanFilterConstraint);
1117
1469
  __privateAdd$5(this, _table$1, void 0);
1118
1470
  __privateAdd$5(this, _repository, void 0);
1119
1471
  __privateAdd$5(this, _data, { filter: {} });
@@ -1170,15 +1522,18 @@ const _Query = class {
1170
1522
  }
1171
1523
  filter(a, b) {
1172
1524
  if (arguments.length === 1) {
1173
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1525
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
1526
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
1527
+ }));
1174
1528
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1175
1529
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1176
1530
  } else {
1177
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1531
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
1532
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1178
1533
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1179
1534
  }
1180
1535
  }
1181
- sort(column, direction) {
1536
+ sort(column, direction = "asc") {
1182
1537
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1183
1538
  const sort = [...originalSort, { column, direction }];
1184
1539
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
@@ -1212,11 +1567,20 @@ const _Query = class {
1212
1567
  }
1213
1568
  }
1214
1569
  async getMany(options = {}) {
1215
- const page = await this.getPaginated(options);
1570
+ const { pagination = {}, ...rest } = options;
1571
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
1572
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
1573
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
1574
+ const results = [...page.records];
1575
+ while (page.hasNextPage() && results.length < size) {
1576
+ page = await page.nextPage();
1577
+ results.push(...page.records);
1578
+ }
1216
1579
  if (page.hasNextPage() && options.pagination?.size === void 0) {
1217
1580
  console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1218
1581
  }
1219
- return page.records;
1582
+ const array = new RecordArray(page, results.slice(0, size));
1583
+ return array;
1220
1584
  }
1221
1585
  async getAll(options = {}) {
1222
1586
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1230,6 +1594,12 @@ const _Query = class {
1230
1594
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1231
1595
  return records[0] ?? null;
1232
1596
  }
1597
+ async getFirstOrThrow(options = {}) {
1598
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1599
+ if (records[0] === void 0)
1600
+ throw new Error("No results found.");
1601
+ return records[0];
1602
+ }
1233
1603
  cache(ttl) {
1234
1604
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1235
1605
  }
@@ -1253,6 +1623,17 @@ let Query = _Query;
1253
1623
  _table$1 = new WeakMap();
1254
1624
  _repository = new WeakMap();
1255
1625
  _data = new WeakMap();
1626
+ _cleanFilterConstraint = new WeakSet();
1627
+ cleanFilterConstraint_fn = function(column, value) {
1628
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1629
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1630
+ return { $includes: value };
1631
+ }
1632
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
1633
+ return value.id;
1634
+ }
1635
+ return value;
1636
+ };
1256
1637
  function cleanParent(data, parent) {
1257
1638
  if (isCursorPaginationOptions(data.pagination)) {
1258
1639
  return { ...parent, sorting: void 0, filter: void 0 };
@@ -1314,12 +1695,16 @@ var __privateMethod$2 = (obj, member, method) => {
1314
1695
  __accessCheck$4(obj, member, "access private method");
1315
1696
  return method;
1316
1697
  };
1317
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1698
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1318
1699
  class Repository extends Query {
1319
1700
  }
1320
1701
  class RestRepository extends Query {
1321
1702
  constructor(options) {
1322
- super(null, options.table, {});
1703
+ super(
1704
+ null,
1705
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1706
+ {}
1707
+ );
1323
1708
  __privateAdd$4(this, _insertRecordWithoutId);
1324
1709
  __privateAdd$4(this, _insertRecordWithId);
1325
1710
  __privateAdd$4(this, _bulkInsertTableRecords);
@@ -1334,168 +1719,255 @@ class RestRepository extends Query {
1334
1719
  __privateAdd$4(this, _db, void 0);
1335
1720
  __privateAdd$4(this, _cache, void 0);
1336
1721
  __privateAdd$4(this, _schemaTables$2, void 0);
1722
+ __privateAdd$4(this, _trace, void 0);
1337
1723
  __privateSet$4(this, _table, options.table);
1338
- __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1339
1724
  __privateSet$4(this, _db, options.db);
1340
1725
  __privateSet$4(this, _cache, options.pluginOptions.cache);
1341
1726
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
1727
+ __privateSet$4(this, _getFetchProps, async () => {
1728
+ const props = await options.pluginOptions.getFetchProps();
1729
+ return { ...props, sessionID: generateUUID() };
1730
+ });
1731
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1732
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1733
+ return trace(name, fn, {
1734
+ ...options2,
1735
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1736
+ [TraceAttributes.KIND]: "sdk-operation",
1737
+ [TraceAttributes.VERSION]: VERSION
1738
+ });
1739
+ });
1342
1740
  }
1343
1741
  async create(a, b, c) {
1344
- if (Array.isArray(a)) {
1345
- if (a.length === 0)
1346
- return [];
1347
- const columns = isStringArray(b) ? b : void 0;
1348
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1349
- }
1350
- if (isString(a) && isObject(b)) {
1351
- if (a === "")
1352
- throw new Error("The id can't be empty");
1353
- const columns = isStringArray(c) ? c : void 0;
1354
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1355
- }
1356
- if (isObject(a) && isString(a.id)) {
1357
- if (a.id === "")
1358
- throw new Error("The id can't be empty");
1359
- const columns = isStringArray(b) ? b : void 0;
1360
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1361
- }
1362
- if (isObject(a)) {
1363
- const columns = isStringArray(b) ? b : void 0;
1364
- return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1365
- }
1366
- throw new Error("Invalid arguments for create method");
1742
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1743
+ if (Array.isArray(a)) {
1744
+ if (a.length === 0)
1745
+ return [];
1746
+ const columns = isStringArray(b) ? b : void 0;
1747
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1748
+ }
1749
+ if (isString(a) && isObject(b)) {
1750
+ if (a === "")
1751
+ throw new Error("The id can't be empty");
1752
+ const columns = isStringArray(c) ? c : void 0;
1753
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1754
+ }
1755
+ if (isObject(a) && isString(a.id)) {
1756
+ if (a.id === "")
1757
+ throw new Error("The id can't be empty");
1758
+ const columns = isStringArray(b) ? b : void 0;
1759
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1760
+ }
1761
+ if (isObject(a)) {
1762
+ const columns = isStringArray(b) ? b : void 0;
1763
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1764
+ }
1765
+ throw new Error("Invalid arguments for create method");
1766
+ });
1367
1767
  }
1368
1768
  async read(a, b) {
1369
- const columns = isStringArray(b) ? b : ["*"];
1370
- if (Array.isArray(a)) {
1371
- if (a.length === 0)
1372
- return [];
1373
- const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1374
- const finalObjects = await this.getAll({ filter: { id: { $any: ids } }, columns });
1375
- const dictionary = finalObjects.reduce((acc, object) => {
1376
- acc[object.id] = object;
1377
- return acc;
1378
- }, {});
1379
- return ids.map((id2) => dictionary[id2] ?? null);
1380
- }
1381
- const id = isString(a) ? a : a.id;
1382
- if (isString(id)) {
1383
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1384
- try {
1385
- const response = await getRecord({
1386
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1387
- queryParams: { columns },
1388
- ...fetchProps
1389
- });
1390
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1391
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1392
- } catch (e) {
1393
- if (isObject(e) && e.status === 404) {
1394
- return null;
1769
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1770
+ const columns = isStringArray(b) ? b : ["*"];
1771
+ if (Array.isArray(a)) {
1772
+ if (a.length === 0)
1773
+ return [];
1774
+ const ids = a.map((item) => extractId(item));
1775
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1776
+ const dictionary = finalObjects.reduce((acc, object) => {
1777
+ acc[object.id] = object;
1778
+ return acc;
1779
+ }, {});
1780
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1781
+ }
1782
+ const id = extractId(a);
1783
+ if (id) {
1784
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1785
+ try {
1786
+ const response = await getRecord({
1787
+ pathParams: {
1788
+ workspace: "{workspaceId}",
1789
+ dbBranchName: "{dbBranch}",
1790
+ tableName: __privateGet$4(this, _table),
1791
+ recordId: id
1792
+ },
1793
+ queryParams: { columns },
1794
+ ...fetchProps
1795
+ });
1796
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1797
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1798
+ } catch (e) {
1799
+ if (isObject(e) && e.status === 404) {
1800
+ return null;
1801
+ }
1802
+ throw e;
1395
1803
  }
1396
- throw e;
1397
1804
  }
1398
- }
1399
- return null;
1805
+ return null;
1806
+ });
1807
+ }
1808
+ async readOrThrow(a, b) {
1809
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
1810
+ const result = await this.read(a, b);
1811
+ if (Array.isArray(result)) {
1812
+ const missingIds = compact(
1813
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1814
+ );
1815
+ if (missingIds.length > 0) {
1816
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1817
+ }
1818
+ return result;
1819
+ }
1820
+ if (result === null) {
1821
+ const id = extractId(a) ?? "unknown";
1822
+ throw new Error(`Record with id ${id} not found`);
1823
+ }
1824
+ return result;
1825
+ });
1400
1826
  }
1401
1827
  async update(a, b, c) {
1402
- if (Array.isArray(a)) {
1403
- if (a.length === 0)
1404
- return [];
1405
- if (a.length > 100) {
1406
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1828
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1829
+ if (Array.isArray(a)) {
1830
+ if (a.length === 0)
1831
+ return [];
1832
+ if (a.length > 100) {
1833
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1834
+ }
1835
+ const columns = isStringArray(b) ? b : ["*"];
1836
+ return Promise.all(a.map((object) => this.update(object, columns)));
1407
1837
  }
1408
- const columns = isStringArray(b) ? b : ["*"];
1409
- return Promise.all(a.map((object) => this.update(object, columns)));
1410
- }
1411
- if (isString(a) && isObject(b)) {
1412
- const columns = isStringArray(c) ? c : void 0;
1413
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1414
- }
1415
- if (isObject(a) && isString(a.id)) {
1416
- const columns = isStringArray(b) ? b : void 0;
1417
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1418
- }
1419
- throw new Error("Invalid arguments for update method");
1838
+ if (isString(a) && isObject(b)) {
1839
+ const columns = isStringArray(c) ? c : void 0;
1840
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1841
+ }
1842
+ if (isObject(a) && isString(a.id)) {
1843
+ const columns = isStringArray(b) ? b : void 0;
1844
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1845
+ }
1846
+ throw new Error("Invalid arguments for update method");
1847
+ });
1848
+ }
1849
+ async updateOrThrow(a, b, c) {
1850
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1851
+ const result = await this.update(a, b, c);
1852
+ if (Array.isArray(result)) {
1853
+ const missingIds = compact(
1854
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1855
+ );
1856
+ if (missingIds.length > 0) {
1857
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1858
+ }
1859
+ return result;
1860
+ }
1861
+ if (result === null) {
1862
+ const id = extractId(a) ?? "unknown";
1863
+ throw new Error(`Record with id ${id} not found`);
1864
+ }
1865
+ return result;
1866
+ });
1420
1867
  }
1421
1868
  async createOrUpdate(a, b, c) {
1422
- if (Array.isArray(a)) {
1423
- if (a.length === 0)
1424
- return [];
1425
- if (a.length > 100) {
1426
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1869
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1870
+ if (Array.isArray(a)) {
1871
+ if (a.length === 0)
1872
+ return [];
1873
+ if (a.length > 100) {
1874
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1875
+ }
1876
+ const columns = isStringArray(b) ? b : ["*"];
1877
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1427
1878
  }
1428
- const columns = isStringArray(b) ? b : ["*"];
1429
- return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1430
- }
1431
- if (isString(a) && isObject(b)) {
1432
- const columns = isStringArray(c) ? c : void 0;
1433
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1434
- }
1435
- if (isObject(a) && isString(a.id)) {
1436
- const columns = isStringArray(c) ? c : void 0;
1437
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1438
- }
1439
- throw new Error("Invalid arguments for createOrUpdate method");
1440
- }
1441
- async delete(a) {
1442
- if (Array.isArray(a)) {
1443
- if (a.length === 0)
1444
- return;
1445
- if (a.length > 100) {
1446
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1879
+ if (isString(a) && isObject(b)) {
1880
+ const columns = isStringArray(c) ? c : void 0;
1881
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1447
1882
  }
1448
- await Promise.all(a.map((id) => this.delete(id)));
1449
- return;
1450
- }
1451
- if (isString(a)) {
1452
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1453
- return;
1454
- }
1455
- if (isObject(a) && isString(a.id)) {
1456
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1457
- return;
1458
- }
1459
- throw new Error("Invalid arguments for delete method");
1883
+ if (isObject(a) && isString(a.id)) {
1884
+ const columns = isStringArray(c) ? c : void 0;
1885
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1886
+ }
1887
+ throw new Error("Invalid arguments for createOrUpdate method");
1888
+ });
1889
+ }
1890
+ async delete(a, b) {
1891
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1892
+ if (Array.isArray(a)) {
1893
+ if (a.length === 0)
1894
+ return [];
1895
+ if (a.length > 100) {
1896
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1897
+ }
1898
+ return Promise.all(a.map((id) => this.delete(id, b)));
1899
+ }
1900
+ if (isString(a)) {
1901
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1902
+ }
1903
+ if (isObject(a) && isString(a.id)) {
1904
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1905
+ }
1906
+ throw new Error("Invalid arguments for delete method");
1907
+ });
1908
+ }
1909
+ async deleteOrThrow(a, b) {
1910
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
1911
+ const result = await this.delete(a, b);
1912
+ if (Array.isArray(result)) {
1913
+ const missingIds = compact(
1914
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1915
+ );
1916
+ if (missingIds.length > 0) {
1917
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1918
+ }
1919
+ return result;
1920
+ } else if (result === null) {
1921
+ const id = extractId(a) ?? "unknown";
1922
+ throw new Error(`Record with id ${id} not found`);
1923
+ }
1924
+ return result;
1925
+ });
1460
1926
  }
1461
1927
  async search(query, options = {}) {
1462
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1463
- const { records } = await searchTable({
1464
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1465
- body: {
1466
- query,
1467
- fuzziness: options.fuzziness,
1468
- prefix: options.prefix,
1469
- highlight: options.highlight,
1470
- filter: options.filter,
1471
- boosters: options.boosters
1472
- },
1473
- ...fetchProps
1928
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1929
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1930
+ const { records } = await searchTable({
1931
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1932
+ body: {
1933
+ query,
1934
+ fuzziness: options.fuzziness,
1935
+ prefix: options.prefix,
1936
+ highlight: options.highlight,
1937
+ filter: options.filter,
1938
+ boosters: options.boosters
1939
+ },
1940
+ ...fetchProps
1941
+ });
1942
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1943
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
1474
1944
  });
1475
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1476
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1477
1945
  }
1478
1946
  async query(query) {
1479
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1480
- if (cacheQuery)
1481
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1482
- const data = query.getQueryOptions();
1483
- const body = {
1484
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1485
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1486
- page: data.pagination,
1487
- columns: data.columns
1488
- };
1489
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1490
- const { meta, records: objects } = await queryTable({
1491
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1492
- body,
1493
- ...fetchProps
1947
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1948
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1949
+ if (cacheQuery)
1950
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1951
+ const data = query.getQueryOptions();
1952
+ const body = {
1953
+ filter: cleanFilter(data.filter),
1954
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1955
+ page: data.pagination,
1956
+ columns: data.columns
1957
+ };
1958
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1959
+ const { meta, records: objects } = await queryTable({
1960
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1961
+ body,
1962
+ ...fetchProps
1963
+ });
1964
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1965
+ const records = objects.map(
1966
+ (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
1967
+ );
1968
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1969
+ return new Page(query, meta, records);
1494
1970
  });
1495
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1496
- const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1497
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1498
- return new Page(query, meta, records);
1499
1971
  }
1500
1972
  }
1501
1973
  _table = new WeakMap();
@@ -1503,6 +1975,7 @@ _getFetchProps = new WeakMap();
1503
1975
  _db = new WeakMap();
1504
1976
  _cache = new WeakMap();
1505
1977
  _schemaTables$2 = new WeakMap();
1978
+ _trace = new WeakMap();
1506
1979
  _insertRecordWithoutId = new WeakSet();
1507
1980
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1508
1981
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -1518,7 +1991,7 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1518
1991
  ...fetchProps
1519
1992
  });
1520
1993
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1521
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1994
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1522
1995
  };
1523
1996
  _insertRecordWithId = new WeakSet();
1524
1997
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
@@ -1536,7 +2009,7 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1536
2009
  ...fetchProps
1537
2010
  });
1538
2011
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1539
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
2012
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1540
2013
  };
1541
2014
  _bulkInsertTableRecords = new WeakSet();
1542
2015
  bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
@@ -1552,20 +2025,27 @@ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1552
2025
  throw new Error("Request included columns but server didn't include them");
1553
2026
  }
1554
2027
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1555
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
2028
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
1556
2029
  };
1557
2030
  _updateRecordWithID = new WeakSet();
1558
2031
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1559
2032
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1560
2033
  const record = transformObjectLinks(object);
1561
- const response = await updateRecordWithID({
1562
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1563
- queryParams: { columns },
1564
- body: record,
1565
- ...fetchProps
1566
- });
1567
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1568
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
2034
+ try {
2035
+ const response = await updateRecordWithID({
2036
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2037
+ queryParams: { columns },
2038
+ body: record,
2039
+ ...fetchProps
2040
+ });
2041
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2042
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2043
+ } catch (e) {
2044
+ if (isObject(e) && e.status === 404) {
2045
+ return null;
2046
+ }
2047
+ throw e;
2048
+ }
1569
2049
  };
1570
2050
  _upsertRecordWithID = new WeakSet();
1571
2051
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
@@ -1577,15 +2057,25 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1577
2057
  ...fetchProps
1578
2058
  });
1579
2059
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1580
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
2060
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1581
2061
  };
1582
2062
  _deleteRecord = new WeakSet();
1583
- deleteRecord_fn = async function(recordId) {
2063
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1584
2064
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1585
- await deleteRecord({
1586
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1587
- ...fetchProps
1588
- });
2065
+ try {
2066
+ const response = await deleteRecord({
2067
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2068
+ queryParams: { columns },
2069
+ ...fetchProps
2070
+ });
2071
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2072
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2073
+ } catch (e) {
2074
+ if (isObject(e) && e.status === 404) {
2075
+ return null;
2076
+ }
2077
+ throw e;
2078
+ }
1589
2079
  };
1590
2080
  _setCacheQuery = new WeakSet();
1591
2081
  setCacheQuery_fn = async function(query, meta, records) {
@@ -1622,7 +2112,7 @@ const transformObjectLinks = (object) => {
1622
2112
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1623
2113
  }, {});
1624
2114
  };
1625
- const initObject = (db, schemaTables, table, object) => {
2115
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
1626
2116
  const result = {};
1627
2117
  const { xata, ...rest } = object ?? {};
1628
2118
  Object.assign(result, rest);
@@ -1630,6 +2120,8 @@ const initObject = (db, schemaTables, table, object) => {
1630
2120
  if (!columns)
1631
2121
  console.error(`Table ${table} not found in schema`);
1632
2122
  for (const column of columns ?? []) {
2123
+ if (!isValidColumn(selectedColumns, column))
2124
+ continue;
1633
2125
  const value = result[column.name];
1634
2126
  switch (column.type) {
1635
2127
  case "datetime": {
@@ -1646,10 +2138,28 @@ const initObject = (db, schemaTables, table, object) => {
1646
2138
  if (!linkTable) {
1647
2139
  console.error(`Failed to parse link for field ${column.name}`);
1648
2140
  } else if (isObject(value)) {
1649
- result[column.name] = initObject(db, schemaTables, linkTable, value);
2141
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
2142
+ if (item === column.name) {
2143
+ return [...acc, "*"];
2144
+ }
2145
+ if (item.startsWith(`${column.name}.`)) {
2146
+ const [, ...path] = item.split(".");
2147
+ return [...acc, path.join(".")];
2148
+ }
2149
+ return acc;
2150
+ }, []);
2151
+ result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2152
+ } else {
2153
+ result[column.name] = null;
1650
2154
  }
1651
2155
  break;
1652
2156
  }
2157
+ default:
2158
+ result[column.name] = value ?? null;
2159
+ if (column.notNull === true && value === null) {
2160
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2161
+ }
2162
+ break;
1653
2163
  }
1654
2164
  }
1655
2165
  result.read = function(columns2) {
@@ -1673,6 +2183,28 @@ const initObject = (db, schemaTables, table, object) => {
1673
2183
  function isResponseWithRecords(value) {
1674
2184
  return isObject(value) && Array.isArray(value.records);
1675
2185
  }
2186
+ function extractId(value) {
2187
+ if (isString(value))
2188
+ return value;
2189
+ if (isObject(value) && isString(value.id))
2190
+ return value.id;
2191
+ return void 0;
2192
+ }
2193
+ function cleanFilter(filter) {
2194
+ if (!filter)
2195
+ return void 0;
2196
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2197
+ return values.length > 0 ? filter : void 0;
2198
+ }
2199
+ function isValidColumn(columns, column) {
2200
+ if (columns.includes("*"))
2201
+ return true;
2202
+ if (column.type === "link") {
2203
+ const linkColumns = columns.filter((item) => item.startsWith(column.name));
2204
+ return linkColumns.length > 0;
2205
+ }
2206
+ return columns.includes(column.name);
2207
+ }
1676
2208
 
1677
2209
  var __accessCheck$3 = (obj, member, msg) => {
1678
2210
  if (!member.has(obj))
@@ -1723,18 +2255,25 @@ class SimpleCache {
1723
2255
  }
1724
2256
  _map = new WeakMap();
1725
2257
 
1726
- const gt = (value) => ({ $gt: value });
1727
- const ge = (value) => ({ $ge: value });
1728
- const gte = (value) => ({ $ge: value });
1729
- const lt = (value) => ({ $lt: value });
1730
- const lte = (value) => ({ $le: value });
1731
- const le = (value) => ({ $le: value });
2258
+ const greaterThan = (value) => ({ $gt: value });
2259
+ const gt = greaterThan;
2260
+ const greaterThanEquals = (value) => ({ $ge: value });
2261
+ const greaterEquals = greaterThanEquals;
2262
+ const gte = greaterThanEquals;
2263
+ const ge = greaterThanEquals;
2264
+ const lessThan = (value) => ({ $lt: value });
2265
+ const lt = lessThan;
2266
+ const lessThanEquals = (value) => ({ $le: value });
2267
+ const lessEquals = lessThanEquals;
2268
+ const lte = lessThanEquals;
2269
+ const le = lessThanEquals;
1732
2270
  const exists = (column) => ({ $exists: column });
1733
2271
  const notExists = (column) => ({ $notExists: column });
1734
2272
  const startsWith = (value) => ({ $startsWith: value });
1735
2273
  const endsWith = (value) => ({ $endsWith: value });
1736
2274
  const pattern = (value) => ({ $pattern: value });
1737
2275
  const is = (value) => ({ $is: value });
2276
+ const equals = is;
1738
2277
  const isNot = (value) => ({ $isNot: value });
1739
2278
  const contains = (value) => ({ $contains: value });
1740
2279
  const includes = (value) => ({ $includes: value });
@@ -1831,7 +2370,7 @@ class SearchPlugin extends XataPlugin {
1831
2370
  const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1832
2371
  return records.map((record) => {
1833
2372
  const { table = "orphan" } = record.xata;
1834
- return { table, record: initObject(this.db, schemaTables, table, record) };
2373
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
1835
2374
  });
1836
2375
  },
1837
2376
  byTable: async (query, options = {}) => {
@@ -1840,7 +2379,7 @@ class SearchPlugin extends XataPlugin {
1840
2379
  return records.reduce((acc, record) => {
1841
2380
  const { table = "orphan" } = record.xata;
1842
2381
  const items = acc[table] ?? [];
1843
- const item = initObject(this.db, schemaTables, table, record);
2382
+ const item = initObject(this.db, schemaTables, table, record, ["*"]);
1844
2383
  return { ...acc, [table]: [...items, item] };
1845
2384
  }, {});
1846
2385
  }
@@ -1911,7 +2450,8 @@ async function resolveXataBranch(gitBranch, options) {
1911
2450
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1912
2451
  workspacesApiUrl: `${protocol}//${host}`,
1913
2452
  pathParams: { dbName, workspace },
1914
- queryParams: { gitBranch, fallbackBranch }
2453
+ queryParams: { gitBranch, fallbackBranch },
2454
+ trace: defaultTrace
1915
2455
  });
1916
2456
  return branch;
1917
2457
  }
@@ -1935,7 +2475,8 @@ async function getDatabaseBranch(branch, options) {
1935
2475
  apiUrl: databaseURL,
1936
2476
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1937
2477
  workspacesApiUrl: `${protocol}//${host}`,
1938
- pathParams: { dbBranchName, workspace }
2478
+ pathParams: { dbBranchName, workspace },
2479
+ trace: defaultTrace
1939
2480
  });
1940
2481
  } catch (err) {
1941
2482
  if (isObject(err) && err.status === 404)
@@ -1987,7 +2528,8 @@ const buildClient = (plugins) => {
1987
2528
  __privateSet(this, _options, safeOptions);
1988
2529
  const pluginOptions = {
1989
2530
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1990
- cache: safeOptions.cache
2531
+ cache: safeOptions.cache,
2532
+ trace: safeOptions.trace
1991
2533
  };
1992
2534
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
1993
2535
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
@@ -2016,12 +2558,23 @@ const buildClient = (plugins) => {
2016
2558
  const databaseURL = options?.databaseURL || getDatabaseURL();
2017
2559
  const apiKey = options?.apiKey || getAPIKey();
2018
2560
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2561
+ const trace = options?.trace ?? defaultTrace;
2019
2562
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2020
- if (!databaseURL || !apiKey) {
2021
- throw new Error("Options databaseURL and apiKey are required");
2563
+ if (!apiKey) {
2564
+ throw new Error("Option apiKey is required");
2022
2565
  }
2023
- return { fetch, databaseURL, apiKey, branch, cache };
2024
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch }) {
2566
+ if (!databaseURL) {
2567
+ throw new Error("Option databaseURL is required");
2568
+ }
2569
+ return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID() };
2570
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
2571
+ fetch,
2572
+ apiKey,
2573
+ databaseURL,
2574
+ branch,
2575
+ trace,
2576
+ clientID
2577
+ }) {
2025
2578
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2026
2579
  if (!branchValue)
2027
2580
  throw new Error("Unable to resolve branch value");
@@ -2031,9 +2584,11 @@ const buildClient = (plugins) => {
2031
2584
  apiUrl: "",
2032
2585
  workspacesApiUrl: (path, params) => {
2033
2586
  const hasBranch = params.dbBranchName ?? params.branch;
2034
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2587
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
2035
2588
  return databaseURL + newPath;
2036
- }
2589
+ },
2590
+ trace,
2591
+ clientID
2037
2592
  };
2038
2593
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2039
2594
  if (__privateGet(this, _branch))
@@ -2056,6 +2611,88 @@ const buildClient = (plugins) => {
2056
2611
  class BaseClient extends buildClient() {
2057
2612
  }
2058
2613
 
2614
+ const META = "__";
2615
+ const VALUE = "___";
2616
+ class Serializer {
2617
+ constructor() {
2618
+ this.classes = {};
2619
+ }
2620
+ add(clazz) {
2621
+ this.classes[clazz.name] = clazz;
2622
+ }
2623
+ toJSON(data) {
2624
+ function visit(obj) {
2625
+ if (Array.isArray(obj))
2626
+ return obj.map(visit);
2627
+ const type = typeof obj;
2628
+ if (type === "undefined")
2629
+ return { [META]: "undefined" };
2630
+ if (type === "bigint")
2631
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2632
+ if (obj === null || type !== "object")
2633
+ return obj;
2634
+ const constructor = obj.constructor;
2635
+ const o = { [META]: constructor.name };
2636
+ for (const [key, value] of Object.entries(obj)) {
2637
+ o[key] = visit(value);
2638
+ }
2639
+ if (constructor === Date)
2640
+ o[VALUE] = obj.toISOString();
2641
+ if (constructor === Map)
2642
+ o[VALUE] = Object.fromEntries(obj);
2643
+ if (constructor === Set)
2644
+ o[VALUE] = [...obj];
2645
+ return o;
2646
+ }
2647
+ return JSON.stringify(visit(data));
2648
+ }
2649
+ fromJSON(json) {
2650
+ return JSON.parse(json, (key, value) => {
2651
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2652
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2653
+ const constructor = this.classes[clazz];
2654
+ if (constructor) {
2655
+ return Object.assign(Object.create(constructor.prototype), rest);
2656
+ }
2657
+ if (clazz === "Date")
2658
+ return new Date(val);
2659
+ if (clazz === "Set")
2660
+ return new Set(val);
2661
+ if (clazz === "Map")
2662
+ return new Map(Object.entries(val));
2663
+ if (clazz === "bigint")
2664
+ return BigInt(val);
2665
+ if (clazz === "undefined")
2666
+ return void 0;
2667
+ return rest;
2668
+ }
2669
+ return value;
2670
+ });
2671
+ }
2672
+ }
2673
+ const defaultSerializer = new Serializer();
2674
+ const serialize = (data) => {
2675
+ return defaultSerializer.toJSON(data);
2676
+ };
2677
+ const deserialize = (json) => {
2678
+ return defaultSerializer.fromJSON(json);
2679
+ };
2680
+
2681
+ function buildWorkerRunner(config) {
2682
+ return function xataWorker(name, _worker) {
2683
+ return async (...args) => {
2684
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2685
+ const result = await fetch(url, {
2686
+ method: "POST",
2687
+ headers: { "Content-Type": "application/json" },
2688
+ body: serialize({ args })
2689
+ });
2690
+ const text = await result.text();
2691
+ return deserialize(text);
2692
+ };
2693
+ };
2694
+ }
2695
+
2059
2696
  class XataError extends Error {
2060
2697
  constructor(message, status) {
2061
2698
  super(message);
@@ -2063,5 +2700,5 @@ class XataError extends Error {
2063
2700
  }
2064
2701
  }
2065
2702
 
2066
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
2703
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, buildClient, buildWorkerRunner, bulkInsertTableRecords, cPCreateDatabase, cPDeleteDatabase, cPGetCPDatabaseMetadata, cPGetDatabaseList, cPUpdateCPDatabaseMetadata, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
2067
2704
  //# sourceMappingURL=index.mjs.map