@noeldemartin/solid-utils 0.1.1-next.51e371bcc6b640f405a570470052808dd2a0970b → 0.1.1-next.58b73c94b4d8c9b5b8fe26c1f1eb97095f1af84a

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/src/helpers/io.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { arr, arrayFilter, arrayReplace,objectWithoutEmpty } from '@noeldemartin/utils';
1
+ import md5 from 'md5';
2
+ import { arr, arrayFilter, arrayReplace, objectWithoutEmpty, stringMatchAll, tap } from '@noeldemartin/utils';
2
3
  import { BlankNode as N3BlankNode, Quad as N3Quad, Parser as TurtleParser, Writer as TurtleWriter } from 'n3';
4
+ import { fromRDF, toRDF } from 'jsonld';
3
5
  import type { JsonLdDocument } from 'jsonld';
4
- import { toRDF } from 'jsonld';
5
- import md5 from 'md5';
6
6
  import type { Quad } from 'rdf-js';
7
7
  import type { Term as N3Term } from 'n3';
8
8
 
@@ -13,10 +13,10 @@ import NetworkRequestError from '@/errors/NetworkRequestError';
13
13
  import NotFoundError from '@/errors/NotFoundError';
14
14
  import UnauthorizedError from '@/errors/UnauthorizedError';
15
15
  import { isJsonLDGraph } from '@/helpers/jsonld';
16
- import type { JsonLD } from '@/helpers/jsonld';
16
+ import type { JsonLD, JsonLDGraph, JsonLDResource } from '@/helpers/jsonld';
17
17
 
18
18
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
- export declare type AnyFetch = (input: any, options?: any) => Promise<any>;
19
+ export declare type AnyFetch = (input: any, options?: any) => Promise<Response>;
20
20
  export declare type TypedFetch = (input: RequestInfo, options?: RequestInit) => Promise<Response>;
21
21
  export declare type Fetch = TypedFetch | AnyFetch;
22
22
 
@@ -44,7 +44,10 @@ async function fetchRawSolidDocument(url: string, fetch: Fetch): Promise<{ body:
44
44
  if (error instanceof UnauthorizedError)
45
45
  throw error;
46
46
 
47
- throw new NetworkRequestError(url);
47
+ if (error instanceof NotFoundError)
48
+ throw error;
49
+
50
+ throw new NetworkRequestError(url, { cause: error });
48
51
  }
49
52
  }
50
53
 
