@typedb/driver-http 3.7.0-rc0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # TypeDB HTTP Typescript Driver
2
+
3
+ ## Driver Architecture
4
+
5
+ To learn about how the TypeDB HTTP driver communicates with the TypeDB Server,
6
+ refer to the [HTTP API Reference](https://typedb.com/docs/reference/http-api).
7
+
8
+ ## API Reference
9
+
10
+ To learn about the methods available for executing queries and retrieving their answers using Typescript, refer to
11
+ the [API Reference](https://typedb.com/docs/reference/http-drivers/typescript).
12
+
13
+ ## Install TypeDB HTTP Typescript Driver through NPM
14
+
15
+ 1. Install `@typedb/driver-http` through npm:
16
+
17
+ ```bash
18
+ npm install @typedb/driver-http
19
+ ```
20
+
21
+ 2. Make sure a [TypeDB Server](https://typedb.com/docs/home/install/) is
22
+ running.
23
+ 3. Use TypeDB Driver in your program:
24
+
25
+ ```ts
26
+ import { TypeDBHttpDriver, isApiErrorResponse } from "@typedb/driver-http";
27
+
28
+ const driver = new TypeDBHttpDriver({
29
+ username: "admin",
30
+ password: "password",
31
+ addresses: [ "localhost:1729" ],
32
+ });
33
+
34
+ const transactionResponse = await driver.openTransaction("database-name", "read");
35
+ if (isApiErrorResponse(transactionResponse)) throw transactionResponse.err;
36
+ const transactionId = transactionResponse.ok.transactionId;
37
+
38
+ const answerResponse = await driver.query(transactionId, "match entity $x;");
39
+ if (isApiErrorResponse(answerResponse)) throw answerResponse.err;
40
+ const answer = answerResponse.ok;
41
+
42
+ if (answer.answerType === "conceptRows") {
43
+ answer.answers.forEach((row) => {
44
+ console.log(row.data)
45
+ })
46
+ }
47
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,193 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// ../../../../../../../../../execroot/typedb_driver/bazel-out/darwin_arm64-opt/bin/http-ts/src/params.ts
2
+ function isBasicParams(params) {
3
+ return `addresses` in params;
4
+ }
5
+ function isTranslatedParams(params) {
6
+ return `translatedAddresses` in params;
7
+ }
8
+ function remoteOrigin(params) {
9
+ if (isBasicParams(params)) return `${params.addresses[0]}`;
10
+ else return `${params.translatedAddresses[0].external}`;
11
+ }
12
+
13
+ // ../../../../../../../../../execroot/typedb_driver/bazel-out/darwin_arm64-opt/bin/http-ts/src/response.ts
14
+ function isApiError(err) {
15
+ return err != null && typeof err.code === "string" && typeof err.message === "string";
16
+ }
17
+ function isOkResponse(res) {
18
+ return typeof res === "object" && "ok" in res;
19
+ }
20
+ function isApiErrorResponse(res) {
21
+ return typeof res === "object" && "err" in res;
22
+ }
23
+
24
+ // ../../../../../../../../../execroot/typedb_driver/bazel-out/darwin_arm64-opt/bin/http-ts/src/analyzed-conjunction.ts
25
+ function getVariableName(structure, variable) {
26
+ return _optionalChain([structure, 'access', _ => _.variables, 'access', _2 => _2[variable.id], 'optionalAccess', _3 => _3.name]);
27
+ }
28
+
29
+ // ../../../../../../../../../execroot/typedb_driver/bazel-out/darwin_arm64-opt/bin/http-ts/src/index.ts
30
+ var HTTP_UNAUTHORIZED = 401;
31
+ var TypeDBHttpDriver = class {
32
+ constructor(params) {
33
+ this.params = params;
34
+ }
35
+ getDatabases() {
36
+ return this.apiGet(`/v1/databases`);
37
+ }
38
+ getDatabase(name) {
39
+ return this.apiGet(`/v1/databases/${encodeURIComponent(name)}`);
40
+ }
41
+ createDatabase(name) {
42
+ return this.apiPost(`/v1/databases/${encodeURIComponent(name)}`, {});
43
+ }
44
+ deleteDatabase(name) {
45
+ return this.apiDelete(`/v1/databases/${encodeURIComponent(name)}`);
46
+ }
47
+ getDatabaseSchema(name) {
48
+ return this.apiGetString(`/v1/databases/${encodeURIComponent(name)}/schema`);
49
+ }
50
+ getDatabaseTypeSchema(name) {
51
+ return this.apiGetString(`/v1/databases/${encodeURIComponent(name)}/type-schema`);
52
+ }
53
+ getUsers() {
54
+ return this.apiGet(`/v1/users`);
55
+ }
56
+ getCurrentUser() {
57
+ return this.apiGet(`/v1/users/${encodeURIComponent(this.params.username)}`);
58
+ }
59
+ getUser(username) {
60
+ return this.apiGet(`/v1/users/${encodeURIComponent(username)}`);
61
+ }
62
+ createUser(username, password) {
63
+ return this.apiPost(`/v1/users/${encodeURIComponent(username)}`, { password });
64
+ }
65
+ updateUser(username, password) {
66
+ return this.apiPut(`/v1/users/${encodeURIComponent(username)}`, { password });
67
+ }
68
+ deleteUser(username) {
69
+ return this.apiDelete(`/v1/users/${encodeURIComponent(username)}`);
70
+ }
71
+ openTransaction(databaseName, transactionType, transactionOptions) {
72
+ return this.apiPost(`/v1/transactions/open`, { databaseName, transactionType, transactionOptions });
73
+ }
74
+ commitTransaction(transactionId) {
75
+ return this.apiPost(`/v1/transactions/${encodeURIComponent(transactionId)}/commit`, {});
76
+ }
77
+ closeTransaction(transactionId) {
78
+ return this.apiPost(`/v1/transactions/${encodeURIComponent(transactionId)}/close`, {});
79
+ }
80
+ rollbackTransaction(transactionId) {
81
+ return this.apiPost(`/v1/transactions/${encodeURIComponent(transactionId)}/rollback`, {});
82
+ }
83
+ analyze(transactionId, query, analyzeOptions) {
84
+ return this.apiPost(`/v1/transactions/${encodeURIComponent(transactionId)}/analyze`, { query, analyzeOptions });
85
+ }
86
+ query(transactionId, query, queryOptions) {
87
+ return this.apiPost(`/v1/transactions/${encodeURIComponent(transactionId)}/query`, { query, queryOptions });
88
+ }
89
+ oneShotQuery(query, commit, databaseName, transactionType, transactionOptions, queryOptions) {
90
+ return this.apiPost(`/v1/query`, { query, commit, databaseName, transactionType, transactionOptions, queryOptions });
91
+ }
92
+ health() {
93
+ return this.apiGet(`/v1/health`);
94
+ }
95
+ version() {
96
+ return this.apiGet(`/v1/version`);
97
+ }
98
+ async apiGetString(path, options) {
99
+ return this.stringApiReq("GET", path, options);
100
+ }
101
+ async apiGet(path, options) {
102
+ return this.jsonApiReqWithoutBody("GET", path, options);
103
+ }
104
+ async apiDelete(path, options) {
105
+ return this.jsonApiReqWithoutBody("DELETE", path, options);
106
+ }
107
+ async apiPost(path, body, options) {
108
+ return this.jsonApiReq("POST", path, body, options);
109
+ }
110
+ async apiPut(path, body, options) {
111
+ return this.jsonApiReq("PUT", path, body, options);
112
+ }
113
+ async jsonApiReqWithoutBody(method, path, options) {
114
+ return this.jsonApiReq(method, path, void 0, options);
115
+ }
116
+ async jsonApiReq(method, path, body, options) {
117
+ const resp = await this.apiReq(method, path, body, options);
118
+ if ("err" in resp) return resp;
119
+ const json = await this.jsonOrNull(resp);
120
+ if (resp.ok) return { ok: json };
121
+ else if (isApiError(json)) return { err: json, status: resp.status };
122
+ else throw resp;
123
+ }
124
+ async stringApiReq(method, path, options) {
125
+ const resp = await this.apiReq(method, path, void 0, options);
126
+ if ("err" in resp) return resp;
127
+ if (resp.ok) return { ok: await _asyncNullishCoalesce(await this.stringOrNull(resp), async () => ( "")) };
128
+ else {
129
+ const json = await this.jsonOrNull(resp);
130
+ if (isApiError(json)) return { err: json, status: resp.status };
131
+ else throw resp;
132
+ }
133
+ }
134
+ async apiReq(method, path, body, options) {
135
+ const url = `${remoteOrigin(this.params)}${path}`;
136
+ let tokenResp = await this.getToken();
137
+ if ("err" in tokenResp) return tokenResp;
138
+ let bodyString = void 0;
139
+ if (body !== void 0) bodyString = JSON.stringify(body);
140
+ let headers = Object.assign({ "Authorization": `Bearer ${tokenResp.ok.token}`, "Content-Type": "application/json" }, _optionalChain([options, 'optionalAccess', _4 => _4.headers]) || {});
141
+ let resp = await fetch(url, { method, body: bodyString, headers });
142
+ if (resp.status === HTTP_UNAUTHORIZED) {
143
+ tokenResp = await this.refreshToken();
144
+ if ("err" in tokenResp) return tokenResp;
145
+ headers = Object.assign({ "Authorization": `Bearer ${tokenResp.ok.token}`, "Content-Type": "application/json" }, _optionalChain([options, 'optionalAccess', _5 => _5.headers]) || {});
146
+ resp = await fetch(url, { method, body: bodyString, headers });
147
+ }
148
+ return resp;
149
+ }
150
+ getToken() {
151
+ if (this.token) {
152
+ const resp = { ok: { token: this.token } };
153
+ return Promise.resolve(resp);
154
+ } else return this.refreshToken();
155
+ }
156
+ async refreshToken() {
157
+ const url = `${remoteOrigin(this.params)}/v1/signin`;
158
+ const body = { username: this.params.username, password: this.params.password };
159
+ const resp = await fetch(url, { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json" } });
160
+ const json = await this.jsonOrNull(resp);
161
+ if (resp.ok) {
162
+ this.token = json.token;
163
+ return { ok: json };
164
+ } else if (isApiError(json)) {
165
+ return { err: json, status: resp.status };
166
+ } else throw resp;
167
+ }
168
+ async jsonOrNull(resp) {
169
+ const contentLengthRaw = resp.headers.get("Content-Length");
170
+ if (!contentLengthRaw) return null;
171
+ const contentLength = parseInt(contentLengthRaw || "");
172
+ if (isNaN(contentLength)) throw `Received invalid Content-Length header: ${contentLengthRaw}`;
173
+ return contentLength > 0 ? await resp.json() : null;
174
+ }
175
+ async stringOrNull(resp) {
176
+ const contentLengthRaw = resp.headers.get("Content-Length");
177
+ if (!contentLengthRaw) return null;
178
+ const contentLength = parseInt(contentLengthRaw || "");
179
+ if (isNaN(contentLength)) throw `Received invalid Content-Length header: ${contentLengthRaw}`;
180
+ return contentLength > 0 ? await resp.text() : null;
181
+ }
182
+ };
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+ exports.TypeDBHttpDriver = TypeDBHttpDriver; exports.getVariableName = getVariableName; exports.isApiError = isApiError; exports.isApiErrorResponse = isApiErrorResponse; exports.isBasicParams = isBasicParams; exports.isOkResponse = isOkResponse; exports.isTranslatedParams = isTranslatedParams; exports.remoteOrigin = remoteOrigin;
193
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,490 @@
1
+ interface DriverParamsBasic {
2
+ username: string;
3
+ password: string;
4
+ addresses: string[];
5
+ }
6
+ interface DriverParamsTranslated {
7
+ username: string;
8
+ password: string;
9
+ translatedAddresses: TranslatedAddress[];
10
+ }
11
+ interface TranslatedAddress {
12
+ external: string;
13
+ internal: string;
14
+ }
15
+ type DriverParams = DriverParamsBasic | DriverParamsTranslated;
16
+ declare function isBasicParams(params: DriverParams): params is DriverParamsBasic;
17
+ declare function isTranslatedParams(params: DriverParams): params is DriverParamsTranslated;
18
+ declare function remoteOrigin(params: DriverParams): string;
19
+
20
+ type TypeKind = "entityType" | "relationType" | "attributeType" | "roleType";
21
+ type ThingKind = "entity" | "relation" | "attribute";
22
+ type ValueKind = "value";
23
+ type ValueType = "boolean" | "integer" | "double" | "decimal" | "date" | "datetime" | "datetime-tz" | "duration" | "string" | "struct";
24
+ type EdgeKind = "isa" | "has" | "links" | "sub" | "owns" | "relates" | "plays" | "isaExact" | "subExact" | "assigned" | "argument";
25
+ interface EntityType {
26
+ kind: "entityType";
27
+ label: string;
28
+ }
29
+ interface RelationType {
30
+ kind: "relationType";
31
+ label: string;
32
+ }
33
+ interface RoleType {
34
+ kind: "roleType";
35
+ label: string;
36
+ }
37
+ type AttributeType = {
38
+ label: string;
39
+ kind: "attributeType";
40
+ valueType: ValueType;
41
+ };
42
+ type Type = InstantiableType | RoleType;
43
+ type InstantiableType = EntityType | RelationType | AttributeType;
44
+ interface Entity {
45
+ kind: "entity";
46
+ iid: string;
47
+ type: EntityType;
48
+ }
49
+ interface Relation {
50
+ kind: "relation";
51
+ iid: string;
52
+ type: RelationType;
53
+ }
54
+ interface Attribute {
55
+ kind: "attribute";
56
+ iid: string;
57
+ value: any;
58
+ valueType: ValueType;
59
+ type: AttributeType;
60
+ }
61
+ interface Value {
62
+ kind: ValueKind;
63
+ value: any;
64
+ valueType: ValueType;
65
+ }
66
+ type Concept = Type | Entity | Relation | Attribute | Value;
67
+
68
+ interface ConceptRowsQueryResponseForStudio {
69
+ answerType: "conceptRows";
70
+ queryType: QueryType;
71
+ comment: string | null;
72
+ query: QueryStructureForStudio | null;
73
+ answers: ConceptRowAnswer[];
74
+ }
75
+ interface QueryStructureForStudio {
76
+ blocks: {
77
+ constraints: QueryConstraintAnyForStudio[];
78
+ }[];
79
+ variables: {
80
+ [name: string]: QueryVariableInfo;
81
+ };
82
+ outputs: string[];
83
+ }
84
+ type QueryConstraintAnyForStudio = QueryConstraintIsa | QueryConstraintIsaExact | QueryConstraintHas | QueryConstraintLinksForStudio | QueryConstraintSub | QueryConstraintSubExact | QueryConstraintOwns | QueryConstraintRelates | QueryConstraintPlays | QueryConstraintExpressionForStudio | QueryConstraintFunction | QueryConstraintComparison | QueryConstraintIs | QueryConstraintIid | QueryConstraintKind | QueryConstraintValue | QueryConstraintLabel;
85
+ interface QueryConstraintLinksForStudio {
86
+ tag: "links";
87
+ textSpan: QueryConstraintSpan;
88
+ relation: QueryVertexVariable;
89
+ player: QueryVertexVariable;
90
+ role: QueryVertexVariable | QueryVertexLabel;
91
+ }
92
+ interface QueryConstraintExpressionForStudio {
93
+ tag: "expression";
94
+ textSpan: QueryConstraintSpan;
95
+ text: string;
96
+ arguments: QueryVertexVariable[];
97
+ assigned: QueryVertexVariable[];
98
+ }
99
+
100
+ declare function getVariableName(structure: QueryStructureForStudio | AnalyzedPipeline, variable: QueryVertexVariable): string | null;
101
+ type QueryVertex = QueryVertexVariable | QueryVertexLabel | QueryVertexValue | QueryVertexNamedRole;
102
+ interface QueryVertexVariable {
103
+ tag: "variable";
104
+ id: string;
105
+ }
106
+ interface QueryVertexLabel {
107
+ tag: "label";
108
+ type: Type;
109
+ }
110
+ interface QueryVertexNamedRole {
111
+ tag: "namedRole";
112
+ variable: string;
113
+ name: string;
114
+ }
115
+ interface QueryVertexValue extends Value {
116
+ tag: "value";
117
+ }
118
+ type ConjunctionIndex$1 = number;
119
+ type QueryVariableInfo = {
120
+ name: string | null;
121
+ };
122
+ type QueryConstraintAny = QueryConstraintIsa | QueryConstraintIsaExact | QueryConstraintHas | QueryConstraintLinks | QueryConstraintSub | QueryConstraintSubExact | QueryConstraintOwns | QueryConstraintRelates | QueryConstraintPlays | QueryConstraintExpression | QueryConstraintFunction | QueryConstraintComparison | QueryConstraintIs | QueryConstraintIid | QueryConstraintKind | QueryConstraintValue | QueryConstraintLabel | QueryConstraintOr | QueryConstraintNot | QueryConstraintTry;
123
+ type QueryConstraintSpan = {
124
+ begin: number;
125
+ end: number;
126
+ };
127
+ interface QueryConstraintIsa {
128
+ tag: "isa";
129
+ textSpan: QueryConstraintSpan;
130
+ instance: QueryVertexVariable;
131
+ type: QueryVertexVariable | QueryVertexLabel;
132
+ }
133
+ interface QueryConstraintIsaExact {
134
+ tag: "isa!";
135
+ textSpan: QueryConstraintSpan;
136
+ instance: QueryVertexVariable;
137
+ type: QueryVertexVariable | QueryVertexLabel;
138
+ }
139
+ interface QueryConstraintHas {
140
+ tag: "has";
141
+ textSpan: QueryConstraintSpan;
142
+ owner: QueryVertexVariable;
143
+ attribute: QueryVertexVariable;
144
+ }
145
+ interface QueryConstraintLinks {
146
+ tag: "links";
147
+ textSpan: QueryConstraintSpan;
148
+ relation: QueryVertexVariable;
149
+ player: QueryVertexVariable;
150
+ role: QueryVertexVariable | QueryVertexNamedRole;
151
+ }
152
+ interface QueryConstraintSub {
153
+ tag: "sub";
154
+ textSpan: QueryConstraintSpan;
155
+ subtype: QueryVertexVariable | QueryVertexLabel;
156
+ supertype: QueryVertexVariable | QueryVertexLabel;
157
+ }
158
+ interface QueryConstraintSubExact {
159
+ tag: "sub!";
160
+ textSpan: QueryConstraintSpan;
161
+ subtype: QueryVertexVariable | QueryVertexLabel;
162
+ supertype: QueryVertexVariable | QueryVertexLabel;
163
+ }
164
+ interface QueryConstraintOwns {
165
+ tag: "owns";
166
+ textSpan: QueryConstraintSpan;
167
+ owner: QueryVertexVariable | QueryVertexLabel;
168
+ attribute: QueryVertexVariable | QueryVertexLabel;
169
+ }
170
+ interface QueryConstraintRelates {
171
+ tag: "relates";
172
+ textSpan: QueryConstraintSpan;
173
+ relation: QueryVertexVariable | QueryVertexLabel;
174
+ role: QueryVertexVariable | QueryVertexLabel;
175
+ }
176
+ interface QueryConstraintPlays {
177
+ tag: "plays";
178
+ textSpan: QueryConstraintSpan;
179
+ player: QueryVertexVariable | QueryVertexLabel;
180
+ role: QueryVertexVariable | QueryVertexLabel;
181
+ }
182
+ interface QueryConstraintExpression {
183
+ tag: "expression";
184
+ textSpan: QueryConstraintSpan;
185
+ text: string;
186
+ arguments: QueryVertexVariable[];
187
+ assigned: QueryVertexVariable;
188
+ }
189
+ interface QueryConstraintFunction {
190
+ tag: "functionCall";
191
+ textSpan: QueryConstraintSpan;
192
+ name: string;
193
+ arguments: QueryVertexVariable[];
194
+ assigned: QueryVertexVariable[];
195
+ }
196
+ interface QueryConstraintComparison {
197
+ tag: "comparison";
198
+ textSpan: QueryConstraintSpan;
199
+ lhs: QueryVertexVariable | QueryVertexValue;
200
+ rhs: QueryVertexVariable | QueryVertexValue;
201
+ comparator: string;
202
+ }
203
+ interface QueryConstraintIs {
204
+ tag: "is";
205
+ textSpan: QueryConstraintSpan;
206
+ lhs: QueryVertexVariable;
207
+ rhs: QueryVertexVariable;
208
+ }
209
+ interface QueryConstraintIid {
210
+ tag: "iid";
211
+ textSpan: QueryConstraintSpan;
212
+ concept: QueryVertexVariable;
213
+ iid: string;
214
+ }
215
+ interface QueryConstraintLabel {
216
+ tag: "label";
217
+ textSpan: QueryConstraintSpan;
218
+ type: QueryVertexVariable;
219
+ label: string;
220
+ }
221
+ interface QueryConstraintValue {
222
+ tag: "value";
223
+ textSpan: QueryConstraintSpan;
224
+ attributeType: QueryVertexVariable;
225
+ valueType: string;
226
+ }
227
+ interface QueryConstraintKind {
228
+ tag: "kind";
229
+ textSpan: QueryConstraintSpan;
230
+ type: QueryVertexVariable;
231
+ kind: string;
232
+ }
233
+ interface QueryConstraintOr {
234
+ tag: "or";
235
+ branches: ConjunctionIndex$1[];
236
+ }
237
+ interface QueryConstraintNot {
238
+ tag: "not";
239
+ conjunction: ConjunctionIndex$1;
240
+ }
241
+ interface QueryConstraintTry {
242
+ tag: "try";
243
+ conjunction: ConjunctionIndex$1;
244
+ }
245
+
246
+ type VariableId = string;
247
+ interface AnalyzedPipeline {
248
+ conjunctions: AnalyzedConjunction[];
249
+ variables: {
250
+ [name: VariableId]: QueryVariableInfo;
251
+ };
252
+ stages: PipelineStage[];
253
+ outputs: string[];
254
+ }
255
+ interface AnalyzedConjunction {
256
+ constraints: QueryConstraintAny[];
257
+ annotations: ConjunctionAnnotations;
258
+ }
259
+ type ConjunctionIndex = number;
260
+ type PipelineStage = {
261
+ tag: "match";
262
+ block: ConjunctionIndex;
263
+ } | {
264
+ tag: "insert";
265
+ block: ConjunctionIndex;
266
+ } | {
267
+ tag: "delete";
268
+ block: ConjunctionIndex;
269
+ deletedVariables: VariableId[];
270
+ } | {
271
+ tag: "put";
272
+ block: ConjunctionIndex;
273
+ } | {
274
+ tag: "update";
275
+ block: ConjunctionIndex;
276
+ } | {
277
+ tag: "select";
278
+ variables: VariableId[];
279
+ } | {
280
+ tag: "sort";
281
+ variables: {
282
+ tag: "Ascending" | "Descending";
283
+ variable: VariableId;
284
+ }[];
285
+ } | {
286
+ tag: "require";
287
+ variables: VariableId;
288
+ } | {
289
+ tag: "offset";
290
+ offset: number;
291
+ } | {
292
+ tag: "limit";
293
+ limit: number;
294
+ } | {
295
+ tag: "distinct";
296
+ } | {
297
+ tag: "reduce";
298
+ reducers: {
299
+ assigned: VariableId;
300
+ reducer: Reducer;
301
+ }[];
302
+ groupby: VariableId[];
303
+ };
304
+ interface AnalyzedFunction {
305
+ arguments: VariableId[];
306
+ returns: FunctionReturnStructure;
307
+ body: AnalyzedPipeline;
308
+ argumentAnnotations: VariableAnnotations[];
309
+ returnAnnotations: {
310
+ tag: "single" | "stream";
311
+ annotations: VariableAnnotations[];
312
+ };
313
+ }
314
+ type Reducer = {
315
+ reducer: string;
316
+ arguments: VariableId[];
317
+ };
318
+ type FunctionSingleReturnSelector = "first" | "last";
319
+ type FunctionReturnStructure = {
320
+ tag: "single";
321
+ variables: VariableId[];
322
+ selector: FunctionSingleReturnSelector;
323
+ } | {
324
+ tag: "stream";
325
+ variables: VariableId[];
326
+ } | {
327
+ tag: "check";
328
+ } | {
329
+ tag: "reduce";
330
+ reducers: Reducer[];
331
+ };
332
+ type VariableAnnotations = {
333
+ isOptional: boolean;
334
+ } & ({
335
+ tag: "instance";
336
+ annotations: Type[];
337
+ } | {
338
+ tag: "type";
339
+ annotations: Type[];
340
+ } | {
341
+ tag: "value";
342
+ valueTypes: ValueType[];
343
+ });
344
+ interface ConjunctionAnnotations {
345
+ variableAnnotations: {
346
+ [name: VariableId]: VariableAnnotations;
347
+ };
348
+ }
349
+ type AnalyzedFetch = {
350
+ tag: "list";
351
+ elements: AnalyzedFetch;
352
+ } | {
353
+ tag: "object";
354
+ possibleFields: FetchAnnotationFieldEntry[];
355
+ } | {
356
+ tag: "value";
357
+ valueTypes: ValueType[];
358
+ };
359
+ type FetchAnnotationFieldEntry = AnalyzedFetch & {
360
+ key: string;
361
+ };
362
+
363
+ interface SignInResponse {
364
+ token: string;
365
+ }
366
+ type Distribution = `TypeDB Cluster` | `TypeDB CE`;
367
+ interface VersionResponse {
368
+ distribution: Distribution;
369
+ version: string;
370
+ }
371
+ interface DatabasesListResponse {
372
+ databases: Database[];
373
+ }
374
+ interface UsersListResponse {
375
+ users: User[];
376
+ }
377
+ interface TransactionOpenResponse {
378
+ transactionId: string;
379
+ }
380
+ type QueryType = "read" | "write" | "schema";
381
+ type AnswerType = "ok" | "conceptRows" | "conceptDocuments";
382
+ interface ConceptRow {
383
+ [varName: string]: Concept | undefined;
384
+ }
385
+ interface ConceptRowAnswer {
386
+ involvedBlocks: number[] | null;
387
+ data: ConceptRow;
388
+ }
389
+ type ConceptDocument = Object;
390
+ type Answer = ConceptRowAnswer | ConceptDocument;
391
+ interface QueryResponseBase {
392
+ answerType: AnswerType;
393
+ queryType: QueryType;
394
+ comment: string | null;
395
+ query: AnalyzedPipeline | null;
396
+ }
397
+ interface OkQueryResponse extends QueryResponseBase {
398
+ answerType: "ok";
399
+ }
400
+ interface ConceptRowsQueryResponse extends QueryResponseBase {
401
+ answerType: "conceptRows";
402
+ answers: ConceptRowAnswer[];
403
+ }
404
+ interface ConceptDocumentsQueryResponse extends QueryResponseBase {
405
+ answerType: "conceptDocuments";
406
+ answers: ConceptDocument[];
407
+ }
408
+ type QueryResponse = OkQueryResponse | ConceptRowsQueryResponse | ConceptDocumentsQueryResponse | ConceptRowsQueryResponseForStudio;
409
+ interface AnalyzeResponse {
410
+ source: string;
411
+ preamble: AnalyzedFunction[];
412
+ query: AnalyzedPipeline;
413
+ fetch: AnalyzedFetch | null;
414
+ }
415
+ type ApiOkResponse<OK_RES = {}> = {
416
+ ok: OK_RES;
417
+ };
418
+ type ApiError = {
419
+ code: string;
420
+ message: string;
421
+ };
422
+ interface ApiErrorResponse {
423
+ err: ApiError;
424
+ status: number;
425
+ }
426
+ declare function isApiError(err: any): err is ApiError;
427
+ type ApiResponse<OK_RES = {} | null> = ApiOkResponse<OK_RES> | ApiErrorResponse;
428
+ declare function isOkResponse<OK_RES>(res: ApiResponse<OK_RES>): res is ApiOkResponse<OK_RES>;
429
+ declare function isApiErrorResponse(res: ApiResponse): res is ApiErrorResponse;
430
+
431
+ declare class TypeDBHttpDriver {
432
+ private params;
433
+ private token?;
434
+ constructor(params: DriverParams);
435
+ getDatabases(): Promise<ApiResponse<DatabasesListResponse>>;
436
+ getDatabase(name: string): Promise<ApiResponse<Database>>;
437
+ createDatabase(name: string): Promise<ApiResponse>;
438
+ deleteDatabase(name: string): Promise<ApiResponse>;
439
+ getDatabaseSchema(name: string): Promise<ApiResponse<string>>;
440
+ getDatabaseTypeSchema(name: string): Promise<ApiResponse<string>>;
441
+ getUsers(): Promise<ApiResponse<UsersListResponse>>;
442
+ getCurrentUser(): Promise<ApiResponse<User>>;
443
+ getUser(username: string): Promise<ApiResponse<User>>;
444
+ createUser(username: string, password: string): Promise<ApiResponse>;
445
+ updateUser(username: string, password: string): Promise<ApiResponse>;
446
+ deleteUser(username: string): Promise<ApiResponse>;
447
+ openTransaction(databaseName: string, transactionType: TransactionType, transactionOptions?: TransactionOptions): Promise<ApiResponse<TransactionOpenResponse>>;
448
+ commitTransaction(transactionId: string): Promise<ApiResponse>;
449
+ closeTransaction(transactionId: string): Promise<ApiResponse>;
450
+ rollbackTransaction(transactionId: string): Promise<ApiResponse>;
451
+ analyze(transactionId: string, query: string, analyzeOptions?: AnalyzeOptions): Promise<ApiResponse<AnalyzeResponse>>;
452
+ query(transactionId: string, query: string, queryOptions?: QueryOptions): Promise<ApiResponse<QueryResponse>>;
453
+ oneShotQuery(query: string, commit: boolean, databaseName: string, transactionType: TransactionType, transactionOptions?: TransactionOptions, queryOptions?: QueryOptions): Promise<ApiResponse<QueryResponse>>;
454
+ health(): Promise<ApiResponse>;
455
+ version(): Promise<ApiResponse<VersionResponse>>;
456
+ private apiGetString;
457
+ private apiGet;
458
+ private apiDelete;
459
+ private apiPost;
460
+ private apiPut;
461
+ private jsonApiReqWithoutBody;
462
+ private jsonApiReq;
463
+ private stringApiReq;
464
+ private apiReq;
465
+ private getToken;
466
+ private refreshToken;
467
+ private jsonOrNull;
468
+ private stringOrNull;
469
+ }
470
+ interface Database {
471
+ name: string;
472
+ }
473
+ type TransactionType = "read" | "write" | "schema";
474
+ interface TransactionOptions {
475
+ schemaLockAcquireTimeoutMillis?: number;
476
+ transactionTimeoutMillis?: number;
477
+ }
478
+ interface QueryOptions {
479
+ includeInstanceTypes?: boolean;
480
+ includeQueryStructure?: boolean;
481
+ answerCountLimit?: number;
482
+ }
483
+ interface AnalyzeOptions {
484
+ include_plan?: boolean;
485
+ }
486
+ interface User {
487
+ username: string;
488
+ }
489
+
490
+ export { type AnalyzeOptions, type AnalyzeResponse, type Answer, type AnswerType, type ApiError, type ApiErrorResponse, type ApiOkResponse, type ApiResponse, type Attribute, type AttributeType, type Concept, type ConceptDocument, type ConceptDocumentsQueryResponse, type ConceptRow, type ConceptRowAnswer, type ConceptRowsQueryResponse, type Database, type DatabasesListResponse, type Distribution, type DriverParams, type DriverParamsBasic, type DriverParamsTranslated, type EdgeKind, type Entity, type EntityType, type InstantiableType, type OkQueryResponse, type QueryConstraintAny, type QueryConstraintComparison, type QueryConstraintExpression, type QueryConstraintFunction, type QueryConstraintHas, type QueryConstraintIid, type QueryConstraintIs, type QueryConstraintIsa, type QueryConstraintIsaExact, type QueryConstraintKind, type QueryConstraintLabel, type QueryConstraintLinks, type QueryConstraintNot, type QueryConstraintOr, type QueryConstraintOwns, type QueryConstraintPlays, type QueryConstraintRelates, type QueryConstraintSpan, type QueryConstraintSub, type QueryConstraintSubExact, type QueryConstraintTry, type QueryConstraintValue, type QueryOptions, type QueryResponse, type QueryResponseBase, type QueryType, type QueryVariableInfo, type QueryVertex, type QueryVertexLabel, type QueryVertexNamedRole, type QueryVertexValue, type QueryVertexVariable, type Relation, type RelationType, type RoleType, type SignInResponse, type ThingKind, type TransactionOpenResponse, type TransactionOptions, type TransactionType, type TranslatedAddress, type Type, TypeDBHttpDriver, type TypeKind, type User, type UsersListResponse, type Value, type ValueKind, type ValueType, type VersionResponse, getVariableName, isApiError, isApiErrorResponse, isBasicParams, isOkResponse, isTranslatedParams, remoteOrigin };
package/dist/index.mjs ADDED
@@ -0,0 +1,193 @@
1
+ // ../../../../../../../../../execroot/typedb_driver/bazel-out/darwin_arm64-opt/bin/http-ts/src/params.ts
2
+ function isBasicParams(params) {
3
+ return `addresses` in params;
4
+ }
5
+ function isTranslatedParams(params) {
6
+ return `translatedAddresses` in params;
7
+ }
8
+ function remoteOrigin(params) {
9
+ if (isBasicParams(params)) return `${params.addresses[0]}`;
10
+ else return `${params.translatedAddresses[0].external}`;
11
+ }
12
+
13
+ // ../../../../../../../../../execroot/typedb_driver/bazel-out/darwin_arm64-opt/bin/http-ts/src/response.ts
14
+ function isApiError(err) {
15
+ return err != null && typeof err.code === "string" && typeof err.message === "string";
16
+ }
17
+ function isOkResponse(res) {
18
+ return typeof res === "object" && "ok" in res;
19
+ }
20
+ function isApiErrorResponse(res) {
21
+ return typeof res === "object" && "err" in res;
22
+ }
23
+
24
+ // ../../../../../../../../../execroot/typedb_driver/bazel-out/darwin_arm64-opt/bin/http-ts/src/analyzed-conjunction.ts
25
+ function getVariableName(structure, variable) {
26
+ return structure.variables[variable.id]?.name;
27
+ }
28
+
29
+ // ../../../../../../../../../execroot/typedb_driver/bazel-out/darwin_arm64-opt/bin/http-ts/src/index.ts
30
+ var HTTP_UNAUTHORIZED = 401;
31
+ var TypeDBHttpDriver = class {
32
+ constructor(params) {
33
+ this.params = params;
34
+ }
35
+ getDatabases() {
36
+ return this.apiGet(`/v1/databases`);
37
+ }
38
+ getDatabase(name) {
39
+ return this.apiGet(`/v1/databases/${encodeURIComponent(name)}`);
40
+ }
41
+ createDatabase(name) {
42
+ return this.apiPost(`/v1/databases/${encodeURIComponent(name)}`, {});
43
+ }
44
+ deleteDatabase(name) {
45
+ return this.apiDelete(`/v1/databases/${encodeURIComponent(name)}`);
46
+ }
47
+ getDatabaseSchema(name) {
48
+ return this.apiGetString(`/v1/databases/${encodeURIComponent(name)}/schema`);
49
+ }
50
+ getDatabaseTypeSchema(name) {
51
+ return this.apiGetString(`/v1/databases/${encodeURIComponent(name)}/type-schema`);
52
+ }
53
+ getUsers() {
54
+ return this.apiGet(`/v1/users`);
55
+ }
56
+ getCurrentUser() {
57
+ return this.apiGet(`/v1/users/${encodeURIComponent(this.params.username)}`);
58
+ }
59
+ getUser(username) {
60
+ return this.apiGet(`/v1/users/${encodeURIComponent(username)}`);
61
+ }
62
+ createUser(username, password) {
63
+ return this.apiPost(`/v1/users/${encodeURIComponent(username)}`, { password });
64
+ }
65
+ updateUser(username, password) {
66
+ return this.apiPut(`/v1/users/${encodeURIComponent(username)}`, { password });
67
+ }
68
+ deleteUser(username) {
69
+ return this.apiDelete(`/v1/users/${encodeURIComponent(username)}`);
70
+ }
71
+ openTransaction(databaseName, transactionType, transactionOptions) {
72
+ return this.apiPost(`/v1/transactions/open`, { databaseName, transactionType, transactionOptions });
73
+ }
74
+ commitTransaction(transactionId) {
75
+ return this.apiPost(`/v1/transactions/${encodeURIComponent(transactionId)}/commit`, {});
76
+ }
77
+ closeTransaction(transactionId) {
78
+ return this.apiPost(`/v1/transactions/${encodeURIComponent(transactionId)}/close`, {});
79
+ }
80
+ rollbackTransaction(transactionId) {
81
+ return this.apiPost(`/v1/transactions/${encodeURIComponent(transactionId)}/rollback`, {});
82
+ }
83
+ analyze(transactionId, query, analyzeOptions) {
84
+ return this.apiPost(`/v1/transactions/${encodeURIComponent(transactionId)}/analyze`, { query, analyzeOptions });
85
+ }
86
+ query(transactionId, query, queryOptions) {
87
+ return this.apiPost(`/v1/transactions/${encodeURIComponent(transactionId)}/query`, { query, queryOptions });
88
+ }
89
+ oneShotQuery(query, commit, databaseName, transactionType, transactionOptions, queryOptions) {
90
+ return this.apiPost(`/v1/query`, { query, commit, databaseName, transactionType, transactionOptions, queryOptions });
91
+ }
92
+ health() {
93
+ return this.apiGet(`/v1/health`);
94
+ }
95
+ version() {
96
+ return this.apiGet(`/v1/version`);
97
+ }
98
+ async apiGetString(path, options) {
99
+ return this.stringApiReq("GET", path, options);
100
+ }
101
+ async apiGet(path, options) {
102
+ return this.jsonApiReqWithoutBody("GET", path, options);
103
+ }
104
+ async apiDelete(path, options) {
105
+ return this.jsonApiReqWithoutBody("DELETE", path, options);
106
+ }
107
+ async apiPost(path, body, options) {
108
+ return this.jsonApiReq("POST", path, body, options);
109
+ }
110
+ async apiPut(path, body, options) {
111
+ return this.jsonApiReq("PUT", path, body, options);
112
+ }
113
+ async jsonApiReqWithoutBody(method, path, options) {
114
+ return this.jsonApiReq(method, path, void 0, options);
115
+ }
116
+ async jsonApiReq(method, path, body, options) {
117
+ const resp = await this.apiReq(method, path, body, options);
118
+ if ("err" in resp) return resp;
119
+ const json = await this.jsonOrNull(resp);
120
+ if (resp.ok) return { ok: json };
121
+ else if (isApiError(json)) return { err: json, status: resp.status };
122
+ else throw resp;
123
+ }
124
+ async stringApiReq(method, path, options) {
125
+ const resp = await this.apiReq(method, path, void 0, options);
126
+ if ("err" in resp) return resp;
127
+ if (resp.ok) return { ok: await this.stringOrNull(resp) ?? "" };
128
+ else {
129
+ const json = await this.jsonOrNull(resp);
130
+ if (isApiError(json)) return { err: json, status: resp.status };
131
+ else throw resp;
132
+ }
133
+ }
134
+ async apiReq(method, path, body, options) {
135
+ const url = `${remoteOrigin(this.params)}${path}`;
136
+ let tokenResp = await this.getToken();
137
+ if ("err" in tokenResp) return tokenResp;
138
+ let bodyString = void 0;
139
+ if (body !== void 0) bodyString = JSON.stringify(body);
140
+ let headers = Object.assign({ "Authorization": `Bearer ${tokenResp.ok.token}`, "Content-Type": "application/json" }, options?.headers || {});
141
+ let resp = await fetch(url, { method, body: bodyString, headers });
142
+ if (resp.status === HTTP_UNAUTHORIZED) {
143
+ tokenResp = await this.refreshToken();
144
+ if ("err" in tokenResp) return tokenResp;
145
+ headers = Object.assign({ "Authorization": `Bearer ${tokenResp.ok.token}`, "Content-Type": "application/json" }, options?.headers || {});
146
+ resp = await fetch(url, { method, body: bodyString, headers });
147
+ }
148
+ return resp;
149
+ }
150
+ getToken() {
151
+ if (this.token) {
152
+ const resp = { ok: { token: this.token } };
153
+ return Promise.resolve(resp);
154
+ } else return this.refreshToken();
155
+ }
156
+ async refreshToken() {
157
+ const url = `${remoteOrigin(this.params)}/v1/signin`;
158
+ const body = { username: this.params.username, password: this.params.password };
159
+ const resp = await fetch(url, { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json" } });
160
+ const json = await this.jsonOrNull(resp);
161
+ if (resp.ok) {
162
+ this.token = json.token;
163
+ return { ok: json };
164
+ } else if (isApiError(json)) {
165
+ return { err: json, status: resp.status };
166
+ } else throw resp;
167
+ }
168
+ async jsonOrNull(resp) {
169
+ const contentLengthRaw = resp.headers.get("Content-Length");
170
+ if (!contentLengthRaw) return null;
171
+ const contentLength = parseInt(contentLengthRaw || "");
172
+ if (isNaN(contentLength)) throw `Received invalid Content-Length header: ${contentLengthRaw}`;
173
+ return contentLength > 0 ? await resp.json() : null;
174
+ }
175
+ async stringOrNull(resp) {
176
+ const contentLengthRaw = resp.headers.get("Content-Length");
177
+ if (!contentLengthRaw) return null;
178
+ const contentLength = parseInt(contentLengthRaw || "");
179
+ if (isNaN(contentLength)) throw `Received invalid Content-Length header: ${contentLengthRaw}`;
180
+ return contentLength > 0 ? await resp.text() : null;
181
+ }
182
+ };
183
+ export {
184
+ TypeDBHttpDriver,
185
+ getVariableName,
186
+ isApiError,
187
+ isApiErrorResponse,
188
+ isBasicParams,
189
+ isOkResponse,
190
+ isTranslatedParams,
191
+ remoteOrigin
192
+ };
193
+ //# sourceMappingURL=index.mjs.map
package/package.json ADDED
@@ -0,0 +1 @@
1
+ {"name": "@typedb/driver-http", "version": "3.7.0-rc0", "description": "TypeDB HTTP Driver", "author": "TypeDB Community <community@typedb.com>", "license": "Apache-2.0", "homepage": "https://typedb.com", "repository": {"type": "git", "url": "https://github.com/typedb/typedb-driver"}, "bugs": {"url": "https://github.com/typedb/typedb-driver/issues"}, "keywords": ["database", "typedb"], "main": "dist/index.cjs", "module": "dist/index.mjs", "types": "dist/index.d.ts", "type": "module", "exports": {".": {"types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.cjs"}}, "scripts": {"build:dev": "tsc", "build": "tsup", "test": "cucumber-js", "docs": "typedoc"}, "private": false, "packageManager": "pnpm@8.15.9", "devDependencies": {"@cucumber/cucumber": "9.0.0", "@types/node": "24.0.12", "tsup": "8.5.0", "typedoc": "^0.28.7", "typescript": "5.8.3"}}