@xata.io/client 0.7.1 → 0.8.1

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.
@@ -19,20 +19,11 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
19
19
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
20
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
21
  };
22
- var __asyncValues = (this && this.__asyncValues) || function (o) {
23
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
24
- var m = o[Symbol.asyncIterator], i;
25
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
26
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
27
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
28
- };
29
- var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _RestRepository_insertRecordWithoutId, _RestRepository_insertRecordWithId, _RestRepository_bulkInsertTableRecords, _RestRepository_updateRecordWithID, _RestRepository_upsertRecordWithID, _RestRepository_deleteRecord, _BaseClient_links, _BaseClient_branch;
22
+ var _RestRepository_instances, _RestRepository_table, _RestRepository_links, _RestRepository_getFetchProps, _RestRepository_insertRecordWithoutId, _RestRepository_insertRecordWithId, _RestRepository_bulkInsertTableRecords, _RestRepository_updateRecordWithID, _RestRepository_upsertRecordWithID, _RestRepository_deleteRecord, _RestRepository_initObject;
30
23
  Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0;
24
+ exports.RestRepository = exports.Repository = void 0;
32
25
  const api_1 = require("../api");
33
- const fetch_1 = require("../util/fetch");
34
26
  const lang_1 = require("../util/lang");
35
- const config_1 = require("./config");
36
27
  const pagination_1 = require("./pagination");
37
28
  const query_1 = require("./query");
38
29
  const record_1 = require("./record");
@@ -44,15 +35,17 @@ class Repository extends query_1.Query {
44
35
  }
45
36
  exports.Repository = Repository;
46
37
  class RestRepository extends query_1.Query {
47
- constructor(client, table) {
48
- super(null, table, {});
38
+ constructor(options) {
39
+ var _a;
40
+ super(null, options.table, {});
49
41
  _RestRepository_instances.add(this);
50
- _RestRepository_client.set(this, void 0);
51
- _RestRepository_fetch.set(this, void 0);
52
42
  _RestRepository_table.set(this, void 0);
53
- __classPrivateFieldSet(this, _RestRepository_client, client, "f");
54
- __classPrivateFieldSet(this, _RestRepository_table, table, "f");
55
- __classPrivateFieldSet(this, _RestRepository_fetch, (0, fetch_1.getFetchImplementation)(__classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch), "f");
43
+ _RestRepository_links.set(this, void 0);
44
+ _RestRepository_getFetchProps.set(this, void 0);
45
+ __classPrivateFieldSet(this, _RestRepository_table, options.table, "f");
46
+ __classPrivateFieldSet(this, _RestRepository_links, (_a = options.links) !== null && _a !== void 0 ? _a : {}, "f");
47
+ __classPrivateFieldSet(this, _RestRepository_getFetchProps, options.getFetchProps, "f");
48
+ this.db = options.db;
56
49
  }
57
50
  create(a, b) {
58
51
  return __awaiter(this, void 0, void 0, function* () {
@@ -82,10 +75,10 @@ class RestRepository extends query_1.Query {
82
75
  // TODO: Add column support: https://github.com/xataio/openapi/issues/139
83
76
  read(recordId) {
84
77
  return __awaiter(this, void 0, void 0, function* () {
85
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
78
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
86
79
  try {
87
80
  const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
88
- return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
81
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, __classPrivateFieldGet(this, _RestRepository_table, "f"), response);
89
82
  }
90
83
  catch (e) {
91
84
  if ((0, lang_1.isObject)(e) && e.status === 404) {
@@ -161,6 +154,13 @@ class RestRepository extends query_1.Query {
161
154
  throw new Error('Invalid arguments for delete method');
162
155
  });
163
156
  }
157
+ search(query, options = {}) {
158
+ return __awaiter(this, void 0, void 0, function* () {
159
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
160
+ const { records } = yield (0, api_1.searchBranch)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}' }, body: { tables: [__classPrivateFieldGet(this, _RestRepository_table, "f")], query, fuzziness: options.fuzziness } }, fetchProps));
161
+ return records.map((item) => __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, __classPrivateFieldGet(this, _RestRepository_table, "f"), item));
162
+ });
163
+ }
164
164
  query(query) {
165
165
  var _a;
166
166
  return __awaiter(this, void 0, void 0, function* () {
@@ -171,39 +171,17 @@ class RestRepository extends query_1.Query {
171
171
  page: data.page,
172
172
  columns: data.columns
173
173
  };
174
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
174
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
175
175
  const { meta, records: objects } = yield (0, api_1.queryTable)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body }, fetchProps));
176
- const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record));
176
+ const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, __classPrivateFieldGet(this, _RestRepository_table, "f"), record));
177
177
  return new pagination_1.Page(query, meta, records);
178
178
  });
