@@ -5,9 +5,11 @@ import { getAllHeaders, getNotFoundHeaders, representationLinks } from '../ldp/h
55import { generateContainerJsonLd , generateLwsContainer , serializeJsonLd } from '../ldp/container.js' ;
66import { generateLinkset } from '../lws/linkset.js' ;
77import { describedbyTargets , conformsToTargets } from '../lws/constraint.js' ;
8- import { isContainer , getContentType , isRdfContentType , getEffectiveUrlPath , safeJsonParse , getPodName , parentContainerUrl } from '../utils/url.js' ;
8+ import { isContainer , getContentType , isRdfContentType , getEffectiveUrlPath , safeJsonParse , getPodName , parentContainerUrl , isBodiedWithoutContentType , missingContentTypeProblem } from '../utils/url.js' ;
99import { parseN3Patch , applyN3Patch , validatePatch } from '../patch/n3-patch.js' ;
1010import { parseSparqlUpdate , applySparqlUpdate } from '../patch/sparql-update.js' ;
11+ import { applyMergePatch } from '../patch/merge-patch.js' ;
12+ import { toDataset } from '../rdf/dataset.js' ;
1113import {
1214 selectContentType ,
1315 canAcceptInput ,
@@ -29,7 +31,7 @@ import { constraintProblem } from '../lws/admission.js';
2931import { parseTypeLinks , typeStorePath , readDeclaredTypes } from '../lws/type-metadata.js' ;
3032import { applyLwsWrite } from '../lws/write.js' ;
3133import { filterReadableEntries } from '../lws/authorized-listing.js' ;
32- import { serveStoredRdf , checkServable , isRdfSourceType , QUADS_OUTPUTS , nonRdfNotAcceptable } from '../rdf/serve.js' ;
34+ import { serveStoredRdf , checkServable , isRdfSourceType , QUADS_OUTPUTS , nonRdfNotAcceptable , datasetToJsonLd , datasetToFormat } from '../rdf/serve.js' ;
3335
3436/**
3537 * Live reload script - injected into HTML when --live-reload is enabled
@@ -42,6 +44,13 @@ const LIVE_RELOAD_SCRIPT = `<script>(function(){var ws=new WebSocket((location.p
4244// where a cached data variant was served on top-level navigation (#315).
4345const RDF_CACHE_CONTROL = 'private, no-cache, must-revalidate' ;
4446
47+ // #7 (Solid #server-patch-n3-accept MUST): stored types PATCH must parse by
48+ // real media type rather than blind JSON — the n3 family (verbatim under
49+ // --lws). JSON/JSON-LD stays on the legacy safeJsonParse-first flow below.
50+ const PATCH_TURTLE_FAMILY = new Set ( [
51+ RDF_TYPES . TURTLE , RDF_TYPES . N3 , RDF_TYPES . NTRIPLES , RDF_TYPES . NQUADS ,
52+ ] ) ;
53+
4554// Detects when the request's Accept header explicitly names a JSON
4655// media type. Used by the container/index.html branches of GET and HEAD
4756// to decide whether to surface the embedded JSON-LD data island —
@@ -1783,6 +1792,15 @@ export async function handlePut(request, reply) {
17831792 }
17841793
17851794 const { urlPath, storagePath, resourceUrl } = getRequestPaths ( request ) ;
1795+
1796+ // P2 (Solid #server-content-type-missing MUST): a bodied write with no
1797+ // Content-Type must 400, not silently fall through to canAcceptInput('')
1798+ // (which treats absence as accept-anything).
1799+ if ( request . lwsEnabled && isBodiedWithoutContentType ( request ) ) {
1800+ return reply . code ( 400 ) . type ( 'application/problem+json' )
1801+ . send ( JSON . stringify ( missingContentTypeProblem ( resourceUrl ) , null , 2 ) ) ;
1802+ }
1803+
17861804 const connegEnabled = request . connegEnabled || false ;
17871805 // Spec §4a: --lws mandates the negotiation surface; conneg is implied by it.
17881806 const negotiate = connegEnabled || request . lwsEnabled ;
@@ -2065,6 +2083,94 @@ export async function handleOptions(request, reply) {
20652083 return reply . code ( 204 ) . send ( ) ;
20662084}
20672085
2086+ /**
2087+ * #7 (Solid #server-patch-n3-accept MUST): PATCH a verbatim-stored
2088+ * Turtle-family resource (resourceExists && storedType is Turtle/N3/NT/NQ).
2089+ * Projects stored bytes -> RDF dataset -> expanded JSON-LD (the same seam
2090+ * the serving arm uses, src/rdf/serve.js datasetToJsonLd) since both
2091+ * n3-patch.js and sparql-update.js operate at the JSON-LD document level,
2092+ * then serializes back through toDataset/datasetToFormat so the write lands
2093+ * in the SAME stored format — Content-Type identity is preserved.
2094+ */
2095+ async function patchTurtleFamilyResource ( request , reply , { storagePath, resourceUrl, storedType, isSparqlUpdate } ) {
2096+ const existingContent = await storage . read ( storagePath ) ;
2097+ if ( existingContent === null ) {
2098+ return reply . code ( 500 ) . send ( { error : 'Read error' } ) ;
2099+ }
2100+
2101+ let dataset ;
2102+ try {
2103+ dataset = await toDataset ( existingContent , storedType , resourceUrl ) ;
2104+ } catch ( e ) {
2105+ return reply . code ( 409 ) . type ( 'application/problem+json' ) . send ( JSON . stringify ( {
2106+ type : 'about:blank' , title : 'Conflict' , status : 409 ,
2107+ detail : `the stored document did not parse as ${ storedType } (${ e . message } ).` ,
2108+ instance : resourceUrl ,
2109+ } , null , 2 ) ) ;
2110+ }
2111+ // datasetToJsonLd returns a bare array of expanded nodes (jsonld.fromRDF's
2112+ // default-graph form) — neither patch applier's native shape (n3-patch.js
2113+ // wants {'@graph': [...] }, sparql-update.js wants the bare array), so each
2114+ // branch below adapts on the way in/out rather than changing the appliers.
2115+ const nodes = await datasetToJsonLd ( dataset ) ;
2116+
2117+ const patchContent = Buffer . isBuffer ( request . body ) ? request . body . toString ( ) : request . body ;
2118+ let updatedNodes ;
2119+
2120+ if ( isSparqlUpdate ) {
2121+ let update ;
2122+ try {
2123+ update = parseSparqlUpdate ( patchContent , resourceUrl ) ;
2124+ } catch ( e ) {
2125+ return reply . code ( 400 ) . send ( { error : 'Bad Request' , message : 'Invalid SPARQL Update: ' + e . message } ) ;
2126+ }
2127+ try {
2128+ const result = applySparqlUpdate ( nodes , update , resourceUrl ) ;
2129+ // applySparqlUpdate collapses a single-node result to a bare object.
2130+ updatedNodes = Array . isArray ( result ) ? result : [ result ] ;
2131+ } catch ( e ) {
2132+ return reply . code ( 409 ) . send ( { error : 'Conflict' , message : 'Failed to apply SPARQL Update: ' + e . message } ) ;
2133+ }
2134+ } else {
2135+ let patch ;
2136+ try {
2137+ patch = parseN3Patch ( patchContent , resourceUrl ) ;
2138+ } catch ( e ) {
2139+ return reply . code ( 400 ) . send ( { error : 'Bad Request' , message : 'Invalid N3 Patch format: ' + e . message } ) ;
2140+ }
2141+ try {
2142+ const result = applyN3Patch ( { '@graph' : nodes } , patch , resourceUrl ) ;
2143+ updatedNodes = Array . isArray ( result [ '@graph' ] ) ? result [ '@graph' ] : nodes ;
2144+ } catch ( e ) {
2145+ return reply . code ( 409 ) . send ( { error : 'Conflict' , message : 'Failed to apply patch: ' + e . message } ) ;
2146+ }
2147+ }
2148+
2149+ let updatedDataset ;
2150+ try {
2151+ updatedDataset = await toDataset ( JSON . stringify ( updatedNodes ) , RDF_TYPES . JSON_LD , resourceUrl ) ;
2152+ } catch ( e ) {
2153+ return reply . code ( 409 ) . send ( { error : 'Conflict' , message : 'Patch produced an invalid document: ' + e . message } ) ;
2154+ }
2155+ const updatedContent = await datasetToFormat ( updatedDataset , QUADS_OUTPUTS [ storedType ] || RDF_TYPES . NQUADS ) ;
2156+
2157+ const success = await storage . write ( storagePath , Buffer . from ( updatedContent ) ) ;
2158+ if ( ! success ) {
2159+ return reply . code ( 500 ) . send ( { error : 'Write failed' } ) ;
2160+ }
2161+
2162+ const origin = request . headers . origin ;
2163+ const headers = getAllHeaders ( { isContainer : false , origin, resourceUrl, lwsEnabled : request . lwsEnabled } ) ;
2164+ Object . entries ( headers ) . forEach ( ( [ k , v ] ) => reply . header ( k , v ) ) ;
2165+
2166+ if ( request . notificationsEnabled ) {
2167+ emitChange ( resourceUrl ) ;
2168+ }
2169+
2170+ // The resource already existed (dispatch precondition) — always 204.
2171+ return reply . code ( 204 ) . send ( ) ;
2172+ }
2173+
20682174/**
20692175 * Handle PATCH request
20702176 * Supports N3 Patch format (text/n3) and SPARQL Update for updating RDF resources
@@ -2077,6 +2183,13 @@ export async function handlePatch(request, reply) {
20772183
20782184 const { urlPath, storagePath, resourceUrl } = getRequestPaths ( request ) ;
20792185
2186+ // P2 (Solid #server-content-type-missing MUST): a bodied write with no
2187+ // Content-Type must 400, not fall through to a guessed patch type.
2188+ if ( request . lwsEnabled && isBodiedWithoutContentType ( request ) ) {
2189+ return reply . code ( 400 ) . type ( 'application/problem+json' )
2190+ . send ( JSON . stringify ( missingContentTypeProblem ( resourceUrl ) , null , 2 ) ) ;
2191+ }
2192+
20802193 // Don't allow PATCH to containers
20812194 if ( isContainer ( urlPath ) ) {
20822195 return reply . code ( 409 ) . send ( { error : 'Cannot PATCH containers' } ) ;
@@ -2086,11 +2199,16 @@ export async function handlePatch(request, reply) {
20862199 const contentType = request . headers [ 'content-type' ] || '' ;
20872200 const isN3Patch = contentType . includes ( 'text/n3' ) || contentType . includes ( 'application/n3' ) ;
20882201 const isSparqlUpdate = contentType . includes ( 'application/sparql-update' ) ;
2202+ // P1 (LWS update-resource MUST: JSON Merge Patch, RFC 7386) — --lws only;
2203+ // the --lws-off 415 gate below stays byte-identical (isMergePatch false).
2204+ const isMergePatch = request . lwsEnabled
2205+ && contentType . split ( ';' ) [ 0 ] . trim ( ) . toLowerCase ( ) === 'application/merge-patch+json' ;
20892206
2090- if ( ! isN3Patch && ! isSparqlUpdate ) {
2207+ if ( ! isN3Patch && ! isSparqlUpdate && ! isMergePatch ) {
20912208 return reply . code ( 415 ) . send ( {
20922209 error : 'Unsupported Media Type' ,
2093- message : 'PATCH requires Content-Type: text/n3 (N3 Patch) or application/sparql-update (SPARQL Update)'
2210+ message : 'PATCH requires Content-Type: text/n3 (N3 Patch), application/sparql-update (SPARQL Update)'
2211+ + ( request . lwsEnabled ? ', or application/merge-patch+json (JSON Merge Patch)' : '' )
20942212 } ) ;
20952213 }
20962214
@@ -2109,6 +2227,21 @@ export async function handlePatch(request, reply) {
21092227 }
21102228 }
21112229
2230+ // #7: a verbatim-stored Turtle-family resource is parsed by its real media
2231+ // type (src/rdf/dataset.js toDataset), not blindly as JSON-LD — the legacy
2232+ // flow below assumes JSON-LD and 409s every Turtle/N3/NT/NQ PATCH target.
2233+ const storedType = ( request . lwsEnabled && resourceExists ) ? getContentType ( storagePath ) : null ;
2234+ if ( storedType && PATCH_TURTLE_FAMILY . has ( storedType ) ) {
2235+ if ( isMergePatch ) {
2236+ return reply . code ( 415 ) . type ( 'application/problem+json' ) . send ( JSON . stringify ( {
2237+ type : 'about:blank' , title : 'Unsupported Media Type' , status : 415 ,
2238+ detail : `JSON Merge Patch applies to JSON documents; this resource is ${ storedType } — use text/n3 (N3 Patch) or application/sparql-update.` ,
2239+ instance : resourceUrl ,
2240+ } , null , 2 ) ) ;
2241+ }
2242+ return patchTurtleFamilyResource ( request , reply , { storagePath, resourceUrl, storedType, isSparqlUpdate } ) ;
2243+ }
2244+
21122245 // Read existing content or start with empty JSON-LD document
21132246 let document ;
21142247 let htmlWrapper = null ; // Track HTML wrapper for data island re-embedding
@@ -2250,7 +2383,20 @@ export async function handlePatch(request, reply) {
22502383
22512384 let updatedDocument ;
22522385
2253- if ( isSparqlUpdate ) {
2386+ if ( isMergePatch ) {
2387+ // P1 (LWS update-resource MUST, RFC 7386): merge-patch applies straight
2388+ // to the stored JSON/JSON-LD document — no triple-level projection needed.
2389+ let patchObj ;
2390+ try {
2391+ patchObj = safeJsonParse ( patchContent ) ;
2392+ } catch ( e ) {
2393+ return reply . code ( 400 ) . send ( {
2394+ error : 'Bad Request' ,
2395+ message : 'Invalid JSON Merge Patch: ' + e . message
2396+ } ) ;
2397+ }
2398+ updatedDocument = applyMergePatch ( document , patchObj ) ;
2399+ } else if ( isSparqlUpdate ) {
22542400 // Handle SPARQL Update
22552401 let update ;
22562402 try {
0 commit comments