@comunica/actor-init-query 5.1.3 → 5.2.2
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/lib/ActorInitQuery.js +4 -1
- package/lib/ActorInitQuery.js.map +1 -1
- package/lib/HttpServiceSparqlEndpoint.d.ts +8 -0
- package/lib/HttpServiceSparqlEndpoint.js +75 -5
- package/lib/HttpServiceSparqlEndpoint.js.map +1 -1
- package/lib/QueryEngineBase.js +23 -4
- package/lib/QueryEngineBase.js.map +1 -1
- package/lib/cli/CliArgsHandlerBase.js +76 -2
- package/lib/cli/CliArgsHandlerBase.js.map +1 -1
- package/lib/sparql-endpoint.html +117 -0
- package/package.json +14 -13
package/lib/ActorInitQuery.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
2
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
6
|
exports.ActorInitQuery = void 0;
|
|
4
7
|
/* eslint-disable import/no-nodejs-modules */
|
|
5
8
|
const node_fs_1 = require("node:fs");
|
|
6
9
|
const context_entries_1 = require("@comunica/context-entries");
|
|
7
10
|
const readable_stream_1 = require("readable-stream");
|
|
8
|
-
const yargs_1 = require("yargs");
|
|
11
|
+
const yargs_1 = __importDefault(require("yargs"));
|
|
9
12
|
const ActorInitQueryBase_1 = require("./ActorInitQueryBase");
|
|
10
13
|
const CliArgsHandlerBase_1 = require("./cli/CliArgsHandlerBase");
|
|
11
14
|
const CliArgsHandlerQuery_1 = require("./cli/CliArgsHandlerQuery");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ActorInitQuery.js","sourceRoot":"","sources":["ActorInitQuery.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ActorInitQuery.js","sourceRoot":"","sources":["ActorInitQuery.ts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Ac,CAAC,KAAM,EAAQ,OAAO,CAAC,CAAC;QAE5E,+CAA+C;QAC/C,IAAI,SAAS,IAAI,WAAW,EAAE,CAAC;YAC7B,OAAO;gBACL,MAAM,EAAE,0BAAQ,CAAC,IAAI,CAAC,CAAE,OAAO,WAAW,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;wBAC5D,2CAA2C;wBAC3C,WAAW,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC;wBACzB,2CAA2C;wBAC3C,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,GAAW,EAAE,KAAU,EAAE,EAAE;4BAC3D,IAAI,GAAG,KAAK,cAAc,EAAE,CAAC;gCAC3B,OAAO,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;4BACjC,CAAC;4BACD,OAAO,KAAK,CAAC;wBACf,CAAC,EAAE,IAAI,CAAC,GAAG,IAAI,CAAE,CAAC;aACrB,CAAC;QACJ,CAAC;QAED,2CAA2C;QAC3C,MAAM,MAAM,GAAwB,CAAC,MAAM,WAAW,CAAC,cAAc,CACnE,WAAW,EACX,IAAI,CAAC,UAAU,EACf,WAAW,CAAC,OAAO,CACpB,CAAC,CAAC,IAAI,CAAC;QAER,OAAO,EAAE,MAAM,EAAE,CAAC;IACpB,CAAC;CACF;AA5FD,wCA4FC;AACD,4CAA4C","sourcesContent":["/* eslint-disable import/no-nodejs-modules */\nimport { readFileSync } from 'node:fs';\nimport type { IActionInit, IActorOutputInit } from '@comunica/bus-init';\nimport { KeysInitQuery } from '@comunica/context-entries';\nimport type { ICliArgsHandler, IQueryContextCommon } from '@comunica/types';\nimport { Readable } from 'readable-stream';\nimport yargs from 'yargs';\nimport type { IActorInitQueryBaseArgs } from './ActorInitQueryBase';\nimport { ActorInitQueryBase } from './ActorInitQueryBase';\nimport { CliArgsHandlerBase } from './cli/CliArgsHandlerBase';\nimport { CliArgsHandlerQuery } from './cli/CliArgsHandlerQuery';\nimport { QueryEngineBase } from './QueryEngineBase';\n\n/**\n * A comunica Query Init Actor.\n */\nexport class ActorInitQuery<QueryContext extends IQueryContextCommon = IQueryContextCommon> extends ActorInitQueryBase {\n public constructor(args: IActorInitQueryBaseArgs) {\n super(args);\n }\n\n public override async run(action: IActionInit): Promise<IActorOutputInit> {\n // Wrap this actor in a query engine so we can conveniently execute queries\n const queryEngine = new QueryEngineBase<QueryContext>(this);\n\n const cliArgsHandlers: ICliArgsHandler[] = [\n new CliArgsHandlerBase(action.context),\n new CliArgsHandlerQuery(\n this.defaultQueryInputFormat,\n this.queryString,\n this.context,\n this.allowNoSources,\n ),\n ...(<ICliArgsHandler[]> action.context?.get(KeysInitQuery.cliArgsHandlers)) || [],\n ];\n\n // Populate yargs arguments object\n let argumentsBuilder = yargs([]);\n for (const cliArgsHandler of cliArgsHandlers) {\n argumentsBuilder = cliArgsHandler.populateYargs(argumentsBuilder);\n }\n\n // Extract raw argument values from parsed yargs object, so that we can handle each of them hereafter\n let args: Record<string, any>;\n try {\n args = await argumentsBuilder.parse(action.argv);\n } catch (error: unknown) {\n return {\n stderr: Readable.from([ `${await argumentsBuilder.getHelp()}\\n\\n${(<Error> error).message}\\n` ]),\n };\n }\n\n // Print supported MIME types\n if (args.listformats) {\n const mediaTypes: Record<string, number> = await queryEngine.getResultMediaTypes();\n return { stdout: Readable.from([ `${Object.keys(mediaTypes).join('\\n')}\\n` ]) };\n }\n\n // Define query\n // We need to do this before the cliArgsHandlers, as we may modify the sources array\n let query: string | undefined;\n if (args.query) {\n query = <string> args.query;\n } else if (args.file) {\n query = readFileSync(args.file, { encoding: 'utf8' });\n } else if (args.sources.length > 0) {\n query = args.sources.at(-1);\n args.sources.pop();\n }\n\n // Invoke args handlers to process any remaining args\n const context: Record<string, any> = {};\n try {\n for (const cliArgsHandler of cliArgsHandlers) {\n await cliArgsHandler.handleArgs(args, context);\n }\n } catch (error: unknown) {\n return { stderr: Readable.from([ (<Error> error).message ]) };\n }\n\n // Evaluate query\n const queryResult = await queryEngine.queryOrExplain(query!, <any> context);\n\n // Output query explanations in a different way\n if ('explain' in queryResult) {\n return {\n stdout: Readable.from([ typeof queryResult.data === 'string' ?\n // eslint-disable-next-line prefer-template\n queryResult.data + '\\n' :\n // eslint-disable-next-line prefer-template\n JSON.stringify(queryResult.data, (key: string, value: any) => {\n if (key === 'scopedSource') {\n return value.source.toString();\n }\n return value;\n }, ' ') + '\\n' ]),\n };\n }\n\n // Serialize output according to media type\n const stdout: Readable = <Readable> (await queryEngine.resultToString(\n queryResult,\n args.outputType,\n queryResult.context,\n )).data;\n\n return { stdout };\n }\n}\n/* eslint-enable import/no-nodejs-modules */\n"]}
|
|
@@ -11,6 +11,7 @@ import { VoidMetadataEmitter } from './VoidMetadataEmitter';
|
|
|
11
11
|
export declare class HttpServiceSparqlEndpoint {
|
|
12
12
|
static readonly MIME_PLAIN = "text/plain";
|
|
13
13
|
static readonly MIME_JSON = "application/json";
|
|
14
|
+
static readonly MIME_HTML = "text/html";
|
|
14
15
|
readonly engine: Promise<QueryEngineBase>;
|
|
15
16
|
readonly context: any;
|
|
16
17
|
readonly timeout: number;
|
|
@@ -92,6 +93,13 @@ export declare class HttpServiceSparqlEndpoint {
|
|
|
92
93
|
*/
|
|
93
94
|
writeQueryResult(engine: QueryEngineBase, stdout: Writable, stderr: Writable, request: http.IncomingMessage, response: http.ServerResponse, queryBody: IQueryBody | undefined, mediaType: string, headOnly: boolean, readOnly: boolean, queryId: number): Promise<void>;
|
|
94
95
|
writeServiceDescription(engine: QueryEngineBase, stdout: Writable, stderr: Writable, request: http.IncomingMessage, response: http.ServerResponse, mediaType: string, headOnly: boolean): Promise<void>;
|
|
96
|
+
/**
|
|
97
|
+
* Writes an HTML view with YASGUI for querying the endpoint.
|
|
98
|
+
* @param {module:stream.internal.Writable} stdout Output stream.
|
|
99
|
+
* @param {module:http.IncomingMessage} request Request object.
|
|
100
|
+
* @param {module:http.ServerResponse} response Response object.
|
|
101
|
+
*/
|
|
102
|
+
writeHtmlView(stdout: Writable, request: http.IncomingMessage, response: http.ServerResponse): Promise<void>;
|
|
95
103
|
/**
|
|
96
104
|
* Stop after timeout or if the connection is terminated
|
|
97
105
|
* @param {module:http.ServerResponse} response Response object.
|
|
@@ -1,14 +1,52 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
2
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
39
|
exports.HttpServiceSparqlEndpoint = void 0;
|
|
4
|
-
const
|
|
5
|
-
const
|
|
6
|
-
const
|
|
40
|
+
const fs = __importStar(require("node:fs"));
|
|
41
|
+
const http = __importStar(require("node:http"));
|
|
42
|
+
const path = __importStar(require("node:path"));
|
|
43
|
+
const querystring = __importStar(require("node:querystring"));
|
|
44
|
+
const url = __importStar(require("node:url"));
|
|
7
45
|
const context_entries_1 = require("@comunica/context-entries");
|
|
8
46
|
const core_1 = require("@comunica/core");
|
|
9
47
|
const utils_algebra_1 = require("@comunica/utils-algebra");
|
|
10
48
|
const asynciterator_1 = require("asynciterator");
|
|
11
|
-
const yargs_1 = require("yargs");
|
|
49
|
+
const yargs_1 = __importDefault(require("yargs"));
|
|
12
50
|
const __1 = require("..");
|
|
13
51
|
const CliArgsHandlerBase_1 = require("./cli/CliArgsHandlerBase");
|
|
14
52
|
const CliArgsHandlerHttp_1 = require("./cli/CliArgsHandlerHttp");
|
|
@@ -25,6 +63,7 @@ const cluster = clusterUntyped;
|
|
|
25
63
|
class HttpServiceSparqlEndpoint {
|
|
26
64
|
static MIME_PLAIN = 'text/plain';
|
|
27
65
|
static MIME_JSON = 'application/json';
|
|
66
|
+
static MIME_HTML = 'text/html';
|
|
28
67
|
engine;
|
|
29
68
|
context;
|
|
30
69
|
timeout;
|
|
@@ -325,6 +364,11 @@ class HttpServiceSparqlEndpoint {
|
|
|
325
364
|
*/
|
|
326
365
|
async writeQueryResult(engine, stdout, stderr, request, response, queryBody, mediaType, headOnly, readOnly, queryId) {
|
|
327
366
|
if (!queryBody || !queryBody.value) {
|
|
367
|
+
// Check if HTML is requested
|
|
368
|
+
const acceptHeader = request.headers.accept ?? '';
|
|
369
|
+
if (acceptHeader.includes('text/html')) {
|
|
370
|
+
return this.writeHtmlView(stdout, request, response);
|
|
371
|
+
}
|
|
328
372
|
return this.writeServiceDescription(engine, stdout, stderr, request, response, mediaType, headOnly);
|
|
329
373
|
}
|
|
330
374
|
// Log the start of the query execution
|
|
@@ -452,7 +496,7 @@ class HttpServiceSparqlEndpoint {
|
|
|
452
496
|
// Flush results
|
|
453
497
|
const { data } = await engine.resultToString({
|
|
454
498
|
resultType: 'quads',
|
|
455
|
-
execute: async () => new asynciterator_1.ArrayIterator(quads),
|
|
499
|
+
execute: async () => new asynciterator_1.ArrayIterator(quads, { autoStart: false }),
|
|
456
500
|
metadata: undefined,
|
|
457
501
|
}, mediaType);
|
|
458
502
|
data.on('error', (error) => {
|
|
@@ -470,6 +514,32 @@ class HttpServiceSparqlEndpoint {
|
|
|
470
514
|
}
|
|
471
515
|
this.stopResponse(response, 0, process.stderr, eventEmitter);
|
|
472
516
|
}
|
|
517
|
+
/**
|
|
518
|
+
* Writes an HTML view with YASGUI for querying the endpoint.
|
|
519
|
+
* @param {module:stream.internal.Writable} stdout Output stream.
|
|
520
|
+
* @param {module:http.IncomingMessage} request Request object.
|
|
521
|
+
* @param {module:http.ServerResponse} response Response object.
|
|
522
|
+
*/
|
|
523
|
+
async writeHtmlView(stdout, request, response) {
|
|
524
|
+
stdout.write(`[200] ${request.method} to ${request.url}\n`);
|
|
525
|
+
stdout.write(' Returning HTML view with YASGUI.\n');
|
|
526
|
+
const defaultQuery = `SELECT * WHERE {
|
|
527
|
+
?s ?p ?o
|
|
528
|
+
} LIMIT 100`;
|
|
529
|
+
// Use the current request URL path as the endpoint
|
|
530
|
+
const endpointPath = request.url ?? '/sparql';
|
|
531
|
+
// Read HTML template from file
|
|
532
|
+
const htmlPath = path.join(__dirname, 'sparql-endpoint.html');
|
|
533
|
+
let html = await fs.promises.readFile(htmlPath, 'utf8');
|
|
534
|
+
// Replace placeholders
|
|
535
|
+
html = html.replaceAll('%%ENDPOINT_PATH%%', endpointPath);
|
|
536
|
+
html = html.replaceAll('%%DEFAULT_QUERY%%', defaultQuery);
|
|
537
|
+
response.writeHead(200, {
|
|
538
|
+
'content-type': HttpServiceSparqlEndpoint.MIME_HTML,
|
|
539
|
+
'Access-Control-Allow-Origin': '*',
|
|
540
|
+
});
|
|
541
|
+
response.end(html);
|
|
542
|
+
}
|
|
473
543
|
/**
|
|
474
544
|
* Stop after timeout or if the connection is terminated
|
|
475
545
|
* @param {module:http.ServerResponse} response Response object.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HttpServiceSparqlEndpoint.js","sourceRoot":"","sources":["HttpServiceSparqlEndpoint.ts"],"names":[],"mappings":";;;AAGA,kCAAkC;AAElC,gDAAgD;AAEhD,gCAAgC;AAChC,+DAA8E;AAC9E,yCAA+C;AAE/C,2DAAkD;AAElD,iDAA8C;AAE9C,iCAA0B;AAI1B,0BAA6D;AAE7D,iEAA8D;AAC9D,iEAA8D;AAC9D,+DAA4D;AAE5D,oHAAoH;AACpH,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;AAC/C,MAAM,OAAO,GAAmB,OAAO,CAAC,UAAU,CAAC,CAAC;AACpD,MAAM,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAEjC,qFAAqF;AACrF,MAAM,OAAO,GAAY,cAAc,CAAC;AAExC;;GAEG;AACH,MAAa,yBAAyB;IAC7B,MAAM,CAAU,UAAU,GAAG,YAAY,CAAC;IAC1C,MAAM,CAAU,SAAS,GAAG,kBAAkB,CAAC;IAEtC,MAAM,CAA2B;IAEjC,OAAO,CAAM;IACb,OAAO,CAAS;IAChB,IAAI,CAAS;IACb,OAAO,CAAS;IAEhB,mBAAmB,CAAU;IAC7B,eAAe,CAAU;IACzB,QAAQ,CAAU;IAElB,mBAAmB,CAAsB;IAElD,WAAW,GAAG,CAAC,CAAC;IAEvB,YAAmB,IAAoC;QACrD,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,IAA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,GAAG,IAAI,CAAC,KAAK,CAAS,aAAa,CAAC,OAAO,CAAC,CAAC;4BACtD,CAAC;4BAAC,OAAO,KAAc,EAAE,CAAC;gCACxB,MAAM,CAAC,IAAI,KAAK,CAAC,6CAAoD,aAAc,CAAC,OAAO,OAAgB,KAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;4BAChI,CAAC;wBACH,CAAC;wBACD,IAAI,aAAa,CAAC,KAAK,EAAE,CAAC;4BACxB,OAAO,OAAO,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAW,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;wBAClF,CAAC;wBACD,IAAI,aAAa,CAAC,MAAM,EAAE,CAAC;4BACzB,OAAO,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAW,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;wBAClF,CAAC;oBACH,CAAC;gBACH,CAAC;gBACD,MAAM,CAAC,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAC,CAAC;YACtF,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;;AA1pBH,8DA2pBC;AAmBD,4CAA4C","sourcesContent":["/* eslint-disable import/no-nodejs-modules,ts/no-require-imports,ts/no-var-requires */\nimport type { Cluster } from 'node:cluster';\nimport type { EventEmitter } from 'node:events';\nimport * as http from 'node:http';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport * as querystring from 'node:querystring';\nimport type { Writable } from 'node:stream';\nimport * as url from 'node:url';\nimport { KeysInitQuery, KeysQueryOperation } from '@comunica/context-entries';\nimport { ActionContext } from '@comunica/core';\nimport type { ICliArgsHandler, QueryQuads, QueryType } from '@comunica/types';\nimport { Algebra } from '@comunica/utils-algebra';\nimport type * as RDF from '@rdfjs/types';\nimport { ArrayIterator } from 'asynciterator';\n\nimport yargs from 'yargs';\n\nimport type { IDynamicQueryEngineOptions } from '..';\n\nimport { QueryEngineBase, QueryEngineFactoryBase } from '..';\n\nimport { CliArgsHandlerBase } from './cli/CliArgsHandlerBase';\nimport { CliArgsHandlerHttp } from './cli/CliArgsHandlerHttp';\nimport { VoidMetadataEmitter } from './VoidMetadataEmitter';\n\n// Use require instead of import for default exports, to be compatible with variants of esModuleInterop in tsconfig.\nconst clusterUntyped = require('node:cluster');\nconst process: NodeJS.Process = require('process/');\nconst quad = require('rdf-quad');\n\n// Force type on Cluster, because there are issues with the Node.js typings since v18\nconst cluster: Cluster = clusterUntyped;\n\n/**\n * An HTTP service that exposes a Comunica engine as a SPARQL endpoint.\n */\nexport class HttpServiceSparqlEndpoint {\n public static readonly MIME_PLAIN = 'text/plain';\n public static readonly MIME_JSON = 'application/json';\n\n public readonly engine: Promise<QueryEngineBase>;\n\n public readonly context: any;\n public readonly timeout: number;\n public readonly port: number;\n public readonly workers: number;\n\n public readonly freshWorkerPerQuery: boolean;\n public readonly contextOverride: boolean;\n public readonly emitVoid: boolean;\n\n public readonly voidMetadataEmitter: VoidMetadataEmitter;\n\n public lastQueryId = 0;\n\n public constructor(args: IHttpServiceSparqlEndpointArgs) {\n this.context = args.context || {};\n this.timeout = args.timeout ?? 60_000;\n this.port = args.port ?? 3_000;\n this.workers = args.workers ?? 1;\n this.freshWorkerPerQuery = Boolean(args.freshWorkerPerQuery);\n this.contextOverride = Boolean(args.contextOverride);\n this.emitVoid = Boolean(args.emitVoid);\n this.voidMetadataEmitter = new VoidMetadataEmitter(this.context);\n\n this.engine = new QueryEngineFactoryBase(\n args.moduleRootPath,\n args.defaultConfigPath,\n actorInitQuery => new QueryEngineBase(actorInitQuery),\n ).create(args);\n }\n\n /**\n * Starts the server\n * @param {string[]} argv The commandline arguments that the script was called with\n * @param {module:stream.internal.Writable} stdout The output stream to log to.\n * @param {module:stream.internal.Writable} stderr The error stream to log errors to.\n * @param {string} moduleRootPath The path to the invoking module.\n * @param {NodeJS.ProcessEnv} env The process env to get constants from.\n * @param {string} defaultConfigPath The path to get the config from if none is defined in the environment.\n * @param {(code: number) => void} exit The callback to invoke to stop the script.\n * @param {ICliArgsHandler[]} cliArgsHandlers Enables manipulation of the CLI arguments and their processing.\n * @return {Promise<void>} A promise that resolves when the server has been started.\n */\n public static async runArgsInProcess(\n argv: string[],\n stdout: Writable,\n stderr: Writable,\n moduleRootPath: string,\n env: NodeJS.ProcessEnv,\n defaultConfigPath: string,\n exit: (code: number) => void,\n cliArgsHandlers: ICliArgsHandler[] = [],\n ): Promise<void> {\n const options = await HttpServiceSparqlEndpoint\n .generateConstructorArguments(argv, moduleRootPath, env, defaultConfigPath, stderr, exit, cliArgsHandlers);\n\n return new Promise<void>((resolve) => {\n new HttpServiceSparqlEndpoint(options || {}).run(stdout, stderr)\n .then(resolve)\n .catch((error) => {\n stderr.write(error);\n exit(1);\n resolve();\n });\n });\n }\n\n /**\n * Takes parsed commandline arguments and turns them into an object used in the HttpServiceSparqlEndpoint constructor\n * @param {args: string[]} argv The commandline arguments that the script was called with\n * @param {string} moduleRootPath The path to the invoking module.\n * @param {NodeJS.ProcessEnv} env The process env to get constants from.\n * @param {string} defaultConfigPath The path to get the config from if none is defined in the environment.\n * @param stderr The error stream.\n * @param exit An exit process callback.\n * @param {ICliArgsHandler[]} cliArgsHandlers Enables manipulation of the CLI arguments and their processing.\n */\n public static async generateConstructorArguments(\n argv: string[],\n moduleRootPath: string,\n env: NodeJS.ProcessEnv,\n defaultConfigPath: string,\n stderr: Writable,\n exit: (code: number) => void,\n cliArgsHandlers: ICliArgsHandler[],\n ): Promise<IHttpServiceSparqlEndpointArgs> {\n // Populate yargs arguments object\n cliArgsHandlers = [\n new CliArgsHandlerBase(),\n new CliArgsHandlerHttp(),\n ...cliArgsHandlers,\n ];\n let argumentsBuilder = yargs([]);\n for (const cliArgsHandler of cliArgsHandlers) {\n argumentsBuilder = cliArgsHandler.populateYargs(argumentsBuilder);\n }\n\n // Extract raw argument values from parsed yargs object, so that we can handle each of them hereafter\n let args: Record<string, any>;\n try {\n args = await argumentsBuilder.parse(argv);\n } catch (error: unknown) {\n stderr.write(`${await argumentsBuilder.getHelp()}\\n\\n${(<Error> error).message}\\n`);\n return <any> exit(1);\n }\n\n // Invoke args handlers to process any remaining args\n const context: Record<string, any> = {};\n try {\n for (const cliArgsHandler of cliArgsHandlers) {\n await cliArgsHandler.handleArgs(args, context);\n }\n } catch (error: unknown) {\n stderr.write(`${(<Error>error).message}/n`);\n exit(1);\n }\n\n const freshWorkerPerQuery: boolean = args.freshWorker;\n const contextOverride: boolean = args.contextOverride;\n const emitVoid: boolean = args.emitVoid;\n const port = args.port;\n const timeout = args.timeout * 1_000;\n const workers = args.workers;\n context[KeysQueryOperation.readOnly.name] = !args.u;\n\n const configPath = env.COMUNICA_CONFIG ? env.COMUNICA_CONFIG : defaultConfigPath;\n\n return {\n defaultConfigPath,\n configPath,\n context,\n freshWorkerPerQuery,\n contextOverride,\n emitVoid,\n moduleRootPath,\n mainModulePath: moduleRootPath,\n port,\n timeout,\n workers,\n };\n }\n\n /**\n * Start the HTTP service.\n * @param {module:stream.internal.Writable} stdout The output stream to log to.\n * @param {module:stream.internal.Writable} stderr The error stream to log errors to.\n */\n public run(stdout: Writable, stderr: Writable): Promise<void> {\n if (cluster.isMaster) {\n return this.runMaster(stdout, stderr);\n }\n return this.runWorker(stdout, stderr);\n }\n\n /**\n * Start the HTTP service as master.\n * @param {module:stream.internal.Writable} stdout The output stream to log to.\n * @param {module:stream.internal.Writable} stderr The error stream to log errors to.\n */\n public async runMaster(stdout: Writable, stderr: Writable): Promise<void> {\n stderr.write(`Server running on http://localhost:${this.port}/sparql\\n`);\n\n // Create workers\n for (let i = 0; i < this.workers; i++) {\n cluster.fork();\n }\n\n // Attach listeners to each new worker\n cluster.on('listening', (worker) => {\n // Respawn crashed workers\n worker.once('exit', (code, signal) => {\n if (!worker.exitedAfterDisconnect) {\n if (code === 9 || signal === 'SIGKILL') {\n stderr.write(`Worker ${worker.process.pid} forcefully killed with ${code || signal}. Killing main process as well.\\n`);\n cluster.disconnect();\n } else {\n stderr.write(`Worker ${worker.process.pid} died with ${code || signal}. Starting new worker.\\n`);\n cluster.fork();\n }\n }\n });\n\n // Handle worker timeouts\n const workerTimeouts: Record<number, NodeJS.Timeout> = {};\n worker.on('message', ({ type, queryId }) => {\n if (type === 'start') {\n stderr.write(`Worker ${worker.process.pid} got assigned a new query (${queryId}).\\n`);\n workerTimeouts[queryId] = setTimeout(() => {\n try {\n if (worker.isConnected()) {\n stderr.write(`Worker ${worker.process.pid} timed out for query ${queryId}.\\n`);\n worker.send('shutdown');\n }\n } catch (error: unknown) {\n stderr.write(`Unable to timeout worker ${worker.process.pid}: ${(<Error> error).message}.\\n`);\n }\n delete workerTimeouts[queryId];\n }, this.timeout);\n } else if (type === 'end' && workerTimeouts[queryId]) {\n stderr.write(`Worker ${worker.process.pid} has completed query ${queryId}.\\n`);\n clearTimeout(workerTimeouts[queryId]);\n delete workerTimeouts[queryId];\n }\n });\n });\n\n // Disconnect from cluster on SIGINT, so that the process can cleanly terminate\n process.once('SIGINT', () => {\n cluster.disconnect();\n });\n }\n\n /**\n * Start the HTTP service as worker.\n * @param {module:stream.internal.Writable} stdout The output stream to log to.\n * @param {module:stream.internal.Writable} stderr The error stream to log errors to.\n */\n public async runWorker(stdout: Writable, stderr: Writable): Promise<void> {\n const engine: QueryEngineBase = await this.engine;\n\n // Determine the allowed media types for requests\n const mediaTypes: Record<string, number> = await engine.getResultMediaTypes();\n const variants: { type: string; quality: number }[] = [];\n for (const type of Object.keys(mediaTypes)) {\n variants.push({ type, quality: mediaTypes[type] });\n }\n\n // Start the server\n // eslint-disable-next-line ts/no-misused-promises\n const server = http.createServer(this.handleRequest.bind(this, engine, variants, stdout, stderr));\n server.listen(this.port);\n stderr.write(`Server worker (${process.pid}) running on http://localhost:${this.port}/sparql\\n`);\n\n // Keep track of all open connections\n const openConnections: Set<ServerResponse> = new Set();\n server.on('request', (request: IncomingMessage, response: ServerResponse) => {\n openConnections.add(response);\n response.on('close', () => {\n openConnections.delete(response);\n });\n });\n\n // Subscribe to shutdown messages\n // eslint-disable-next-line ts/no-misused-promises\n process.on('message', async(message: string): Promise<void> => {\n if (message === 'shutdown') {\n stderr.write(`Shutting down worker ${process.pid} with ${openConnections.size} open connections.\\n`);\n\n // Stop new connections from being accepted\n server.close();\n\n // Close all open connections\n for (const connection of openConnections) {\n await new Promise<void>(resolve => connection.end('!TIMEDOUT!', resolve));\n }\n\n // Kill the worker once the connections have been closed\n process.exit(15);\n }\n });\n\n // Catch global errors, and cleanly close open connections\n // eslint-disable-next-line ts/no-misused-promises\n process.on('uncaughtException', async(error) => {\n stderr.write(`Terminating worker ${process.pid} with ${openConnections.size} open connections due to uncaught exception.\\n`);\n stderr.write(error.stack);\n\n // Stop new connections from being accepted\n server.close();\n\n // Close all open connections\n for (const connection of openConnections) {\n await new Promise<void>(resolve => connection.end('!ERROR!', resolve));\n }\n\n // Kill the worker once the connections have been closed\n process.exit(15);\n });\n }\n\n /**\n * Handles an HTTP request.\n * @param {QueryEngineBase} engine A SPARQL engine.\n * @param {{type: string; quality: number}[]} variants Allowed variants.\n * @param {module:stream.internal.Writable} stdout Output stream.\n * @param {module:stream.internal.Writable} stderr Error output stream.\n * @param {module:http.IncomingMessage} request Request object.\n * @param {module:http.ServerResponse} response Response object.\n */\n public async handleRequest(\n engine: QueryEngineBase,\n variants: { type: string; quality: number }[],\n stdout: Writable,\n stderr: Writable,\n request: http.IncomingMessage,\n response: http.ServerResponse,\n ): Promise<void> {\n const negotiated = require('negotiate').choose(variants, request)\n .sort((first: any, second: any) => second.qts - first.qts);\n const variant: any = request.headers.accept ? negotiated[0] : null;\n // Require qts strictly larger than 2, as 1 and 2 respectively allow * and */* matching.\n // For qts 0, 1, and 2, we fallback to our built-in media type defaults, for which we pass null.\n const mediaType: string = variant && variant.qts > 2 ? variant.type : null;\n\n // Verify the path\n // eslint-disable-next-line node/no-deprecated-api\n const requestUrl = url.parse(request.url ?? '', true);\n if (requestUrl.pathname === '/' || request.url === '/') {\n stdout.write('[301] Permanently moved. Redirected to /sparql.\\n');\n response.writeHead(301, { 'content-type': HttpServiceSparqlEndpoint.MIME_JSON, 'Access-Control-Allow-Origin': '*', Location: `http://localhost:${this.port}/sparql${requestUrl.search ?? ''}` });\n response.end(JSON.stringify({ message: 'Queries are accepted on /sparql. Redirected.' }));\n return;\n }\n if (requestUrl.pathname !== '/sparql') {\n stdout.write('[404] Resource not found. Queries are accepted on /sparql.\\n');\n response.writeHead(\n 404,\n { 'content-type': HttpServiceSparqlEndpoint.MIME_JSON, 'Access-Control-Allow-Origin': '*' },\n );\n response.end(JSON.stringify({ message: 'Resource not found. Queries are accepted on /sparql.' }));\n return;\n }\n\n // Parse the query, depending on the HTTP method\n let queryBody: IQueryBody | undefined;\n switch (request.method) {\n case 'POST':\n queryBody = await this.parseBody(request);\n await this.writeQueryResult(\n engine,\n stdout,\n stderr,\n request,\n response,\n queryBody,\n mediaType,\n false,\n false,\n this.lastQueryId++,\n );\n break;\n case 'HEAD':\n case 'GET':\n // eslint-disable-next-line no-case-declarations\n const queryValue = <string> requestUrl.query.query;\n queryBody = queryValue ? { type: 'query', value: queryValue, context: undefined } : undefined;\n // eslint-disable-next-line no-case-declarations\n const headOnly = request.method === 'HEAD';\n await this.writeQueryResult(\n engine,\n stdout,\n stderr,\n request,\n response,\n queryBody,\n mediaType,\n headOnly,\n true,\n this.lastQueryId++,\n );\n break;\n default:\n stdout.write(`[405] ${request.method} to ${request.url}\\n`);\n response.writeHead(\n 405,\n { 'content-type': HttpServiceSparqlEndpoint.MIME_JSON, 'Access-Control-Allow-Origin': '*' },\n );\n response.end(JSON.stringify({ message: 'Incorrect HTTP method' }));\n }\n }\n\n /**\n * Writes the result of the given SPARQL query.\n * @param {QueryEngineBase} engine A SPARQL engine.\n * @param {module:stream.internal.Writable} stdout Output stream.\n * @param {module:stream.internal.Writable} stderr Error output stream.\n * @param {module:http.IncomingMessage} request Request object.\n * @param {module:http.ServerResponse} response Response object.\n * @param {IQueryBody | undefined} queryBody The query body.\n * @param {string} mediaType The requested response media type.\n * @param {boolean} headOnly If only the header should be written.\n * @param {boolean} readOnly If only data can be read, but not updated. (i.e., if we're in a GET request)\n * @param queryId The unique id of this query.\n */\n public async writeQueryResult(\n engine: QueryEngineBase,\n stdout: Writable,\n stderr: Writable,\n request: http.IncomingMessage,\n response: http.ServerResponse,\n queryBody: IQueryBody | undefined,\n mediaType: string,\n headOnly: boolean,\n readOnly: boolean,\n queryId: number,\n ): Promise<void> {\n if (!queryBody || !queryBody.value) {\n return this.writeServiceDescription(engine, stdout, stderr, request, response, mediaType, headOnly);\n }\n\n // Log the start of the query execution\n stdout.write(`[200] ${request.method} to ${request.url}\\n`);\n stdout.write(` Requested media type: ${mediaType}\\n`);\n stdout.write(` Received ${queryBody.type} query: ${queryBody.value}\\n`);\n\n // Send message to master process to indicate the start of an execution\n process.send!({ type: 'start', queryId });\n\n // Determine context\n let context = {\n ...this.context,\n ...this.contextOverride ? queryBody.context : undefined,\n };\n if (readOnly) {\n context = { ...context, [KeysQueryOperation.readOnly.name]: readOnly };\n }\n\n let result: QueryType;\n try {\n result = await engine.query(queryBody.value, context);\n\n // For update queries, also await the result\n if (result.resultType === 'void') {\n await result.execute();\n }\n } catch (error: unknown) {\n stdout.write('[400] Bad request\\n');\n response.writeHead(\n 400,\n { 'content-type': HttpServiceSparqlEndpoint.MIME_PLAIN, 'Access-Control-Allow-Origin': '*' },\n );\n response.end((<Error> error).message);\n return;\n }\n\n // If the query was an update query, invalidate the void metadata emitter cache\n if (this.emitVoid &&\n // Try to check parsed operation\n ((result.context && result.context.has(KeysQueryOperation.operation) &&\n // eslint-disable-next-line ts/prefer-nullish-coalescing\n result.context.getSafe(KeysQueryOperation.operation).type === Algebra.Types.DELETE_INSERT) ||\n // Fallback to query string\n /(INSERT|DELETE)/iu.test(queryBody.value))) {\n this.voidMetadataEmitter.invalidateCache();\n }\n\n // Default to SPARQL JSON for bindings and boolean\n if (!mediaType) {\n switch (result.resultType) {\n case 'quads':\n mediaType = 'application/trig';\n break;\n case 'void':\n mediaType = 'simple';\n break;\n default:\n mediaType = 'application/sparql-results+json';\n break;\n }\n }\n\n // Write header of response\n response.writeHead(200, { 'content-type': mediaType, 'Access-Control-Allow-Origin': '*' });\n stdout.write(` Resolved to result media type: ${mediaType}\\n`);\n\n // Stop further processing for HEAD requests\n if (headOnly) {\n response.end();\n return;\n }\n\n let eventEmitter: EventEmitter | undefined;\n try {\n const { data } = await engine.resultToString(result, mediaType);\n data.on('error', (error: Error) => {\n stdout.write(`[500] Server error in results: ${error.message} \\n`);\n if (!response.writableEnded) {\n response.end('An internal server error occurred.\\n');\n }\n });\n data.pipe(response);\n eventEmitter = data;\n } catch {\n stdout.write('[400] Bad request, invalid media type\\n');\n response.writeHead(\n 400,\n { 'content-type': HttpServiceSparqlEndpoint.MIME_PLAIN, 'Access-Control-Allow-Origin': '*' },\n );\n response.end('The response for the given query could not be serialized for the requested media type\\n');\n }\n\n // Send message to master process to indicate the end of an execution\n response.on('close', () => {\n process.send!({ type: 'end', queryId });\n });\n\n this.stopResponse(response, queryId, process.stderr, eventEmitter);\n }\n\n public async writeServiceDescription(\n engine: QueryEngineBase,\n stdout: Writable,\n stderr: Writable,\n request: http.IncomingMessage,\n response: http.ServerResponse,\n mediaType: string,\n headOnly: boolean,\n ): Promise<void> {\n stdout.write(`[200] ${request.method} to ${request.url}\\n`);\n stdout.write(` Requested media type: ${mediaType}\\n`);\n stdout.write(' Received query for service description.\\n');\n response.writeHead(200, { 'content-type': mediaType, 'Access-Control-Allow-Origin': '*' });\n\n if (headOnly) {\n response.end();\n return;\n }\n\n const s = request.url;\n const sd = 'http://www.w3.org/ns/sparql-service-description#';\n const quads: RDF.Quad[] = [\n // Basic metadata\n quad(s, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', `${sd}Service`),\n quad(s, `${sd}endpoint`, '/sparql'),\n quad(s, `${sd}url`, '/sparql'),\n\n // Features\n quad(s, `${sd}feature`, `${sd}BasicFederatedQuery`),\n quad(s, `${sd}supportedLanguage`, `${sd}SPARQL10Query`),\n quad(s, `${sd}supportedLanguage`, `${sd}SPARQL11Query`),\n ];\n\n let eventEmitter: EventEmitter;\n try {\n const actionContext = ActionContext.ensureActionContext(this.context);\n\n // Append result formats\n const formats = await engine.getResultMediaTypeFormats(actionContext);\n for (const format in formats) {\n quads.push(quad(s, `${sd}resultFormat`, formats[format]));\n }\n\n // Append extension functions\n const functions = actionContext.get(KeysInitQuery.extensionFunctions);\n for (const value in functions) {\n quads.push(quad(s, `${sd}extensionFunction`, value));\n }\n\n if (this.emitVoid) {\n for (const quad of await this.voidMetadataEmitter.getVoIDQuads(engine, stdout, request, response)) {\n quads.push(quad);\n }\n }\n\n // Flush results\n const { data } = await engine.resultToString(<QueryQuads>{\n resultType: 'quads',\n execute: async() => new ArrayIterator(quads),\n metadata: <any>undefined,\n }, mediaType);\n data.on('error', (error: Error) => {\n stdout.write(`[500] Server error in results: ${error.message} \\n`);\n response.end('An internal server error occurred.\\n');\n });\n data.pipe(response);\n eventEmitter = data;\n } catch {\n stdout.write('[400] Bad request, invalid media type\\n');\n response.writeHead(\n 400,\n { 'content-type': HttpServiceSparqlEndpoint.MIME_PLAIN, 'Access-Control-Allow-Origin': '*' },\n );\n response.end('The response for the given query could not be serialized for the requested media type\\n');\n return;\n }\n this.stopResponse(response, 0, process.stderr, eventEmitter);\n }\n\n /**\n * Stop after timeout or if the connection is terminated\n * @param {module:http.ServerResponse} response Response object.\n * @param queryId The unique query id.\n * @param stderr Error stream to write to.\n * @param {NodeJS.ReadableStream} eventEmitter Query result stream.\n */\n public stopResponse(\n response: http.ServerResponse,\n queryId: number,\n stderr: Writable,\n eventEmitter?: EventEmitter,\n ): void {\n response.on('close', killClient);\n // eslint-disable-next-line ts/no-this-alias\n const self = this;\n function killClient(): void {\n if (eventEmitter) {\n // Remove all listeners so we are sure no more write calls are made\n eventEmitter.removeAllListeners();\n eventEmitter.on('error', () => {\n // Void any errors that may still occur\n });\n eventEmitter.emit('end');\n }\n try {\n response.end();\n } catch {\n // Do nothing\n }\n\n // Kill the worker if we want fresh workers per query\n if (self.freshWorkerPerQuery) {\n stderr.write(`Killing fresh worker ${process.pid} after query ${queryId}.\\n`);\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(15);\n }\n }\n }\n\n /**\n * Parses the body of a SPARQL POST request\n * @param {module:http.IncomingMessage} request Request object.\n * @return {Promise<IQueryBody>} A promise resolving to a query body object.\n */\n public parseBody(request: http.IncomingMessage): Promise<IQueryBody> {\n return new Promise((resolve, reject) => {\n let body = '';\n request.setEncoding('utf8');\n request.on('error', reject);\n request.on('data', (chunk) => {\n body += chunk;\n });\n request.on('end', () => {\n const contentType: string | undefined = request.headers['content-type'];\n if (contentType) {\n if (contentType.includes('application/sparql-query')) {\n return resolve({ type: 'query', value: body, context: undefined });\n }\n if (contentType.includes('application/sparql-update')) {\n return resolve({ type: 'void', value: body, context: undefined });\n }\n if (contentType.includes('application/x-www-form-urlencoded')) {\n const bodyStructure = querystring.parse(body);\n let context: Record<string, any> | undefined;\n if (bodyStructure.context) {\n try {\n context = JSON.parse(<string>bodyStructure.context);\n } catch (error: unknown) {\n reject(new Error(`Invalid POST body with context received ('${(<any> bodyStructure).context}'): ${(<Error> error).message}`));\n }\n }\n if (bodyStructure.query) {\n return resolve({ type: 'query', value: <string> bodyStructure.query, context });\n }\n if (bodyStructure.update) {\n return resolve({ type: 'void', value: <string> bodyStructure.update, context });\n }\n }\n }\n reject(new Error(`Invalid POST body received, query type could not be determined`));\n });\n });\n }\n}\n\nexport interface IQueryBody {\n type: 'query' | 'void';\n value: string;\n context: Record<string, any> | undefined;\n}\n\nexport interface IHttpServiceSparqlEndpointArgs extends IDynamicQueryEngineOptions {\n context?: any;\n timeout?: number;\n port?: number;\n workers?: number;\n freshWorkerPerQuery?: boolean;\n contextOverride?: boolean;\n emitVoid?: boolean;\n moduleRootPath: string;\n defaultConfigPath: string;\n}\n/* esl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CAAC;wBACD,IAAI,aAAa,CAAC,KAAK,EAAE,CAAC;4BACxB,OAAO,OAAO,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAW,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;wBAClF,CAAC;wBACD,IAAI,aAAa,CAAC,MAAM,EAAE,CAAC;4BACzB,OAAO,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAW,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;wBAClF,CAAC;oBACH,CAAC;gBACH,CAAC;gBACD,MAAM,CAAC,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAC,CAAC;YACtF,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;;AApsBH,8DAqsBC;AAmBD,4CAA4C","sourcesContent":["/* eslint-disable import/no-nodejs-modules,ts/no-require-imports,ts/no-var-requires */\nimport type { Cluster } from 'node:cluster';\nimport type { EventEmitter } from 'node:events';\nimport * as fs from 'node:fs';\nimport * as http from 'node:http';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport * as path from 'node:path';\nimport * as querystring from 'node:querystring';\nimport type { Writable } from 'node:stream';\nimport * as url from 'node:url';\nimport { KeysInitQuery, KeysQueryOperation } from '@comunica/context-entries';\nimport { ActionContext } from '@comunica/core';\nimport type { ICliArgsHandler, QueryQuads, QueryType } from '@comunica/types';\nimport { Algebra } from '@comunica/utils-algebra';\nimport type * as RDF from '@rdfjs/types';\nimport { ArrayIterator } from 'asynciterator';\n\nimport yargs from 'yargs';\n\nimport type { IDynamicQueryEngineOptions } from '..';\n\nimport { QueryEngineBase, QueryEngineFactoryBase } from '..';\n\nimport { CliArgsHandlerBase } from './cli/CliArgsHandlerBase';\nimport { CliArgsHandlerHttp } from './cli/CliArgsHandlerHttp';\nimport { VoidMetadataEmitter } from './VoidMetadataEmitter';\n\n// Use require instead of import for default exports, to be compatible with variants of esModuleInterop in tsconfig.\nconst clusterUntyped = require('node:cluster');\nconst process: NodeJS.Process = require('process/');\nconst quad = require('rdf-quad');\n\n// Force type on Cluster, because there are issues with the Node.js typings since v18\nconst cluster: Cluster = clusterUntyped;\n\n/**\n * An HTTP service that exposes a Comunica engine as a SPARQL endpoint.\n */\nexport class HttpServiceSparqlEndpoint {\n public static readonly MIME_PLAIN = 'text/plain';\n public static readonly MIME_JSON = 'application/json';\n public static readonly MIME_HTML = 'text/html';\n\n public readonly engine: Promise<QueryEngineBase>;\n\n public readonly context: any;\n public readonly timeout: number;\n public readonly port: number;\n public readonly workers: number;\n\n public readonly freshWorkerPerQuery: boolean;\n public readonly contextOverride: boolean;\n public readonly emitVoid: boolean;\n\n public readonly voidMetadataEmitter: VoidMetadataEmitter;\n\n public lastQueryId = 0;\n\n public constructor(args: IHttpServiceSparqlEndpointArgs) {\n this.context = args.context || {};\n this.timeout = args.timeout ?? 60_000;\n this.port = args.port ?? 3_000;\n this.workers = args.workers ?? 1;\n this.freshWorkerPerQuery = Boolean(args.freshWorkerPerQuery);\n this.contextOverride = Boolean(args.contextOverride);\n this.emitVoid = Boolean(args.emitVoid);\n this.voidMetadataEmitter = new VoidMetadataEmitter(this.context);\n\n this.engine = new QueryEngineFactoryBase(\n args.moduleRootPath,\n args.defaultConfigPath,\n actorInitQuery => new QueryEngineBase(actorInitQuery),\n ).create(args);\n }\n\n /**\n * Starts the server\n * @param {string[]} argv The commandline arguments that the script was called with\n * @param {module:stream.internal.Writable} stdout The output stream to log to.\n * @param {module:stream.internal.Writable} stderr The error stream to log errors to.\n * @param {string} moduleRootPath The path to the invoking module.\n * @param {NodeJS.ProcessEnv} env The process env to get constants from.\n * @param {string} defaultConfigPath The path to get the config from if none is defined in the environment.\n * @param {(code: number) => void} exit The callback to invoke to stop the script.\n * @param {ICliArgsHandler[]} cliArgsHandlers Enables manipulation of the CLI arguments and their processing.\n * @return {Promise<void>} A promise that resolves when the server has been started.\n */\n public static async runArgsInProcess(\n argv: string[],\n stdout: Writable,\n stderr: Writable,\n moduleRootPath: string,\n env: NodeJS.ProcessEnv,\n defaultConfigPath: string,\n exit: (code: number) => void,\n cliArgsHandlers: ICliArgsHandler[] = [],\n ): Promise<void> {\n const options = await HttpServiceSparqlEndpoint\n .generateConstructorArguments(argv, moduleRootPath, env, defaultConfigPath, stderr, exit, cliArgsHandlers);\n\n return new Promise<void>((resolve) => {\n new HttpServiceSparqlEndpoint(options || {}).run(stdout, stderr)\n .then(resolve)\n .catch((error) => {\n stderr.write(error);\n exit(1);\n resolve();\n });\n });\n }\n\n /**\n * Takes parsed commandline arguments and turns them into an object used in the HttpServiceSparqlEndpoint constructor\n * @param {args: string[]} argv The commandline arguments that the script was called with\n * @param {string} moduleRootPath The path to the invoking module.\n * @param {NodeJS.ProcessEnv} env The process env to get constants from.\n * @param {string} defaultConfigPath The path to get the config from if none is defined in the environment.\n * @param stderr The error stream.\n * @param exit An exit process callback.\n * @param {ICliArgsHandler[]} cliArgsHandlers Enables manipulation of the CLI arguments and their processing.\n */\n public static async generateConstructorArguments(\n argv: string[],\n moduleRootPath: string,\n env: NodeJS.ProcessEnv,\n defaultConfigPath: string,\n stderr: Writable,\n exit: (code: number) => void,\n cliArgsHandlers: ICliArgsHandler[],\n ): Promise<IHttpServiceSparqlEndpointArgs> {\n // Populate yargs arguments object\n cliArgsHandlers = [\n new CliArgsHandlerBase(),\n new CliArgsHandlerHttp(),\n ...cliArgsHandlers,\n ];\n let argumentsBuilder = yargs([]);\n for (const cliArgsHandler of cliArgsHandlers) {\n argumentsBuilder = cliArgsHandler.populateYargs(argumentsBuilder);\n }\n\n // Extract raw argument values from parsed yargs object, so that we can handle each of them hereafter\n let args: Record<string, any>;\n try {\n args = await argumentsBuilder.parse(argv);\n } catch (error: unknown) {\n stderr.write(`${await argumentsBuilder.getHelp()}\\n\\n${(<Error> error).message}\\n`);\n return <any> exit(1);\n }\n\n // Invoke args handlers to process any remaining args\n const context: Record<string, any> = {};\n try {\n for (const cliArgsHandler of cliArgsHandlers) {\n await cliArgsHandler.handleArgs(args, context);\n }\n } catch (error: unknown) {\n stderr.write(`${(<Error>error).message}/n`);\n exit(1);\n }\n\n const freshWorkerPerQuery: boolean = args.freshWorker;\n const contextOverride: boolean = args.contextOverride;\n const emitVoid: boolean = args.emitVoid;\n const port = args.port;\n const timeout = args.timeout * 1_000;\n const workers = args.workers;\n context[KeysQueryOperation.readOnly.name] = !args.u;\n\n const configPath = env.COMUNICA_CONFIG ? env.COMUNICA_CONFIG : defaultConfigPath;\n\n return {\n defaultConfigPath,\n configPath,\n context,\n freshWorkerPerQuery,\n contextOverride,\n emitVoid,\n moduleRootPath,\n mainModulePath: moduleRootPath,\n port,\n timeout,\n workers,\n };\n }\n\n /**\n * Start the HTTP service.\n * @param {module:stream.internal.Writable} stdout The output stream to log to.\n * @param {module:stream.internal.Writable} stderr The error stream to log errors to.\n */\n public run(stdout: Writable, stderr: Writable): Promise<void> {\n if (cluster.isMaster) {\n return this.runMaster(stdout, stderr);\n }\n return this.runWorker(stdout, stderr);\n }\n\n /**\n * Start the HTTP service as master.\n * @param {module:stream.internal.Writable} stdout The output stream to log to.\n * @param {module:stream.internal.Writable} stderr The error stream to log errors to.\n */\n public async runMaster(stdout: Writable, stderr: Writable): Promise<void> {\n stderr.write(`Server running on http://localhost:${this.port}/sparql\\n`);\n\n // Create workers\n for (let i = 0; i < this.workers; i++) {\n cluster.fork();\n }\n\n // Attach listeners to each new worker\n cluster.on('listening', (worker) => {\n // Respawn crashed workers\n worker.once('exit', (code, signal) => {\n if (!worker.exitedAfterDisconnect) {\n if (code === 9 || signal === 'SIGKILL') {\n stderr.write(`Worker ${worker.process.pid} forcefully killed with ${code || signal}. Killing main process as well.\\n`);\n cluster.disconnect();\n } else {\n stderr.write(`Worker ${worker.process.pid} died with ${code || signal}. Starting new worker.\\n`);\n cluster.fork();\n }\n }\n });\n\n // Handle worker timeouts\n const workerTimeouts: Record<number, NodeJS.Timeout> = {};\n worker.on('message', ({ type, queryId }) => {\n if (type === 'start') {\n stderr.write(`Worker ${worker.process.pid} got assigned a new query (${queryId}).\\n`);\n workerTimeouts[queryId] = setTimeout(() => {\n try {\n if (worker.isConnected()) {\n stderr.write(`Worker ${worker.process.pid} timed out for query ${queryId}.\\n`);\n worker.send('shutdown');\n }\n } catch (error: unknown) {\n stderr.write(`Unable to timeout worker ${worker.process.pid}: ${(<Error> error).message}.\\n`);\n }\n delete workerTimeouts[queryId];\n }, this.timeout);\n } else if (type === 'end' && workerTimeouts[queryId]) {\n stderr.write(`Worker ${worker.process.pid} has completed query ${queryId}.\\n`);\n clearTimeout(workerTimeouts[queryId]);\n delete workerTimeouts[queryId];\n }\n });\n });\n\n // Disconnect from cluster on SIGINT, so that the process can cleanly terminate\n process.once('SIGINT', () => {\n cluster.disconnect();\n });\n }\n\n /**\n * Start the HTTP service as worker.\n * @param {module:stream.internal.Writable} stdout The output stream to log to.\n * @param {module:stream.internal.Writable} stderr The error stream to log errors to.\n */\n public async runWorker(stdout: Writable, stderr: Writable): Promise<void> {\n const engine: QueryEngineBase = await this.engine;\n\n // Determine the allowed media types for requests\n const mediaTypes: Record<string, number> = await engine.getResultMediaTypes();\n const variants: { type: string; quality: number }[] = [];\n for (const type of Object.keys(mediaTypes)) {\n variants.push({ type, quality: mediaTypes[type] });\n }\n\n // Start the server\n // eslint-disable-next-line ts/no-misused-promises\n const server = http.createServer(this.handleRequest.bind(this, engine, variants, stdout, stderr));\n server.listen(this.port);\n stderr.write(`Server worker (${process.pid}) running on http://localhost:${this.port}/sparql\\n`);\n\n // Keep track of all open connections\n const openConnections: Set<ServerResponse> = new Set();\n server.on('request', (request: IncomingMessage, response: ServerResponse) => {\n openConnections.add(response);\n response.on('close', () => {\n openConnections.delete(response);\n });\n });\n\n // Subscribe to shutdown messages\n // eslint-disable-next-line ts/no-misused-promises\n process.on('message', async(message: string): Promise<void> => {\n if (message === 'shutdown') {\n stderr.write(`Shutting down worker ${process.pid} with ${openConnections.size} open connections.\\n`);\n\n // Stop new connections from being accepted\n server.close();\n\n // Close all open connections\n for (const connection of openConnections) {\n await new Promise<void>(resolve => connection.end('!TIMEDOUT!', resolve));\n }\n\n // Kill the worker once the connections have been closed\n process.exit(15);\n }\n });\n\n // Catch global errors, and cleanly close open connections\n // eslint-disable-next-line ts/no-misused-promises\n process.on('uncaughtException', async(error) => {\n stderr.write(`Terminating worker ${process.pid} with ${openConnections.size} open connections due to uncaught exception.\\n`);\n stderr.write(error.stack);\n\n // Stop new connections from being accepted\n server.close();\n\n // Close all open connections\n for (const connection of openConnections) {\n await new Promise<void>(resolve => connection.end('!ERROR!', resolve));\n }\n\n // Kill the worker once the connections have been closed\n process.exit(15);\n });\n }\n\n /**\n * Handles an HTTP request.\n * @param {QueryEngineBase} engine A SPARQL engine.\n * @param {{type: string; quality: number}[]} variants Allowed variants.\n * @param {module:stream.internal.Writable} stdout Output stream.\n * @param {module:stream.internal.Writable} stderr Error output stream.\n * @param {module:http.IncomingMessage} request Request object.\n * @param {module:http.ServerResponse} response Response object.\n */\n public async handleRequest(\n engine: QueryEngineBase,\n variants: { type: string; quality: number }[],\n stdout: Writable,\n stderr: Writable,\n request: http.IncomingMessage,\n response: http.ServerResponse,\n ): Promise<void> {\n const negotiated = require('negotiate').choose(variants, request)\n .sort((first: any, second: any) => second.qts - first.qts);\n const variant: any = request.headers.accept ? negotiated[0] : null;\n // Require qts strictly larger than 2, as 1 and 2 respectively allow * and */* matching.\n // For qts 0, 1, and 2, we fallback to our built-in media type defaults, for which we pass null.\n const mediaType: string = variant && variant.qts > 2 ? variant.type : null;\n\n // Verify the path\n // eslint-disable-next-line node/no-deprecated-api\n const requestUrl = url.parse(request.url ?? '', true);\n if (requestUrl.pathname === '/' || request.url === '/') {\n stdout.write('[301] Permanently moved. Redirected to /sparql.\\n');\n response.writeHead(301, { 'content-type': HttpServiceSparqlEndpoint.MIME_JSON, 'Access-Control-Allow-Origin': '*', Location: `http://localhost:${this.port}/sparql${requestUrl.search ?? ''}` });\n response.end(JSON.stringify({ message: 'Queries are accepted on /sparql. Redirected.' }));\n return;\n }\n if (requestUrl.pathname !== '/sparql') {\n stdout.write('[404] Resource not found. Queries are accepted on /sparql.\\n');\n response.writeHead(\n 404,\n { 'content-type': HttpServiceSparqlEndpoint.MIME_JSON, 'Access-Control-Allow-Origin': '*' },\n );\n response.end(JSON.stringify({ message: 'Resource not found. Queries are accepted on /sparql.' }));\n return;\n }\n\n // Parse the query, depending on the HTTP method\n let queryBody: IQueryBody | undefined;\n switch (request.method) {\n case 'POST':\n queryBody = await this.parseBody(request);\n await this.writeQueryResult(\n engine,\n stdout,\n stderr,\n request,\n response,\n queryBody,\n mediaType,\n false,\n false,\n this.lastQueryId++,\n );\n break;\n case 'HEAD':\n case 'GET':\n // eslint-disable-next-line no-case-declarations\n const queryValue = <string> requestUrl.query.query;\n queryBody = queryValue ? { type: 'query', value: queryValue, context: undefined } : undefined;\n // eslint-disable-next-line no-case-declarations\n const headOnly = request.method === 'HEAD';\n await this.writeQueryResult(\n engine,\n stdout,\n stderr,\n request,\n response,\n queryBody,\n mediaType,\n headOnly,\n true,\n this.lastQueryId++,\n );\n break;\n default:\n stdout.write(`[405] ${request.method} to ${request.url}\\n`);\n response.writeHead(\n 405,\n { 'content-type': HttpServiceSparqlEndpoint.MIME_JSON, 'Access-Control-Allow-Origin': '*' },\n );\n response.end(JSON.stringify({ message: 'Incorrect HTTP method' }));\n }\n }\n\n /**\n * Writes the result of the given SPARQL query.\n * @param {QueryEngineBase} engine A SPARQL engine.\n * @param {module:stream.internal.Writable} stdout Output stream.\n * @param {module:stream.internal.Writable} stderr Error output stream.\n * @param {module:http.IncomingMessage} request Request object.\n * @param {module:http.ServerResponse} response Response object.\n * @param {IQueryBody | undefined} queryBody The query body.\n * @param {string} mediaType The requested response media type.\n * @param {boolean} headOnly If only the header should be written.\n * @param {boolean} readOnly If only data can be read, but not updated. (i.e., if we're in a GET request)\n * @param queryId The unique id of this query.\n */\n public async writeQueryResult(\n engine: QueryEngineBase,\n stdout: Writable,\n stderr: Writable,\n request: http.IncomingMessage,\n response: http.ServerResponse,\n queryBody: IQueryBody | undefined,\n mediaType: string,\n headOnly: boolean,\n readOnly: boolean,\n queryId: number,\n ): Promise<void> {\n if (!queryBody || !queryBody.value) {\n // Check if HTML is requested\n const acceptHeader = request.headers.accept ?? '';\n if (acceptHeader.includes('text/html')) {\n return this.writeHtmlView(stdout, request, response);\n }\n return this.writeServiceDescription(engine, stdout, stderr, request, response, mediaType, headOnly);\n }\n\n // Log the start of the query execution\n stdout.write(`[200] ${request.method} to ${request.url}\\n`);\n stdout.write(` Requested media type: ${mediaType}\\n`);\n stdout.write(` Received ${queryBody.type} query: ${queryBody.value}\\n`);\n\n // Send message to master process to indicate the start of an execution\n process.send!({ type: 'start', queryId });\n\n // Determine context\n let context = {\n ...this.context,\n ...this.contextOverride ? queryBody.context : undefined,\n };\n if (readOnly) {\n context = { ...context, [KeysQueryOperation.readOnly.name]: readOnly };\n }\n\n let result: QueryType;\n try {\n result = await engine.query(queryBody.value, context);\n\n // For update queries, also await the result\n if (result.resultType === 'void') {\n await result.execute();\n }\n } catch (error: unknown) {\n stdout.write('[400] Bad request\\n');\n response.writeHead(\n 400,\n { 'content-type': HttpServiceSparqlEndpoint.MIME_PLAIN, 'Access-Control-Allow-Origin': '*' },\n );\n response.end((<Error> error).message);\n return;\n }\n\n // If the query was an update query, invalidate the void metadata emitter cache\n if (this.emitVoid &&\n // Try to check parsed operation\n ((result.context && result.context.has(KeysQueryOperation.operation) &&\n // eslint-disable-next-line ts/prefer-nullish-coalescing\n result.context.getSafe(KeysQueryOperation.operation).type === Algebra.Types.DELETE_INSERT) ||\n // Fallback to query string\n /(INSERT|DELETE)/iu.test(queryBody.value))) {\n this.voidMetadataEmitter.invalidateCache();\n }\n\n // Default to SPARQL JSON for bindings and boolean\n if (!mediaType) {\n switch (result.resultType) {\n case 'quads':\n mediaType = 'application/trig';\n break;\n case 'void':\n mediaType = 'simple';\n break;\n default:\n mediaType = 'application/sparql-results+json';\n break;\n }\n }\n\n // Write header of response\n response.writeHead(200, { 'content-type': mediaType, 'Access-Control-Allow-Origin': '*' });\n stdout.write(` Resolved to result media type: ${mediaType}\\n`);\n\n // Stop further processing for HEAD requests\n if (headOnly) {\n response.end();\n return;\n }\n\n let eventEmitter: EventEmitter | undefined;\n try {\n const { data } = await engine.resultToString(result, mediaType);\n data.on('error', (error: Error) => {\n stdout.write(`[500] Server error in results: ${error.message} \\n`);\n if (!response.writableEnded) {\n response.end('An internal server error occurred.\\n');\n }\n });\n data.pipe(response);\n eventEmitter = data;\n } catch {\n stdout.write('[400] Bad request, invalid media type\\n');\n response.writeHead(\n 400,\n { 'content-type': HttpServiceSparqlEndpoint.MIME_PLAIN, 'Access-Control-Allow-Origin': '*' },\n );\n response.end('The response for the given query could not be serialized for the requested media type\\n');\n }\n\n // Send message to master process to indicate the end of an execution\n response.on('close', () => {\n process.send!({ type: 'end', queryId });\n });\n\n this.stopResponse(response, queryId, process.stderr, eventEmitter);\n }\n\n public async writeServiceDescription(\n engine: QueryEngineBase,\n stdout: Writable,\n stderr: Writable,\n request: http.IncomingMessage,\n response: http.ServerResponse,\n mediaType: string,\n headOnly: boolean,\n ): Promise<void> {\n stdout.write(`[200] ${request.method} to ${request.url}\\n`);\n stdout.write(` Requested media type: ${mediaType}\\n`);\n stdout.write(' Received query for service description.\\n');\n response.writeHead(200, { 'content-type': mediaType, 'Access-Control-Allow-Origin': '*' });\n\n if (headOnly) {\n response.end();\n return;\n }\n\n const s = request.url;\n const sd = 'http://www.w3.org/ns/sparql-service-description#';\n const quads: RDF.Quad[] = [\n // Basic metadata\n quad(s, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', `${sd}Service`),\n quad(s, `${sd}endpoint`, '/sparql'),\n quad(s, `${sd}url`, '/sparql'),\n\n // Features\n quad(s, `${sd}feature`, `${sd}BasicFederatedQuery`),\n quad(s, `${sd}supportedLanguage`, `${sd}SPARQL10Query`),\n quad(s, `${sd}supportedLanguage`, `${sd}SPARQL11Query`),\n ];\n\n let eventEmitter: EventEmitter;\n try {\n const actionContext = ActionContext.ensureActionContext(this.context);\n\n // Append result formats\n const formats = await engine.getResultMediaTypeFormats(actionContext);\n for (const format in formats) {\n quads.push(quad(s, `${sd}resultFormat`, formats[format]));\n }\n\n // Append extension functions\n const functions = actionContext.get(KeysInitQuery.extensionFunctions);\n for (const value in functions) {\n quads.push(quad(s, `${sd}extensionFunction`, value));\n }\n\n if (this.emitVoid) {\n for (const quad of await this.voidMetadataEmitter.getVoIDQuads(engine, stdout, request, response)) {\n quads.push(quad);\n }\n }\n\n // Flush results\n const { data } = await engine.resultToString(<QueryQuads>{\n resultType: 'quads',\n execute: async() => new ArrayIterator(quads, { autoStart: false }),\n metadata: <any>undefined,\n }, mediaType);\n data.on('error', (error: Error) => {\n stdout.write(`[500] Server error in results: ${error.message} \\n`);\n response.end('An internal server error occurred.\\n');\n });\n data.pipe(response);\n eventEmitter = data;\n } catch {\n stdout.write('[400] Bad request, invalid media type\\n');\n response.writeHead(\n 400,\n { 'content-type': HttpServiceSparqlEndpoint.MIME_PLAIN, 'Access-Control-Allow-Origin': '*' },\n );\n response.end('The response for the given query could not be serialized for the requested media type\\n');\n return;\n }\n this.stopResponse(response, 0, process.stderr, eventEmitter);\n }\n\n /**\n * Writes an HTML view with YASGUI for querying the endpoint.\n * @param {module:stream.internal.Writable} stdout Output stream.\n * @param {module:http.IncomingMessage} request Request object.\n * @param {module:http.ServerResponse} response Response object.\n */\n public async writeHtmlView(\n stdout: Writable,\n request: http.IncomingMessage,\n response: http.ServerResponse,\n ): Promise<void> {\n stdout.write(`[200] ${request.method} to ${request.url}\\n`);\n stdout.write(' Returning HTML view with YASGUI.\\n');\n\n const defaultQuery = `SELECT * WHERE {\n ?s ?p ?o\n} LIMIT 100`;\n\n // Use the current request URL path as the endpoint\n const endpointPath = request.url ?? '/sparql';\n\n // Read HTML template from file\n const htmlPath = path.join(__dirname, 'sparql-endpoint.html');\n let html = await fs.promises.readFile(htmlPath, 'utf8');\n\n // Replace placeholders\n html = html.replaceAll('%%ENDPOINT_PATH%%', endpointPath);\n html = html.replaceAll('%%DEFAULT_QUERY%%', defaultQuery);\n\n response.writeHead(200, {\n 'content-type': HttpServiceSparqlEndpoint.MIME_HTML,\n 'Access-Control-Allow-Origin': '*',\n });\n response.end(html);\n }\n\n /**\n * Stop after timeout or if the connection is terminated\n * @param {module:http.ServerResponse} response Response object.\n * @param queryId The unique query id.\n * @param stderr Error stream to write to.\n * @param {NodeJS.ReadableStream} eventEmitter Query result stream.\n */\n public stopResponse(\n response: http.ServerResponse,\n queryId: number,\n stderr: Writable,\n eventEmitter?: EventEmitter,\n ): void {\n response.on('close', killClient);\n // eslint-disable-next-line ts/no-this-alias\n const self = this;\n function killClient(): void {\n if (eventEmitter) {\n // Remove all listeners so we are sure no more write calls are made\n eventEmitter.removeAllListeners();\n eventEmitter.on('error', () => {\n // Void any errors that may still occur\n });\n eventEmitter.emit('end');\n }\n try {\n response.end();\n } catch {\n // Do nothing\n }\n\n // Kill the worker if we want fresh workers per query\n if (self.freshWorkerPerQuery) {\n stderr.write(`Killing fresh worker ${process.pid} after query ${queryId}.\\n`);\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(15);\n }\n }\n }\n\n /**\n * Parses the body of a SPARQL POST request\n * @param {module:http.IncomingMessage} request Request object.\n * @return {Promise<IQueryBody>} A promise resolving to a query body object.\n */\n public parseBody(request: http.IncomingMessage): Promise<IQueryBody> {\n return new Promise((resolve, reject) => {\n let body = '';\n request.setEncoding('utf8');\n request.on('error', reject);\n request.on('data', (chunk) => {\n body += chunk;\n });\n request.on('end', () => {\n const contentType: string | undefined = request.headers['content-type'];\n if (contentType) {\n if (contentType.includes('application/sparql-query')) {\n return resolve({ type: 'query', value: body, context: undefined });\n }\n if (contentType.includes('application/sparql-update')) {\n return resolve({ type: 'void', value: body, context: undefined });\n }\n if (contentType.includes('application/x-www-form-urlencoded')) {\n const bodyStructure = querystring.parse(body);\n let context: Record<string, any> | undefined;\n if (bodyStructure.context) {\n try {\n context = JSON.parse(<string>bodyStructure.context);\n } catch (error: unknown) {\n reject(new Error(`Invalid POST body with context received ('${(<any> bodyStructure).context}'): ${(<Error> error).message}`));\n }\n }\n if (bodyStructure.query) {\n return resolve({ type: 'query', value: <string> bodyStructure.query, context });\n }\n if (bodyStructure.update) {\n return resolve({ type: 'void', value: <string> bodyStructure.update, context });\n }\n }\n }\n reject(new Error(`Invalid POST body received, query type could not be determined`));\n });\n });\n }\n}\n\nexport interface IQueryBody {\n type: 'query' | 'void';\n value: string;\n context: Record<string, any> | undefined;\n}\n\nexport interface IHttpServiceSparqlEndpointArgs extends IDynamicQueryEngineOptions {\n context?: any;\n timeout?: number;\n port?: number;\n workers?: number;\n freshWorkerPerQuery?: boolean;\n contextOverride?: boolean;\n emitVoid?: boolean;\n moduleRootPath: string;\n defaultConfigPath: string;\n}\n/* eslint-enable import/no-nodejs-modules */\n"]}
|
package/lib/QueryEngineBase.js
CHANGED
|
@@ -136,11 +136,17 @@ class QueryEngineBase {
|
|
|
136
136
|
* @param internalResult An intermediary query result.
|
|
137
137
|
*/
|
|
138
138
|
static internalToFinalResult(internalResult) {
|
|
139
|
+
const logger = internalResult.context?.get(context_entries_1.KeysCore.log);
|
|
139
140
|
switch (internalResult.type) {
|
|
140
141
|
case 'bindings':
|
|
141
142
|
return {
|
|
142
143
|
resultType: 'bindings',
|
|
143
|
-
execute: async () =>
|
|
144
|
+
execute: async () => {
|
|
145
|
+
if (logger) {
|
|
146
|
+
internalResult.bindingsStream.on?.('end', () => logger.flush());
|
|
147
|
+
}
|
|
148
|
+
return internalResult.bindingsStream;
|
|
149
|
+
},
|
|
144
150
|
metadata: async () => {
|
|
145
151
|
const meta = await internalResult.metadata();
|
|
146
152
|
meta.variables = meta.variables.map((variable) => variable.variable);
|
|
@@ -151,20 +157,33 @@ class QueryEngineBase {
|
|
|
151
157
|
case 'quads':
|
|
152
158
|
return {
|
|
153
159
|
resultType: 'quads',
|
|
154
|
-
execute: async () =>
|
|
160
|
+
execute: async () => {
|
|
161
|
+
if (logger) {
|
|
162
|
+
internalResult.quadStream.on?.('end', () => logger.flush());
|
|
163
|
+
}
|
|
164
|
+
return internalResult.quadStream;
|
|
165
|
+
},
|
|
155
166
|
metadata: async () => await internalResult.metadata(),
|
|
156
167
|
context: internalResult.context,
|
|
157
168
|
};
|
|
158
169
|
case 'boolean':
|
|
159
170
|
return {
|
|
160
171
|
resultType: 'boolean',
|
|
161
|
-
execute: async () =>
|
|
172
|
+
execute: async () => {
|
|
173
|
+
const result = await internalResult.execute();
|
|
174
|
+
logger?.flush();
|
|
175
|
+
return result;
|
|
176
|
+
},
|
|
162
177
|
context: internalResult.context,
|
|
163
178
|
};
|
|
164
179
|
case 'void':
|
|
165
180
|
return {
|
|
166
181
|
resultType: 'void',
|
|
167
|
-
execute: async () =>
|
|
182
|
+
execute: async () => {
|
|
183
|
+
const result = await internalResult.execute();
|
|
184
|
+
logger?.flush();
|
|
185
|
+
return result;
|
|
186
|
+
},
|
|
168
187
|
context: internalResult.context,
|
|
169
188
|
};
|
|
170
189
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryEngineBase.js","sourceRoot":"","sources":["QueryEngineBase.ts"],"names":[],"mappings":";;;AACA,+DAA0D;AAC1D,yCAA+C;AAqB/C;;GAEG;AACH,MAAa,eAAe;IAOT,cAAc,CAAqB;IAEpD,YAAmB,cAAkC;QACnD,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;IAEM,KAAK,CAAC,aAAa,CACxB,KAA2B,EAC3B,OAAkG;QAElG,OAAO,IAAI,CAAC,WAAW,CAA+C,KAAK,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;IACpG,CAAC;IAEM,KAAK,CAAC,UAAU,CACrB,KAA2B,EAC3B,OAAkG;QAElG,OAAO,IAAI,CAAC,WAAW,CAA4C,KAAK,EAAE,OAAO,EAAE,O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AC1F,OAAO,IAAI,CAAC;oBACd,CAAC;iBACF,CAAC;YACJ,KAAK,OAAO;gBACV,OAAO;oBACL,IAAI,EAAE,OAAO;oBACb,UAAU,EAA4B,MAAM,WAAW,CAAC,OAAO,EAAE;oBACjE,QAAQ,EAAE,KAAK,IAAG,EAAE,CAAO,MAAM,WAAW,CAAC,QAAQ,EAAE;iBACxD,CAAC;YACJ,KAAK,SAAS;gBACZ,OAAO;oBACL,IAAI,EAAE,SAAS;oBACf,OAAO,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE;iBACrC,CAAC;YACJ,KAAK,MAAM;gBACT,OAAO;oBACL,IAAI,EAAE,MAAM;oBACZ,OAAO,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE;iBACrC,CAAC;QACN,CAAC;IACH,CAAC;CACF;AAxPD,0CAwPC","sourcesContent":["import type { IActionSparqlSerialize, IActorQueryResultSerializeOutput } from '@comunica/bus-query-result-serialize';\nimport { KeysInitQuery } from '@comunica/context-entries';\nimport { ActionContext } from '@comunica/core';\nimport type {\n IActionContext,\n IQueryOperationResult,\n IQueryEngine,\n IQueryExplained,\n QueryFormatType,\n QueryType,\n QueryExplainMode,\n BindingsStream,\n QueryAlgebraContext,\n QueryStringContext,\n IQueryBindingsEnhanced,\n IQueryQuadsEnhanced,\n QueryEnhanced,\n IQueryContextCommon,\n} from '@comunica/types';\nimport type * as RDF from '@rdfjs/types';\nimport type { AsyncIterator } from 'asynciterator';\nimport type { ActorInitQueryBase } from './ActorInitQueryBase';\n\n/**\n * Base implementation of a Comunica query engine.\n */\nexport class QueryEngineBase<\n // eslint-disable-next-line unused-imports/no-unused-vars\n QueryContext extends IQueryContextCommon = IQueryContextCommon,\n QueryStringContextInner extends RDF.QueryStringContext = QueryStringContext,\n QueryAlgebraContextInner extends RDF.QueryAlgebraContext = QueryAlgebraContext,\n>\nimplements IQueryEngine<QueryStringContextInner, QueryAlgebraContextInner> {\n private readonly actorInitQuery: ActorInitQueryBase;\n\n public constructor(actorInitQuery: ActorInitQueryBase) {\n this.actorInitQuery = actorInitQuery;\n }\n\n public async queryBindings<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<BindingsStream> {\n return this.queryOfType<QueryFormatTypeInner, IQueryBindingsEnhanced>(query, context, 'bindings');\n }\n\n public async queryQuads<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<AsyncIterator<RDF.Quad> & RDF.ResultStream<RDF.Quad>> {\n return this.queryOfType<QueryFormatTypeInner, IQueryQuadsEnhanced>(query, context, 'quads');\n }\n\n public async queryBoolean<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<boolean> {\n return this.queryOfType<QueryFormatTypeInner, RDF.QueryBoolean>(query, context, 'boolean');\n }\n\n public async queryVoid<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<void> {\n return this.queryOfType<QueryFormatTypeInner, RDF.QueryVoid>(query, context, 'void');\n }\n\n protected async queryOfType<QueryFormatTypeInner extends QueryFormatType, QueryTypeOut extends QueryEnhanced>(\n query: QueryFormatTypeInner,\n context: undefined | (QueryFormatTypeInner extends string ?\n QueryStringContextInner : QueryAlgebraContextInner),\n expectedType: QueryTypeOut['resultType'],\n ): Promise<ReturnType<QueryTypeOut['execute']>> {\n const result = await this.query<QueryFormatTypeInner>(query, context);\n if (result.resultType === expectedType) {\n return <ReturnType<QueryTypeOut['execute']>> await result.execute();\n }\n throw new Error(`Query result type '${expectedType}' was expected, while '${result.resultType}' was found.`);\n }\n\n /**\n * Evaluate the given query\n * @param query A query string or algebra.\n * @param context An optional query context.\n * @return {Promise<QueryType>} A promise that resolves to the query output.\n */\n public async query<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<QueryType> {\n const output = await this.queryOrExplain(query, context);\n if ('explain' in output) {\n throw new Error(`Tried to explain a query when in query-only mode`);\n }\n return output;\n }\n\n /**\n * Explain the given query\n * @param query A query string or algebra.\n * @param context An optional query context.\n * @param explainMode The explain mode.\n * @return {Promise<QueryType | IQueryExplained>} A promise that resolves to\n * the query output or explanation.\n */\n public async explain<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n explainMode: QueryExplainMode,\n ): Promise<IQueryExplained> {\n context.explain = explainMode;\n const output = await this.queryOrExplain(query, context);\n return <IQueryExplained> output;\n }\n\n /**\n * Evaluate or explain the given query\n * @param query A query string or algebra.\n * @param context An optional query context.\n * @return {Promise<QueryType | IQueryExplained>} A promise that resolves to\n * the query output or explanation.\n */\n public async queryOrExplain<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<QueryType | IQueryExplained> {\n const actionContext: IActionContext = ActionContext.ensureActionContext(context);\n\n // Invalidate caches if cache argument is set to false\n if (actionContext.get(KeysInitQuery.invalidateCache)) {\n await this.invalidateHttpCache();\n }\n\n // Invoke query process\n const { result } = await this.actorInitQuery.mediatorQueryProcess.mediate({ query, context: actionContext });\n if ('explain' in result) {\n return result;\n }\n return QueryEngineBase.internalToFinalResult(result);\n }\n\n /**\n * @param context An optional context.\n * @return {Promise<{[p: string]: number}>} All available SPARQL (weighted) result media types.\n */\n public async getResultMediaTypes(context?: any): Promise<Record<string, number>> {\n context = ActionContext.ensureActionContext(context);\n return (await this.actorInitQuery.mediatorQueryResultSerializeMediaTypeCombiner\n .mediate({ context, mediaTypes: true })).mediaTypes;\n }\n\n /**\n * @param context An optional context.\n * @return {Promise<{[p: string]: number}>} All available SPARQL result media type formats.\n */\n public async getResultMediaTypeFormats(context?: any): Promise<Record<string, string>> {\n context = ActionContext.ensureActionContext(context);\n return (await this.actorInitQuery.mediatorQueryResultSerializeMediaTypeFormatCombiner\n .mediate({ context, mediaTypeFormats: true })).mediaTypeFormats;\n }\n\n /**\n * Convert a query result to a string stream based on a certain media type.\n * @param {IQueryOperationResult} queryResult A query result.\n * @param {string} mediaType A media type.\n * @param {ActionContext} context An optional context.\n * @return {Promise<IActorQueryResultSerializeOutput>} A text stream.\n */\n public async resultToString(queryResult: RDF.Query<any>, mediaType?: string, context?: any):\n Promise<IActorQueryResultSerializeOutput> {\n context = ActionContext.ensureActionContext(context);\n if (!mediaType) {\n switch (queryResult.resultType) {\n case 'bindings':\n mediaType = 'application/json';\n break;\n case 'quads':\n mediaType = 'application/trig';\n break;\n default:\n mediaType = 'simple';\n break;\n }\n }\n const handle: IActionSparqlSerialize = { ...await QueryEngineBase.finalToInternalResult(queryResult), context };\n return (await this.actorInitQuery.mediatorQueryResultSerialize\n .mediate({ context, handle, handleMediaType: mediaType })).handle;\n }\n\n /**\n * Invalidate all internal caches related to the given page URL.\n * If no page URL is given, then all pages will be invalidated.\n * @param {string} url The page URL to invalidate.\n * @param context An optional ActionContext to pass to the actors.\n * @return {Promise<any>} A promise resolving when the caches have been invalidated.\n */\n public invalidateHttpCache(url?: string, context?: any): Promise<any> {\n context = ActionContext.ensureActionContext(context);\n return this.actorInitQuery.mediatorHttpInvalidate.mediate({ url, context });\n }\n\n /**\n * Convert an internal query result to a final one.\n * @param internalResult An intermediary query result.\n */\n public static internalToFinalResult(internalResult: IQueryOperationResult): QueryType {\n switch (internalResult.type) {\n case 'bindings':\n return {\n resultType: 'bindings',\n execute: async() => internalResult.bindingsStream,\n metadata: async() => {\n const meta = <any> await internalResult.metadata();\n meta.variables = meta.variables.map((variable: any) => variable.variable);\n return meta;\n },\n context: internalResult.context,\n };\n case 'quads':\n return {\n resultType: 'quads',\n execute: async() => internalResult.quadStream,\n metadata: async() => <any> await internalResult.metadata(),\n context: internalResult.context,\n };\n case 'boolean':\n return {\n resultType: 'boolean',\n execute: async() => internalResult.execute(),\n context: internalResult.context,\n };\n case 'void':\n return {\n resultType: 'void',\n execute: async() => internalResult.execute(),\n context: internalResult.context,\n };\n }\n }\n\n /**\n * Convert a final query result to an internal one.\n * @param finalResult A final query result.\n */\n public static async finalToInternalResult(finalResult: RDF.Query<any>): Promise<IQueryOperationResult> {\n switch (finalResult.resultType) {\n case 'bindings':\n return {\n type: 'bindings',\n bindingsStream: <BindingsStream> await finalResult.execute(),\n metadata: async() => {\n const meta = <any> await finalResult.metadata();\n meta.variables = meta.variables.map((variable: any) => ({ variable, canBeUndef: false }));\n return meta;\n },\n };\n case 'quads':\n return {\n type: 'quads',\n quadStream: <AsyncIterator<RDF.Quad>> await finalResult.execute(),\n metadata: async() => <any> await finalResult.metadata(),\n };\n case 'boolean':\n return {\n type: 'boolean',\n execute: () => finalResult.execute(),\n };\n case 'void':\n return {\n type: 'void',\n execute: () => finalResult.execute(),\n };\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"QueryEngineBase.js","sourceRoot":"","sources":["QueryEngineBase.ts"],"names":[],"mappings":";;;AACA,+DAAoE;AACpE,yCAA+C;AAqB/C;;GAEG;AACH,MAAa,eAAe;IAOT,cAAc,CAAqB;IAEpD,YAAmB,cAAkC;QACnD,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;IAEM,KAAK,CAAC,aAAa,CACxB,KAA2B,EAC3B,OAAkG;QAElG,OAAO,IAAI,CAAC,WAAW,CAA+C,KAAK,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;IACpG,CAAC;IAEM,KAAK,CAAC,UAAU,CACrB,KAA2B,EAC3B,OAAkG;QAElG,OA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;IACH,CAAC;CACF;AA3QD,0CA2QC","sourcesContent":["import type { IActionSparqlSerialize, IActorQueryResultSerializeOutput } from '@comunica/bus-query-result-serialize';\nimport { KeysCore, KeysInitQuery } from '@comunica/context-entries';\nimport { ActionContext } from '@comunica/core';\nimport type {\n IActionContext,\n IQueryOperationResult,\n IQueryEngine,\n IQueryExplained,\n QueryFormatType,\n QueryType,\n QueryExplainMode,\n BindingsStream,\n QueryAlgebraContext,\n QueryStringContext,\n IQueryBindingsEnhanced,\n IQueryQuadsEnhanced,\n QueryEnhanced,\n IQueryContextCommon,\n} from '@comunica/types';\nimport type * as RDF from '@rdfjs/types';\nimport type { AsyncIterator } from 'asynciterator';\nimport type { ActorInitQueryBase } from './ActorInitQueryBase';\n\n/**\n * Base implementation of a Comunica query engine.\n */\nexport class QueryEngineBase<\n // eslint-disable-next-line unused-imports/no-unused-vars\n QueryContext extends IQueryContextCommon = IQueryContextCommon,\n QueryStringContextInner extends RDF.QueryStringContext = QueryStringContext,\n QueryAlgebraContextInner extends RDF.QueryAlgebraContext = QueryAlgebraContext,\n>\nimplements IQueryEngine<QueryStringContextInner, QueryAlgebraContextInner> {\n private readonly actorInitQuery: ActorInitQueryBase;\n\n public constructor(actorInitQuery: ActorInitQueryBase) {\n this.actorInitQuery = actorInitQuery;\n }\n\n public async queryBindings<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<BindingsStream> {\n return this.queryOfType<QueryFormatTypeInner, IQueryBindingsEnhanced>(query, context, 'bindings');\n }\n\n public async queryQuads<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<AsyncIterator<RDF.Quad> & RDF.ResultStream<RDF.Quad>> {\n return this.queryOfType<QueryFormatTypeInner, IQueryQuadsEnhanced>(query, context, 'quads');\n }\n\n public async queryBoolean<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<boolean> {\n return this.queryOfType<QueryFormatTypeInner, RDF.QueryBoolean>(query, context, 'boolean');\n }\n\n public async queryVoid<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<void> {\n return this.queryOfType<QueryFormatTypeInner, RDF.QueryVoid>(query, context, 'void');\n }\n\n protected async queryOfType<QueryFormatTypeInner extends QueryFormatType, QueryTypeOut extends QueryEnhanced>(\n query: QueryFormatTypeInner,\n context: undefined | (QueryFormatTypeInner extends string ?\n QueryStringContextInner : QueryAlgebraContextInner),\n expectedType: QueryTypeOut['resultType'],\n ): Promise<ReturnType<QueryTypeOut['execute']>> {\n const result = await this.query<QueryFormatTypeInner>(query, context);\n if (result.resultType === expectedType) {\n return <ReturnType<QueryTypeOut['execute']>> await result.execute();\n }\n throw new Error(`Query result type '${expectedType}' was expected, while '${result.resultType}' was found.`);\n }\n\n /**\n * Evaluate the given query\n * @param query A query string or algebra.\n * @param context An optional query context.\n * @return {Promise<QueryType>} A promise that resolves to the query output.\n */\n public async query<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<QueryType> {\n const output = await this.queryOrExplain(query, context);\n if ('explain' in output) {\n throw new Error(`Tried to explain a query when in query-only mode`);\n }\n return output;\n }\n\n /**\n * Explain the given query\n * @param query A query string or algebra.\n * @param context An optional query context.\n * @param explainMode The explain mode.\n * @return {Promise<QueryType | IQueryExplained>} A promise that resolves to\n * the query output or explanation.\n */\n public async explain<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n explainMode: QueryExplainMode,\n ): Promise<IQueryExplained> {\n context.explain = explainMode;\n const output = await this.queryOrExplain(query, context);\n return <IQueryExplained> output;\n }\n\n /**\n * Evaluate or explain the given query\n * @param query A query string or algebra.\n * @param context An optional query context.\n * @return {Promise<QueryType | IQueryExplained>} A promise that resolves to\n * the query output or explanation.\n */\n public async queryOrExplain<QueryFormatTypeInner extends QueryFormatType>(\n query: QueryFormatTypeInner,\n context?: QueryFormatTypeInner extends string ? QueryStringContextInner : QueryAlgebraContextInner,\n ): Promise<QueryType | IQueryExplained> {\n const actionContext: IActionContext = ActionContext.ensureActionContext(context);\n\n // Invalidate caches if cache argument is set to false\n if (actionContext.get(KeysInitQuery.invalidateCache)) {\n await this.invalidateHttpCache();\n }\n\n // Invoke query process\n const { result } = await this.actorInitQuery.mediatorQueryProcess.mediate({ query, context: actionContext });\n if ('explain' in result) {\n return result;\n }\n return QueryEngineBase.internalToFinalResult(result);\n }\n\n /**\n * @param context An optional context.\n * @return {Promise<{[p: string]: number}>} All available SPARQL (weighted) result media types.\n */\n public async getResultMediaTypes(context?: any): Promise<Record<string, number>> {\n context = ActionContext.ensureActionContext(context);\n return (await this.actorInitQuery.mediatorQueryResultSerializeMediaTypeCombiner\n .mediate({ context, mediaTypes: true })).mediaTypes;\n }\n\n /**\n * @param context An optional context.\n * @return {Promise<{[p: string]: number}>} All available SPARQL result media type formats.\n */\n public async getResultMediaTypeFormats(context?: any): Promise<Record<string, string>> {\n context = ActionContext.ensureActionContext(context);\n return (await this.actorInitQuery.mediatorQueryResultSerializeMediaTypeFormatCombiner\n .mediate({ context, mediaTypeFormats: true })).mediaTypeFormats;\n }\n\n /**\n * Convert a query result to a string stream based on a certain media type.\n * @param {IQueryOperationResult} queryResult A query result.\n * @param {string} mediaType A media type.\n * @param {ActionContext} context An optional context.\n * @return {Promise<IActorQueryResultSerializeOutput>} A text stream.\n */\n public async resultToString(queryResult: RDF.Query<any>, mediaType?: string, context?: any):\n Promise<IActorQueryResultSerializeOutput> {\n context = ActionContext.ensureActionContext(context);\n if (!mediaType) {\n switch (queryResult.resultType) {\n case 'bindings':\n mediaType = 'application/json';\n break;\n case 'quads':\n mediaType = 'application/trig';\n break;\n default:\n mediaType = 'simple';\n break;\n }\n }\n const handle: IActionSparqlSerialize = { ...await QueryEngineBase.finalToInternalResult(queryResult), context };\n return (await this.actorInitQuery.mediatorQueryResultSerialize\n .mediate({ context, handle, handleMediaType: mediaType })).handle;\n }\n\n /**\n * Invalidate all internal caches related to the given page URL.\n * If no page URL is given, then all pages will be invalidated.\n * @param {string} url The page URL to invalidate.\n * @param context An optional ActionContext to pass to the actors.\n * @return {Promise<any>} A promise resolving when the caches have been invalidated.\n */\n public invalidateHttpCache(url?: string, context?: any): Promise<any> {\n context = ActionContext.ensureActionContext(context);\n return this.actorInitQuery.mediatorHttpInvalidate.mediate({ url, context });\n }\n\n /**\n * Convert an internal query result to a final one.\n * @param internalResult An intermediary query result.\n */\n public static internalToFinalResult(internalResult: IQueryOperationResult): QueryType {\n const logger = internalResult.context?.get(KeysCore.log);\n switch (internalResult.type) {\n case 'bindings':\n return {\n resultType: 'bindings',\n execute: async() => {\n if (logger) {\n internalResult.bindingsStream.on?.('end', () => logger.flush());\n }\n return internalResult.bindingsStream;\n },\n metadata: async() => {\n const meta = <any> await internalResult.metadata();\n meta.variables = meta.variables.map((variable: any) => variable.variable);\n return meta;\n },\n context: internalResult.context,\n };\n case 'quads':\n return {\n resultType: 'quads',\n execute: async() => {\n if (logger) {\n internalResult.quadStream.on?.('end', () => logger.flush());\n }\n return internalResult.quadStream;\n },\n metadata: async() => <any> await internalResult.metadata(),\n context: internalResult.context,\n };\n case 'boolean':\n return {\n resultType: 'boolean',\n execute: async() => {\n const result = await internalResult.execute();\n logger?.flush();\n return result;\n },\n context: internalResult.context,\n };\n case 'void':\n return {\n resultType: 'void',\n execute: async() => {\n const result = await internalResult.execute();\n logger?.flush();\n return result;\n },\n context: internalResult.context,\n };\n }\n }\n\n /**\n * Convert a final query result to an internal one.\n * @param finalResult A final query result.\n */\n public static async finalToInternalResult(finalResult: RDF.Query<any>): Promise<IQueryOperationResult> {\n switch (finalResult.resultType) {\n case 'bindings':\n return {\n type: 'bindings',\n bindingsStream: <BindingsStream> await finalResult.execute(),\n metadata: async() => {\n const meta = <any> await finalResult.metadata();\n meta.variables = meta.variables.map((variable: any) => ({ variable, canBeUndef: false }));\n return meta;\n },\n };\n case 'quads':\n return {\n type: 'quads',\n quadStream: <AsyncIterator<RDF.Quad>> await finalResult.execute(),\n metadata: async() => <any> await finalResult.metadata(),\n };\n case 'boolean':\n return {\n type: 'boolean',\n execute: () => finalResult.execute(),\n };\n case 'void':\n return {\n type: 'void',\n execute: () => finalResult.execute(),\n };\n }\n }\n}\n"]}
|
|
@@ -1,11 +1,44 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
2
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
36
|
exports.CliArgsHandlerBase = void 0;
|
|
4
37
|
/* eslint-disable import/no-nodejs-modules */
|
|
5
38
|
const node_child_process_1 = require("node:child_process");
|
|
6
39
|
const node_fs_1 = require("node:fs");
|
|
7
|
-
const OS = require("node:os");
|
|
8
|
-
const Path = require("node:path");
|
|
40
|
+
const OS = __importStar(require("node:os"));
|
|
41
|
+
const Path = __importStar(require("node:path"));
|
|
9
42
|
const context_entries_1 = require("@comunica/context-entries");
|
|
10
43
|
const core_1 = require("@comunica/core");
|
|
11
44
|
const logger_pretty_1 = require("@comunica/logger-pretty");
|
|
@@ -135,6 +168,22 @@ class CliArgsHandlerBase {
|
|
|
135
168
|
type: 'number',
|
|
136
169
|
describe: 'The upper limit in milliseconds for the delay between fetch retries',
|
|
137
170
|
},
|
|
171
|
+
httpRetryBodyCount: {
|
|
172
|
+
type: 'number',
|
|
173
|
+
describe: 'The number of retries to perform when the response body stream errors',
|
|
174
|
+
},
|
|
175
|
+
httpRetryBodyDelayFallback: {
|
|
176
|
+
type: 'number',
|
|
177
|
+
describe: 'The fallback delay in milliseconds between body retries',
|
|
178
|
+
},
|
|
179
|
+
httpRetryBodyAllowUnsafe: {
|
|
180
|
+
type: 'boolean',
|
|
181
|
+
describe: 'Allow body retries for non-idempotent requests',
|
|
182
|
+
},
|
|
183
|
+
httpRetryBodyMaxBytes: {
|
|
184
|
+
type: 'number',
|
|
185
|
+
describe: 'Maximum number of bytes to buffer when retrying response body streams',
|
|
186
|
+
},
|
|
138
187
|
httpCache: {
|
|
139
188
|
type: 'boolean',
|
|
140
189
|
describe: 'Enables HTTP-level caching',
|
|
@@ -255,6 +304,31 @@ class CliArgsHandlerBase {
|
|
|
255
304
|
}
|
|
256
305
|
context[context_entries_1.KeysHttp.httpRetryDelayLimit.name] = args.httpRetryDelayLimit;
|
|
257
306
|
}
|
|
307
|
+
// Define HTTP body retry count
|
|
308
|
+
if (args.httpRetryBodyCount) {
|
|
309
|
+
context[context_entries_1.KeysHttp.httpRetryBodyCount.name] = args.httpRetryBodyCount;
|
|
310
|
+
}
|
|
311
|
+
// Define fallback HTTP delay between body retries
|
|
312
|
+
if (args.httpRetryBodyDelayFallback) {
|
|
313
|
+
if (!args.httpRetryBodyCount) {
|
|
314
|
+
throw new Error('The --httpRetryBodyDelayFallback option requires the --httpRetryBodyCount option to be set');
|
|
315
|
+
}
|
|
316
|
+
context[context_entries_1.KeysHttp.httpRetryBodyDelayFallback.name] = args.httpRetryBodyDelayFallback;
|
|
317
|
+
}
|
|
318
|
+
// Define if body retries are allowed for non-idempotent methods
|
|
319
|
+
if (args.httpRetryBodyAllowUnsafe) {
|
|
320
|
+
if (!args.httpRetryBodyCount) {
|
|
321
|
+
throw new Error('The --httpRetryBodyAllowUnsafe option requires the --httpRetryBodyCount option to be set');
|
|
322
|
+
}
|
|
323
|
+
context[context_entries_1.KeysHttp.httpRetryBodyAllowUnsafe.name] = true;
|
|
324
|
+
}
|
|
325
|
+
// Define max bytes to buffer for body retries
|
|
326
|
+
if (args.httpRetryBodyMaxBytes) {
|
|
327
|
+
if (!args.httpRetryBodyCount) {
|
|
328
|
+
throw new Error('The --httpRetryBodyMaxBytes option requires the --httpRetryBodyCount option to be set');
|
|
329
|
+
}
|
|
330
|
+
context[context_entries_1.KeysHttp.httpRetryBodyMaxBytes.name] = args.httpRetryBodyMaxBytes;
|
|
331
|
+
}
|
|
258
332
|
// Define union default graph
|
|
259
333
|
if (args.unionDefaultGraph) {
|
|
260
334
|
context[context_entries_1.KeysQueryOperation.unionDefaultGraph.name] = true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CliArgsHandlerBase.js","sourceRoot":"","sources":["CliArgsHandlerBase.ts"],"names":[],"mappings":";;;AAAA,6CAA6C;AAC7C,2DAA0C;AAC1C,qCAAmD;AACnD,8BAA8B;AAC9B,kCAAkC;AAClC,+DAA4G;AAC5G,yCAA+C;AAC/C,2DAAuD;AAIvD,MAAM,OAAO,GAAmB,OAAO,CAAC,UAAU,CAAC,CAAC;AAEpD;;GAEG;AACH,MAAa,kBAAkB;IACZ,cAAc,CAAkB;IAEjD,YAAmB,cAA+B;QAChD,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;IAEM,MAAM,CAAC,eAAe,CAAC,OAAe,EAAE,QAAgB;QAC7D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC7B,IAAA,yBAAI,EAAC,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE;gBACtC,IAAI,KAAK,EAAE,CAAC;oBACV,OAAO,CAAC,QAAQ,CAAC,CAAC;gBACpB,CAAC;gBACD,OAAO,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;YACxC,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAEM,MAAM,CAAC,wBAAwB;QACpC,OAAO,IAAA,oBAAU,EAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC,CAAC;IACxD,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,yBAAyB,CAAC,YAAoB;QAC1D,MAAM,MAAM,GAAwB,EAAE,CAAC;QACvC,MAAM,cAAc,GAAG,YAAY,CAAC;QACpC,MAAM,gBA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+BAAa,CAAC,iBAAiB,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;QACvD,CAAC;QAED,sCAAsC;QACtC,IAAI,IAAI,CAAC,gCAAgC,EAAE,CAAC;YAC1C,OAAO,CAAC,+BAAa,CAAC,gCAAgC,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;QACtE,CAAC;IACH,CAAC;CACF;AAjSD,gDAiSC;AACD,4CAA4C","sourcesContent":["/* eslint-disable import/no-nodejs-modules */\nimport { exec } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport * as OS from 'node:os';\nimport * as Path from 'node:path';\nimport { KeysHttp, KeysInitQuery, KeysQueryOperation, KeysRdfUpdateQuads } from '@comunica/context-entries';\nimport { ActionContext } from '@comunica/core';\nimport { LoggerPretty } from '@comunica/logger-pretty';\nimport type { IActionContext, ICliArgsHandler } from '@comunica/types';\nimport type { Argv } from 'yargs';\n\nconst process: NodeJS.Process = require('process/');\n\n/**\n * Basic CLI arguments handler that handles common options.\n */\nexport class CliArgsHandlerBase implements ICliArgsHandler {\n private readonly initialContext?: IActionContext;\n\n public constructor(initialContext?: IActionContext) {\n this.initialContext = initialContext;\n }\n\n public static getScriptOutput(command: string, fallback: string): Promise<string> {\n return new Promise((resolve) => {\n exec(command, (error, stdout, stderr) => {\n if (error) {\n resolve(fallback);\n }\n resolve((stdout || stderr).trimEnd());\n });\n });\n }\n\n public static isDevelopmentEnvironment(): boolean {\n return existsSync(Path.join(__dirname, `../../test`));\n }\n\n /**\n * Converts an URL like 'hypermedia@http://user:passwd@example.com to an IDataSource\n * @param {string} sourceString An url with possibly a type and authorization.\n * @return {[id: string]: any} An IDataSource which represents the sourceString.\n */\n public static getSourceObjectFromString(sourceString: string): Record<string, any> {\n const source: Record<string, any> = {};\n const mediaTypeRegex = /^([^:]*)@/u;\n const mediaTypeMatches = mediaTypeRegex.exec(sourceString);\n if (mediaTypeMatches) {\n source.type = mediaTypeMatches[1];\n sourceString = sourceString.slice((<number> source.type.length) + 1);\n }\n const authRegex = /\\/\\/(.*:.*)@/u;\n const authMatches = authRegex.exec(sourceString);\n if (authMatches) {\n const credentials = authMatches[1];\n source.context = new ActionContext({\n [KeysHttp.auth.name]: decodeURIComponent(credentials),\n });\n sourceString = sourceString.slice(0, authMatches.index + 2) +\n sourceString.slice(authMatches.index + credentials.length + 3);\n }\n source.value = sourceString;\n return source;\n }\n\n public populateYargs(argumentsBuilder: Argv<any>): Argv<any> {\n return argumentsBuilder\n .command(\n '$0 [sources...]',\n 'evaluates SPARQL queries',\n () => {\n // Do nothing\n },\n () => {\n // Do nothing\n },\n )\n .default('sources', [])\n .hide('sources')\n .wrap(160)\n .version(false)\n .options({\n context: {\n alias: 'c',\n type: 'string',\n describe: 'Use the given JSON context string or file (e.g., config.json)',\n },\n to: {\n type: 'string',\n describe: 'Destination for update queries',\n },\n baseIRI: {\n alias: 'b',\n type: 'string',\n describe: 'base IRI for the query (e.g., http://example.org/)',\n },\n fileBaseIRI: {\n type: 'string',\n describe: 'base IRI for the file (e.g., http://example.org/), useful when using comunica-sparql-file',\n },\n dateTime: {\n alias: 'd',\n type: 'string',\n describe: 'Sets a datetime for querying Memento-enabled archives',\n },\n logLevel: {\n alias: 'l',\n type: 'string',\n describe: 'Sets the log level (e.g., debug, info, warn, ...)',\n default: 'warn',\n },\n lenient: {\n type: 'boolean',\n describe: 'If failing requests and parsing errors should be logged instead of causing a hard crash',\n },\n parseUnsupportedVersions: {\n type: 'boolean',\n describe: 'If no error should be emitted on unsupported versions',\n },\n version: {\n alias: 'v',\n type: 'boolean',\n describe: 'Prints version information',\n },\n showStackTrace: {\n type: 'boolean',\n describe: 'Prints the full stacktrace when errors are thrown',\n },\n httpTimeout: {\n type: 'number',\n describe: 'HTTP requests timeout in milliseconds',\n },\n httpBodyTimeout: {\n type: 'boolean',\n describe: 'Makes the HTTP timeout take into account the response body stream read',\n },\n httpRetryCount: {\n type: 'number',\n describe: 'The number of retries to perform on failed fetch requests',\n },\n httpRetryDelayFallback: {\n type: 'number',\n describe: 'The fallback delay in milliseconds between fetch retries',\n },\n httpRetryDelayLimit: {\n type: 'number',\n describe: 'The upper limit in milliseconds for the delay between fetch retries',\n },\n httpCache: {\n type: 'boolean',\n describe: 'Enables HTTP-level caching',\n },\n unionDefaultGraph: {\n type: 'boolean',\n describe: 'If the default graph should also contain the union of all named graphs',\n },\n invalidateCache: {\n type: 'boolean',\n describe: 'Enable cache invalidation before each query execution',\n },\n distinctConstruct: {\n type: 'boolean',\n describe: 'If the query engine should deduplicate resulting triples',\n },\n extensionFunctionsAlwaysPushdown: {\n type: 'boolean',\n describe: 'If extension functions must always be pushed down',\n },\n })\n .exitProcess(false)\n .fail(false)\n .help(false);\n }\n\n public async handleArgs(args: Record<string, any>, context: Record<string, any>): Promise<void> {\n // Print version information\n if (args.version) {\n // eslint-disable-next-line ts/no-require-imports,ts/no-var-requires,import/extensions\n const comunicaVersion: string = require('../../package.json').version;\n const dev: string = CliArgsHandlerBase.isDevelopmentEnvironment() ? '(dev)' : '';\n const nodeVersion: string = process.version;\n const npmVersion: string = await CliArgsHandlerBase.getScriptOutput('npm -v', '_NPM is unavailable_');\n const yarnVersion: string = await CliArgsHandlerBase.getScriptOutput('yarn -v', '_Yarn is unavailable_');\n const os = `${OS.platform()} (${OS.type()} ${OS.release()})`;\n\n const message = `| software | version\n| ---------------- | -------\n| Comunica Engine | ${comunicaVersion} ${dev}\n| node | ${nodeVersion}\n| npm | ${npmVersion}\n| yarn | ${yarnVersion}\n| Operating System | ${os}\n`;\n\n throw new Error(message);\n }\n\n // Inherit default context options\n if (this.initialContext) {\n Object.assign(context, this.initialContext.toJS());\n }\n\n // Define context\n if (args.context) {\n Object.assign(context, JSON.parse(existsSync(args.context) ? readFileSync(args.c, 'utf8') : args.context));\n } else if (args.sources[0]?.startsWith('{')) {\n // For backwards compatibility inline JSON\n Object.assign(context, JSON.parse(args.sources[0]));\n args.sources.shift();\n }\n\n // Add sources to context\n if (args.sources.length > 0) {\n context.sources = context.sources || [];\n // eslint-disable-next-line unicorn/no-array-for-each\n args.sources.forEach((sourceValue: string) => {\n const source = CliArgsHandlerBase.getSourceObjectFromString(sourceValue);\n context.sources.push(source);\n });\n }\n\n // Add destination to context\n if (args.to) {\n context[KeysRdfUpdateQuads.destination.name] = args.to;\n }\n\n // Set the logger\n if (!context.log) {\n context.log = new LoggerPretty({ level: args.logLevel });\n }\n\n // Define the base IRI\n if (args.baseIRI) {\n context[KeysInitQuery.baseIRI.name] = args.baseIRI;\n }\n\n // Define the file base IRI\n if (args.fileBaseIRI) {\n context[KeysInitQuery.fileBaseIRI.name] = args.fileBaseIRI;\n }\n\n // Define lenient-mode\n if (args.lenient) {\n context[KeysInitQuery.lenient.name] = true;\n }\n\n // Define parseUnsupportedVersions\n if (args.parseUnsupportedVersions) {\n context[KeysInitQuery.parseUnsupportedVersions.name] = true;\n }\n\n // Define HTTP timeout\n if (args.httpTimeout) {\n context[KeysHttp.httpTimeout.name] = args.httpTimeout;\n }\n\n // Define HTTP body timeout\n if (args.httpBodyTimeout) {\n if (!args.httpTimeout) {\n throw new Error('The --httpBodyTimeout option requires the --httpTimeout option to be set');\n }\n context[KeysHttp.httpBodyTimeout.name] = args.httpBodyTimeout;\n }\n\n // Define HTTP retry count\n if (args.httpRetryCount) {\n context[KeysHttp.httpRetryCount.name] = args.httpRetryCount;\n }\n\n // Define fallback HTTP delay between retries\n if (args.httpRetryDelayFallback) {\n if (!args.httpRetryCount) {\n throw new Error('The --httpRetryDelayFallback option requires the --httpRetryCount option to be set');\n }\n context[KeysHttp.httpRetryDelayFallback.name] = args.httpRetryDelayFallback;\n }\n\n // Define limit to the delay between HTTP retries\n if (args.httpRetryDelayLimit) {\n if (!args.httpRetryCount) {\n throw new Error('The --httpRetryDelayLimit option requires the --httpRetryCount option to be set');\n }\n context[KeysHttp.httpRetryDelayLimit.name] = args.httpRetryDelayLimit;\n }\n\n // Define union default graph\n if (args.unionDefaultGraph) {\n context[KeysQueryOperation.unionDefaultGraph.name] = true;\n }\n\n // Define if cache should be disabled\n if (args.invalidateCache) {\n context[KeysInitQuery.invalidateCache.name] = true;\n }\n\n // Define if results should be deduplicated\n if (args.distinctConstruct) {\n context[KeysInitQuery.distinctConstruct.name] = true;\n }\n\n // Pushing down of extension functions\n if (args.extensionFunctionsAlwaysPushdown) {\n context[KeysInitQuery.extensionFunctionsAlwaysPushdown.name] = true;\n }\n }\n}\n/* eslint-enable import/no-nodejs-modules */\n"]}
|
|
1
|
+
{"version":3,"file":"CliArgsHandlerBase.js","sourceRoot":"","sources":["CliArgsHandlerBase.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6CAA6C;AAC7C,2DAA0C;AAC1C,qCAAmD;AACnD,4CAA8B;AAC9B,gDAAkC;AAClC,+DAA4G;AAC5G,yCAA+C;AAC/C,2DAAuD;AAIvD,MAAM,OAAO,GAAmB,OAAO,CAAC,UAAU,CAAC,CAAC;AAEpD;;GAEG;AACH,MAAa,kBAAkB;IACZ,cAAc,CAAkB;IAEjD,YAAmB,cAA+B;QAChD,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;IAEM,MAAM,CAAC,eAAe,CAAC,OAAe,EAAE,QAAgB;QAC7D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC7B,IAAA,yBAAI,EAAC,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE;gBACtC,IAAI,KAAK,EAAE,CAAC;oBACV,OAAO,CAAC,QAAQ,CAAC,CAAC;gBACpB,CAAC;gBACD,OAAO,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;YACxC,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAEM,MAAM,CAAC,wBAAwB;QACpC,OAAO,IAAA,oBAAU,EAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,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AG,IAAI,CAAC;QAC5D,CAAC;QAED,qCAAqC;QACrC,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACzB,OAAO,CAAC,+BAAa,CAAC,eAAe,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;QACrD,CAAC;QAED,2CAA2C;QAC3C,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC3B,OAAO,CAAC,+BAAa,CAAC,iBAAiB,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;QACvD,CAAC;QAED,sCAAsC;QACtC,IAAI,IAAI,CAAC,gCAAgC,EAAE,CAAC;YAC1C,OAAO,CAAC,+BAAa,CAAC,gCAAgC,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;QACtE,CAAC;IACH,CAAC;CACF;AA9UD,gDA8UC;AACD,4CAA4C","sourcesContent":["/* eslint-disable import/no-nodejs-modules */\nimport { exec } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport * as OS from 'node:os';\nimport * as Path from 'node:path';\nimport { KeysHttp, KeysInitQuery, KeysQueryOperation, KeysRdfUpdateQuads } from '@comunica/context-entries';\nimport { ActionContext } from '@comunica/core';\nimport { LoggerPretty } from '@comunica/logger-pretty';\nimport type { IActionContext, ICliArgsHandler } from '@comunica/types';\nimport type { Argv } from 'yargs';\n\nconst process: NodeJS.Process = require('process/');\n\n/**\n * Basic CLI arguments handler that handles common options.\n */\nexport class CliArgsHandlerBase implements ICliArgsHandler {\n private readonly initialContext?: IActionContext;\n\n public constructor(initialContext?: IActionContext) {\n this.initialContext = initialContext;\n }\n\n public static getScriptOutput(command: string, fallback: string): Promise<string> {\n return new Promise((resolve) => {\n exec(command, (error, stdout, stderr) => {\n if (error) {\n resolve(fallback);\n }\n resolve((stdout || stderr).trimEnd());\n });\n });\n }\n\n public static isDevelopmentEnvironment(): boolean {\n return existsSync(Path.join(__dirname, `../../test`));\n }\n\n /**\n * Converts an URL like 'hypermedia@http://user:passwd@example.com to an IDataSource\n * @param {string} sourceString An url with possibly a type and authorization.\n * @return {[id: string]: any} An IDataSource which represents the sourceString.\n */\n public static getSourceObjectFromString(sourceString: string): Record<string, any> {\n const source: Record<string, any> = {};\n const mediaTypeRegex = /^([^:]*)@/u;\n const mediaTypeMatches = mediaTypeRegex.exec(sourceString);\n if (mediaTypeMatches) {\n source.type = mediaTypeMatches[1];\n sourceString = sourceString.slice((<number> source.type.length) + 1);\n }\n const authRegex = /\\/\\/(.*:.*)@/u;\n const authMatches = authRegex.exec(sourceString);\n if (authMatches) {\n const credentials = authMatches[1];\n source.context = new ActionContext({\n [KeysHttp.auth.name]: decodeURIComponent(credentials),\n });\n sourceString = sourceString.slice(0, authMatches.index + 2) +\n sourceString.slice(authMatches.index + credentials.length + 3);\n }\n source.value = sourceString;\n return source;\n }\n\n public populateYargs(argumentsBuilder: Argv<any>): Argv<any> {\n return argumentsBuilder\n .command(\n '$0 [sources...]',\n 'evaluates SPARQL queries',\n () => {\n // Do nothing\n },\n () => {\n // Do nothing\n },\n )\n .default('sources', [])\n .hide('sources')\n .wrap(160)\n .version(false)\n .options({\n context: {\n alias: 'c',\n type: 'string',\n describe: 'Use the given JSON context string or file (e.g., config.json)',\n },\n to: {\n type: 'string',\n describe: 'Destination for update queries',\n },\n baseIRI: {\n alias: 'b',\n type: 'string',\n describe: 'base IRI for the query (e.g., http://example.org/)',\n },\n fileBaseIRI: {\n type: 'string',\n describe: 'base IRI for the file (e.g., http://example.org/), useful when using comunica-sparql-file',\n },\n dateTime: {\n alias: 'd',\n type: 'string',\n describe: 'Sets a datetime for querying Memento-enabled archives',\n },\n logLevel: {\n alias: 'l',\n type: 'string',\n describe: 'Sets the log level (e.g., debug, info, warn, ...)',\n default: 'warn',\n },\n lenient: {\n type: 'boolean',\n describe: 'If failing requests and parsing errors should be logged instead of causing a hard crash',\n },\n parseUnsupportedVersions: {\n type: 'boolean',\n describe: 'If no error should be emitted on unsupported versions',\n },\n version: {\n alias: 'v',\n type: 'boolean',\n describe: 'Prints version information',\n },\n showStackTrace: {\n type: 'boolean',\n describe: 'Prints the full stacktrace when errors are thrown',\n },\n httpTimeout: {\n type: 'number',\n describe: 'HTTP requests timeout in milliseconds',\n },\n httpBodyTimeout: {\n type: 'boolean',\n describe: 'Makes the HTTP timeout take into account the response body stream read',\n },\n httpRetryCount: {\n type: 'number',\n describe: 'The number of retries to perform on failed fetch requests',\n },\n httpRetryDelayFallback: {\n type: 'number',\n describe: 'The fallback delay in milliseconds between fetch retries',\n },\n httpRetryDelayLimit: {\n type: 'number',\n describe: 'The upper limit in milliseconds for the delay between fetch retries',\n },\n httpRetryBodyCount: {\n type: 'number',\n describe: 'The number of retries to perform when the response body stream errors',\n },\n httpRetryBodyDelayFallback: {\n type: 'number',\n describe: 'The fallback delay in milliseconds between body retries',\n },\n httpRetryBodyAllowUnsafe: {\n type: 'boolean',\n describe: 'Allow body retries for non-idempotent requests',\n },\n httpRetryBodyMaxBytes: {\n type: 'number',\n describe: 'Maximum number of bytes to buffer when retrying response body streams',\n },\n httpCache: {\n type: 'boolean',\n describe: 'Enables HTTP-level caching',\n },\n unionDefaultGraph: {\n type: 'boolean',\n describe: 'If the default graph should also contain the union of all named graphs',\n },\n invalidateCache: {\n type: 'boolean',\n describe: 'Enable cache invalidation before each query execution',\n },\n distinctConstruct: {\n type: 'boolean',\n describe: 'If the query engine should deduplicate resulting triples',\n },\n extensionFunctionsAlwaysPushdown: {\n type: 'boolean',\n describe: 'If extension functions must always be pushed down',\n },\n })\n .exitProcess(false)\n .fail(false)\n .help(false);\n }\n\n public async handleArgs(args: Record<string, any>, context: Record<string, any>): Promise<void> {\n // Print version information\n if (args.version) {\n // eslint-disable-next-line ts/no-require-imports,ts/no-var-requires,import/extensions\n const comunicaVersion: string = require('../../package.json').version;\n const dev: string = CliArgsHandlerBase.isDevelopmentEnvironment() ? '(dev)' : '';\n const nodeVersion: string = process.version;\n const npmVersion: string = await CliArgsHandlerBase.getScriptOutput('npm -v', '_NPM is unavailable_');\n const yarnVersion: string = await CliArgsHandlerBase.getScriptOutput('yarn -v', '_Yarn is unavailable_');\n const os = `${OS.platform()} (${OS.type()} ${OS.release()})`;\n\n const message = `| software | version\n| ---------------- | -------\n| Comunica Engine | ${comunicaVersion} ${dev}\n| node | ${nodeVersion}\n| npm | ${npmVersion}\n| yarn | ${yarnVersion}\n| Operating System | ${os}\n`;\n\n throw new Error(message);\n }\n\n // Inherit default context options\n if (this.initialContext) {\n Object.assign(context, this.initialContext.toJS());\n }\n\n // Define context\n if (args.context) {\n Object.assign(context, JSON.parse(existsSync(args.context) ? readFileSync(args.c, 'utf8') : args.context));\n } else if (args.sources[0]?.startsWith('{')) {\n // For backwards compatibility inline JSON\n Object.assign(context, JSON.parse(args.sources[0]));\n args.sources.shift();\n }\n\n // Add sources to context\n if (args.sources.length > 0) {\n context.sources = context.sources || [];\n // eslint-disable-next-line unicorn/no-array-for-each\n args.sources.forEach((sourceValue: string) => {\n const source = CliArgsHandlerBase.getSourceObjectFromString(sourceValue);\n context.sources.push(source);\n });\n }\n\n // Add destination to context\n if (args.to) {\n context[KeysRdfUpdateQuads.destination.name] = args.to;\n }\n\n // Set the logger\n if (!context.log) {\n context.log = new LoggerPretty({ level: args.logLevel });\n }\n\n // Define the base IRI\n if (args.baseIRI) {\n context[KeysInitQuery.baseIRI.name] = args.baseIRI;\n }\n\n // Define the file base IRI\n if (args.fileBaseIRI) {\n context[KeysInitQuery.fileBaseIRI.name] = args.fileBaseIRI;\n }\n\n // Define lenient-mode\n if (args.lenient) {\n context[KeysInitQuery.lenient.name] = true;\n }\n\n // Define parseUnsupportedVersions\n if (args.parseUnsupportedVersions) {\n context[KeysInitQuery.parseUnsupportedVersions.name] = true;\n }\n\n // Define HTTP timeout\n if (args.httpTimeout) {\n context[KeysHttp.httpTimeout.name] = args.httpTimeout;\n }\n\n // Define HTTP body timeout\n if (args.httpBodyTimeout) {\n if (!args.httpTimeout) {\n throw new Error('The --httpBodyTimeout option requires the --httpTimeout option to be set');\n }\n context[KeysHttp.httpBodyTimeout.name] = args.httpBodyTimeout;\n }\n\n // Define HTTP retry count\n if (args.httpRetryCount) {\n context[KeysHttp.httpRetryCount.name] = args.httpRetryCount;\n }\n\n // Define fallback HTTP delay between retries\n if (args.httpRetryDelayFallback) {\n if (!args.httpRetryCount) {\n throw new Error('The --httpRetryDelayFallback option requires the --httpRetryCount option to be set');\n }\n context[KeysHttp.httpRetryDelayFallback.name] = args.httpRetryDelayFallback;\n }\n\n // Define limit to the delay between HTTP retries\n if (args.httpRetryDelayLimit) {\n if (!args.httpRetryCount) {\n throw new Error('The --httpRetryDelayLimit option requires the --httpRetryCount option to be set');\n }\n context[KeysHttp.httpRetryDelayLimit.name] = args.httpRetryDelayLimit;\n }\n\n // Define HTTP body retry count\n if (args.httpRetryBodyCount) {\n context[KeysHttp.httpRetryBodyCount.name] = args.httpRetryBodyCount;\n }\n\n // Define fallback HTTP delay between body retries\n if (args.httpRetryBodyDelayFallback) {\n if (!args.httpRetryBodyCount) {\n throw new Error('The --httpRetryBodyDelayFallback option requires the --httpRetryBodyCount option to be set');\n }\n context[KeysHttp.httpRetryBodyDelayFallback.name] = args.httpRetryBodyDelayFallback;\n }\n\n // Define if body retries are allowed for non-idempotent methods\n if (args.httpRetryBodyAllowUnsafe) {\n if (!args.httpRetryBodyCount) {\n throw new Error('The --httpRetryBodyAllowUnsafe option requires the --httpRetryBodyCount option to be set');\n }\n context[KeysHttp.httpRetryBodyAllowUnsafe.name] = true;\n }\n\n // Define max bytes to buffer for body retries\n if (args.httpRetryBodyMaxBytes) {\n if (!args.httpRetryBodyCount) {\n throw new Error('The --httpRetryBodyMaxBytes option requires the --httpRetryBodyCount option to be set');\n }\n context[KeysHttp.httpRetryBodyMaxBytes.name] = args.httpRetryBodyMaxBytes;\n }\n\n // Define union default graph\n if (args.unionDefaultGraph) {\n context[KeysQueryOperation.unionDefaultGraph.name] = true;\n }\n\n // Define if cache should be disabled\n if (args.invalidateCache) {\n context[KeysInitQuery.invalidateCache.name] = true;\n }\n\n // Define if results should be deduplicated\n if (args.distinctConstruct) {\n context[KeysInitQuery.distinctConstruct.name] = true;\n }\n\n // Pushing down of extension functions\n if (args.extensionFunctionsAlwaysPushdown) {\n context[KeysInitQuery.extensionFunctionsAlwaysPushdown.name] = true;\n }\n }\n}\n/* eslint-enable import/no-nodejs-modules */\n"]}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
6
|
+
<title>Comunica SPARQL Endpoint</title>
|
|
7
|
+
<link href="https://cdn.jsdelivr.net/npm/@zazuko/yasgui/build/yasgui.min.css" rel="stylesheet" type="text/css" />
|
|
8
|
+
<style>
|
|
9
|
+
* {
|
|
10
|
+
box-sizing: border-box;
|
|
11
|
+
}
|
|
12
|
+
body {
|
|
13
|
+
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
|
|
14
|
+
margin: 0;
|
|
15
|
+
padding: 0;
|
|
16
|
+
background: #ffffff;
|
|
17
|
+
color: #333;
|
|
18
|
+
}
|
|
19
|
+
.header {
|
|
20
|
+
background: #9C0510;
|
|
21
|
+
color: white;
|
|
22
|
+
padding: 1rem 3rem;
|
|
23
|
+
height: 3.5rem;
|
|
24
|
+
display: flex;
|
|
25
|
+
align-items: center;
|
|
26
|
+
}
|
|
27
|
+
.header-content {
|
|
28
|
+
max-width: 1200px;
|
|
29
|
+
width: 100%;
|
|
30
|
+
margin: 0 auto;
|
|
31
|
+
display: flex;
|
|
32
|
+
align-items: center;
|
|
33
|
+
justify-content: space-between;
|
|
34
|
+
}
|
|
35
|
+
.header h1 {
|
|
36
|
+
margin: 0;
|
|
37
|
+
font-size: 1.5rem;
|
|
38
|
+
font-weight: 600;
|
|
39
|
+
}
|
|
40
|
+
.header p {
|
|
41
|
+
margin: 0;
|
|
42
|
+
font-size: 1rem;
|
|
43
|
+
}
|
|
44
|
+
.header a {
|
|
45
|
+
color: #FFFFFF;
|
|
46
|
+
text-decoration: none;
|
|
47
|
+
padding: 0 4px 4px 4px;
|
|
48
|
+
}
|
|
49
|
+
.header a:hover,
|
|
50
|
+
.header a:focus,
|
|
51
|
+
.header a:active {
|
|
52
|
+
text-decoration: none;
|
|
53
|
+
border-bottom: 2px solid #FFFFFF;
|
|
54
|
+
}
|
|
55
|
+
.container {
|
|
56
|
+
max-width: 1200px;
|
|
57
|
+
margin: 2rem auto;
|
|
58
|
+
padding: 0 1rem;
|
|
59
|
+
}
|
|
60
|
+
#yasgui {
|
|
61
|
+
margin-top: 1rem;
|
|
62
|
+
max-width: 100%;
|
|
63
|
+
overflow-x: auto;
|
|
64
|
+
}
|
|
65
|
+
#yasgui .yasgui .yasqe,
|
|
66
|
+
#yasgui .yasgui .yasr {
|
|
67
|
+
max-width: 100%;
|
|
68
|
+
}
|
|
69
|
+
#yasgui .yasr_results {
|
|
70
|
+
max-width: 100%;
|
|
71
|
+
overflow-x: auto;
|
|
72
|
+
}
|
|
73
|
+
@media (max-width: 768px) {
|
|
74
|
+
.header {
|
|
75
|
+
padding: 1rem;
|
|
76
|
+
height: auto;
|
|
77
|
+
flex-direction: column;
|
|
78
|
+
align-items: flex-start;
|
|
79
|
+
}
|
|
80
|
+
.header-content {
|
|
81
|
+
flex-direction: column;
|
|
82
|
+
align-items: flex-start;
|
|
83
|
+
}
|
|
84
|
+
.header h1 {
|
|
85
|
+
font-size: 1.25rem;
|
|
86
|
+
margin-bottom: 0.5rem;
|
|
87
|
+
}
|
|
88
|
+
.header p {
|
|
89
|
+
font-size: 0.9rem;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
</style>
|
|
93
|
+
</head>
|
|
94
|
+
<body>
|
|
95
|
+
<div class="header">
|
|
96
|
+
<div class="header-content">
|
|
97
|
+
<h1>Comunica SPARQL Endpoint</h1>
|
|
98
|
+
<p>Query this endpoint or visit <a href="https://query.comunica.dev/" target="_blank" rel="noopener">query.comunica.dev</a> for federated queries</p>
|
|
99
|
+
</div>
|
|
100
|
+
</div>
|
|
101
|
+
<div class="container">
|
|
102
|
+
<div id="yasgui"></div>
|
|
103
|
+
</div>
|
|
104
|
+
<script src="https://cdn.jsdelivr.net/npm/@zazuko/yasgui/build/yasgui.min.js"></script>
|
|
105
|
+
<script>
|
|
106
|
+
const yasgui = new Yasgui(document.getElementById("yasgui"), {
|
|
107
|
+
requestConfig: {
|
|
108
|
+
endpoint: window.location.origin + "%%ENDPOINT_PATH%%"
|
|
109
|
+
},
|
|
110
|
+
copyEndpointOnNewTab: false
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
// Set default query
|
|
114
|
+
yasgui.getTab().setQuery(`%%DEFAULT_QUERY%%`);
|
|
115
|
+
</script>
|
|
116
|
+
</body>
|
|
117
|
+
</html>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@comunica/actor-init-query",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.2.2",
|
|
4
4
|
"description": "A query init actor",
|
|
5
5
|
"lsd:module": true,
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"files": [
|
|
33
33
|
"components",
|
|
34
34
|
"lib/**/*.d.ts",
|
|
35
|
+
"lib/**/*.html",
|
|
35
36
|
"lib/**/*.js",
|
|
36
37
|
"lib/**/*.js.map"
|
|
37
38
|
],
|
|
@@ -41,17 +42,17 @@
|
|
|
41
42
|
"build:components": "componentsjs-generator"
|
|
42
43
|
},
|
|
43
44
|
"dependencies": {
|
|
44
|
-
"@comunica/actor-http-proxy": "^5.
|
|
45
|
-
"@comunica/bus-http-invalidate": "^5.
|
|
46
|
-
"@comunica/bus-init": "^5.
|
|
47
|
-
"@comunica/bus-query-process": "^5.
|
|
48
|
-
"@comunica/bus-query-result-serialize": "^5.
|
|
49
|
-
"@comunica/context-entries": "^5.
|
|
50
|
-
"@comunica/core": "^5.
|
|
51
|
-
"@comunica/logger-pretty": "^5.
|
|
52
|
-
"@comunica/runner": "^5.
|
|
53
|
-
"@comunica/types": "^5.
|
|
54
|
-
"@comunica/utils-algebra": "^5.
|
|
45
|
+
"@comunica/actor-http-proxy": "^5.2.2",
|
|
46
|
+
"@comunica/bus-http-invalidate": "^5.2.2",
|
|
47
|
+
"@comunica/bus-init": "^5.2.2",
|
|
48
|
+
"@comunica/bus-query-process": "^5.2.2",
|
|
49
|
+
"@comunica/bus-query-result-serialize": "^5.2.2",
|
|
50
|
+
"@comunica/context-entries": "^5.2.2",
|
|
51
|
+
"@comunica/core": "^5.2.2",
|
|
52
|
+
"@comunica/logger-pretty": "^5.2.0",
|
|
53
|
+
"@comunica/runner": "^5.2.2",
|
|
54
|
+
"@comunica/types": "^5.2.0",
|
|
55
|
+
"@comunica/utils-algebra": "^5.2.0",
|
|
55
56
|
"@rdfjs/types": "*",
|
|
56
57
|
"@types/yargs": "^17.0.24",
|
|
57
58
|
"asynciterator": "^3.10.0",
|
|
@@ -67,5 +68,5 @@
|
|
|
67
68
|
"browser": {
|
|
68
69
|
"./lib/index.js": "./lib/index-browser.js"
|
|
69
70
|
},
|
|
70
|
-
"gitHead": "
|
|
71
|
+
"gitHead": "c064abdfd8943e84c2aacbe01faec643ed8d289b"
|
|
71
72
|
}
|