@@ -52,26 +55,23 @@ function normalizeBlankNodes(quads: Quad[]): Quad[] {
52
55
  const normalizedQuads = quads.slice(0);
53
56
  const quadsIndexes: Record<string, Set<number>> = {};
54
57
  const blankNodeIds = arr(quads)
55
- .flatMap((quad, index) => {
56
- const ids = arrayFilter([
57
- quad.object.termType === 'BlankNode' ? quad.object.value : null,
58
- quad.subject.termType === 'BlankNode' ? quad.subject.value : null,
59
- ]);
60
-
61
- for (const id of ids) {
62
- quadsIndexes[id] = quadsIndexes[id] ?? new Set();
63
- quadsIndexes[id].add(index);
64
- }
65
-
66
- return ids;
67
- })
58
+ .flatMap(
59
+ (quad, index) => tap(
60
+ arrayFilter([
61
+ quad.object.termType === 'BlankNode' ? quad.object.value : null,
62
+ quad.subject.termType === 'BlankNode' ? quad.subject.value : null,
63
+ ]),
64
+ ids => ids.forEach(id => (quadsIndexes[id] ??= new Set()).add(index)),
65
+ ),
66
+ )
68
67
  .filter()
69
68
  .unique();
70
69
 
71
70
  for (const originalId of blankNodeIds) {
71
+ const quadIndexes = quadsIndexes[originalId] as Set<number>;
72
72
  const normalizedId = md5(
73
- arr(quadsIndexes[originalId])
74
- .map(index => quads[index])
73
+ arr(quadIndexes)
74
+ .map(index => quads[index] as Quad)
75
75
  .filter(({ subject: { termType, value } }) => termType === 'BlankNode' && value === originalId)
76
76
  .map(
77
77
  ({ predicate, object }) => object.termType === 'BlankNode'
@@ -82,9 +82,12 @@ function normalizeBlankNodes(quads: Quad[]): Quad[] {
82
82
  .join(),
83
83
  );
84
84
 
85
- for (const index of quadsIndexes[originalId]) {
86
- const quad = normalizedQuads[index];
87
- const terms: Record<string, N3Term> = { subject: quad.subject as N3Term, object: quad.object as N3Term };
85
+ for (const index of quadIndexes) {
86
+ const quad = normalizedQuads[index] as Quad;
87
+ const terms: Record<string, N3Term> = {
88
+ subject: quad.subject as N3Term,
89
+ object: quad.object as N3Term,
90
+ };
88
91
 
89
92
  for (const [termName, termValue] of Object.entries(terms)) {
90
93
  if (termValue.termType !== 'BlankNode' || termValue.value !== originalId)
@@ -93,7 +96,15 @@ function normalizeBlankNodes(quads: Quad[]): Quad[] {
93
96
  terms[termName] = new N3BlankNode(normalizedId);
94
97
  }
95
98
 
96
- arrayReplace(normalizedQuads, quad, new N3Quad(terms.subject, quad.predicate as N3Term, terms.object));
99
+ arrayReplace(
100
+ normalizedQuads,
101
+ quad,
102
+ new N3Quad(
103
+ terms.subject as N3Term,
104
+ quad.predicate as N3Term,
105
+ terms.object as N3Term,
106
+ ),
107
+ );
97
108
  }
98
109
  }
99
110
 
@@ -106,7 +117,7 @@ export interface ParsingOptions {
106
117
  }
107
118
 
108
119
  export async function createSolidDocument(url: string, body: string, fetch?: Fetch): Promise<SolidDocument> {
109
- fetch = fetch ?? window.fetch;
120
+ fetch = fetch ?? window.fetch.bind(window);
110
121
 
111
122
  const statements = await turtleToQuads(body);
112
123
 
@@ -126,6 +137,19 @@ export async function fetchSolidDocument(url: string, fetch?: Fetch): Promise<So
126
137
  return new SolidDocument(url, statements, headers);
127
138
  }
128
139
 
140
+ export async function fetchSolidDocumentIfFound(url: string, fetch?: Fetch): Promise<SolidDocument | null> {
141
+ try {
142
+ const document = await fetchSolidDocument(url, fetch);
143
+
144
+ return document;
145
+ } catch (error) {
146
+ if (!(error instanceof NotFoundError))
147
+ throw error;
148
+
149
+ return null;
150
+ }
151
+ }
152
+
129
153
  export async function jsonldToQuads(jsonld: JsonLD): Promise<Quad[]> {
130
154
  if (isJsonLDGraph(jsonld)) {
131
155
  const graphQuads = await Promise.all(jsonld['@graph'].map(jsonldToQuads));
@@ -149,6 +173,14 @@ export function normalizeSparql(sparql: string): string {
149
173
  .join(' ;\n');
150
174
  }
151
175
 
176
+ export async function quadsToJsonLD(quads: Quad[]): Promise<JsonLDGraph> {
177
+ const graph = await fromRDF(quads);
178
+
179
+ return {
180
+ '@graph': graph as JsonLDResource[],
181
+ };
182
+ }
183
+
152
184
  export function quadsToTurtle(quads: Quad[]): string {
153
185
  const writer = new TurtleWriter;
154
186
 
@@ -175,7 +207,7 @@ export async function sparqlToQuads(
175
207
  sparql: string,
176
208
  options: Partial<ParsingOptions> = {},
177
209
  ): Promise<Record<string, Quad[]>> {
178
- const operations = sparql.matchAll(/(\w+) DATA {([^}]+)}/g);
210
+ const operations = stringMatchAll<3>(sparql, /(\w+) DATA {([^}]+)}/g);
179
211
  const quads: Record<string, Quad[]> = {};
180
212
 
181
213
  await Promise.all([...operations].map(async operation => {
@@ -189,7 +221,7 @@ export async function sparqlToQuads(
189
221
  }
190
222
 
191
223
  export function sparqlToQuadsSync(sparql: string, options: Partial<ParsingOptions> = {}): Record<string, Quad[]> {
192
- const operations = sparql.matchAll(/(\w+) DATA {([^}]+)}/g);
224
+ const operations = stringMatchAll<3>(sparql, /(\w+) DATA {([^}]+)}/g);
193
225
  const quads: Record<string, Quad[]> = {};
194
226
 
195
227
  for (const operation of operations) {
@@ -244,12 +276,16 @@ export function turtleToQuadsSync(turtle: string, options: Partial<ParsingOption
244
276
  ? normalizeBlankNodes(quads)
245
277
  : quads;
246
278
  } catch (error) {
247
- throw new MalformedSolidDocumentError(options.documentUrl ?? null, SolidDocumentFormat.Turtle, error.message);
279
+ throw new MalformedSolidDocumentError(
280
+ options.documentUrl ?? null,
281
+ SolidDocumentFormat.Turtle,
282
+ (error as Error).message ?? '',
283
+ );
248
284
  }
249
285
  }
250
286
 
251
287
  export async function updateSolidDocument(url: string, body: string, fetch?: Fetch): Promise<void> {
252
- fetch = fetch ?? window.fetch;
288
+ fetch = fetch ?? window.fetch.bind(window);
253
289
 
254
290
  await fetch(url, {
255
291
  method: 'PATCH',
@@ -1,4 +1,4 @@
1
- import { Error, arrayRemove, pull } from '@noeldemartin/utils';
1
+ import { Error, arrayRemove, pull, stringMatchAll } from '@noeldemartin/utils';
2
2
  import type { JsonLD } from '@/helpers/jsonld';
3
3
  import type { Quad, Quad_Object } from 'rdf-js';
4
4
 
@@ -32,37 +32,36 @@ function containsPatterns(value: string): boolean {
32
32
  return /\[\[(.*\]\[)?([^\]]+)\]\]/.test(value);
33
33
  }
34
34
 
35
- function quadValueEquals(expected: string, actual: string): boolean {
36
- if (!containsPatterns(expected))
37
- return expected === actual;
38
-
35
+ function createPatternRegexp(expected: string): RegExp {
39
36
  const patternAliases = [];
37
+ const patternMatches = stringMatchAll<4, 1 | 2>(
38
+ expected,
39
+ /\[\[((.*?)\]\[)?([^\]]+)\]\]/g,
40
+ );
41
+ const patterns: string[] = [];
42
+ let expectedRegExp = expected;
40
43
 
41
- if (!(expected in patternsRegExpsIndex)) {
42
- const patternMatches = expected.matchAll(/\[\[((.*?)\]\[)?([^\]]+)\]\]/g);
43
- const patterns: string[] = [];
44
- let expectedRegExp = expected;
45
-
46
- for (const patternMatch of patternMatches) {
47
- if (patternMatch[2]) {
48
- patternAliases.push(patternMatch[2]);
49
- }
44
+ for (const patternMatch of patternMatches) {
45
+ patternMatch[2] && patternAliases.push(patternMatch[2]);
50
46
 
51
- patterns.push(patternMatch[3]);
52
-
53
- expectedRegExp = expectedRegExp.replace(patternMatch[0], `%PATTERN${patterns.length - 1}%`);
54
- }
47
+ patterns.push(patternMatch[3]);
55
48
 
56
- expectedRegExp = expectedRegExp.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
49
+ expectedRegExp = expectedRegExp.replace(patternMatch[0], `%PATTERN${patterns.length - 1}%`);
50
+ }
57
51
 
58
- for (const [patternIndex, pattern] of Object.entries(patterns)) {
59
- expectedRegExp = expectedRegExp.replace(`%PATTERN${patternIndex}%`, builtInPatterns[pattern] ?? pattern);
60
- }
52
+ expectedRegExp = expectedRegExp.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
61
53
 
62
- patternsRegExpsIndex[expected] = new RegExp(expectedRegExp);
54
+ for (const [patternIndex, pattern] of Object.entries(patterns)) {
55
+ expectedRegExp = expectedRegExp.replace(`%PATTERN${patternIndex}%`, builtInPatterns[pattern] ?? pattern);
63
56
  }
64
57
 
65
- return patternsRegExpsIndex[expected].test(actual);
58
+ return new RegExp(expectedRegExp);
59
+ }
60
+
61
+ function quadValueEquals(expected: string, actual: string): boolean {
62
+ return containsPatterns(expected)
63
+ ? (patternsRegExpsIndex[expected] ??= createPatternRegexp(expected)).test(actual)
64
+ : expected === actual;
66
65
  }
67
66
 
68
67
  function quadObjectEquals(expected: Quad_Object, actual: Quad_Object): boolean {
@@ -6,6 +6,7 @@ export interface ExpandIRIOptions {
6
6
  }
7
7
 
8
8
  const knownPrefixes: RDFContext = {
9
+ acl: 'http://www.w3.org/ns/auth/acl#',
9
10
  foaf: 'http://xmlns.com/foaf/0.1/',
10
11
  pim: 'http://www.w3.org/ns/pim/space#',
11
12
  purl: 'http://purl.org/dc/terms/',
@@ -25,7 +26,7 @@ export function expandIRI(iri: string, options: Partial<ExpandIRIOptions> = {}):
25
26
 
26
27
  const [prefix, name] = iri.split(':');
27
28
 
28
- if (name) {
29
+ if (prefix && name) {
29
30
  const expandedPrefix = knownPrefixes[prefix] ?? options.extraContext?.[prefix] ?? null;
30
31
 
31
32
  if (!expandedPrefix)
@@ -0,0 +1,41 @@
1
+ import { objectWithoutEmpty, requireUrlParentDirectory } from '@noeldemartin/utils';
2
+
3
+ import { fetchSolidDocumentIfFound } from '@/helpers/io';
4
+ import type SolidDocument from '@/models/SolidDocument';
5
+ import type { Fetch } from '@/helpers/io';
6
+
7
+ async function fetchACLResourceUrl(resourceUrl: string, fetch: Fetch): Promise<string> {
8
+ fetch = fetch ?? window.fetch.bind(window);
9
+
10
+ const resourceHead = await fetch(resourceUrl, { method: 'HEAD' });
11
+ const linkHeader = resourceHead.headers.get('Link') ?? '';
12
+ const url = linkHeader.match(/<([^>]+)>;\s*rel="acl"/)?.[1] ?? null;
13
+
14
+ return url ?? fail(`Could not find ACL Resource for '${resourceUrl}'`);
15
+ }
16
+
17
+ async function fetchEffectiveACL(
18
+ resourceUrl: string,
19
+ fetch: Fetch,
20
+ aclResourceUrl?: string | null,
21
+ ): Promise<SolidDocument> {
22
+ aclResourceUrl = aclResourceUrl ?? await fetchACLResourceUrl(resourceUrl, fetch);
23
+
24
+ return await fetchSolidDocumentIfFound(aclResourceUrl ?? '', fetch)
25
+ ?? await fetchEffectiveACL(requireUrlParentDirectory(resourceUrl), fetch);
26
+ }
27
+
28
+ export async function fetchSolidDocumentACL(documentUrl: string, fetch: Fetch): Promise<{
29
+ url: string;
30
+ effectiveUrl: string;
31
+ document: SolidDocument;
32
+ }> {
33
+ const url = await fetchACLResourceUrl(documentUrl, fetch);
34
+ const document = await fetchEffectiveACL(documentUrl, fetch, url);
35
+
36
+ return objectWithoutEmpty({
37
+ url,
38
+ effectiveUrl: document.url,
39
+ document,
40
+ });
41
+ }