Repository navigation
Expand file tree
/
Copy pathLDMClient.js
More file actions
480 lines (427 loc) · 22.1 KB
/
Copy pathLDMClient.js
File metadata and controls
480 lines (427 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import * as $rdf from 'rdflib';
import { parseRdf } from './rdf-parse.js';
const DEFAULT_ACCEPT = 'text/turtle, application/rdf+xml;q=0.9, application/ld+json;q=0.8, application/json;q=0.7';
/**
* Forward predicate -> the predicate that names the reverse direction.
*
* Exported because it is also **the set of link types queried**: `discoverIncomingLinks`
* sends `[...INVERSE_LINK_TYPES.keys()]` as `linkType`, and LQE answers only "what points
* here via this predicate". A predicate absent from this map is never asked about, so its
* incoming links come back as an empty result that cannot be told apart from "nothing
* links here". Tests assert membership for that reason.
*/
export { DOMAIN, LINK_PROFILE, LINK_OWNER_DOMAIN, BUILTIN_INVERSE_LABELS } from './link-profile.js';
export const INVERSE_LINK_TYPES = new Map([
['http://open-services.net/ns/core#related', 'http://open-services.net/ns/core#related'],
['http://open-services.net/ns/rm#constraints', 'http://open-services.net/ns/rm#constrainedBy'],
['http://open-services.net/ns/rm#constrainedBy', 'http://open-services.net/ns/rm#constraints'],
['http://open-services.net/ns/rm#decomposes', 'http://open-services.net/ns/rm#decomposedBy'],
['http://open-services.net/ns/rm#decomposedBy', 'http://open-services.net/ns/rm#decomposes'],
['http://open-services.net/ns/rm#elaborates', 'http://open-services.net/ns/rm#elaboratedBy'],
['http://open-services.net/ns/rm#elaboratedBy', 'http://open-services.net/ns/rm#elaborates'],
['http://open-services.net/ns/rm#satisfies', 'http://open-services.net/ns/rm#satisfiedBy'],
['http://open-services.net/ns/rm#satisfiedBy', 'http://open-services.net/ns/rm#satisfies'],
['http://open-services.net/ns/rm#specifies', 'http://open-services.net/ns/rm#specifiedBy'],
['http://open-services.net/ns/rm#specifiedBy', 'http://open-services.net/ns/rm#specifies'],
['http://open-services.net/ns/qm#validatesRequirement', 'http://open-services.net/ns/rm#validatedBy'],
['http://open-services.net/ns/qm#validatesRequirementCollection', 'http://open-services.net/ns/rm#validatedBy'],
['http://open-services.net/ns/cm#implementsRequirement', 'http://open-services.net/ns/rm#implementedBy'],
['http://open-services.net/ns/cm#tracksRequirement', 'http://open-services.net/ns/rm#trackedBy'],
['http://open-services.net/ns/cm#affectsRequirement', 'http://open-services.net/ns/rm#affectedBy'],
['http://open-services.net/ns/rm#implementedBy', 'http://open-services.net/ns/cm#implementsRequirement'],
['http://open-services.net/ns/rm#trackedBy', 'http://open-services.net/ns/cm#tracksRequirement'],
['http://open-services.net/ns/rm#affectedBy', 'http://open-services.net/ns/cm#affectsRequirement'],
// Architecture Management links. The Link Ownership table gives all six an owner domain of AM
// and a secondary predicate of -unspecified-, which is why they map to THEMSELVES as
// oslc:core#related does: there is no passive-side predicate to name. DOORS Next renders the
// reverse as "Traced By / Satisfied By / Derives Architecture Element" but asserts nothing
// for it.
//
// What the key buys is discovery. This map is also the set of linkType values queried, so
// while these were absent an incoming AM link was never asked about and came back as an empty
// result indistinguishable from "nothing links here" — which made a correctly stored AM-side
// trace invisible from the requirement, and made the wrong direction look like the only one
// that worked.
//
// The reverse LABEL is supplied by the shape, not by this map: genOSLC servers declare
// oslc:inversePropertyLabel and the caller prefers it (RN's oslc.service getInverseLabel),
// falling back to a label derived from the predicate. DOORS Next declares no such extension,
// which is why the label has to come from the AM side at all.
['http://jazz.net/ns/dm/linktypes#trace', 'http://jazz.net/ns/dm/linktypes#trace'],
['http://jazz.net/ns/dm/linktypes#satisfy', 'http://jazz.net/ns/dm/linktypes#satisfy'],
['http://jazz.net/ns/dm/linktypes#refine', 'http://jazz.net/ns/dm/linktypes#refine'],
['http://jazz.net/ns/dm/linktypes#derives', 'http://jazz.net/ns/dm/linktypes#derives'],
['http://jazz.net/ns/dm/linktypes#elaborates', 'http://jazz.net/ns/dm/linktypes#elaborates'],
['http://jazz.net/ns/dm/linktypes#external', 'http://jazz.net/ns/dm/linktypes#external'],
['http://open-services.net/ns/cm#testedByTestCase', 'http://open-services.net/ns/qm#testsChangeRequest'],
['http://open-services.net/ns/qm#testsChangeRequest', 'http://open-services.net/ns/cm#testedByTestCase'],
['http://open-services.net/ns/cm#relatedTestScript', 'http://open-services.net/ns/qm#relatedChangeRequest'],
['http://open-services.net/ns/cm#relatedTestCase', 'http://open-services.net/ns/qm#relatedChangeRequest'],
['http://open-services.net/ns/cm#relatedTestPlan', 'http://open-services.net/ns/qm#relatedChangeRequest'],
['http://open-services.net/ns/cm#relatedTestExecutionRecord', 'http://open-services.net/ns/qm#relatedChangeRequest'],
['http://open-services.net/ns/cm#blocksTestExecutionRecord', 'http://open-services.net/ns/qm#blockedByChangeRequest'],
['http://open-services.net/ns/qm#blockedByChangeRequest', 'http://open-services.net/ns/cm#blocksTestExecutionRecord'],
['http://open-services.net/ns/cm#affectsTestResult', 'http://open-services.net/ns/qm#affectedByChangeRequest'],
['http://open-services.net/ns/qm#affectedByChangeRequest', 'http://open-services.net/ns/cm#affectsTestResult'],
['http://open-services.net/ns/cm#affectedByDefect', 'http://open-services.net/ns/cm#affectsPlanItem'],
['http://open-services.net/ns/cm#affectsPlanItem', 'http://open-services.net/ns/cm#affectedByDefect'],
['http://jazz.net/ns/rm/navigation#parent', 'http://jazz.net/ns/rm/navigation#children'],
['http://jazz.net/ns/rm/navigation#children', 'http://jazz.net/ns/rm/navigation#parent'],
// CM -> AM, following the CM -> QM pattern above: the four cm#relatedTest* link types all
// invert to qm#relatedChangeRequest, and this is the same shape of relationship reaching an
// architecture resource instead of a test one.
//
// This map is also the set of link types queried: discoverIncomingLinks sends
// [...INVERSE_LINK_TYPES.keys()] as `linkType`, and LQE answers "what points here VIA THIS
// PREDICATE". A predicate missing from the keys is never asked about, and its incoming links
// come back as an empty result indistinguishable from "nothing links here". Measured
// 2026-09-28: LQE already held two EWM change requests pointing at a BMM Objective and
// returned both the moment it was asked with cm#relatedArchitectureElement; the client had
// never asked.
//
// The VALUE names the reverse direction for display. It is NOT a property anyone declares or
// stores: OSLC AM declares no properties at all (only LinkType and Resource), and adding a
// real am#relatedChangeRequest would create a redundant backlink -- a second stored assertion
// for a relationship already recorded once on the change request, which is exactly what link
// discovery exists to make unnecessary. ETM does declare oslc_qm:relatedChangeRequest; that is
// the thing not to copy. Nothing ever asserts this URI.
['http://open-services.net/ns/cm#relatedArchitectureElement', 'http://open-services.net/ns/am#relatedChangeRequest']
]);
function normalizeBaseUrl(url) {
if (!url) {
throw new Error('LDMServerBaseURL is required');
}
return url.endsWith('/') ? url.slice(0, -1) : url;
}
function asUrlString(value, name) {
if (typeof value !== 'string' || !value.trim()) {
throw new Error(`${name} must be a non-empty string`);
}
return value;
}
function parseRdfTriples({ data, contentType, baseIRI }) {
const store = $rdf.graph();
const ct = contentType?.split(';')[0]?.trim() || 'text/turtle';
parseRdf(data, store, baseIRI, ct);
return store.statementsMatching(null, null, null).map(st => ({
sourceURL: st.subject.value,
linkType: st.predicate.value,
targetURL: st.object.value
}));
}
/**
* LDMClient is a composition helper that uses an OSLCClient instance for HTTP requests.
* It provides Link Discovery Management (LDM) functionality for discovering
* incoming links to OSLC resources.
*/
export default class LDMClient {
/**
* Create an LDMClient instance.
* @param {OSLCClient} oslcClient - An initialized OSLCClient instance (provides client, userid, password, configuration_context)
* @param {string} ldmServerBaseUrl - Base URL of the LDM server (e.g., https://server/ldm)
*/
constructor(oslcClient, ldmServerBaseUrl) {
this.oslcClient = oslcClient;
this.client = oslcClient.client;
this.LDMServerBaseURL = normalizeBaseUrl(ldmServerBaseUrl);
this._warnedMissingInverseLinkTypes = new Set();
this.#resolvedEndpoint = null;
}
/** The endpoint shape that last answered successfully, so the candidate probe
* runs once rather than on every query. Reset when it stops working. */
#resolvedEndpoint = null;
/**
* Get incoming links to one or more target resources.
* @param {string[]} targetResourceURLs - Array of resource URLs to find incoming links for
* @param {string[]} linkTypes - Optional array of link type URIs to filter by
* @param {string|null} configurationContext - Optional configuration context (overrides constructor value)
* @returns {Promise<Array<{sourceURL: string, linkType: string, targetURL: string}>>}
*/
async getIncomingLinks(targetResourceURLs, linkTypes = [], configurationContext = null) {
if (!Array.isArray(targetResourceURLs) || targetResourceURLs.length === 0) {
throw new Error('targetResourceURLs must be a non-empty array');
}
if (!Array.isArray(linkTypes)) {
throw new Error('linkTypes must be an array');
}
// Use provided configurationContext or fall back to the one set in constructor
const effectiveConfigContext = configurationContext || this.oslcClient.configuration_context;
// Endpoint choice used to be `LDMServerBaseURL.includes('/lqe')`, i.e. decided
// by how the URL was spelled, and EXCLUSIVELY: an /ldx base was sent only to
// /discover-links, which LDX does not serve, so no setting could work. In
// fact the /incoming-links REST API is served by BOTH LQE and LDX (servlet
// mapping /incoming-links, ELM 7.1.0+), and its documented examples address a
// dataset (/incoming-links/default); /discover-links is the unrelated OSLC LDM
// specification endpoint.
//
// So: try every endpoint a server might offer. The URL is used only to ORDER
// the candidates — never to exclude one — so a mis-hinted base costs a wasted
// request, not a broken feature. The winner is remembered, so the probe
// happens once per base URL rather than on every query.
const notFound = err => err?.response?.status === 404;
let firstError = null;
for (const candidate of this.#endpointCandidates()) {
try {
const links = await this.#queryCandidate(
candidate, targetResourceURLs, linkTypes, effectiveConfigContext
);
this.#resolvedEndpoint = candidate;
return links;
} catch (err) {
// Only a 404 means "not this one" — anything else is a real failure and
// must not be masked by trying another endpoint.
if (!notFound(err)) throw err;
// Keep the FIRST failure, not the last. Candidates are ordered
// most-likely-first, so the first endpoint's message is the informative
// one — e.g. LQE explaining that a configuration "does not exist in the
// index", which is a real answer. Reporting the last attempt instead
// replaced that with the fallback endpoint's generic 404.
if (!firstError) firstError = err;
this.#resolvedEndpoint = null;
}
}
throw firstError || new Error('No incoming-links endpoint answered');
}
/**
* Endpoints to try, most likely first. A previously successful endpoint is
* returned alone. Ordering is a hint only; every candidate is reachable.
* @returns {Array<{kind: 'lqe'|'ldm', dataset?: string}>}
*/
#endpointCandidates() {
if (this.#resolvedEndpoint) return [this.#resolvedEndpoint];
// No dataset-qualified candidate: the servlet mapping is exactly
// /incoming-links (confirmed against 7.1.0 SR1 — GET /lqe/incoming-links
// returns 500 from the servlet, GET /lqe/incoming-links/default returns a
// routing 404). The API doc's curl examples showing /incoming-links/default
// contradict its own Implementation Reference. Where a deployment does need a
// dataset segment, it belongs in configuration rather than a hardcoded guess.
const lqe = [{ kind: 'lqe' }];
const ldm = [{ kind: 'ldm' }];
// An /ldm base is an OSLC LDM server; anything else (including /lqe and /ldx)
// most likely speaks the Jazz incoming-links REST API.
return /\/ldm(\/|$)/.test(this.LDMServerBaseURL) ? [...ldm, ...lqe] : [...lqe, ...ldm];
}
#queryCandidate(candidate, targetResourceURLs, linkTypes, configurationContext) {
return candidate.kind === 'ldm'
? this.#getIncomingLinksViaLdm(targetResourceURLs, linkTypes, configurationContext)
: this.#getIncomingLinksViaLqe(targetResourceURLs, linkTypes, configurationContext, candidate.dataset ?? null);
}
/**
* Invert a list of triples, swapping source and target and mapping to inverse link types.
* @param {Array<{sourceURL: string, linkType: string, targetURL: string}>} triples
* @returns {Array<{targetURL: string, inverseLinkType: string, sourceURL: string}>}
*/
invert(triples) {
if (!Array.isArray(triples)) {
throw new Error('triples must be an array');
}
const debugLqe = typeof process !== 'undefined' && process?.env?.DEBUG_LQE === 'true';
return triples.map(t => {
const sourceURL = Array.isArray(t) ? t[0] : t?.sourceURL;
const linkType = Array.isArray(t) ? t[1] : t?.linkType;
const targetURL = Array.isArray(t) ? t[2] : t?.targetURL;
const source = asUrlString(sourceURL, 'sourceURL');
const predicate = asUrlString(linkType, 'linkType');
const target = asUrlString(targetURL, 'targetURL');
let inverseLinkType = INVERSE_LINK_TYPES.get(predicate);
if (!inverseLinkType) {
const matches = [];
for (const [k, v] of INVERSE_LINK_TYPES.entries()) {
if (v === predicate) {
matches.push(k);
}
}
if (matches.length === 1) {
inverseLinkType = matches[0];
} else if (matches.length > 1) {
inverseLinkType = matches[0];
if (debugLqe && !this._warnedMissingInverseLinkTypes.has(predicate)) {
this._warnedMissingInverseLinkTypes.add(predicate);
console.warn(`[LDMClient] Multiple inverse link type mappings found for predicate: ${predicate}. Using: ${inverseLinkType}`);
}
}
}
if (!inverseLinkType) {
if (debugLqe && !this._warnedMissingInverseLinkTypes.has(predicate)) {
this._warnedMissingInverseLinkTypes.add(predicate);
console.warn(`[LDMClient] No inverse link type mapping found for predicate: ${predicate}`);
}
}
return {
targetURL: target,
inverseLinkType: inverseLinkType || predicate,
sourceURL: source
};
});
}
async #getIncomingLinksViaLdm(targetResourceURLs, linkTypes, configurationContext) {
const url = `${this.LDMServerBaseURL}/discover-links`;
const headers = {
'Accept': DEFAULT_ACCEPT
};
if (configurationContext) {
headers['Configuration-Context'] = asUrlString(configurationContext, 'configurationContext');
}
const postRdfRequest = async () => {
const oslcLdmNamespace = 'http://open-services.net/ns/ldm#';
const resourceList = targetResourceURLs
.map(u => `<${asUrlString(u, 'targetResourceURL')}>`)
.join(', ');
const predicateList = (Array.isArray(linkTypes) && linkTypes.length > 0)
? linkTypes.map(u => `<${asUrlString(u, 'linkType')}>`).join(', ')
: null;
let turtle = `@prefix oslc_ldm: <${oslcLdmNamespace}> .\n`;
turtle += `[] oslc_ldm:resources ${resourceList}`;
if (predicateList) {
turtle += ` ;\n oslc_ldm:linkPredicates ${predicateList}`;
}
turtle += ` .\n`;
const response = await this.client.post(url, turtle, {
headers: {
...headers,
'Content-Type': 'text/turtle'
}
});
const contentType = response?.headers?.['content-type'] || 'text/turtle';
return parseRdfTriples({
data: response.data,
contentType,
baseIRI: url
});
};
const postLegacyFormRequest = async objectFieldName => {
const params = new URLSearchParams();
for (const target of targetResourceURLs) {
params.append(objectFieldName, asUrlString(target, 'targetResourceURL'));
}
for (const predicate of linkTypes) {
params.append('predicateFilters', asUrlString(predicate, 'linkType'));
}
const response = await this.client.post(url, params.toString(), {
headers: {
...headers,
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const contentType = response?.headers?.['content-type'] || 'text/turtle';
return parseRdfTriples({
data: response.data,
contentType,
baseIRI: url
});
};
try {
// Prefer the latest LDM spec behavior: RDF request/response bodies.
return await postRdfRequest();
} catch (err) {
// Fallback for older/out-of-date servers.
try {
return await postLegacyFormRequest('objectResources');
} catch (err2) {
return await postLegacyFormRequest('objectConceptResources');
}
}
}
/**
* Query the LQE/LDX Incoming Links REST API (ELM 7.1.0+).
* @param {string|null} dataset - optional dataset segment, e.g. 'default'
*/
async #getIncomingLinksViaLqe(targetResourceURLs, linkTypes, configurationContext, dataset = null) {
const endpoint = dataset
? `${this.LDMServerBaseURL}/incoming-links/${dataset}`
: `${this.LDMServerBaseURL}/incoming-links`;
const debugLqe = typeof process !== 'undefined' && process?.env?.DEBUG_LQE === 'true';
if (debugLqe) {
console.debug(`[LDMClient] LQE base URL: ${this.LDMServerBaseURL}`);
console.debug(`[LDMClient] POST incoming-links to: ${endpoint}`);
}
// Build form-encoded body
const params = new URLSearchParams();
for (const url of targetResourceURLs) {
params.append('targetUrl', asUrlString(url, 'targetResourceURL'));
}
// linkType is required by LQE — if none specified, send all known link types
const effectiveLinkTypes = (Array.isArray(linkTypes) && linkTypes.length > 0)
? linkTypes
: [...INVERSE_LINK_TYPES.keys()];
for (const lt of effectiveLinkTypes) {
params.append('linkType', asUrlString(lt, 'linkType'));
}
if (configurationContext) {
params.append('oslc_config.context', asUrlString(configurationContext, 'configurationContext'));
}
// X-Jazz-CSRF-Prevent is added by OSLCClient's request interceptor for every
// mutating request. Setting it here too would shadow the interceptor's value,
// which prefers the JSESSIONID cookie over the '1' placeholder.
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
};
if (configurationContext) {
headers['Configuration-Context'] = asUrlString(configurationContext, 'configurationContext');
}
const hasAuthorizationHeader = () => {
const common = this.client?.defaults?.headers?.common;
return !!(common?.Authorization || common?.authorization);
};
const requestAuth = !hasAuthorizationHeader() && this.oslcClient.userid && this.oslcClient.password
? { username: this.oslcClient.userid, password: this.oslcClient.password }
: undefined;
if (debugLqe) {
console.debug(`[LDMClient] incoming-links request body: ${params.toString()}`);
}
try {
const response = await this.client.post(endpoint, params.toString(), {
auth: requestAuth,
headers,
});
const data = response.data;
if (debugLqe) {
console.debug(`[LDMClient] incoming-links response: numberOfResults=${data?.numberOfResults}`);
}
if (data?.error) {
throw new Error(`LQE incoming-links error: ${data.error}`);
}
// REST API format (LQE 7.1.0+ with relational store)
if (data?.queryResults) {
return data.queryResults.map(r => ({
sourceURL: r.sourceUrl || '',
linkType: r.linkType || '',
targetURL: r.targetUrl || ''
}));
}
// SPARQL JSON format (LQE with Jena store)
// Variables: sURL (source), linkType, tURL (target), indLinkType
if (data?.results?.bindings) {
return data.results.bindings.map(b => ({
sourceURL: b.sURL?.value || '',
linkType: b.linkType?.value || '',
targetURL: b.tURL?.value || ''
}));
}
return [];
} catch (error) {
const status = error?.response?.status;
// The body is where the server explains itself. JSON responses use an
// `error` field, but LQE returns text/plain for some failures — reading only
// data.error meant those degraded to "Request failed with status code 404"
// and the actual reason ("Configuration ... does not exist in the index or
// is not a configuration") never reached the caller.
const data = error?.response?.data;
const bodyText = typeof data === 'string' ? data.trim() : data?.error;
const msg = bodyText
? bodyText.slice(0, 500)
: error?.message || 'Unknown error';
const wrapped = new Error(
`request=POST ${endpoint} ` +
`${status ? `status=${status} ` : ''}${msg}`
);
// Preserve the response so callers can branch on the status. getIncomingLinks
// treats 404 as "this endpoint/dataset is absent, try the next candidate";
// without this the wrapper hid the status and every failure looked terminal.
if (error?.response) wrapped.response = error.response;
wrapped.cause = error;
throw wrapped;
}
}
}