-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathconneg.js
More file actions
239 lines (204 loc) · 7.17 KB
/
conneg.js
File metadata and controls
239 lines (204 loc) · 7.17 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
/**
* Content Negotiation for RDF Resources
*
* Handles Accept header parsing and format selection.
* OFF by default - this is a JSON-LD native implementation.
* Enable with { conneg: true } in server options.
*/
import { turtleToJsonLd, jsonLdToTurtle } from './turtle.js';
import { safeJsonParse } from '../utils/url.js';
// RDF content types we support
export const RDF_TYPES = {
JSON_LD: 'application/ld+json',
TURTLE: 'text/turtle',
N3: 'text/n3',
NTRIPLES: 'application/n-triples',
RDF_XML: 'application/rdf+xml' // Not supported, but recognized
};
// Content types we can serve (when conneg enabled)
const SUPPORTED_OUTPUT = [RDF_TYPES.JSON_LD, RDF_TYPES.TURTLE];
// Content types we can accept for input (when conneg enabled)
const SUPPORTED_INPUT = [RDF_TYPES.JSON_LD, RDF_TYPES.TURTLE, RDF_TYPES.N3];
/**
* Parse Accept header and select best content type
* @param {string} acceptHeader - Accept header value
* @param {boolean} connegEnabled - Whether content negotiation is enabled
* @returns {string} Selected content type
*/
export function selectContentType(acceptHeader, connegEnabled = false) {
// If conneg disabled, always return JSON-LD
if (!connegEnabled) {
return RDF_TYPES.JSON_LD;
}
if (!acceptHeader) {
return RDF_TYPES.JSON_LD;
}
// Parse Accept header
const accepts = parseAcceptHeader(acceptHeader);
// Find best match
for (const { type } of accepts) {
if (type === '*/*' || type === 'application/*') {
return RDF_TYPES.JSON_LD;
}
if (SUPPORTED_OUTPUT.includes(type)) {
return type;
}
// Handle text/* preference
if (type === 'text/*') {
return RDF_TYPES.TURTLE;
}
}
// Default to JSON-LD
return RDF_TYPES.JSON_LD;
}
/**
* Parse Accept header into sorted list
*/
function parseAcceptHeader(header) {
const types = header.split(',').map(part => {
const [type, ...params] = part.trim().split(';');
let q = 1;
for (const param of params) {
const [key, value] = param.trim().split('=');
if (key === 'q') {
q = parseFloat(value) || 0;
}
}
return { type: type.trim().toLowerCase(), q };
});
// Sort by q value descending
return types.sort((a, b) => b.q - a.q);
}
/**
* Check if content type is RDF
*/
export function isRdfType(contentType) {
if (!contentType) return false;
const type = contentType.split(';')[0].trim().toLowerCase();
return Object.values(RDF_TYPES).includes(type) ||
type === 'application/json'; // Treat as JSON-LD
}
/**
* Check if we can accept this input type for RDF resources
* Non-RDF content types are always accepted (passthrough)
*/
export function canAcceptInput(contentType, connegEnabled = false) {
if (!contentType) return true; // No content type = accept
const type = contentType.split(';')[0].trim().toLowerCase();
// Always accept JSON-LD and JSON
if (type === RDF_TYPES.JSON_LD || type === 'application/json') {
return true;
}
// Check if it's an RDF type we need to handle
const isRdf = Object.values(RDF_TYPES).includes(type);
// Non-RDF types are accepted as-is (passthrough)
if (!isRdf) {
return true;
}
// RDF types other than JSON-LD only if conneg enabled
if (connegEnabled) {
return SUPPORTED_INPUT.includes(type);
}
// RDF type but conneg disabled - reject (should use JSON-LD)
return false;
}
/**
* Convert content to JSON-LD (internal storage format)
* @param {Buffer|string} content - Input content
* @param {string} contentType - Content-Type header
* @param {string} baseUri - Base URI
* @param {boolean} connegEnabled - Whether conneg is enabled
* @returns {Promise<object>} JSON-LD document
*/
export async function toJsonLd(content, contentType, baseUri, connegEnabled = false) {
const type = (contentType || '').split(';')[0].trim().toLowerCase();
const text = Buffer.isBuffer(content) ? content.toString() : content;
// JSON-LD or JSON
if (type === RDF_TYPES.JSON_LD || type === 'application/json' || !type) {
return safeJsonParse(text);
}
// Turtle/N3 - only if conneg enabled
if (connegEnabled && (type === RDF_TYPES.TURTLE || type === RDF_TYPES.N3)) {
return turtleToJsonLd(text, baseUri);
}
throw new Error(`Unsupported content type: ${type}`);
}
/**
* Convert JSON-LD to requested format
* @param {object} jsonLd - JSON-LD document
* @param {string} targetType - Target content type
* @param {string} baseUri - Base URI
* @param {boolean} connegEnabled - Whether conneg is enabled
* @returns {Promise<{content: string, contentType: string}>}
*/
export async function fromJsonLd(jsonLd, targetType, baseUri, connegEnabled = false) {
// If conneg disabled, always output JSON-LD
if (!connegEnabled) {
return {
content: JSON.stringify(jsonLd, null, 2),
contentType: RDF_TYPES.JSON_LD
};
}
// JSON-LD
if (targetType === RDF_TYPES.JSON_LD || !targetType) {
return {
content: JSON.stringify(jsonLd, null, 2),
contentType: RDF_TYPES.JSON_LD
};
}
// Turtle
if (targetType === RDF_TYPES.TURTLE) {
const turtle = await jsonLdToTurtle(jsonLd, baseUri);
return { content: turtle, contentType: RDF_TYPES.TURTLE };
}
// Fallback to JSON-LD
return {
content: JSON.stringify(jsonLd, null, 2),
contentType: RDF_TYPES.JSON_LD
};
}
/**
* Get Vary header value for content negotiation
*
* Must be identical across all variants of a given URL — inconsistent Vary
* across variants confuses browser caches and can cause the wrong variant
* to be served on reload (see #315).
*
* - `Accept` — response body depends on Accept (conneg or mashlib HTML shell)
* - `Authorization` — response body depends on the authenticated user (WAC)
* - `Origin` — CORS headers echo the request's Origin
*/
export function getVaryHeader(connegEnabled, mashlibEnabled = false) {
return (connegEnabled || mashlibEnabled)
? 'Accept, Authorization, Origin'
: 'Authorization, Origin';
}
/**
* Get Accept-* headers for responses.
*
* The explicitly listed RDF types are aligned with the formats this
* module accepts so clients can discover support consistently:
* - JSON-LD (application/ld+json) and JSON (application/json alias)
* are advertised in all conneg modes.
* - Turtle (text/turtle) and N3 (text/n3) are advertised only when
* conneg is enabled (SUPPORTED_INPUT in this file).
*
* Note: a wildcard (asterisk-slash-asterisk) is included as a broad
* interoperability hint for generic clients and proxies. It is not a
* strict contract that every media type matching the wildcard will be
* accepted by canAcceptInput() (e.g., application/n-triples and
* application/rdf+xml are not accepted).
*/
export function getAcceptHeaders(connegEnabled, isContainer = false) {
const headers = {};
if (isContainer) {
headers['Accept-Post'] = connegEnabled
? `${RDF_TYPES.JSON_LD}, application/json, ${RDF_TYPES.TURTLE}, ${RDF_TYPES.N3}, */*`
: `${RDF_TYPES.JSON_LD}, application/json, */*`;
}
headers['Accept-Put'] = connegEnabled
? `${RDF_TYPES.JSON_LD}, application/json, ${RDF_TYPES.TURTLE}, ${RDF_TYPES.N3}, */*`
: `${RDF_TYPES.JSON_LD}, application/json, */*`;
headers['Accept-Patch'] = 'text/n3, application/sparql-update';
return headers;
}