@matdata/tripletrail-client 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,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/NOTICE ADDED
@@ -0,0 +1,94 @@
1
+ TripleTrail
2
+ Copyright 2026 Matdata
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ "TripleTrail" is the product name used by Matdata. TripleTrail is not affiliated with
6
+ or endorsed by the Oxigraph project.
7
+
8
+ This product includes software developed by third parties:
9
+
10
+ - Oxigraph (https://github.com/oxigraph/oxigraph), by Thomas Pellissier Tanon
11
+ and the Oxigraph contributors, used as dependencies (oxigraph, spargebra,
12
+ spareval, oxrdf, oxttl, oxrdfxml and related crates) under the MIT license or
13
+ the Apache License 2.0.
14
+
15
+ - sparopt 0.3.9, Oxigraph's SPARQL optimizer, vendored and modified in
16
+ vendor/sparopt (changes marked "tripletrail:", listed in
17
+ vendor/sparopt/TRIPLETRAIL.md), used under the MIT license; see
18
+ vendor/sparopt/LICENSE-MIT.
19
+
20
+ - pyoxigraph 0.5.13, Oxigraph's Python binding: its RDF model, I/O, dataset and
21
+ query result classes, vendored and modified in python/src/ox (changes marked
22
+ "tripletrail:", listed in python/src/ox/README.md), used under the MIT license;
23
+ see python/src/ox/LICENSE-MIT. Its tests are adapted in python/tests/compat.
24
+
25
+ - oxrdflib 0.5.0 (https://github.com/oxigraph/oxrdflib), Copyright 2020
26
+ Oxrdflib authors: its rdflib store, adapted in python/tripletrail/rdflib.py,
27
+ under the BSD 3-Clause license; see python/tripletrail/licenses/oxrdflib-LICENSE.md.
28
+
29
+ - MatGUI 6.15.0 (https://github.com/Matdata-eu/Matgui), a fork of YASGUI,
30
+ Copyright (c) Triply B.V. and the MatGUI contributors, embedded in the server
31
+ under the MIT license; see crates/tripletrail-server/ui/vendor/matgui/LICENSE.
32
+ Its bundle includes further third-party web components (icons, fonts and map
33
+ assets) under their own licenses.
34
+
35
+ - The coordinate reference system definitions in
36
+ crates/tripletrail-geo/src/national.rs (names, parameters, datum shifts, OGC WKT
37
+ and areas of use) are derived from the EPSG Geodetic Parameter Dataset
38
+ (https://epsg.org), Copyright IOGP, as distributed with PROJ, and used under
39
+ the EPSG Dataset terms of use. The other EPSG definitions come with the
40
+ crs-definitions crate (CC0-1.0, https://github.com/frewsxcv/crs-definitions),
41
+ built from crs-csv (https://github.com/DanielJDufour/crs-csv), also derived
42
+ from the EPSG Geodetic Parameter Dataset.
43
+
44
+ - SPARQL Anything (https://github.com/SPARQL-Anything/sparql.anything), Copyright
45
+ the SPARQL Anything contributors: test files of its spreadsheet, YAML,
46
+ archive, Markdown and HTML triplifiers, copied unchanged into crates/tripletrail-fx/tests/sparql-anything
47
+ under the Apache License 2.0; see the LICENSE and README.md there.
48
+
49
+ - Semargl (https://github.com/semarglproject/semargl), Copyright 2012-2013 Lev
50
+ Khomich, and Apache Any23 (https://any23.apache.org), Copyright The Apache
51
+ Software Foundation, as SPARQL Anything includes them, both under the Apache
52
+ License 2.0: the RDFa processing and the Microdata extraction in
53
+ crates/tripletrail-fx/src/html/metadata.rs follow their code (Semargl's
54
+ RdfaParser and EvalContext, Any23's MicrodataParser and MicrodataExtractor),
55
+ translated to Rust. Apache Any23 includes software developed at The Apache
56
+ Software Foundation (https://www.apache.org/).
57
+
58
+ - CodeMirror 6 (https://codemirror.net), Copyright (C) 2018-2021 by Marijn
59
+ Haverbeke and others, with its dependencies (Lezer, style-mod, crelt,
60
+ w3c-keyname), bundled into the server's Workbench under the MIT license; see
61
+ crates/tripletrail-server/ui/vendor/codemirror/LICENSES.txt.
62
+
63
+ - Tabulator 6.3.1 (https://tabulator.info), Copyright (c) 2015-2025 Oli
64
+ Folkerd, embedded in the server's Workbench under the MIT license; see
65
+ crates/tripletrail-server/ui/vendor/tabulator/LICENSE.
66
+
67
+ - MapLibre GL JS 6.16.0 (https://maplibre.org), Copyright (c) 2023, MapLibre
68
+ contributors, embedded in the server's web UI for the describe pages' map
69
+ under the BSD 3-Clause license, with the notices of the components it
70
+ bundles; see crates/tripletrail-server/ui/vendor/maplibre/LICENSE.txt.
71
+
72
+ - Swagger UI 5.34.0 (https://swagger.io/tools/swagger-ui/), Copyright
73
+ 2020-2021 SmartBear Software Inc., embedded in the server's web UI for the
74
+ REST API's docs page under the Apache License 2.0, with the notices of the
75
+ components its bundle includes (React, DOMPurify, ieee754 and others, under
76
+ MIT, BSD-3-Clause and Apache-2.0); see
77
+ crates/tripletrail-server/ui/vendor/swagger-ui/LICENSE, NOTICE and THIRD-PARTY.txt.
78
+
79
+ - three.js r170 (https://threejs.org), Copyright 2010-2024 three.js authors,
80
+ self-hosted by the website (website/) for the home page's 3D map under the
81
+ MIT license; see website/src/assets/vendor/three.LICENSE.txt.
82
+
83
+ - The Barlow typeface, Copyright 2017 The Barlow Project Authors, self-hosted
84
+ by the website under the SIL Open Font License 1.1; see
85
+ website/src/assets/fonts/Barlow-OFL.txt. The website's map of Europe uses
86
+ Natural Earth country outlines (public domain).
87
+
88
+ - The Rust crates listed in Cargo.lock and python/Cargo.lock, under their own
89
+ licenses (MIT, Apache-2.0, BSD-2-Clause, BSD-3-Clause, ISC, Zlib, MPL-2.0,
90
+ Unicode-3.0, CDLA-Permissive-2.0 and others). The allowed licenses are
91
+ checked by cargo-deny (deny.toml). The full list, with each crate's license
92
+ texts, is THIRD_PARTY_LICENSES.md in each release archive and in the
93
+ container image (/usr/share/doc/tripletrail), generated by
94
+ .github/scripts/third-party-licenses.py.
package/README.md CHANGED
@@ -1,3 +1,20 @@
1
- # Temporary Holding Version
1
+ # TripleTrail JavaScript client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A client for [TripleTrail](../../README.md) in browsers and Node 18 and later: SPARQL queries and
4
+ updates, the Graph Store Protocol and the admin API, over `fetch`, with no dependencies and
5
+ TypeScript types.
6
+
7
+ ```js
8
+ import { TripleTrail, toValues } from "./src/index.js";
9
+
10
+ const rail = new TripleTrail("http://localhost:7878", { dataset: "rail" });
11
+ const result = await rail.select("SELECT ?s ?label { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label }");
12
+ console.log(toValues(result));
13
+ ```
14
+
15
+ The calls are listed in [Using TripleTrail as a library](../../docs/library.md#javascript-client),
16
+ and chapter 10 of the [user guide](../../docs/guide/10-maps-and-apis.md#from-javascript) has an
17
+ example. It is not published to npm yet.
18
+
19
+ Tests: `npm test` (or `node --test`) starts `tripletrail serve` from `target/debug/tripletrail`
20
+ (build it with `cargo build -p tripletrail-server`, or set `TRIPLETRAIL_BIN`) and runs against it.
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@matdata/tripletrail-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "TripleTrail client for browsers and Node: SPARQL queries and updates, the Graph Store Protocol and the admin API",
5
+ "license": "Apache-2.0",
6
+ "author": "MatData BV",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/Matdata-eu/tripletrail",
10
+ "directory": "clients/js"
11
+ },
12
+ "homepage": "https://tripletrail.eu",
13
+ "bugs": {
14
+ "url": "https://github.com/Matdata-eu/tripletrail/issues"
15
+ },
16
+ "keywords": [
17
+ "sparql",
18
+ "rdf",
19
+ "geosparql",
20
+ "knowledge-graph",
21
+ "tripletrail"
22
+ ],
23
+ "type": "module",
24
+ "main": "./src/index.js",
25
+ "types": "./src/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./src/index.d.ts",
29
+ "default": "./src/index.js"
30
+ }
31
+ },
32
+ "files": [
33
+ "src",
34
+ "NOTICE"
35
+ ],
36
+ "engines": {
37
+ "node": ">=18"
38
+ },
39
+ "scripts": {
40
+ "test": "node --test"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public",
44
+ "provenance": true
45
+ }
46
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,115 @@
1
+ // Types of the TripleTrail JavaScript client (#223).
2
+
3
+ /** A term of a SPARQL JSON result. */
4
+ export interface Term {
5
+ type: "uri" | "literal" | "bnode" | "triple";
6
+ value: string;
7
+ datatype?: string;
8
+ "xml:lang"?: string;
9
+ }
10
+
11
+ export type Row = Record<string, Term>;
12
+
13
+ export interface SelectResult {
14
+ variables: string[];
15
+ rows: Row[];
16
+ /** The server cut the answer at its row budget (`partial: true`). */
17
+ incomplete: boolean;
18
+ }
19
+
20
+ export type Value = string | number | bigint | boolean;
21
+
22
+ export function toValue(term: Term | undefined): Value | undefined;
23
+ export function toValues(result: SelectResult): Record<string, Value | undefined>[];
24
+
25
+ export class TripleTrailError extends Error {
26
+ status: number;
27
+ body: string;
28
+ }
29
+
30
+ export interface ClientOptions {
31
+ /** The dataset of queries, updates and graphs (`ds`). */
32
+ dataset?: string;
33
+ /** Sent as `Authorization: Bearer`. */
34
+ token?: string;
35
+ /** Sent as `X-API-Key`. */
36
+ apiKey?: string;
37
+ headers?: Record<string, string>;
38
+ fetch?: typeof fetch;
39
+ }
40
+
41
+ export interface QueryOptions {
42
+ /** `default-graph-uri`: the default graph of the query. */
43
+ defaultGraphs?: string[];
44
+ /** `named-graph-uri`: its named graphs. */
45
+ namedGraphs?: string[];
46
+ /** Seconds; the server takes it if it is below its own timeout. */
47
+ timeout?: number;
48
+ /** A row budget below the server's. */
49
+ maxRows?: number;
50
+ /** Answer the first rows of a larger result instead of refusing it (413). */
51
+ partial?: boolean;
52
+ /** The format of the answer, for `query` and `construct`. */
53
+ accept?: string;
54
+ signal?: AbortSignal;
55
+ }
56
+
57
+ export interface UpdateOptions {
58
+ /** `using-graph-uri`. */
59
+ usingGraphs?: string[];
60
+ /** `using-named-graph-uri`. */
61
+ usingNamedGraphs?: string[];
62
+ timeout?: number;
63
+ signal?: AbortSignal;
64
+ }
65
+
66
+ export interface RequestOptions {
67
+ params?: Record<string, string | number | string[] | undefined | null>;
68
+ headers?: Record<string, string>;
69
+ body?: BodyInit;
70
+ signal?: AbortSignal;
71
+ }
72
+
73
+ /** A graph IRI, or `null` (or `"default"`) for the default graph. */
74
+ export type GraphName = string | null;
75
+
76
+ export class TripleTrail {
77
+ constructor(url: string, options?: ClientOptions);
78
+ readonly url: string;
79
+ readonly datasetName: string;
80
+ readonly graphs: GraphStore;
81
+ readonly admin: Admin;
82
+ dataset(name: string): TripleTrail;
83
+ request(method: string, path: string, options?: RequestOptions): Promise<Response>;
84
+ query(query: string, options?: QueryOptions): Promise<Response>;
85
+ select(query: string, options?: QueryOptions): Promise<SelectResult>;
86
+ ask(query: string, options?: QueryOptions): Promise<boolean>;
87
+ construct(query: string, options?: QueryOptions): Promise<string>;
88
+ update(update: string, options?: UpdateOptions): Promise<void>;
89
+ }
90
+
91
+ export class GraphStore {
92
+ get(graph: GraphName, options?: { accept?: string; signal?: AbortSignal }): Promise<string>;
93
+ put(graph: GraphName, data: BodyInit, options?: { contentType?: string; signal?: AbortSignal }): Promise<void>;
94
+ post(graph: GraphName, data: BodyInit, options?: { contentType?: string; signal?: AbortSignal }): Promise<void>;
95
+ delete(graph: GraphName, options?: { signal?: AbortSignal }): Promise<void>;
96
+ }
97
+
98
+ export interface CreateDatasetOptions {
99
+ type?: "mem" | "disk";
100
+ location?: string;
101
+ mode?: string;
102
+ aliasOf?: string;
103
+ [parameter: string]: string | undefined;
104
+ }
105
+
106
+ export class Admin {
107
+ ping(): Promise<boolean>;
108
+ ready(): Promise<{ ready: boolean; [key: string]: unknown }>;
109
+ server(): Promise<Record<string, unknown>>;
110
+ datasets(): Promise<Record<string, unknown>[]>;
111
+ dataset(name: string): Promise<Record<string, unknown>>;
112
+ createDataset(name: string, options?: CreateDatasetOptions): Promise<void>;
113
+ deleteDataset(name: string, options?: { deleteFiles?: boolean; force?: boolean }): Promise<void>;
114
+ stats(name?: string): Promise<Record<string, unknown>>;
115
+ }
package/src/index.js ADDED
@@ -0,0 +1,347 @@
1
+ // TripleTrail client for browsers and Node 18+ (#223): SPARQL queries and updates, the Graph
2
+ // Store Protocol and the admin API, over `fetch`. No dependencies.
3
+
4
+ /** An answer the server refused: `status` is the HTTP status, `body` its text. */
5
+ export class TripleTrailError extends Error {
6
+ constructor(message, status, body) {
7
+ super(message);
8
+ this.name = "TripleTrailError";
9
+ this.status = status;
10
+ this.body = body;
11
+ }
12
+ }
13
+
14
+ const XSD = "http://www.w3.org/2001/XMLSchema#";
15
+ const INTEGERS = new Set(
16
+ [
17
+ "integer", "int", "long", "short", "byte", "nonNegativeInteger", "positiveInteger",
18
+ "nonPositiveInteger", "negativeInteger", "unsignedLong", "unsignedInt", "unsignedShort",
19
+ "unsignedByte",
20
+ ].map((t) => XSD + t),
21
+ );
22
+
23
+ /**
24
+ * A SPARQL JSON term as a plain JavaScript value: a number for a numeric literal (a `bigint`
25
+ * for an integer too large for a number), a boolean for `xsd:boolean`, the IRI, label or text
26
+ * otherwise. `undefined` for an unbound variable.
27
+ */
28
+ export function toValue(term) {
29
+ if (!term) return undefined;
30
+ if (term.type !== "literal" || !term.datatype) return term.value;
31
+ const d = term.datatype;
32
+ if (d === XSD + "boolean") {
33
+ if (["true", "1"].includes(term.value)) return true;
34
+ if (["false", "0"].includes(term.value)) return false;
35
+ return term.value;
36
+ }
37
+ const v = term.value.trim();
38
+ // An ill-typed literal ("abc"^^xsd:integer) stays text.
39
+ if (INTEGERS.has(d)) {
40
+ if (!/^[+-]?\d+$/.test(v)) return term.value;
41
+ const n = Number(v);
42
+ return Number.isSafeInteger(n) ? n : BigInt(v.replace(/^\+/, ""));
43
+ }
44
+ if (d === XSD + "decimal" || d === XSD + "double" || d === XSD + "float") {
45
+ if (v === "INF") return Infinity;
46
+ if (v === "-INF") return -Infinity;
47
+ if (v === "NaN") return NaN;
48
+ const n = Number(v);
49
+ return v === "" || Number.isNaN(n) ? term.value : n;
50
+ }
51
+ return term.value;
52
+ }
53
+
54
+ /** The rows of a `select` answer with every term as [`toValue`] gives it. */
55
+ export function toValues(result) {
56
+ return result.rows.map((row) =>
57
+ Object.fromEntries(Object.entries(row).map(([k, t]) => [k, toValue(t)])),
58
+ );
59
+ }
60
+
61
+ function join(base, path) {
62
+ return base.replace(/\/+$/, "") + "/" + path.replace(/^\/+/, "");
63
+ }
64
+
65
+ /**
66
+ * A TripleTrail server, or one dataset of it.
67
+ *
68
+ * ```js
69
+ * const rail = new TripleTrail("http://localhost:7878", { dataset: "rail", token });
70
+ * const { rows } = await rail.select("SELECT ?s { ?s a <urn:Station> }");
71
+ * ```
72
+ */
73
+ export class TripleTrail {
74
+ /**
75
+ * @param {string} url the server, such as `http://localhost:7878`
76
+ * @param {object} [options]
77
+ * @param {string} [options.dataset] the dataset of queries, updates and graphs (`ds`)
78
+ * @param {string} [options.token] sent as `Authorization: Bearer` (`--admin-token`,
79
+ * `--update-token`, or an API key)
80
+ * @param {string} [options.apiKey] sent as `X-API-Key`
81
+ * @param {Record<string, string>} [options.headers] sent with every request
82
+ * @param {typeof fetch} [options.fetch] the `fetch` to use (the global one by default)
83
+ */
84
+ constructor(url, options = {}) {
85
+ this.url = url;
86
+ this.datasetName = options.dataset ?? "ds";
87
+ this.options = options;
88
+ this.graphs = new GraphStore(this);
89
+ }
90
+
91
+ /** The same server, for another dataset. */
92
+ dataset(name) {
93
+ return new TripleTrail(this.url, { ...this.options, dataset: name });
94
+ }
95
+
96
+ /** A request to the server; answers the response, or throws a [`TripleTrailError`]. */
97
+ async request(method, path, { params, headers, body, signal } = {}) {
98
+ const url = new URL(join(this.url, path));
99
+ for (const [k, v] of Object.entries(params ?? {})) {
100
+ if (v === undefined || v === null) continue;
101
+ for (const one of Array.isArray(v) ? v : [v]) url.searchParams.append(k, String(one));
102
+ }
103
+ const all = { ...(this.options.headers ?? {}), ...(headers ?? {}) };
104
+ if (this.options.token) all.Authorization = `Bearer ${this.options.token}`;
105
+ if (this.options.apiKey) all["X-API-Key"] = this.options.apiKey;
106
+ const f = this.options.fetch ?? globalThis.fetch;
107
+ const response = await f(url, { method, headers: all, body, signal });
108
+ if (!response.ok) {
109
+ const text = await response.text().catch(() => "");
110
+ const first = text.split("\n").find((l) => l.trim()) ?? "";
111
+ throw new TripleTrailError(
112
+ `${method} ${url.pathname}: ${response.status} ${first}`.trim(),
113
+ response.status,
114
+ text,
115
+ );
116
+ }
117
+ return response;
118
+ }
119
+
120
+ /**
121
+ * A SPARQL query, answered as the raw response in the `accept` format.
122
+ * @param {string} query
123
+ * @param {QueryOptions} [options]
124
+ */
125
+ async query(query, options = {}) {
126
+ return this.request("POST", `${encodeURIComponent(this.datasetName)}/query`, {
127
+ params: {
128
+ "default-graph-uri": options.defaultGraphs,
129
+ "named-graph-uri": options.namedGraphs,
130
+ timeout: options.timeout,
131
+ "max-rows": options.maxRows,
132
+ partial: options.partial ? "true" : undefined,
133
+ },
134
+ headers: {
135
+ "Content-Type": "application/sparql-query",
136
+ Accept: options.accept ?? "application/sparql-results+json",
137
+ },
138
+ body: query,
139
+ signal: options.signal,
140
+ });
141
+ }
142
+
143
+ /**
144
+ * A `SELECT` query: its variables and rows, each row a map from variable to SPARQL JSON term
145
+ * (`{type, value, datatype?, "xml:lang"?}`; [`toValues`] gives plain values). `incomplete`
146
+ * is true when the server cut the answer at its row budget (`partial: true`).
147
+ */
148
+ async select(query, options = {}) {
149
+ const response = await this.query(query, {
150
+ ...options,
151
+ accept: "application/sparql-results+json",
152
+ });
153
+ const json = await response.json();
154
+ if (!json.results) throw new TripleTrailError("not a SELECT query", response.status, "");
155
+ return {
156
+ variables: json.head?.vars ?? [],
157
+ rows: json.results.bindings,
158
+ incomplete: response.headers.has("X-Result-Incomplete"),
159
+ };
160
+ }
161
+
162
+ /** An `ASK` query. */
163
+ async ask(query, options = {}) {
164
+ const response = await this.query(query, {
165
+ ...options,
166
+ accept: "application/sparql-results+json",
167
+ });
168
+ const json = await response.json();
169
+ if (typeof json.boolean !== "boolean") {
170
+ throw new TripleTrailError("not an ASK query", response.status, "");
171
+ }
172
+ return json.boolean;
173
+ }
174
+
175
+ /**
176
+ * A `CONSTRUCT` or `DESCRIBE` query, as RDF text (N-Triples unless `accept` names another
177
+ * format, such as `text/turtle` or `application/ld+json`).
178
+ */
179
+ async construct(query, options = {}) {
180
+ const response = await this.query(query, {
181
+ ...options,
182
+ accept: options.accept ?? "application/n-triples",
183
+ });
184
+ return response.text();
185
+ }
186
+
187
+ /**
188
+ * A SPARQL update.
189
+ * @param {string} update
190
+ * @param {UpdateOptions} [options]
191
+ */
192
+ async update(update, options = {}) {
193
+ await this.request("POST", `${encodeURIComponent(this.datasetName)}/update`, {
194
+ params: {
195
+ "using-graph-uri": options.usingGraphs,
196
+ "using-named-graph-uri": options.usingNamedGraphs,
197
+ timeout: options.timeout,
198
+ },
199
+ headers: { "Content-Type": "application/sparql-update" },
200
+ body: update,
201
+ signal: options.signal,
202
+ });
203
+ }
204
+
205
+ /** The admin API (`/$/…`). */
206
+ get admin() {
207
+ return new Admin(this);
208
+ }
209
+ }
210
+
211
+ /** A graph of the Graph Store Protocol: an IRI, or `null` for the default graph. */
212
+ function graphParams(graph) {
213
+ return graph === null || graph === undefined || graph === "default"
214
+ ? { default: "" }
215
+ : { graph };
216
+ }
217
+
218
+ /** The Graph Store Protocol of a dataset (`/{dataset}/data`). */
219
+ export class GraphStore {
220
+ constructor(client) {
221
+ this.client = client;
222
+ }
223
+
224
+ path() {
225
+ return `${encodeURIComponent(this.client.datasetName)}/data`;
226
+ }
227
+
228
+ /** A graph (`null` for the default graph) as RDF text, N-Triples unless `accept` says. */
229
+ async get(graph, { accept = "application/n-triples", signal } = {}) {
230
+ const response = await this.client.request("GET", this.path(), {
231
+ params: graphParams(graph),
232
+ headers: { Accept: accept },
233
+ signal,
234
+ });
235
+ return response.text();
236
+ }
237
+
238
+ /** Replaces a graph with `data` (RDF text in `contentType`, Turtle by default). */
239
+ async put(graph, data, { contentType = "text/turtle", signal } = {}) {
240
+ await this.client.request("PUT", this.path(), {
241
+ params: graphParams(graph),
242
+ headers: { "Content-Type": contentType },
243
+ body: data,
244
+ signal,
245
+ });
246
+ }
247
+
248
+ /** Adds `data` to a graph. */
249
+ async post(graph, data, { contentType = "text/turtle", signal } = {}) {
250
+ await this.client.request("POST", this.path(), {
251
+ params: graphParams(graph),
252
+ headers: { "Content-Type": contentType },
253
+ body: data,
254
+ signal,
255
+ });
256
+ }
257
+
258
+ /** Removes a graph (empties the default graph). */
259
+ async delete(graph, { signal } = {}) {
260
+ await this.client.request("DELETE", this.path(), { params: graphParams(graph), signal });
261
+ }
262
+ }
263
+
264
+ /** The admin API (`/$/…`): needs the admin token when the server sets one. */
265
+ export class Admin {
266
+ constructor(client) {
267
+ this.client = client;
268
+ }
269
+
270
+ async json(method, path, params) {
271
+ const response = await this.client.request(method, `$/${path}`, {
272
+ params,
273
+ headers: { Accept: "application/json" },
274
+ });
275
+ const text = await response.text();
276
+ return text ? JSON.parse(text) : null;
277
+ }
278
+
279
+ /** True when the server answers `/$/ping`. */
280
+ async ping() {
281
+ const response = await this.client.request("GET", "$/ping");
282
+ return (await response.text()).trim() === "ok";
283
+ }
284
+
285
+ /** `/$/ready`: whether every dataset is open, per dataset (does not throw on 503). */
286
+ async ready() {
287
+ try {
288
+ return { ready: true, ...(await this.json("GET", "ready")) };
289
+ } catch (e) {
290
+ if (e instanceof TripleTrailError && e.status === 503) {
291
+ let detail = {};
292
+ try {
293
+ detail = JSON.parse(e.body);
294
+ } catch {
295
+ // Not JSON: no detail.
296
+ }
297
+ return { ...detail, ready: false };
298
+ }
299
+ throw e;
300
+ }
301
+ }
302
+
303
+ /** `/$/server`: version, uptime, settings and datasets. */
304
+ server() {
305
+ return this.json("GET", "server");
306
+ }
307
+
308
+ /** `/$/datasets`: the datasets and aliases, as `datasets` (Fuseki's list). */
309
+ async datasets() {
310
+ const json = await this.json("GET", "datasets");
311
+ return json.datasets ?? json;
312
+ }
313
+
314
+ /** `/$/datasets/{name}`: one dataset, with triple and graph counts. */
315
+ dataset(name) {
316
+ return this.json("GET", `datasets/${encodeURIComponent(name)}`);
317
+ }
318
+
319
+ /**
320
+ * Creates a dataset: `type` `mem` (the default) or `disk`, or `location` and `mode` to
321
+ * attach a directory, `aliasOf` for an alias, and the other parameters of `POST
322
+ * /$/datasets` by their own names (`unionDefaultGraph`, `entailment`…).
323
+ */
324
+ async createDataset(name, { type, location, mode, aliasOf, ...rest } = {}) {
325
+ await this.json("POST", "datasets", {
326
+ name,
327
+ type: type ?? (location || aliasOf ? undefined : "mem"),
328
+ location,
329
+ mode,
330
+ "alias-of": aliasOf,
331
+ ...rest,
332
+ });
333
+ }
334
+
335
+ /** Detaches a dataset; `deleteFiles: true` also removes its directory. */
336
+ async deleteDataset(name, { deleteFiles = false, force = false } = {}) {
337
+ await this.json("DELETE", `datasets/${encodeURIComponent(name)}`, {
338
+ "delete-files": deleteFiles ? "true" : undefined,
339
+ force: force ? "true" : undefined,
340
+ });
341
+ }
342
+
343
+ /** `/$/stats` or `/$/stats/{name}`: request and data counts. */
344
+ stats(name) {
345
+ return this.json("GET", name ? `stats/${encodeURIComponent(name)}` : "stats");
346
+ }
347
+ }