179
179
  }
180
180
  }
181
181
  exports.RestRepository = RestRepository;
182
- _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() {
183
- var _a;
184
- return __awaiter(this, void 0, void 0, function* () {
185
- const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
186
- const apiKey = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey) !== null && _a !== void 0 ? _a : (0, config_1.getAPIKey)();
187
- if (!apiKey) {
188
- throw new Error('Could not resolve a valid apiKey');
189
- }
190
- return {
191
- fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
192
- apiKey,
193
- apiUrl: '',
194
- // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
195
- workspacesApiUrl: (path, params) => {
196
- var _a, _b;
197
- const baseUrl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.databaseURL) !== null && _a !== void 0 ? _a : '';
198
- const hasBranch = (_b = params.dbBranchName) !== null && _b !== void 0 ? _b : params.branch;
199
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branch}` : '');
200
- return baseUrl + newPath;
201
- }
202
- };
203
- });
204
- }, _RestRepository_insertRecordWithoutId = function _RestRepository_insertRecordWithoutId(object) {
182
+ _RestRepository_table = new WeakMap(), _RestRepository_links = new WeakMap(), _RestRepository_getFetchProps = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_insertRecordWithoutId = function _RestRepository_insertRecordWithoutId(object) {
205
183
  return __awaiter(this, void 0, void 0, function* () {
206
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
184
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
207
185
  const record = transformObjectLinks(object);
208
186
  const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: {
209
187
  workspace: '{workspaceId}',
@@ -218,7 +196,7 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
218
196
  });
219
197
  }, _RestRepository_insertRecordWithId = function _RestRepository_insertRecordWithId(recordId, object) {
220
198
  return __awaiter(this, void 0, void 0, function* () {
221
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
199
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
222
200
  const record = transformObjectLinks(object);
223
201
  const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
224
202
  workspace: '{workspaceId}',
@@ -234,7 +212,7 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
234
212
  });
235
213
  }, _RestRepository_bulkInsertTableRecords = function _RestRepository_bulkInsertTableRecords(objects) {
236
214
  return __awaiter(this, void 0, void 0, function* () {
237
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
215
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
238
216
  const records = objects.map((object) => transformObjectLinks(object));
239
217
  const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
240
218
  const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
@@ -245,7 +223,7 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
245
223
  });
246
224
  }, _RestRepository_updateRecordWithID = function _RestRepository_updateRecordWithID(recordId, object) {
247
225
  return __awaiter(this, void 0, void 0, function* () {
248
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
226
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
249
227
  const record = transformObjectLinks(object);
250
228
  const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: record }, fetchProps));
251
229
  const item = yield this.read(response.id);
@@ -255,7 +233,7 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
255
233
  });
256
234
  }, _RestRepository_upsertRecordWithID = function _RestRepository_upsertRecordWithID(recordId, object) {
257
235
  return __awaiter(this, void 0, void 0, function* () {
258
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
236
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
259
237
  const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
260
238
  const item = yield this.read(response.id);
261
239
  if (!item)
@@ -264,111 +242,35 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
264
242
  });
265
243
  }, _RestRepository_deleteRecord = function _RestRepository_deleteRecord(recordId) {
266
244
  return __awaiter(this, void 0, void 0, function* () {
267
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
245
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
268
246
  yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
269
247
  });
270
- };
271
- class RestRespositoryFactory {
272
- createRepository(client, table) {
273
- return new RestRepository(client, table);
274
- }
275
- }
276
- exports.RestRespositoryFactory = RestRespositoryFactory;
277
- function resolveXataClientOptions(options) {
278
- const databaseURL = (options === null || options === void 0 ? void 0 : options.databaseURL) || (0, config_1.getDatabaseUrl)() || '';
279
- const apiKey = (options === null || options === void 0 ? void 0 : options.apiKey) || (0, config_1.getAPIKey)() || '';
280
- const branch = (options === null || options === void 0 ? void 0 : options.branch) ||
281
- (() => (0, config_1.getBranch)({
282
- apiKey,
283
- apiUrl: databaseURL,
284
- fetchImpl: (0, fetch_1.getFetchImplementation)(options === null || options === void 0 ? void 0 : options.fetch)
285
- }));
286
- if (!databaseURL || !apiKey) {
287
- throw new Error('Options databaseURL and apiKey are required');
288
- }
289
- return Object.assign(Object.assign({}, options), { databaseURL,
290
- apiKey,
291
- branch });
292
- }
293
- class BaseClient {
294
- constructor(options = {}, links = {}) {
295
- _BaseClient_links.set(this, void 0);
296
- _BaseClient_branch.set(this, void 0);
297
- this.options = resolveXataClientOptions(options);
298
- // Make this property not enumerable so it doesn't show up in console.dir, etc.
299
- Object.defineProperty(this.options, 'apiKey', { enumerable: false });
300
- __classPrivateFieldSet(this, _BaseClient_links, links, "f");
301
- const factory = this.options.repositoryFactory || new RestRespositoryFactory();
302
- this.db = new Proxy({}, {
303
- get: (_target, prop) => {
304
- if (typeof prop !== 'string')
305
- throw new Error('Invalid table name');
306
- return factory.createRepository(this, prop);
307
- }
308
- });
309
- }
310
- initObject(table, object) {
311
- const result = {};
312
- Object.assign(result, object);
313
- const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
314
- for (const link of tableLinks) {
315
- const [field, linkTable] = link;
316
- const value = result[field];
317
- if (value && (0, lang_1.isObject)(value)) {
318
- result[field] = this.initObject(linkTable, value);
319
- }
248
+ }, _RestRepository_initObject = function _RestRepository_initObject(table, object) {
249
+ const result = {};
250
+ Object.assign(result, object);
251
+ const tableLinks = __classPrivateFieldGet(this, _RestRepository_links, "f")[table] || [];
252
+ for (const link of tableLinks) {
253
+ const [field, linkTable] = link;
254
+ const value = result[field];
255
+ if (value && (0, lang_1.isObject)(value)) {
256
+ result[field] = __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, linkTable, value);
320
257
  }
321
- const db = this.db;
322
- result.read = function () {
323
- return db[table].read(result['id']);
324
- };
325
- result.update = function (data) {
326
- return db[table].update(result['id'], data);
327
- };
328
- result.delete = function () {
329
- return db[table].delete(result['id']);
330
- };
331
- for (const prop of ['read', 'update', 'delete']) {
332
- Object.defineProperty(result, prop, { enumerable: false });
333
- }
334
- Object.freeze(result);
335
- return result;
336
258
  }
337
- getBranch() {
338
- var e_1, _a;
339
- return __awaiter(this, void 0, void 0, function* () {
340
- if (__classPrivateFieldGet(this, _BaseClient_branch, "f"))
341
- return __classPrivateFieldGet(this, _BaseClient_branch, "f");
342
- const { branch: param } = this.options;
343
- const strategies = Array.isArray(param) ? [...param] : [param];
344
- const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
345
- return isBranchStrategyBuilder(strategy) ? yield strategy() : strategy;
346
- });
347
- try {
348
- for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) {
349
- const strategy = strategies_1_1.value;
350
- const branch = yield evaluateBranch(strategy);
351
- if (branch) {
352
- __classPrivateFieldSet(this, _BaseClient_branch, branch, "f");
353
- return branch;
354
- }
355
- }
356
- }
357
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
358
- finally {
359
- try {
360
- if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1);
361
- }
362
- finally { if (e_1) throw e_1.error; }
363
- }
364
- throw new Error('Unable to resolve branch value');
365
- });
259
+ const db = this.db;
260
+ result.read = function () {
261
+ return db[table].read(result['id']);
262
+ };
263
+ result.update = function (data) {
264
+ return db[table].update(result['id'], data);
265
+ };
266
+ result.delete = function () {
267
+ return db[table].delete(result['id']);
268
+ };
269
+ for (const prop of ['read', 'update', 'delete']) {
270
+ Object.defineProperty(result, prop, { enumerable: false });
366
271
  }
367
- }
368
- exports.BaseClient = BaseClient;
369
- _BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
370
- const isBranchStrategyBuilder = (strategy) => {
371
- return typeof strategy === 'function';
272
+ Object.freeze(result);
273
+ return result;
372
274
  };
373
275
  const transformObjectLinks = (object) => {
374
276
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  /* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-floating-promises */
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
+ const vitest_1 = require("vitest");
4
5
  // SelectableColumn<O> //
5
6
  // --------------------------------------------------------------------------- //
6
7
  const validTeamColumns = [
@@ -198,6 +199,6 @@ function test8(user) {
198
199
  user.partner = null;
199
200
  user.team = null;
200
201
  }
201
- test('fake test', () => {
202
+ (0, vitest_1.test)('fake test', () => {
202
203
  // This is a fake test to make sure that the type definitions in this file are working
203
204
  });
@@ -1,4 +1,4 @@
1
- import { SingleOrArray, Values } from '../util/types';
1
+ import { SingleOrArray, StringKeys, Values } from '../util/types';
2
2
  import { XataRecord } from './record';
3
3
  import { SelectableColumn } from './selection';
4
4
  export declare type SortDirection = 'asc' | 'desc';
@@ -6,12 +6,17 @@ export declare type SortFilterExtended<T extends XataRecord> = {
6
6
  column: SelectableColumn<T>;
7
7
  direction?: SortDirection;
8
8
  };
9
- export declare type SortFilter<T extends XataRecord> = SelectableColumn<T> | SortFilterExtended<T>;
9
+ export declare type SortFilter<T extends XataRecord> = SelectableColumn<T> | SortFilterExtended<T> | SortFilterBase<T>;
10
+ declare type SortFilterBase<T extends XataRecord> = {
11
+ [Key in StringKeys<T>]: SortDirection;
12
+ };
10
13
  export declare type ApiSortFilter<T extends XataRecord> = SingleOrArray<Values<{
11
- [key in SelectableColumn<T>]: {
12
- [K in key]: SortDirection;
14
+ [Key in SelectableColumn<T>]: {
15
+ [K in Key]: SortDirection;
13
16
  };
14
17
  }>>;
15
18
  export declare function isSortFilterString<T extends XataRecord>(value: any): value is SelectableColumn<T>;
19
+ export declare function isSortFilterBase<T extends XataRecord>(filter: SortFilter<T>): filter is SortFilterBase<T>;
16
20
  export declare function isSortFilterObject<T extends XataRecord>(filter: SortFilter<T>): filter is SortFilterExtended<T>;
17
21
  export declare function buildSortFilter<T extends XataRecord>(filter: SingleOrArray<SortFilter<T>>): ApiSortFilter<T>;
22
+ export {};
@@ -1,13 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildSortFilter = exports.isSortFilterObject = exports.isSortFilterString = void 0;
3
+ exports.buildSortFilter = exports.isSortFilterObject = exports.isSortFilterBase = exports.isSortFilterString = void 0;
4
4
  const lang_1 = require("../util/lang");
5
5
  function isSortFilterString(value) {
6
6
  return (0, lang_1.isString)(value);
7
7
  }
8
8
  exports.isSortFilterString = isSortFilterString;
9
+ function isSortFilterBase(filter) {
10
+ return (0, lang_1.isObject)(filter) && Object.values(filter).every((value) => value === 'asc' || value === 'desc');
11
+ }
12
+ exports.isSortFilterBase = isSortFilterBase;
9
13
  function isSortFilterObject(filter) {
10
- return (0, lang_1.isObject)(filter) && filter.column !== undefined;
14
+ return (0, lang_1.isObject)(filter) && !isSortFilterBase(filter) && filter.column !== undefined;
11
15
  }
12
16
  exports.isSortFilterObject = isSortFilterObject;
13
17
  function buildSortFilter(filter) {
@@ -18,6 +22,9 @@ function buildSortFilter(filter) {
18
22
  else if (Array.isArray(filter)) {
19
23
  return filter.map((item) => buildSortFilter(item));
20
24
  }
25
+ else if (isSortFilterBase(filter)) {
26
+ return filter;
27
+ }
21
28
  else if (isSortFilterObject(filter)) {
22
29
  return { [filter.column]: (_a = filter.direction) !== null && _a !== void 0 ? _a : 'asc' };
23
30
  }
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ /* eslint-disable @typescript-eslint/no-unused-vars */
4
+ const vitest_1 = require("vitest");
3
5
  // Simple sorting
4
6
  const simpleSorting = { name: 'asc' };
5
7
  // Array of simple sorting
6
8
  const arrayOfSimpleSorting = [{ name: 'asc' }, { age: 'desc' }];
7
- test('fake test', () => {
9
+ (0, vitest_1.test)('fake test', () => {
8
10
  // This is a fake test to make sure that the type definitions in this file are working
9
11
  });
@@ -0,0 +1,34 @@
1
+ import { XataPlugin, XataPluginOptions } from '../plugins';
2
+ import { BaseData, XataRecord } from '../schema/record';
3
+ import { SelectedPick } from '../schema/selection';
4
+ import { GetArrayInnerType, Values } from '../util/types';
5
+ export declare class SearchPlugin<Schemas extends Record<string, BaseData>> extends XataPlugin {
6
+ #private;
7
+ build({ getFetchProps }: XataPluginOptions): {
8
+ all: <Tables extends Extract<keyof Schemas, string>>(query: string, options?: {
9
+ fuzziness?: number | undefined;
10
+ tables?: Tables[] | undefined;
11
+ }) => Promise<Values<{ [Model in Tables]: {
12
+ table: Model;
13
+ record: Awaited<SelectedPick<Schemas[Model] & XataRecord & {
14
+ xata: {
15
+ table: string;
16
+ };
17
+ }, ["*"]>>;
18
+ }; }>[]>;
19
+ byTable: <Tables_1 extends Extract<keyof Schemas, string>>(query: string, options?: {
20
+ fuzziness?: number | undefined;
21
+ tables?: Tables_1[] | undefined;
22
+ }) => Promise<{ [Model_1 in Tables_1]: SelectedPick<Schemas[Model_1] & XataRecord & {
23
+ xata: {
24
+ table: string;
25
+ };
26
+ }, ["*"]>[]; }>;
27
+ };
28
+ }
29
+ declare type SearchXataRecord = XataRecord & {
30
+ xata: {
31
+ table: string;
32
+ };
33
+ };
34
+ export {};
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
12
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
14
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15
+ };
16
+ var _SearchPlugin_instances, _SearchPlugin_search;
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.SearchPlugin = void 0;
19
+ const api_1 = require("../api");
20
+ const plugins_1 = require("../plugins");
21
+ class SearchPlugin extends plugins_1.XataPlugin {
22
+ constructor() {
23
+ super(...arguments);
24
+ _SearchPlugin_instances.add(this);
25
+ }
26
+ build({ getFetchProps }) {
27
+ return {
28
+ all: (query, options = {}) => __awaiter(this, void 0, void 0, function* () {
29
+ const records = yield __classPrivateFieldGet(this, _SearchPlugin_instances, "m", _SearchPlugin_search).call(this, query, options, getFetchProps);
30
+ return records.map((record) => {
31
+ const { table = 'orphan' } = record.xata;
32
+ return { table, record };
33
+ });
34
+ }),
35
+ byTable: (query, options = {}) => __awaiter(this, void 0, void 0, function* () {
36
+ const records = yield __classPrivateFieldGet(this, _SearchPlugin_instances, "m", _SearchPlugin_search).call(this, query, options, getFetchProps);
37
+ return records.reduce((acc, record) => {
38
+ var _a;
39
+ const { table = 'orphan' } = record.xata;
40
+ const items = (_a = acc[table]) !== null && _a !== void 0 ? _a : [];
41
+ return Object.assign(Object.assign({}, acc), { [table]: [...items, record] });
42
+ }, {});
43
+ })
44
+ };
45
+ }
46
+ }
47
+ exports.SearchPlugin = SearchPlugin;
48
+ _SearchPlugin_instances = new WeakSet(), _SearchPlugin_search = function _SearchPlugin_search(query, options, getFetchProps) {
49
+ return __awaiter(this, void 0, void 0, function* () {
50
+ const fetchProps = yield getFetchProps();
51
+ const { tables, fuzziness } = options !== null && options !== void 0 ? options : {};
52
+ const { records } = yield (0, api_1.searchBranch)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}' }, body: { tables, query, fuzziness } }, fetchProps));
53
+ return records;
54
+ });
55
+ };
@@ -0,0 +1,5 @@
1
+ export declare type BranchStrategyValue = string | undefined | null;
2
+ export declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>;
3
+ export declare type BranchStrategy = BranchStrategyValue | BranchStrategyBuilder;
4
+ export declare type BranchStrategyOption = NonNullable<BranchStrategy | BranchStrategy[]>;
5
+ export declare const isBranchStrategyBuilder: (strategy: BranchStrategy) => strategy is BranchStrategyBuilder;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isBranchStrategyBuilder = void 0;
4
+ const isBranchStrategyBuilder = (strategy) => {
5
+ return typeof strategy === 'function';
6
+ };
7
+ exports.isBranchStrategyBuilder = isBranchStrategyBuilder;
@@ -0,0 +1,11 @@
1
+ import { FetchImpl } from '../api/fetcher';
2
+ declare type BranchResolutionOptions = {
3
+ databaseURL?: string;
4
+ apiKey?: string;
5
+ fetchImpl?: FetchImpl;
6
+ };
7
+ export declare function getCurrentBranchName(options?: BranchResolutionOptions): Promise<string | undefined>;
8
+ export declare function getCurrentBranchDetails(options?: BranchResolutionOptions): Promise<import("../api/schemas").DBBranch | null>;
9
+ export declare function getDatabaseURL(): string | undefined;
10
+ export declare function getAPIKey(): string | undefined;
11
+ export {};
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getAPIKey = exports.getDatabaseURL = exports.getCurrentBranchDetails = exports.getCurrentBranchName = void 0;
13
+ const api_1 = require("../api");
14
+ const environment_1 = require("./environment");
15
+ const fetch_1 = require("./fetch");
16
+ const lang_1 = require("./lang");
17
+ const envBranchNames = [
18
+ 'XATA_BRANCH',
19
+ 'VERCEL_GIT_COMMIT_REF',
20
+ 'CF_PAGES_BRANCH',
21
+ 'BRANCH' // Netlify. Putting it the last one because it is more ambiguous
22
+ ];
23
+ const defaultBranch = 'main';
24
+ function getCurrentBranchName(options) {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const env = yield getBranchByEnvVariable();
27
+ if (env)
28
+ return env;
29
+ const branch = yield (0, environment_1.getGitBranch)();
30
+ if (!branch)
31
+ return defaultBranch;
32
+ // TODO: in the future, call /resolve endpoint
33
+ // For now, call API to see if the branch exists. If not, use a default value.
34
+ const details = yield getDatabaseBranch(branch, options);
35
+ if (details)
36
+ return branch;
37
+ return defaultBranch;
38
+ });
39
+ }
40
+ exports.getCurrentBranchName = getCurrentBranchName;
41
+ function getCurrentBranchDetails(options) {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ const env = yield getBranchByEnvVariable();
44
+ if (env)
45
+ return getDatabaseBranch(env, options);
46
+ const branch = yield (0, environment_1.getGitBranch)();
47
+ if (!branch)
48
+ return getDatabaseBranch(defaultBranch, options);
49
+ // TODO: in the future, call /resolve endpoint
50
+ // For now, call API to see if the branch exists. If not, use a default value.
51
+ const details = yield getDatabaseBranch(branch, options);
52
+ if (details)
53
+ return details;
54
+ return getDatabaseBranch(defaultBranch, options);
55
+ });
56
+ }
57
+ exports.getCurrentBranchDetails = getCurrentBranchDetails;
58
+ function getDatabaseBranch(branch, options) {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ const databaseURL = (options === null || options === void 0 ? void 0 : options.databaseURL) || getDatabaseURL();
61
+ const apiKey = (options === null || options === void 0 ? void 0 : options.apiKey) || getAPIKey();
62
+ if (!databaseURL)
63
+ throw new Error('A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely');
64
+ if (!apiKey)
65
+ throw new Error('An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely');
66
+ const [protocol, , host, , database] = databaseURL.split('/');
67
+ const [workspace] = host.split('.');
68
+ const dbBranchName = `${database}:${branch}`;
69
+ try {
70
+ return yield (0, api_1.getBranchDetails)({
71
+ apiKey,
72
+ apiUrl: databaseURL,
73
+ fetchImpl: (0, fetch_1.getFetchImplementation)(options === null || options === void 0 ? void 0 : options.fetchImpl),
74
+ workspacesApiUrl: `${protocol}//${host}`,
75
+ pathParams: {
76
+ dbBranchName,
77
+ workspace
78
+ }
79
+ });
80
+ }
81
+ catch (err) {
82
+ if ((0, lang_1.isObject)(err) && err.status === 404)
83
+ return null;
84
+ throw err;
85
+ }
86
+ });
87
+ }
88
+ function getBranchByEnvVariable() {
89
+ for (const name of envBranchNames) {
90
+ const value = (0, environment_1.getEnvVariable)(name);
91
+ if (value) {
92
+ return value;
93
+ }
94
+ }
95
+ try {
96
+ return XATA_BRANCH;
97
+ }
98
+ catch (err) {
99
+ // Ignore ReferenceError. Only CloudFlare workers set env variables as global variables
100
+ }
101
+ }
102
+ function getDatabaseURL() {
103
+ var _a;
104
+ try {
105
+ return (_a = (0, environment_1.getEnvVariable)('XATA_DATABASE_URL')) !== null && _a !== void 0 ? _a : XATA_DATABASE_URL;
106
+ }
107
+ catch (err) {
108
+ return undefined;
109
+ }
110
+ }
111
+ exports.getDatabaseURL = getDatabaseURL;
112
+ function getAPIKey() {
113
+ var _a;
114
+ try {
115
+ return (_a = (0, environment_1.getEnvVariable)('XATA_API_KEY')) !== null && _a !== void 0 ? _a : XATA_API_KEY;
116
+ }
117
+ catch (err) {
118
+ return undefined;
119
+ }
120
+ }
121
+ exports.getAPIKey = getAPIKey;
@@ -12,8 +12,8 @@ export declare type RequiredBy<T, K extends keyof T> = T & {
12
12
  [P in K]-?: NonNullable<T[P]>;
13
13
  };
14
14
  export declare type GetArrayInnerType<T extends readonly any[]> = T[number];
15
- export declare type NonNullableValues<Obj> = {
16
- [K in keyof Obj]: NonNullable<Obj[K]>;
15
+ export declare type AllRequired<T> = {
16
+ [P in keyof T]-?: T[P];
17
17
  };
18
18
  export declare type KeysOfUnion<T> = T extends T ? keyof T : never;
19
19
  declare type Impossible<K extends keyof any> = {
@@ -21,4 +21,5 @@ declare type Impossible<K extends keyof any> = {
21
21
  };
22
22
  export declare type Exactly<T, U extends T = T> = U & Impossible<Exclude<keyof U, keyof T>>;
23
23
  export declare type SingleOrArray<T> = T | T[];
24
+ export declare type Dictionary<T> = Record<string, T>;
24
25
  export {};