@startinblox/core 0.17.19 → 0.17.21-beta.10
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/dist/components/solid-ac-checker.js +3 -10
- package/dist/components/solid-ac-checker.js.map +1 -1
- package/dist/components/solid-display.js +1 -1
- package/dist/components/solid-display.js.map +1 -1
- package/dist/components/solid-form-search.js.map +1 -1
- package/dist/libs/filter.js +214 -0
- package/dist/libs/filter.js.map +1 -0
- package/dist/libs/interfaces.js.map +1 -1
- package/dist/libs/store/store.js +113 -18
- package/dist/libs/store/store.js.map +1 -1
- package/dist/mixins/filterMixin.js +2 -61
- package/dist/mixins/filterMixin.js.map +1 -1
- package/dist/mixins/widgetMixin.js +2 -2
- package/dist/mixins/widgetMixin.js.map +1 -1
- package/dist/new-widgets/templates/defaultTemplatesDirectory.js +4 -3
- package/dist/new-widgets/templates/defaultTemplatesDirectory.js.map +1 -1
- package/dist/new-widgets/templates/displayTemplatesDirectory.js +4 -3
- package/dist/new-widgets/templates/displayTemplatesDirectory.js.map +1 -1
- package/dist/new-widgets/templates/formTemplatesDirectory.js +3 -3
- package/dist/new-widgets/templates/formTemplatesDirectory.js.map +1 -1
- package/dist/new-widgets/templatesDependencies/linkTextMixin.js +14 -0
- package/dist/new-widgets/templatesDependencies/linkTextMixin.js.map +1 -0
- package/dist/new-widgets/templatesDependencies/multipleFormMixin.js +18 -0
- package/dist/new-widgets/templatesDependencies/multipleFormMixin.js.map +1 -1
- package/package.json +2 -2
package/dist/libs/store/store.js
CHANGED
|
@@ -58,8 +58,10 @@ class Store {
|
|
|
58
58
|
this.subscriptionIndex = new Map();
|
|
59
59
|
this.subscriptionVirtualContainersIndex = new Map();
|
|
60
60
|
this.loadingList = new Set();
|
|
61
|
-
this.headers =
|
|
62
|
-
|
|
61
|
+
this.headers = {
|
|
62
|
+
'Content-Type': 'application/ld+json',
|
|
63
|
+
'Cache-Control': 'must-revalidate'
|
|
64
|
+
};
|
|
63
65
|
this.fetch = this.storeOptions.fetchMethod;
|
|
64
66
|
this.session = this.storeOptions.session;
|
|
65
67
|
}
|
|
@@ -68,6 +70,8 @@ class Store {
|
|
|
68
70
|
* @param id - uri of the resource to fetch
|
|
69
71
|
* @param context - context used to expand id and predicates when accessing the resource
|
|
70
72
|
* @param idParent - uri of the parent caller used to expand uri for local files
|
|
73
|
+
* @param localData - data to put in cache
|
|
74
|
+
* @param forceFetch - force the fetch of data
|
|
71
75
|
*
|
|
72
76
|
* @returns The fetched resource
|
|
73
77
|
*
|
|
@@ -75,10 +79,10 @@ class Store {
|
|
|
75
79
|
*/
|
|
76
80
|
|
|
77
81
|
|
|
78
|
-
async getData(id, context = {}, idParent = "", localData) {
|
|
82
|
+
async getData(id, context = {}, idParent = "", localData, forceFetch = false) {
|
|
79
83
|
if (localData == null && this.cache.has(id) && !this.loadingList.has(id)) {
|
|
80
84
|
const resource = this.get(id);
|
|
81
|
-
if (resource && resource.isFullResource()) return resource; // if resource is not complete, re-fetch it
|
|
85
|
+
if (resource && resource.isFullResource() && !forceFetch) return resource; // if resource is not complete, re-fetch it
|
|
82
86
|
}
|
|
83
87
|
|
|
84
88
|
return new Promise(async resolve => {
|
|
@@ -122,14 +126,31 @@ class Store {
|
|
|
122
126
|
async fetchAuthn(iri, options) {
|
|
123
127
|
let authenticated = false;
|
|
124
128
|
if (this.session) authenticated = await this.session;
|
|
125
|
-
|
|
129
|
+
|
|
130
|
+
if (this.fetch && authenticated) {
|
|
131
|
+
// authenticated
|
|
132
|
+
return this.fetch.then(fn => fn(iri, options));
|
|
133
|
+
} else {
|
|
134
|
+
// anonymous
|
|
135
|
+
if (options.headers) options.headers = this._convertHeaders(options.headers);
|
|
136
|
+
return fetch(iri, options).then(function (response) {
|
|
137
|
+
if (options.method === "PURGE" && !response.ok && response.status === 404) {
|
|
138
|
+
const err = new Error("PURGE call is returning 404");
|
|
139
|
+
throw err;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return response;
|
|
143
|
+
});
|
|
144
|
+
}
|
|
126
145
|
}
|
|
127
146
|
|
|
128
147
|
async fetchData(id, context = {}, idParent = "") {
|
|
129
148
|
const iri = this._getAbsoluteIri(id, context, idParent);
|
|
130
149
|
|
|
131
|
-
const headers = this.headers
|
|
132
|
-
|
|
150
|
+
const headers = { ...this.headers,
|
|
151
|
+
'accept-language': this._getLanguage()
|
|
152
|
+
}; // console.log("Request Headers:", headers);
|
|
153
|
+
|
|
133
154
|
return this.fetchAuthn(iri, {
|
|
134
155
|
method: 'GET',
|
|
135
156
|
headers: headers,
|
|
@@ -195,11 +216,19 @@ class Store {
|
|
|
195
216
|
await this.cacheGraph(key, resourceProxy, clientContext, parentContext, parentId);
|
|
196
217
|
}
|
|
197
218
|
}
|
|
219
|
+
/**
|
|
220
|
+
* Update fetch
|
|
221
|
+
* @param method - 'POST', 'PATCH', 'PUT', '_LOCAL'
|
|
222
|
+
* @param resource - resource to send
|
|
223
|
+
* @param id - uri to update
|
|
224
|
+
* @returns - object
|
|
225
|
+
*/
|
|
226
|
+
|
|
198
227
|
|
|
199
228
|
async _fetch(method, resource, id) {
|
|
200
|
-
if (method !== '_LOCAL') return
|
|
229
|
+
if (method !== '_LOCAL') return this.fetchAuthn(id, {
|
|
201
230
|
method: method,
|
|
202
|
-
headers:
|
|
231
|
+
headers: this.headers,
|
|
203
232
|
body: JSON.stringify(resource),
|
|
204
233
|
credentials: 'include'
|
|
205
234
|
});
|
|
@@ -218,11 +247,15 @@ class Store {
|
|
|
218
247
|
|
|
219
248
|
const expandedId = this._getExpandedId(id, context);
|
|
220
249
|
|
|
221
|
-
return this._fetch(method, resource, id).then(response => {
|
|
250
|
+
return this._fetch(method, resource, id).then(async response => {
|
|
222
251
|
if (response.ok) {
|
|
223
252
|
var _response$headers;
|
|
224
253
|
|
|
225
|
-
if (method !== '_LOCAL')
|
|
254
|
+
if (method !== '_LOCAL') {
|
|
255
|
+
// await this.purge(id);
|
|
256
|
+
this.clearCache(expandedId);
|
|
257
|
+
} // clear cache
|
|
258
|
+
|
|
226
259
|
|
|
227
260
|
this.getData(expandedId, resource['@context']).then(async () => {
|
|
228
261
|
// re-fetch data
|
|
@@ -378,6 +411,41 @@ class Store {
|
|
|
378
411
|
async patch(resource, id) {
|
|
379
412
|
return this._updateResource('PATCH', resource, id);
|
|
380
413
|
}
|
|
414
|
+
/**
|
|
415
|
+
* Send a PURGE request to remove a resource from REDIS AD cache
|
|
416
|
+
* @param id - uri of the resource to patch
|
|
417
|
+
*
|
|
418
|
+
* @returns id of the edited resource
|
|
419
|
+
*/
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
async purge(id) {
|
|
423
|
+
// console.log('Purging resource ' + id);
|
|
424
|
+
await this.fetchAuthn(id, {
|
|
425
|
+
method: "PURGE",
|
|
426
|
+
headers: this.headers
|
|
427
|
+
}).catch(function (error) {
|
|
428
|
+
console.warn('No purge method allowed: ' + error);
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
try {
|
|
432
|
+
const fullURL = new URL(id);
|
|
433
|
+
var pathArray = fullURL.pathname.split('/');
|
|
434
|
+
var containerUrl = fullURL.origin + '/' + pathArray[1] + '/';
|
|
435
|
+
const headers = { ...this.headers,
|
|
436
|
+
'X-Cache-Purge-Match': 'startswith'
|
|
437
|
+
};
|
|
438
|
+
await this.fetchAuthn(containerUrl, {
|
|
439
|
+
method: "PURGE",
|
|
440
|
+
headers: headers
|
|
441
|
+
}).catch(function (error) {
|
|
442
|
+
console.warn('No purge method allowed: ' + error);
|
|
443
|
+
});
|
|
444
|
+
} catch (error) {
|
|
445
|
+
console.warn('The resource ID is not a complete URL: ' + error);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
381
449
|
/**
|
|
382
450
|
* Send a DELETE request to delete a resource
|
|
383
451
|
* @param id - uri of the resource to delete
|
|
@@ -394,12 +462,29 @@ class Store {
|
|
|
394
462
|
method: 'DELETE',
|
|
395
463
|
headers: this.headers,
|
|
396
464
|
credentials: 'include'
|
|
397
|
-
});
|
|
465
|
+
}); // await this.purge(id);
|
|
466
|
+
|
|
398
467
|
const resourcesToNotify = this.subscriptionIndex.get(expandedId) || [];
|
|
399
468
|
const resourcesToRefresh = this.subscriptionVirtualContainersIndex.get(expandedId) || [];
|
|
400
469
|
this.refreshResources([...resourcesToNotify, ...resourcesToRefresh]).then(resourceIds => this.notifyResources(resourceIds));
|
|
401
470
|
return deleted;
|
|
402
471
|
}
|
|
472
|
+
/**
|
|
473
|
+
* Convert headers object to Headers
|
|
474
|
+
* @param headersObject - object
|
|
475
|
+
* @returns {Headers}
|
|
476
|
+
*/
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
_convertHeaders(headersObject) {
|
|
480
|
+
const headers = new Headers();
|
|
481
|
+
|
|
482
|
+
for (const [key, value] of Object.entries(headersObject)) {
|
|
483
|
+
headers.set(key, value);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
return headers;
|
|
487
|
+
}
|
|
403
488
|
|
|
404
489
|
_getExpandedId(id, context) {
|
|
405
490
|
return context && Object.keys(context) ? ContextParser.expandTerm(id, context) : id;
|
|
@@ -600,11 +685,12 @@ class CustomGetter {
|
|
|
600
685
|
* @param id
|
|
601
686
|
* @param context
|
|
602
687
|
* @param iriParent
|
|
688
|
+
* @param forceFetch
|
|
603
689
|
*/
|
|
604
690
|
|
|
605
691
|
|
|
606
|
-
async getResource(id, context, iriParent) {
|
|
607
|
-
return store.getData(id, context, iriParent);
|
|
692
|
+
async getResource(id, context, iriParent, forceFetch = false) {
|
|
693
|
+
return store.getData(id, context, iriParent, undefined, forceFetch);
|
|
608
694
|
}
|
|
609
695
|
/**
|
|
610
696
|
* Return true if the resource is a container
|
|
@@ -687,8 +773,16 @@ class CustomGetter {
|
|
|
687
773
|
return Object.keys(this.resource).filter(p => !p.startsWith('@')).length > 0;
|
|
688
774
|
}
|
|
689
775
|
|
|
690
|
-
getPermissions() {
|
|
691
|
-
const
|
|
776
|
+
async getPermissions() {
|
|
777
|
+
const permissionPredicate = this.getExpandedPredicate("permissions");
|
|
778
|
+
let permissions = this.resource[permissionPredicate];
|
|
779
|
+
|
|
780
|
+
if (!permissions) {
|
|
781
|
+
// if no permission, re-fetch data
|
|
782
|
+
await this.getResource(this.resourceId, this.clientContext, this.parentId, true);
|
|
783
|
+
permissions = this.resource[permissionPredicate];
|
|
784
|
+
}
|
|
785
|
+
|
|
692
786
|
return permissions ? permissions.map(perm => ContextParser.expandTerm(perm.mode['@type'], this.serverContext, true)) : [];
|
|
693
787
|
}
|
|
694
788
|
/**
|
|
@@ -732,8 +826,9 @@ class CustomGetter {
|
|
|
732
826
|
|
|
733
827
|
switch (property) {
|
|
734
828
|
case '@id':
|
|
735
|
-
return this.getCompactedIri(this.resource['@id']);
|
|
736
|
-
|
|
829
|
+
if (this.resource['@id']) return this.getCompactedIri(this.resource['@id']); // Compact @id if possible
|
|
830
|
+
else console.log(this.resource, this.resource['@id']);
|
|
831
|
+
return;
|
|
737
832
|
|
|
738
833
|
case '@type':
|
|
739
834
|
return this.resource['@type'];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["store.ts"],"names":["JSONLDContextParser","PubSub","ContextParser","myParser","base_context","rdf","rdfs","ldp","foaf","name","acl","permissions","mode","geo","lat","lng","Store","constructor","storeOptions","id","resolve","handler","event","detail","resource","document","removeEventListener","cache","Map","subscriptionIndex","subscriptionVirtualContainersIndex","loadingList","Set","headers","Headers","set","fetch","fetchMethod","session","getData","context","idParent","localData","has","get","isFullResource","Promise","addEventListener","resolveResource","add","clientContext","parse","_isLocalId","fetchData","error","console","delete","serverContext","resourceProxy","CustomGetter","getProxy","cacheGraph","dispatchEvent","CustomEvent","fetchAuthn","iri","options","authenticated","then","fn","_getAbsoluteIri","_getLanguage","method","credentials","response","ok","json","key","parentContext","parentId","properties","merge","getSubObjects","res","newParentContext","getChildren","cacheChildrenPromises","subscribeResourceTo","push","all","match","_fetch","body","JSON","stringify","store","clearCache","_updateResource","includes","Error","expandedId","_getExpandedId","nestedResources","getNestedResources","resourcesToRefresh","resourcesToNotify","refreshResources","resourceIds","notifyResources","filter","resourceWithContexts","map","resourceId","publish","cachedResource","isContainer","nestedProperties","excludeKeys","p","Object","keys","forEach","child","setLocalData","post","put","patch","deleted","expandTerm","startsWith","nestedResourceId","existingSubscriptions","subscribeVirtualContainerTo","virtualContainerId","parentIri","URL","location","href","_resourceIsComplete","length","localStorage","getItem","window","navigator","language","slice","selectLanguage","selectedLanguageCode","setItem","sibStore","sibAuth","querySelector","sibAuthDefined","customElements","whenDefined","localName","getFetch","Symbol","toPrimitive","expandProperties","prop","objectReplaceProperty","object","oldProp","newProp","defineProperty","getOwnPropertyDescriptor","path","path1","split","path2","value","getResource","getExpandedPredicate","e","lastPath1El","pop","unshift","undefined","join","iriParent","getProperties","getCompactedPredicate","getLdpContains","children","subObjects","property","isFullNestedResource","getResourceData","getPermissions","perm","compactIri","getCompactedIri","toString","Proxy","bind"],"mappings":";;;;AAAA,OAAOA,mBAAP,MAAgC,uBAAhC,C,CACA;;AACA,OAAOC,MAAP,MAAmB,mCAAnB;AAGA,MAAMC,aAAa,GAAGF,mBAAmB,CAACE,aAA1C;AACA,MAAMC,QAAQ,GAAG,IAAID,aAAJ,EAAjB;AAEA,OAAO,MAAME,YAAY,GAAG;AAC1B,YAAU,2BADgB;AAE1BC,EAAAA,GAAG,EAAE,6CAFqB;AAG1BC,EAAAA,IAAI,EAAE,uCAHoB;AAI1BC,EAAAA,GAAG,EAAE,2BAJqB;AAK1BC,EAAAA,IAAI,EAAE,4BALoB;AAM1BC,EAAAA,IAAI,EAAE,YANoB;AAO1BC,EAAAA,GAAG,EAAE,gCAPqB;AAQ1BC,EAAAA,WAAW,EAAE,mBARa;AAS1BC,EAAAA,IAAI,EAAE,UAToB;AAU1BC,EAAAA,GAAG,EAAE,0CAVqB;AAW1BC,EAAAA,GAAG,EAAE,SAXqB;AAY1BC,EAAAA,GAAG,EAAE;AAZqB,CAArB;;AAeP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AP;;AACF,eAAK,cAAL;AACE,mBAAO,KAAKE,cAAL,EAAP;AAA8B;;AAChC,eAAK,aAAL;AACE,mBAAO,KAAKM,cAAL,EAAP;AAA8B;;AAChC,eAAK,eAAL;AACE,mBAAO,KAAK3I,aAAZ;AAA2B;;AAC7B,eAAK,MAAL;AACE;;AACF;AACE,mBAAO1B,QAAQ,CAACoB,GAAT,CAAa8I,QAAb,CAAP;AAhBJ;AAkBD;AAvBoB,KAAhB,CAAP;AAyBD;;AA7MgB","sourcesContent":["import JSONLDContextParser from 'jsonld-context-parser';\n//@ts-ignore\nimport PubSub from 'https://cdn.skypack.dev/pubsub-js';\nimport type { Resource } from '../../mixins/interfaces';\n\nconst ContextParser = JSONLDContextParser.ContextParser;\nconst myParser = new ContextParser();\n\nexport const base_context = {\n '@vocab': 'http://happy-dev.fr/owl/#',\n rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\n rdfs: 'http://www.w3.org/2000/01/rdf-schema#',\n ldp: 'http://www.w3.org/ns/ldp#',\n foaf: 'http://xmlns.com/foaf/0.1/',\n name: 'rdfs:label',\n acl: 'http://www.w3.org/ns/auth/acl#',\n permissions: 'acl:accessControl',\n mode: 'acl:mode',\n geo: \"http://www.w3.org/2003/01/geo/wgs84_pos#\",\n lat: \"geo:lat\",\n lng: \"geo:long\"\n};\n\nclass Store {\n cache: Map<string, any>;\n subscriptionIndex: Map<string, any>; // index of all the containers per resource\n subscriptionVirtualContainersIndex: Map<string, any>; // index of all the containers per resource\n loadingList: Set<String>;\n headers: Headers;\n fetch: Promise<any> | undefined;\n session: Promise<any> | undefined;\n\n constructor(private storeOptions: StoreOptions) {\n this.cache = new Map();\n this.subscriptionIndex = new Map();\n this.subscriptionVirtualContainersIndex = new Map();\n this.loadingList = new Set();\n this.headers = new Headers();\n this.headers.set('Content-Type', 'application/ld+json');\n this.fetch = this.storeOptions.fetchMethod;\n this.session = this.storeOptions.session;\n }\n\n /**\n * Fetch data and cache it\n * @param id - uri of the resource to fetch\n * @param context - context used to expand id and predicates when accessing the resource\n * @param idParent - uri of the parent caller used to expand uri for local files\n *\n * @returns The fetched resource\n *\n * @async\n */\n\n async getData(id: string, context:any = {}, idParent = \"\", localData?: object): Promise<Resource|null> {\n if (localData == null && this.cache.has(id) && !this.loadingList.has(id)) {\n const resource = this.get(id);\n if (resource && resource.isFullResource()) return resource; // if resource is not complete, re-fetch it\n }\n\n return new Promise(async (resolve) => {\n document.addEventListener('resourceReady', this.resolveResource(id, resolve));\n\n if (this.loadingList.has(id)) return;\n this.loadingList.add(id);\n\n // Generate proxy\n const clientContext = await myParser.parse(context);\n let resource: any = null;\n if(this._isLocalId(id)) {\n if(localData == null) localData = {};\n localData[\"@id\"] = id;\n resource = localData;\n } else try {\n resource = localData || await this.fetchData(id, clientContext, idParent);\n } catch (error) { console.error(error) }\n if (!resource) {\n this.loadingList.delete(id);\n resolve(null);\n return;\n }\n const serverContext = await myParser.parse([resource['@context'] || {}]);\n const resourceProxy = new CustomGetter(id, resource, clientContext, serverContext, idParent).getProxy();\n\n // Cache proxy\n await this.cacheGraph(id, resourceProxy, clientContext, serverContext, idParent || id);\n this.loadingList.delete(id);\n document.dispatchEvent(new CustomEvent('resourceReady', { detail: { id: id, resource: this.get(id) } }));\n });\n }\n\n async fetchAuthn(iri: string, options: any) {\n let authenticated = false;\n if (this.session) authenticated = await this.session;\n return (this.fetch && authenticated)\n ? this.fetch.then(fn => fn(iri, options))\n : fetch(iri, options);\n }\n\n async fetchData(id: string, context = {}, idParent = \"\") {\n const iri = this._getAbsoluteIri(id, context, idParent);\n const headers = this.headers;\n headers.set('accept-language', this._getLanguage());\n return this.fetchAuthn(iri, {\n method: 'GET',\n headers: headers,\n credentials: 'include'\n }).then(response => {\n if (!response.ok) return;\n return response.json()\n })\n }\n\n async cacheGraph(key: string, resource: any, clientContext: object, parentContext: object, parentId: string) {\n if (resource.properties) { // if proxy, cache it\n if (this.get(key)) { // if already cached, merge data\n this.cache.get(key).merge(resource);\n } else { // else, put in cache\n this.cache.set(key, resource);\n }\n }\n\n // Cache nested resources\n if (resource.getSubObjects) {\n for (let res of resource.getSubObjects()) {\n let newParentContext = parentContext;\n // If additional context in resource, use it to expand properties\n if (res['@context']) newParentContext = await myParser.parse({ ...parentContext, ...res['@context'] });\n const resourceProxy = new CustomGetter(res['@id'], res, clientContext, newParentContext, parentId).getProxy();\n // this.subscribeResourceTo(resource['@id'], res['@id']); // removed to prevent useless updates\n await this.cacheGraph(res['@id'], resourceProxy, clientContext, parentContext, parentId);\n }\n }\n\n // Cache children of container\n if (resource['@type'] == \"ldp:Container\" && resource.getChildren) {\n const cacheChildrenPromises: Promise<void>[] = [];\n for (let res of resource.getChildren()) {\n this.subscribeResourceTo(resource['@id'], res['@id']);\n cacheChildrenPromises.push(this.cacheGraph(res['@id'], res, clientContext, parentContext, parentId))\n }\n await Promise.all(cacheChildrenPromises);\n return;\n }\n\n // Create proxy, (fetch data) and cache resource\n if (resource['@id'] && !resource.properties) {\n if (resource['@id'].match(/^b\\d+$/)) return; // not anonymous node\n // Fetch data if\n if (resource['@type'] === \"sib:federatedContainer\" && resource['@cache'] !== 'false') { // if object is federated container\n await this.getData(resource['@id'], clientContext, parentId); // then init graph\n return;\n }\n const resourceProxy = new CustomGetter(resource['@id'], resource, clientContext, parentContext, parentId).getProxy();\n await this.cacheGraph(key, resourceProxy, clientContext, parentContext, parentId);\n }\n }\n\n async _fetch(method: string, resource: object, id: string): Promise<any> {\n if(method !== '_LOCAL')\n return fetch(id, {\n method: method,\n headers: await this.headers,\n body: JSON.stringify(resource),\n credentials: 'include'\n })\n\n const resourceProxy = store.get(id);\n const clientContext = resourceProxy ? resourceProxy.clientContext : resource['@context']\n this.clearCache(id);\n await this.getData(id, clientContext, '', resource);\n return {ok: true}\n }\n\n async _updateResource(method: string, resource: object, id: string) {\n if (!['POST', 'PUT', 'PATCH', '_LOCAL'].includes(method)) throw new Error('Error: method not allowed');\n\n const context = await myParser.parse([resource['@context'] || {}]); // parse context before expandTerm\n const expandedId = this._getExpandedId(id, context);\n return this._fetch(method, resource, id).then(response => {\n if (response.ok) {\n if(method !== '_LOCAL') this.clearCache(expandedId); // clear cache\n this.getData(expandedId, resource['@context']).then(async () => { // re-fetch data\n const nestedResources = await this.getNestedResources(resource, id);\n const resourcesToRefresh = this.subscriptionVirtualContainersIndex.get(expandedId) || [];\n const resourcesToNotify = this.subscriptionIndex.get(expandedId) || [];\n\n return this.refreshResources([...nestedResources, ...resourcesToRefresh]) // refresh related resources\n .then(resourceIds => this.notifyResources([expandedId, ...resourceIds, ...resourcesToNotify])); // notify components\n });\n return response.headers?.get('Location') || null;\n } else {\n throw response;\n }\n });\n }\n\n /**\n * Clear cache and refetch data for a list of ids\n * @param resourceIds -\n * @returns - all the resource ids\n */\n async refreshResources(resourceIds: string[]) {\n resourceIds = [...new Set(resourceIds.filter(id => this.cache.has(id)))]; // remove duplicates and not cached resources\n const resourceWithContexts = resourceIds.map(resourceId => ({ \"id\": resourceId, \"context\": store.get(resourceId)?.clientContext }));\n for (const resource of resourceWithContexts) {\n if (!this._isLocalId(resource.id)) this.clearCache(resource.id);\n }\n await Promise.all(resourceWithContexts.map(({ id, context }) => this.getData(id, context || base_context)))\n return resourceIds;\n }\n /**\n * Notifies all components for a list of ids\n * @param resourceIds -\n */\n async notifyResources(resourceIds: string[]) {\n resourceIds = [...new Set(resourceIds)]; // remove duplicates\n for (const id of resourceIds) PubSub.publish(id);\n }\n\n /**\n * Return id of nested properties of a resource\n * @param resource - object\n * @param id - string\n */\n async getNestedResources(resource: object, id: string) {\n const cachedResource = store.get(id);\n if (!cachedResource || cachedResource.isContainer()) return [];\n let nestedProperties:any[] = [];\n const excludeKeys = ['@context'];\n for (let p of Object.keys(resource)) {\n if (resource[p]\n && typeof resource[p] === 'object'\n && !excludeKeys.includes(p)\n && resource[p]['@id']) {\n nestedProperties.push(resource[p]['@id']);\n }\n }\n return nestedProperties;\n }\n\n /**\n * Returns the resource with id from the cache\n * @param id - id of the resource to retrieve\n *\n * @returns Resource (Proxy) if in the cache, null otherwise\n */\n get(id: string): Resource | null {\n return this.cache.get(id) || null;\n }\n\n\n /**\n * Removes a resource from the cache\n * @param id - id of the resource to remove from the cache\n */\n clearCache(id: string): void {\n if (this.cache.has(id)) {\n // For federation, clear each source\n const resource = this.cache.get(id);\n if (resource['@type'] === 'ldp:Container') {\n resource['ldp:contains'].forEach((child: object) => {\n if (child && child['@type'] === 'ldp:Container') this.cache.delete(child['@id'])\n })\n }\n\n this.cache.delete(id);\n }\n }\n\n /**\n * Send data to create a local resource in a container\n * @param resource - resource to create\n * @param id - uri of the container to add resource. should start with ``\n *\n * @returns id of the posted resource\n */\n async setLocalData(resource: object, id: string): Promise<string | null> {\n return this._updateResource('_LOCAL', resource, id);\n }\n\n /**\n * Send a POST request to create a resource in a container\n * @param resource - resource to create\n * @param id - uri of the container to add resource\n *\n * @returns id of the posted resource\n */\n async post(resource: object, id: string): Promise<string | null> {\n return this._updateResource('POST', resource, id);\n }\n\n /**\n * Send a PUT request to edit a resource\n * @param resource - resource data to send\n * @param id - uri of the resource to edit\n *\n * @returns id of the edited resource\n */\n async put(resource: object, id: string): Promise<string | null> {\n return this._updateResource('PUT', resource, id);\n }\n\n /**\n * Send a PATCH request to edit a resource\n * @param resource - resource data to send\n * @param id - uri of the resource to patch\n *\n * @returns id of the edited resource\n */\n async patch(resource: object, id: string): Promise<string | null> {\n return this._updateResource('PATCH', resource, id);\n }\n\n /**\n * Send a DELETE request to delete a resource\n * @param id - uri of the resource to delete\n * @param context - can be used to expand id\n *\n * @returns id of the deleted resource\n */\n async delete(id: string, context: object = {}) {\n const expandedId = this._getExpandedId(id, context);\n const deleted = await this.fetchAuthn(expandedId, {\n method: 'DELETE',\n headers: this.headers,\n credentials: 'include'\n });\n\n const resourcesToNotify = this.subscriptionIndex.get(expandedId) || [];\n const resourcesToRefresh = this.subscriptionVirtualContainersIndex.get(expandedId) || [];\n\n this.refreshResources([...resourcesToNotify, ...resourcesToRefresh])\n .then(resourceIds => this.notifyResources(resourceIds));\n\n return deleted;\n }\n\n _getExpandedId(id: string, context: object) {\n return (context && Object.keys(context)) ? ContextParser.expandTerm(id, context) : id;\n }\n\n _isLocalId(id: string) {\n return id.startsWith('store://local.');\n }\n\n /**\n * Make a resource listen changes of another one\n * @param resourceId - id of the resource which needs to be updated\n * @param nestedResourceId - id of the resource which will change\n */\n subscribeResourceTo(resourceId: string, nestedResourceId: string) {\n const existingSubscriptions = this.subscriptionIndex.get(nestedResourceId) || [];\n this.subscriptionIndex.set(nestedResourceId, [...new Set([...existingSubscriptions, resourceId])])\n }\n\n /**\n * Make a virtual container listen for changes of a resource\n * @param virtualContainerId - id of the container which needs to be updated\n * @param nestedResourceId - id of the resource which will change\n */\n subscribeVirtualContainerTo(virtualContainerId: string, nestedResourceId: string) {\n const existingSubscriptions = this.subscriptionVirtualContainersIndex.get(nestedResourceId) || [];\n this.subscriptionVirtualContainersIndex.set(nestedResourceId, [...new Set([...existingSubscriptions, virtualContainerId])])\n }\n\n /**\n * Return absolute IRI of the resource\n * @param id\n * @param context\n * @param parentId\n */\n _getAbsoluteIri(id: string, context: object, parentId: string): string {\n let iri = ContextParser.expandTerm(id, context); // expand if reduced ids\n if (parentId) { // and get full URL from parent caller for local files\n let parentIri = new URL(parentId, document.location.href).href;\n iri = new URL(iri, parentIri).href;\n } else {\n iri = new URL(iri, document.location.href).href;\n }\n return iri;\n }\n\n /**\n * Check if object is a full resource\n * @param resource\n */\n _resourceIsComplete(resource: object) {\n return !!(Object.keys(resource).filter(p => !p.startsWith('@')).length > 0 && resource['@id'])\n }\n\n /**\n * Return language of the users\n */\n _getLanguage() {\n return localStorage.getItem('language') || window.navigator.language.slice(0,2);\n }\n\n /**\n * Save the preferred language of the user\n * @param selectedLanguageCode\n */\n selectLanguage(selectedLanguageCode: string) {\n localStorage.setItem('language', selectedLanguageCode);\n }\n\n resolveResource = function(id: string, resolve) {\n const handler = function(event) {\n if (event.detail.id === id) {\n resolve(event.detail.resource);\n // TODO : callback\n document.removeEventListener('resourceReady', handler);\n }\n };\n return handler;\n };\n}\n\nlet store: Store;\nif (window.sibStore) {\n store = window.sibStore;\n} else {\n const sibAuth = document.querySelector('sib-auth');\n const storeOptions: StoreOptions = {}\n\n if (sibAuth) {\n const sibAuthDefined = customElements.whenDefined(sibAuth.localName);\n storeOptions.session = sibAuthDefined.then(() => (sibAuth as any).session)\n storeOptions.fetchMethod = sibAuthDefined.then(() => (sibAuth as any).getFetch())\n }\n\n store = new Store(storeOptions);\n window.sibStore = store;\n}\n\nexport {\n store\n};\n\n\nclass CustomGetter {\n resource: any; // content of the requested resource\n resourceId: string;\n clientContext: object; // context given by the app\n serverContext: object; // context given by the server\n parentId: string; // id of the parent resource, used to get the absolute url of the current resource\n\n constructor(resourceId: string, resource: object, clientContext: object, serverContext: object = {}, parentId: string = \"\") {\n this.clientContext = clientContext;\n this.serverContext = serverContext;\n this.parentId = parentId;\n this.resource = this.expandProperties({ ...resource }, serverContext);\n this.resourceId = resourceId;\n }\n\n /**\n * Expand all predicates of a resource with a given context\n * @param resource: object\n * @param context: object\n */\n expandProperties(resource: object, context: object | string) {\n for (let prop of Object.keys(resource)) {\n if (!prop) continue;\n this.objectReplaceProperty(resource, prop, ContextParser.expandTerm(prop, context as JSONLDContextParser.IJsonLdContextNormalized, true));\n }\n return resource\n }\n\n /**\n * Change the key of an object\n * @param object: object\n * @param oldProp: string - current key\n * @param newProp: string - new key to set\n */\n objectReplaceProperty(object: object, oldProp: string, newProp: string) {\n if (newProp !== oldProp) {\n Object.defineProperty(\n object,\n newProp,\n Object.getOwnPropertyDescriptor(object, oldProp) || ''\n );\n delete object[oldProp];\n }\n }\n\n /**\n * Get the property of a resource for a given path\n * @param path: string\n */\n async get(path: any) {\n if (!path) return;\n const path1: string[] = path.split('.');\n const path2: string[] = [];\n let value: any;\n if (!this.isFullResource()) { // if resource is not complete, fetch it first\n await this.getResource(this.resourceId, this.clientContext, this.parentId);\n }\n while (true) {\n try {\n value = this.resource[this.getExpandedPredicate(path1[0])];\n } catch (e) { break }\n\n if (path1.length <= 1) break; // no dot path\n const lastPath1El = path1.pop();\n if(lastPath1El) path2.unshift(lastPath1El);\n }\n if (path2.length === 0) { // end of the path\n if (!value || !value['@id']) return value; // no value or not a resource\n return await this.getResource(value['@id'], this.clientContext, this.parentId || this.resourceId); // return complete resource\n }\n if (!value) return undefined;\n let resource = await this.getResource(value['@id'], this.clientContext, this.parentId || this.resourceId);\n\n store.subscribeResourceTo(this.resourceId, value['@id']);\n return resource ? await resource[path2.join('.')] : undefined; // return value\n }\n\n /**\n * Cache resource in the store, and return the created proxy\n * @param id\n * @param context\n * @param iriParent\n */\n async getResource(id: string, context: object, iriParent: string): Promise<Resource | null> {\n return store.getData(id, context, iriParent);\n }\n\n /**\n * Return true if the resource is a container\n */\n isContainer(): boolean {\n return this.resource[\"@type\"] == \"ldp:Container\" || this.resource[\"@type\"] == \"sib:federatedContainer\";\n }\n\n /**\n * Get all properties of a resource\n */\n getProperties(): string[] {\n return Object.keys(this.resource).map(prop => this.getCompactedPredicate(prop));\n }\n\n /**\n * Get children of container as objects\n */\n getChildren(): object[] {\n return this.resource[this.getExpandedPredicate(\"ldp:contains\")] || [];\n }\n\n /**\n * Get children of container as Proxys\n */\n getLdpContains(): CustomGetter[] {\n const children = this.resource[this.getExpandedPredicate(\"ldp:contains\")];\n return children ? children.map((res: object) => store.get(res['@id'])) : [];\n }\n\n /**\n * Get all nested resource or containers which contains datas\n */\n getSubObjects() {\n let subObjects: any = [];\n for (let p of Object.keys(this.resource)) {\n let property = this.resource[p];\n if (!this.isFullNestedResource(property)) continue; // if not a resource, stop\n if (property['@type'] == \"ldp:Container\" &&\n (property['ldp:contains'] == undefined ||\n (property['ldp:contains'].length >= 1 && !this.isFullNestedResource(property['ldp:contains'][0])))\n ) continue; // if not a full container\n subObjects.push(property)\n }\n return subObjects;\n }\n\n merge(resource: CustomGetter) {\n this.resource = {...this.getResourceData(), ...resource.getResourceData()}\n }\n\n getResourceData(): object { return this.resource }\n\n /**\n * return true if prop is a resource with an @id and some properties\n * @param prop\n */\n isFullNestedResource(prop: any): boolean {\n return prop &&\n typeof prop == \"object\" &&\n prop['@id'] != undefined &&\n Object.keys(prop).filter(p => !p.startsWith('@')).length > 0;\n }\n /**\n * return true resource seems complete\n * @param prop\n */\n isFullResource(): boolean {\n return Object.keys(this.resource).filter(p => !p.startsWith('@')).length > 0;\n }\n\n getPermissions(): string[] {\n const permissions = this.resource[this.getExpandedPredicate(\"permissions\")];\n return permissions ? permissions.map(perm => ContextParser.expandTerm(perm.mode['@type'], this.serverContext, true)) : [];\n }\n\n /**\n * Remove the resource from the cache\n */\n clearCache(): void {\n store.clearCache(this.resourceId);\n }\n\n getExpandedPredicate(property: string) { return ContextParser.expandTerm(property, this.clientContext, true) }\n getCompactedPredicate(property: string) { return ContextParser.compactIri(property, this.clientContext, true) }\n getCompactedIri(id: string) { return ContextParser.compactIri(id, this.clientContext) }\n toString() { return this.getCompactedIri(this.resource['@id']) }\n [Symbol.toPrimitive]() { return this.getCompactedIri(this.resource['@id']) }\n\n\n /**\n * Returns a Proxy which handles the different get requests\n */\n getProxy() {\n return new Proxy(this, {\n get: (resource, property) => {\n if (!this.resource) return undefined;\n if (typeof resource[property] === 'function') return resource[property].bind(resource)\n\n switch (property) {\n case '@id':\n return this.getCompactedIri(this.resource['@id']); // Compact @id if possible\n case '@type':\n return this.resource['@type']; // return synchronously\n case 'properties':\n return this.getProperties();\n case 'ldp:contains':\n return this.getLdpContains(); // returns standard arrays synchronously\n case 'permissions':\n return this.getPermissions(); // get expanded permissions\n case 'clientContext':\n return this.clientContext; // get saved client context to re-fetch easily a resource\n case 'then':\n return;\n default:\n return resource.get(property);\n }\n }\n })\n }\n}"]}
|
|
1
|
+
{"version":3,"sources":["store.ts"],"names":["JSONLDContextParser","PubSub","ContextParser","myParser","base_context","rdf","rdfs","ldp","foaf","name","acl","permissions","mode","geo","lat","lng","Store","constructor","storeOptions","id","resolve","handler","event","detail","resource","document","removeEventListener","cache","Map","subscriptionIndex","subscriptionVirtualContainersIndex","loadingList","Set","headers","fetch","fetchMethod","session","getData","context","idParent","localData","forceFetch","has","get","isFullResource","Promise","addEventListener","resolveResource","add","clientContext","parse","_isLocalId","fetchData","error","console","delete","serverContext","resourceProxy","CustomGetter","getProxy","cacheGraph","dispatchEvent","CustomEvent","fetchAuthn","iri","options","authenticated","then","fn","_convertHeaders","response","method","ok","status","err","Error","_getAbsoluteIri","_getLanguage","credentials","json","key","parentContext","parentId","properties","merge","set","getSubObjects","res","newParentContext","getChildren","cacheChildrenPromises","subscribeResourceTo","push","all","match","_fetch","body","JSON","stringify","store","clearCache","_updateResource","includes","expandedId","_getExpandedId","nestedResources","getNestedResources","resourcesToRefresh","resourcesToNotify","refreshResources","resourceIds","notifyResources","filter","resourceWithContexts","map","resourceId","publish","cachedResource","isContainer","nestedProperties","excludeKeys","p","Object","keys","forEach","child","setLocalData","post","put","patch","purge","catch","warn","fullURL","URL","pathArray","pathname","split","containerUrl","origin","deleted","headersObject","Headers","value","entries","expandTerm","startsWith","nestedResourceId","existingSubscriptions","subscribeVirtualContainerTo","virtualContainerId","parentIri","location","href","_resourceIsComplete","length","localStorage","getItem","window","navigator","language","slice","selectLanguage","selectedLanguageCode","setItem","sibStore","sibAuth","querySelector","sibAuthDefined","customElements","whenDefined","localName","getFetch","Symbol","toPrimitive","expandProperties","prop","objectReplaceProperty","object","oldProp","newProp","defineProperty","getOwnPropertyDescriptor","path","path1","path2","getResource","getExpandedPredicate","e","lastPath1El","pop","unshift","undefined","join","iriParent","getProperties","getCompactedPredicate","getLdpContains","children","subObjects","property","isFullNestedResource","getResourceData","getPermissions","permissionPredicate","perm","compactIri","getCompactedIri","toString","Proxy","bind","log"],"mappings":";;;;AAAA,OAAOA,mBAAP,MAAgC,uBAAhC,C,CACA;;AACA,OAAOC,MAAP,MAAmB,mCAAnB;AAGA,MAAMC,aAAa,GAAGF,mBAAmB,CAACE,aAA1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ACgL,QAAD,CAAR,CAAmBU,IAAnB,CAAwB1L,QAAxB,CAAP;;AAE9C,gBAAQgL,QAAR;AACE,eAAK,KAAL;AACE,gBAAI,KAAKhL,QAAL,CAAc,KAAd,CAAJ,EACE,OAAO,KAAKuL,eAAL,CAAqB,KAAKvL,QAAL,CAAc,KAAd,CAArB,CAAP,CADF,CACqD;AADrD,iBAGE8B,OAAO,CAAC6J,GAAR,CAAY,KAAK3L,QAAjB,EAA2B,KAAKA,QAAL,CAAc,KAAd,CAA3B;AACA;;AACJ,eAAK,OAAL;AACE,mBAAO,KAAKA,QAAL,CAAc,OAAd,CAAP;AAA+B;;AACjC,eAAK,YAAL;AACE,mBAAO,KAAK2K,aAAL,EAAP;;AACF,eAAK,cAAL;AACE,mBAAO,KAAKE,cAAL,EAAP;AAA8B;;AAChC,eAAK,aAAL;AACE,mBAAO,KAAKM,cAAL,EAAP;AAA8B;;AAChC,eAAK,eAAL;AACE,mBAAO,KAAK1J,aAAZ;AAA2B;;AAC7B,eAAK,MAAL;AACE;;AACF;AACE,mBAAOzB,QAAQ,CAACmB,GAAT,CAAa6J,QAAb,CAAP;AApBJ;AAsBD;AA3BoB,KAAhB,CAAP;AA6BD;;AAvNgB","sourcesContent":["import JSONLDContextParser from 'jsonld-context-parser';\n//@ts-ignore\nimport PubSub from 'https://cdn.skypack.dev/pubsub-js';\nimport type { Resource } from '../../mixins/interfaces';\n\nconst ContextParser = JSONLDContextParser.ContextParser;\nconst myParser = new ContextParser();\n\nexport const base_context = {\n '@vocab': 'http://happy-dev.fr/owl/#',\n rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\n rdfs: 'http://www.w3.org/2000/01/rdf-schema#',\n ldp: 'http://www.w3.org/ns/ldp#',\n foaf: 'http://xmlns.com/foaf/0.1/',\n name: 'rdfs:label',\n acl: 'http://www.w3.org/ns/auth/acl#',\n permissions: 'acl:accessControl',\n mode: 'acl:mode',\n geo: \"http://www.w3.org/2003/01/geo/wgs84_pos#\",\n lat: \"geo:lat\",\n lng: \"geo:long\"\n};\n\nclass Store {\n cache: Map<string, any>;\n subscriptionIndex: Map<string, any>; // index of all the containers per resource\n subscriptionVirtualContainersIndex: Map<string, any>; // index of all the containers per resource\n loadingList: Set<String>;\n headers: object;\n fetch: Promise<any> | undefined;\n session: Promise<any> | undefined;\n\n constructor(private storeOptions: StoreOptions) {\n this.cache = new Map();\n this.subscriptionIndex = new Map();\n this.subscriptionVirtualContainersIndex = new Map();\n this.loadingList = new Set();\n this.headers = {'Content-Type': 'application/ld+json', 'Cache-Control': 'must-revalidate'};\n this.fetch = this.storeOptions.fetchMethod;\n this.session = this.storeOptions.session;\n }\n\n /**\n * Fetch data and cache it\n * @param id - uri of the resource to fetch\n * @param context - context used to expand id and predicates when accessing the resource\n * @param idParent - uri of the parent caller used to expand uri for local files\n * @param localData - data to put in cache\n * @param forceFetch - force the fetch of data\n *\n * @returns The fetched resource\n *\n * @async\n */\n\n async getData(id: string, context:any = {}, idParent = \"\", localData?: object, forceFetch: boolean = false): Promise<Resource|null> {\n if (localData == null && this.cache.has(id) && !this.loadingList.has(id)) {\n const resource = this.get(id);\n if (resource && resource.isFullResource() && !forceFetch) return resource; // if resource is not complete, re-fetch it\n }\n\n return new Promise(async (resolve) => {\n document.addEventListener('resourceReady', this.resolveResource(id, resolve));\n\n if (this.loadingList.has(id)) return;\n this.loadingList.add(id);\n\n // Generate proxy\n const clientContext = await myParser.parse(context);\n let resource: any = null;\n if(this._isLocalId(id)) {\n if(localData == null) localData = {};\n localData[\"@id\"] = id;\n resource = localData;\n } else try {\n resource = localData || await this.fetchData(id, clientContext, idParent);\n } catch (error) { console.error(error) }\n if (!resource) {\n this.loadingList.delete(id);\n resolve(null);\n return;\n }\n const serverContext = await myParser.parse([resource['@context'] || {}]);\n const resourceProxy = new CustomGetter(id, resource, clientContext, serverContext, idParent).getProxy();\n\n // Cache proxy\n await this.cacheGraph(id, resourceProxy, clientContext, serverContext, idParent || id);\n this.loadingList.delete(id);\n document.dispatchEvent(new CustomEvent('resourceReady', { detail: { id: id, resource: this.get(id) } }));\n });\n }\n\n async fetchAuthn(iri: string, options: any) {\n let authenticated = false;\n if (this.session) authenticated = await this.session;\n\n if (this.fetch && authenticated) { // authenticated\n return this.fetch.then(fn => fn(iri, options))\n } else { // anonymous\n if (options.headers) options.headers = this._convertHeaders(options.headers);\n return fetch(iri, options).then(function(response) {\n if (options.method === \"PURGE\" && !response.ok && response.status === 404) {\n const err = new Error(\"PURGE call is returning 404\");\n throw err;\n }\n return response;\n });\n }\n }\n\n async fetchData(id: string, context = {}, idParent = \"\") {\n const iri = this._getAbsoluteIri(id, context, idParent);\n const headers = { ...this.headers, 'accept-language': this._getLanguage() };\n // console.log(\"Request Headers:\", headers);\n return this.fetchAuthn(iri, {\n method: 'GET',\n headers: headers,\n credentials: 'include'\n }).then(response => {\n if (!response.ok) return;\n return response.json()\n })\n }\n\n async cacheGraph(key: string, resource: any, clientContext: object, parentContext: object, parentId: string) {\n if (resource.properties) { // if proxy, cache it\n if (this.get(key)) { // if already cached, merge data\n this.cache.get(key).merge(resource);\n } else { // else, put in cache\n this.cache.set(key, resource);\n }\n }\n\n // Cache nested resources\n if (resource.getSubObjects) {\n for (let res of resource.getSubObjects()) {\n let newParentContext = parentContext;\n // If additional context in resource, use it to expand properties\n if (res['@context']) newParentContext = await myParser.parse({ ...parentContext, ...res['@context'] });\n const resourceProxy = new CustomGetter(res['@id'], res, clientContext, newParentContext, parentId).getProxy();\n // this.subscribeResourceTo(resource['@id'], res['@id']); // removed to prevent useless updates\n await this.cacheGraph(res['@id'], resourceProxy, clientContext, parentContext, parentId);\n }\n }\n\n // Cache children of container\n if (resource['@type'] == \"ldp:Container\" && resource.getChildren) {\n const cacheChildrenPromises: Promise<void>[] = [];\n for (let res of resource.getChildren()) {\n this.subscribeResourceTo(resource['@id'], res['@id']);\n cacheChildrenPromises.push(this.cacheGraph(res['@id'], res, clientContext, parentContext, parentId))\n }\n await Promise.all(cacheChildrenPromises);\n return;\n }\n\n // Create proxy, (fetch data) and cache resource\n if (resource['@id'] && !resource.properties) {\n if (resource['@id'].match(/^b\\d+$/)) return; // not anonymous node\n // Fetch data if\n if (resource['@type'] === \"sib:federatedContainer\" && resource['@cache'] !== 'false') { // if object is federated container\n await this.getData(resource['@id'], clientContext, parentId); // then init graph\n return;\n }\n const resourceProxy = new CustomGetter(resource['@id'], resource, clientContext, parentContext, parentId).getProxy();\n await this.cacheGraph(key, resourceProxy, clientContext, parentContext, parentId);\n }\n }\n\n /**\n * Update fetch\n * @param method - 'POST', 'PATCH', 'PUT', '_LOCAL'\n * @param resource - resource to send\n * @param id - uri to update\n * @returns - object\n */\n async _fetch(method: string, resource: object, id: string): Promise<any> {\n if (method !== '_LOCAL')\n return this.fetchAuthn(id, {\n method: method,\n headers: this.headers,\n body: JSON.stringify(resource),\n credentials: 'include'\n });\n\n const resourceProxy = store.get(id);\n const clientContext = resourceProxy ? resourceProxy.clientContext : resource['@context']\n this.clearCache(id);\n await this.getData(id, clientContext, '', resource);\n return {ok: true}\n }\n\n async _updateResource(method: string, resource: object, id: string) {\n if (!['POST', 'PUT', 'PATCH', '_LOCAL'].includes(method)) throw new Error('Error: method not allowed');\n\n const context = await myParser.parse([resource['@context'] || {}]); // parse context before expandTerm\n const expandedId = this._getExpandedId(id, context);\n return this._fetch(method, resource, id).then(async(response) => {\n if (response.ok) {\n if(method !== '_LOCAL') {\n // await this.purge(id);\n this.clearCache(expandedId);\n } // clear cache\n this.getData(expandedId, resource['@context']).then(async () => { // re-fetch data\n const nestedResources = await this.getNestedResources(resource, id);\n const resourcesToRefresh = this.subscriptionVirtualContainersIndex.get(expandedId) || [];\n const resourcesToNotify = this.subscriptionIndex.get(expandedId) || [];\n\n return this.refreshResources([...nestedResources, ...resourcesToRefresh]) // refresh related resources\n .then(resourceIds => this.notifyResources([expandedId, ...resourceIds, ...resourcesToNotify])); // notify components\n });\n return response.headers?.get('Location') || null;\n } else {\n throw response;\n }\n });\n }\n\n /**\n * Clear cache and refetch data for a list of ids\n * @param resourceIds -\n * @returns - all the resource ids\n */\n async refreshResources(resourceIds: string[]) {\n resourceIds = [...new Set(resourceIds.filter(id => this.cache.has(id)))]; // remove duplicates and not cached resources\n const resourceWithContexts = resourceIds.map(resourceId => ({ \"id\": resourceId, \"context\": store.get(resourceId)?.clientContext }));\n for (const resource of resourceWithContexts) {\n if (!this._isLocalId(resource.id)) this.clearCache(resource.id);\n }\n await Promise.all(resourceWithContexts.map(({ id, context }) => this.getData(id, context || base_context)))\n return resourceIds;\n }\n /**\n * Notifies all components for a list of ids\n * @param resourceIds -\n */\n async notifyResources(resourceIds: string[]) {\n resourceIds = [...new Set(resourceIds)]; // remove duplicates\n for (const id of resourceIds) PubSub.publish(id);\n }\n\n /**\n * Return id of nested properties of a resource\n * @param resource - object\n * @param id - string\n */\n async getNestedResources(resource: object, id: string) {\n const cachedResource = store.get(id);\n if (!cachedResource || cachedResource.isContainer()) return [];\n let nestedProperties:any[] = [];\n const excludeKeys = ['@context'];\n for (let p of Object.keys(resource)) {\n if (resource[p]\n && typeof resource[p] === 'object'\n && !excludeKeys.includes(p)\n && resource[p]['@id']) {\n nestedProperties.push(resource[p]['@id']);\n }\n }\n return nestedProperties;\n }\n\n /**\n * Returns the resource with id from the cache\n * @param id - id of the resource to retrieve\n *\n * @returns Resource (Proxy) if in the cache, null otherwise\n */\n get(id: string): Resource | null {\n return this.cache.get(id) || null;\n }\n\n\n /**\n * Removes a resource from the cache\n * @param id - id of the resource to remove from the cache\n */\n clearCache(id: string): void {\n if (this.cache.has(id)) {\n // For federation, clear each source\n const resource = this.cache.get(id);\n if (resource['@type'] === 'ldp:Container') {\n resource['ldp:contains'].forEach((child: object) => {\n if (child && child['@type'] === 'ldp:Container') this.cache.delete(child['@id'])\n })\n }\n\n this.cache.delete(id);\n }\n }\n\n /**\n * Send data to create a local resource in a container\n * @param resource - resource to create\n * @param id - uri of the container to add resource. should start with ``\n *\n * @returns id of the posted resource\n */\n async setLocalData(resource: object, id: string): Promise<string | null> {\n return this._updateResource('_LOCAL', resource, id);\n }\n\n /**\n * Send a POST request to create a resource in a container\n * @param resource - resource to create\n * @param id - uri of the container to add resource\n *\n * @returns id of the posted resource\n */\n async post(resource: object, id: string): Promise<string | null> {\n return this._updateResource('POST', resource, id);\n }\n\n /**\n * Send a PUT request to edit a resource\n * @param resource - resource data to send\n * @param id - uri of the resource to edit\n *\n * @returns id of the edited resource\n */\n async put(resource: object, id: string): Promise<string | null> {\n return this._updateResource('PUT', resource, id);\n }\n\n /**\n * Send a PATCH request to edit a resource\n * @param resource - resource data to send\n * @param id - uri of the resource to patch\n *\n * @returns id of the edited resource\n */\n async patch(resource: object, id: string): Promise<string | null> {\n return this._updateResource('PATCH', resource, id);\n }\n\n /**\n * Send a PURGE request to remove a resource from REDIS AD cache\n * @param id - uri of the resource to patch\n *\n * @returns id of the edited resource\n */\n async purge(id: string) {\n // console.log('Purging resource ' + id);\n await this.fetchAuthn(id, {\n method: \"PURGE\",\n headers: this.headers\n }).catch(function(error) {\n console.warn('No purge method allowed: ' + error)\n });\n\n try {\n const fullURL = new URL(id);\n var pathArray = fullURL.pathname.split('/');\n var containerUrl = fullURL.origin + '/' + pathArray[1] + '/';\n const headers = { ...this.headers, 'X-Cache-Purge-Match': 'startswith' };\n await this.fetchAuthn(containerUrl, {\n method: \"PURGE\",\n headers: headers\n }).catch(function(error) {\n console.warn('No purge method allowed: ' + error)\n });\n } catch (error) {\n console.warn('The resource ID is not a complete URL: ' + error);\n return;\n }\n }\n\n /**\n * Send a DELETE request to delete a resource\n * @param id - uri of the resource to delete\n * @param context - can be used to expand id\n *\n * @returns id of the deleted resource\n */\n async delete(id: string, context: object = {}) {\n const expandedId = this._getExpandedId(id, context);\n const deleted = await this.fetchAuthn(expandedId, {\n method: 'DELETE',\n headers: this.headers,\n credentials: 'include'\n });\n // await this.purge(id);\n\n const resourcesToNotify = this.subscriptionIndex.get(expandedId) || [];\n const resourcesToRefresh = this.subscriptionVirtualContainersIndex.get(expandedId) || [];\n\n this.refreshResources([...resourcesToNotify, ...resourcesToRefresh])\n .then(resourceIds => this.notifyResources(resourceIds));\n\n return deleted;\n }\n\n /**\n * Convert headers object to Headers\n * @param headersObject - object\n * @returns {Headers}\n */\n _convertHeaders(headersObject: object): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(headersObject)){\n headers.set(key, value as string);\n }\n return headers;\n }\n\n _getExpandedId(id: string, context: object) {\n return (context && Object.keys(context)) ? ContextParser.expandTerm(id, context) : id;\n }\n\n _isLocalId(id: string) {\n return id.startsWith('store://local.');\n }\n\n /**\n * Make a resource listen changes of another one\n * @param resourceId - id of the resource which needs to be updated\n * @param nestedResourceId - id of the resource which will change\n */\n subscribeResourceTo(resourceId: string, nestedResourceId: string) {\n const existingSubscriptions = this.subscriptionIndex.get(nestedResourceId) || [];\n this.subscriptionIndex.set(nestedResourceId, [...new Set([...existingSubscriptions, resourceId])])\n }\n\n /**\n * Make a virtual container listen for changes of a resource\n * @param virtualContainerId - id of the container which needs to be updated\n * @param nestedResourceId - id of the resource which will change\n */\n subscribeVirtualContainerTo(virtualContainerId: string, nestedResourceId: string) {\n const existingSubscriptions = this.subscriptionVirtualContainersIndex.get(nestedResourceId) || [];\n this.subscriptionVirtualContainersIndex.set(nestedResourceId, [...new Set([...existingSubscriptions, virtualContainerId])])\n }\n\n /**\n * Return absolute IRI of the resource\n * @param id\n * @param context\n * @param parentId\n */\n _getAbsoluteIri(id: string, context: object, parentId: string): string {\n let iri = ContextParser.expandTerm(id, context); // expand if reduced ids\n if (parentId) { // and get full URL from parent caller for local files\n let parentIri = new URL(parentId, document.location.href).href;\n iri = new URL(iri, parentIri).href;\n } else {\n iri = new URL(iri, document.location.href).href;\n }\n return iri;\n }\n\n /**\n * Check if object is a full resource\n * @param resource\n */\n _resourceIsComplete(resource: object) {\n return !!(Object.keys(resource).filter(p => !p.startsWith('@')).length > 0 && resource['@id'])\n }\n\n /**\n * Return language of the users\n */\n _getLanguage() {\n return localStorage.getItem('language') || window.navigator.language.slice(0,2);\n }\n\n /**\n * Save the preferred language of the user\n * @param selectedLanguageCode\n */\n selectLanguage(selectedLanguageCode: string) {\n localStorage.setItem('language', selectedLanguageCode);\n }\n\n resolveResource = function(id: string, resolve) {\n const handler = function(event) {\n if (event.detail.id === id) {\n resolve(event.detail.resource);\n // TODO : callback\n document.removeEventListener('resourceReady', handler);\n }\n };\n return handler;\n };\n}\n\nlet store: Store;\nif (window.sibStore) {\n store = window.sibStore;\n} else {\n const sibAuth = document.querySelector('sib-auth');\n const storeOptions: StoreOptions = {}\n\n if (sibAuth) {\n const sibAuthDefined = customElements.whenDefined(sibAuth.localName);\n storeOptions.session = sibAuthDefined.then(() => (sibAuth as any).session)\n storeOptions.fetchMethod = sibAuthDefined.then(() => (sibAuth as any).getFetch())\n }\n\n store = new Store(storeOptions);\n window.sibStore = store;\n}\n\nexport {\n store\n};\n\n\nclass CustomGetter {\n resource: any; // content of the requested resource\n resourceId: string;\n clientContext: object; // context given by the app\n serverContext: object; // context given by the server\n parentId: string; // id of the parent resource, used to get the absolute url of the current resource\n\n constructor(resourceId: string, resource: object, clientContext: object, serverContext: object = {}, parentId: string = \"\") {\n this.clientContext = clientContext;\n this.serverContext = serverContext;\n this.parentId = parentId;\n this.resource = this.expandProperties({ ...resource }, serverContext);\n this.resourceId = resourceId;\n }\n\n /**\n * Expand all predicates of a resource with a given context\n * @param resource: object\n * @param context: object\n */\n expandProperties(resource: object, context: object | string) {\n for (let prop of Object.keys(resource)) {\n if (!prop) continue;\n this.objectReplaceProperty(resource, prop, ContextParser.expandTerm(prop, context as JSONLDContextParser.IJsonLdContextNormalized, true));\n }\n return resource\n }\n\n /**\n * Change the key of an object\n * @param object: object\n * @param oldProp: string - current key\n * @param newProp: string - new key to set\n */\n objectReplaceProperty(object: object, oldProp: string, newProp: string) {\n if (newProp !== oldProp) {\n Object.defineProperty(\n object,\n newProp,\n Object.getOwnPropertyDescriptor(object, oldProp) || ''\n );\n delete object[oldProp];\n }\n }\n\n /**\n * Get the property of a resource for a given path\n * @param path: string\n */\n async get(path: any) {\n if (!path) return;\n const path1: string[] = path.split('.');\n const path2: string[] = [];\n let value: any;\n if (!this.isFullResource()) { // if resource is not complete, fetch it first\n await this.getResource(this.resourceId, this.clientContext, this.parentId);\n }\n while (true) {\n try {\n value = this.resource[this.getExpandedPredicate(path1[0])];\n } catch (e) { break }\n\n if (path1.length <= 1) break; // no dot path\n const lastPath1El = path1.pop();\n if(lastPath1El) path2.unshift(lastPath1El);\n }\n if (path2.length === 0) { // end of the path\n if (!value || !value['@id']) return value; // no value or not a resource\n return await this.getResource(value['@id'], this.clientContext, this.parentId || this.resourceId); // return complete resource\n }\n if (!value) return undefined;\n let resource = await this.getResource(value['@id'], this.clientContext, this.parentId || this.resourceId);\n\n store.subscribeResourceTo(this.resourceId, value['@id']);\n return resource ? await resource[path2.join('.')] : undefined; // return value\n }\n\n /**\n * Cache resource in the store, and return the created proxy\n * @param id\n * @param context\n * @param iriParent\n * @param forceFetch\n */\n async getResource(id: string, context: object, iriParent: string, forceFetch: boolean = false): Promise<Resource | null> {\n return store.getData(id, context, iriParent, undefined, forceFetch);\n }\n\n /**\n * Return true if the resource is a container\n */\n isContainer(): boolean {\n return this.resource[\"@type\"] == \"ldp:Container\" || this.resource[\"@type\"] == \"sib:federatedContainer\";\n }\n\n /**\n * Get all properties of a resource\n */\n getProperties(): string[] {\n return Object.keys(this.resource).map(prop => this.getCompactedPredicate(prop));\n }\n\n /**\n * Get children of container as objects\n */\n getChildren(): object[] {\n return this.resource[this.getExpandedPredicate(\"ldp:contains\")] || [];\n }\n\n /**\n * Get children of container as Proxys\n */\n getLdpContains(): CustomGetter[] {\n const children = this.resource[this.getExpandedPredicate(\"ldp:contains\")];\n return children ? children.map((res: object) => store.get(res['@id'])) : [];\n }\n\n /**\n * Get all nested resource or containers which contains datas\n */\n getSubObjects() {\n let subObjects: any = [];\n for (let p of Object.keys(this.resource)) {\n let property = this.resource[p];\n if (!this.isFullNestedResource(property)) continue; // if not a resource, stop\n if (property['@type'] == \"ldp:Container\" &&\n (property['ldp:contains'] == undefined ||\n (property['ldp:contains'].length >= 1 && !this.isFullNestedResource(property['ldp:contains'][0])))\n ) continue; // if not a full container\n subObjects.push(property)\n }\n return subObjects;\n }\n\n merge(resource: CustomGetter) {\n this.resource = {...this.getResourceData(), ...resource.getResourceData()}\n }\n\n getResourceData(): object { return this.resource }\n\n /**\n * return true if prop is a resource with an @id and some properties\n * @param prop\n */\n isFullNestedResource(prop: any): boolean {\n return prop &&\n typeof prop == \"object\" &&\n prop['@id'] != undefined &&\n Object.keys(prop).filter(p => !p.startsWith('@')).length > 0;\n }\n /**\n * return true resource seems complete\n * @param prop\n */\n isFullResource(): boolean {\n return Object.keys(this.resource).filter(p => !p.startsWith('@')).length > 0;\n }\n\n async getPermissions(): Promise<string[]> {\n const permissionPredicate = this.getExpandedPredicate(\"permissions\");\n let permissions = this.resource[permissionPredicate];\n if (!permissions) { // if no permission, re-fetch data\n await this.getResource(this.resourceId, this.clientContext, this.parentId, true);\n permissions = this.resource[permissionPredicate];\n }\n return permissions ? permissions.map(perm => ContextParser.expandTerm(perm.mode['@type'], this.serverContext, true)) : [];\n }\n\n /**\n * Remove the resource from the cache\n */\n clearCache(): void {\n store.clearCache(this.resourceId);\n }\n\n getExpandedPredicate(property: string) { return ContextParser.expandTerm(property, this.clientContext, true) }\n getCompactedPredicate(property: string) { return ContextParser.compactIri(property, this.clientContext, true) }\n getCompactedIri(id: string) { return ContextParser.compactIri(id, this.clientContext) }\n toString() { return this.getCompactedIri(this.resource['@id']) }\n [Symbol.toPrimitive]() { return this.getCompactedIri(this.resource['@id']) }\n\n\n /**\n * Returns a Proxy which handles the different get requests\n */\n getProxy() {\n return new Proxy(this, {\n get: (resource, property) => {\n if (!this.resource) return undefined;\n if (typeof resource[property] === 'function') return resource[property].bind(resource)\n\n switch (property) {\n case '@id':\n if (this.resource['@id'])\n return this.getCompactedIri(this.resource['@id']); // Compact @id if possible\n else\n console.log(this.resource, this.resource['@id']);\n return;\n case '@type':\n return this.resource['@type']; // return synchronously\n case 'properties':\n return this.getProperties();\n case 'ldp:contains':\n return this.getLdpContains(); // returns standard arrays synchronously\n case 'permissions':\n return this.getPermissions(); // get expanded permissions\n case 'clientContext':\n return this.clientContext; // get saved client context to re-fetch easily a resource\n case 'then':\n return;\n default:\n return resource.get(property);\n }\n }\n })\n }\n}"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { searchInResources } from '../libs/filter.js';
|
|
2
2
|
const FilterMixin = {
|
|
3
3
|
name: 'filter-mixin',
|
|
4
4
|
use: [],
|
|
@@ -55,7 +55,7 @@ const FilterMixin = {
|
|
|
55
55
|
if (this.filteredBy || this.searchFields) {
|
|
56
56
|
if (!this.searchCount.has(context)) this.searchCount.set(context, 1);
|
|
57
57
|
if (!this.searchForm) await this.createFilter(context);
|
|
58
|
-
const filteredResources = await
|
|
58
|
+
const filteredResources = await searchInResources(resources, this.filters, this.fields, this.searchForm);
|
|
59
59
|
resources = resources.filter((_v, index) => filteredResources[index]);
|
|
60
60
|
}
|
|
61
61
|
|
|
@@ -70,56 +70,6 @@ const FilterMixin = {
|
|
|
70
70
|
await this.populate();
|
|
71
71
|
},
|
|
72
72
|
|
|
73
|
-
async matchValue(subject, query) {
|
|
74
|
-
var _subject$isContainer;
|
|
75
|
-
|
|
76
|
-
if (subject == null && query.value === '') return true; // filter not set and subject not existing -> ignore filter
|
|
77
|
-
|
|
78
|
-
if (subject == null) return false; // property does not exist on resource
|
|
79
|
-
// Filter on a container
|
|
80
|
-
|
|
81
|
-
if (query.list) {
|
|
82
|
-
if (query.value.length === 0) return true;
|
|
83
|
-
|
|
84
|
-
for (const v of query.value) {
|
|
85
|
-
const q = {
|
|
86
|
-
type: query.type,
|
|
87
|
-
value: v
|
|
88
|
-
};
|
|
89
|
-
if (await this.matchValue(subject, q)) return true;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
return false;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
if ((_subject$isContainer = subject.isContainer) !== null && _subject$isContainer !== void 0 && _subject$isContainer.call(subject)) {
|
|
96
|
-
let ret = Promise.resolve(query.value === ''); // if no query, return a match
|
|
97
|
-
|
|
98
|
-
for (const value of subject['ldp:contains']) {
|
|
99
|
-
ret = (await ret) || (await this.matchValue(value, query));
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
return ret;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
return compare[query.type](subject, query.value);
|
|
106
|
-
},
|
|
107
|
-
|
|
108
|
-
async matchFilter(resource, filter, query) {
|
|
109
|
-
let fields = [];
|
|
110
|
-
if (this.isSet(filter)) fields = this.getSet(filter);else if (this.isSearchField(filter)) fields = this.getSearchField(filter); // search on 1 field
|
|
111
|
-
|
|
112
|
-
if (fields.length == 0) return this.matchValue(await resource[filter], query); // search on multiple fields
|
|
113
|
-
|
|
114
|
-
return fields.reduce( // return true if it matches at least one of the fields
|
|
115
|
-
async (initial, field) => (await initial) || (await this.matchFilter(resource, field, query)), Promise.resolve(false));
|
|
116
|
-
},
|
|
117
|
-
|
|
118
|
-
async matchFilters(resource) {
|
|
119
|
-
//return true if all filters values are contained in the corresponding field of the resource
|
|
120
|
-
return Object.keys(this.filters).reduce(async (initial, filter) => (await initial) && (await this.matchFilter(resource, filter, this.filters[filter])), Promise.resolve(true));
|
|
121
|
-
},
|
|
122
|
-
|
|
123
73
|
async getValuesOfField(field) {
|
|
124
74
|
const arrayOfDataObjects = this.resource['ldp:contains'];
|
|
125
75
|
const arrayOfDataIds = [];
|
|
@@ -179,15 +129,6 @@ const FilterMixin = {
|
|
|
179
129
|
});
|
|
180
130
|
this.element.insertBefore(this.searchForm, this.element.firstChild);
|
|
181
131
|
await this.searchForm.component.populate();
|
|
182
|
-
},
|
|
183
|
-
|
|
184
|
-
// Search fields
|
|
185
|
-
isSearchField(field) {
|
|
186
|
-
return this.searchForm.hasAttribute('search-' + field);
|
|
187
|
-
},
|
|
188
|
-
|
|
189
|
-
getSearchField(field) {
|
|
190
|
-
return parseFieldsString(this.searchForm.getAttribute('search-' + field));
|
|
191
132
|
}
|
|
192
133
|
|
|
193
134
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["filterMixin.ts"],"names":["compare","parseFieldsString","FilterMixin","name","use","initialState","searchCount","attributes","searchFields","type","String","default","filteredBy","callback","newValue","searchForm","getAttribute","component","detach","populate","created","Map","element","addEventListener","window","document","contains","updateAutoRanges","attached","listPostProcessors","push","filterCallback","bind","filters","value","filterList","resources","div","context","has","set","createFilter","filteredResources","Promise","all","map","matchFilters","filter","_v","index","nextProcessor","shift","get","resource","empty","matchValue","subject","query","list","length","v","q","isContainer","ret","resolve","matchFilter","fields","isSet","getSet","isSearchField","getSearchField","reduce","initial","field","Object","keys","getValuesOfField","arrayOfDataObjects","arrayOfDataIds","obj","nextArrayOfObjects","console","warn","nextArrayOfIds","getElementById","createElement","attach","toggleAttribute","searchAttributes","Array","from","attr","startsWith","replace","forEach","setAttribute","insertBefore","firstChild","hasAttribute"],"mappings":"AAAA,SAASA,OAAT,EAAkBC,iBAAlB,QAA2C,iBAA3C;AAEA,MAAMC,WAAW,GAAG;AAClBC,EAAAA,IAAI,EAAE,cADY;AAElBC,EAAAA,GAAG,EAAE,EAFa;AAGlBC,EAAAA,YAAY,EAAE;AACZC,IAAAA,WAAW,EAAE;AADD,GAHI;AAMlBC,EAAAA,UAAU,EAAE;AACVC,IAAAA,YAAY,EAAE;AACZC,MAAAA,IAAI,EAAEC,MADM;AAEZC,MAAAA,OAAO,EAAE;AAFG,KADJ;AAKVC,IAAAA,UAAU,EAAE;AACVH,MAAAA,IAAI,EAAEC,MADI;AAEVC,MAAAA,OAAO,EAAE,IAFC;;AAGVE,MAAAA,QAAQ,CAACC,QAAD,EAAmB;AACzB;AACA,YAAIA,QAAQ,IAAI,KAAKC,UAAjB,IAA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AAyB,CAAC;AAAC3F,MAAAA,IAAD;AAAO+B,MAAAA;AAAP,KAAD,KAAmB;AAC1C,WAAKnB,UAAL,CAAgBgF,YAAhB,CAA6B5F,IAA7B,EAAmC+B,KAAnC;AACD,KAFD;AAIA,SAAKZ,OAAL,CAAa0E,YAAb,CAA0B,KAAKjF,UAA/B,EAA2C,KAAKO,OAAL,CAAa2E,UAAxD;AACA,UAAM,KAAKlF,UAAL,CAAgBE,SAAhB,CAA0BE,QAA1B,EAAN;AACD,GAhKiB;;AAiKlB;AACAkD,EAAAA,aAAa,CAACI,KAAD,EAAgB;AAC3B,WAAO,KAAK1D,UAAL,CAAgBmF,YAAhB,CAA6B,YAAYzB,KAAzC,CAAP;AACD,GApKiB;;AAqKlBH,EAAAA,cAAc,CAACG,KAAD,EAA0B;AACtC,WAAOxE,iBAAiB,CAAC,KAAKc,UAAL,CAAgBC,YAAhB,CAA6B,YAAYyD,KAAzC,CAAD,CAAxB;AACD;;AAvKiB,CAApB;AA0KA,SACEvE,WADF","sourcesContent":["import { compare, parseFieldsString } from '../libs/helpers';\n\nconst FilterMixin = {\n name: 'filter-mixin',\n use: [],\n initialState: {\n searchCount: null,\n },\n attributes: {\n searchFields: {\n type: String,\n default: null\n },\n filteredBy: {\n type: String,\n default: null,\n callback(newValue: string) {\n // if we change search form, re-populate\n if (newValue && this.searchForm && newValue !== this.searchForm.getAttribute('id')) {\n this.searchForm.component.detach(this);\n this.searchForm = null;\n this.populate();\n }\n }\n }\n },\n created() {\n this.searchCount = new Map();\n this.element.addEventListener('populate', () => {\n if (!window.document.contains(this.element)) return;\n this.searchForm?.component.updateAutoRanges();\n })\n },\n attached(): void {\n this.listPostProcessors.push(this.filterCallback.bind(this));\n },\n get filters(): object {\n return this.searchForm?.component.value ?? {};\n },\n set filters(filters) {\n this.searchForm.component.value = filters;\n this.filterList();\n },\n async filterCallback(resources: object[], listPostProcessors: Function[], div: HTMLElement, context: string): Promise<void> {\n if (this.filteredBy || this.searchFields) {\n if (!this.searchCount.has(context)) this.searchCount.set(context, 1);\n if (!this.searchForm) await this.createFilter(context);\n const filteredResources = await Promise.all(resources.map(this.matchFilters.bind(this)));\n resources =\tresources.filter((_v, index) => filteredResources[index]);\n }\n\n const nextProcessor = listPostProcessors.shift();\n if(nextProcessor) await nextProcessor(resources, listPostProcessors, div, context + (this.searchCount.get(context) || ''));\n },\n async filterList(context: string): Promise<void> {\n this.searchCount.set(context, this.searchCount.get(context) + 1);\n if (!this.resource) return;\n this.empty();\n await this.populate();\n },\n async matchValue(subject, query): Promise<boolean> {\n if (subject == null && query.value === '') return true; // filter not set and subject not existing -> ignore filter\n if (subject == null) return false; // property does not exist on resource\n // Filter on a container\n if (query.list) {\n if(query.value.length === 0) return true;\n for(const v of query.value) {\n const q = {\n type: query.type,\n value: v,\n }\n if(await this.matchValue(subject, q)) return true;\n }\n return false;\n }\n if (subject.isContainer?.()) {\n let ret = Promise.resolve(query.value === ''); // if no query, return a match\n for (const value of subject['ldp:contains']) {\n ret = await ret || await this.matchValue(value, query)\n }\n return ret;\n }\n return compare[query.type](subject, query.value);\n },\n async matchFilter(resource: object, filter: string, query: any): Promise<boolean> {\n let fields: string[] = [];\n if (this.isSet(filter)) fields = this.getSet(filter);\n else if (this.isSearchField(filter)) fields = this.getSearchField(filter);\n\n // search on 1 field\n if (fields.length == 0)\n return this.matchValue(await resource[filter], query);\n\n // search on multiple fields\n return fields.reduce( // return true if it matches at least one of the fields\n async (initial, field) => await initial || await this.matchFilter(resource, field, query),\n Promise.resolve(false),\n );\n },\n async matchFilters(resource: object): Promise<boolean> {\n //return true if all filters values are contained in the corresponding field of the resource\n return Object.keys(this.filters).reduce(\n async (initial, filter) =>\n await initial && await this.matchFilter(resource, filter, this.filters[filter]),\n Promise.resolve(true)\n );\n },\n async getValuesOfField(field: string) {\n const arrayOfDataObjects = this.resource['ldp:contains'];\n const arrayOfDataIds: string[] = [];\n for (const obj of arrayOfDataObjects) {\n // for each element, if it's an object, catch all elements in 'ldp:contains' key\n const nextArrayOfObjects = await obj[field];\n if (!nextArrayOfObjects) continue;\n\n if (typeof nextArrayOfObjects !== \"object\") {\n console.warn(`The format value of ${field} is not suitable with auto-range-[field] attribute`);\n continue;\n }\n\n const nextArrayOfIds = nextArrayOfObjects['ldp:contains'];\n for (const obj of nextArrayOfIds) {\n // catch each element id\n arrayOfDataIds.push(obj['@id']);\n }\n if (nextArrayOfObjects['@type'] !== 'ldp:Container') {\n // if no element in 'ldp:contains', catch object id\n arrayOfDataIds.push(nextArrayOfObjects['@id']);\n }\n }\n return arrayOfDataIds;\n },\n async createFilter(context: string): Promise<void> {\n const filteredBy = this.filteredBy;\n if (filteredBy != null) {\n this.searchForm = document.getElementById(filteredBy)\n if (!this.searchForm) throw `#${filteredBy} is not in DOM`;\n } else {\n this.searchForm = document.createElement(`solid-form-search`);\n }\n this.searchForm.component.attach(this);\n this.searchForm.addEventListener('formChange', () => {\n this.filterList(context);\n });\n this.searchForm.toggleAttribute('naked', true);\n\n if (filteredBy) return;\n\n //pass attributes to search form\n const searchAttributes = Array.from((this.element as Element).attributes)\n .filter(attr => attr['name'].startsWith('search-'))\n .map(attr => ({\n name: attr['name'].replace('search-', ''),\n value: attr['value'],\n }));\n\n searchAttributes.forEach(({name, value}) => {\n this.searchForm.setAttribute(name, value);\n });\n\n this.element.insertBefore(this.searchForm, this.element.firstChild);\n await this.searchForm.component.populate();\n },\n // Search fields\n isSearchField(field: string) {\n return this.searchForm.hasAttribute('search-' + field);\n },\n getSearchField(field: string): string[] {\n return parseFieldsString(this.searchForm.getAttribute('search-' + field));\n },\n}\n\nexport {\n FilterMixin\n}"]}
|
|
1
|
+
{"version":3,"sources":["filterMixin.ts"],"names":["searchInResources","FilterMixin","name","use","initialState","searchCount","attributes","searchFields","type","String","default","filteredBy","callback","newValue","searchForm","getAttribute","component","detach","populate","created","Map","element","addEventListener","window","document","contains","updateAutoRanges","attached","listPostProcessors","push","filterCallback","bind","filters","value","filterList","resources","div","context","has","set","createFilter","filteredResources","fields","filter","_v","index","nextProcessor","shift","get","resource","empty","getValuesOfField","field","arrayOfDataObjects","arrayOfDataIds","obj","nextArrayOfObjects","console","warn","nextArrayOfIds","getElementById","createElement","attach","toggleAttribute","searchAttributes","Array","from","attr","startsWith","map","replace","forEach","setAttribute","insertBefore","firstChild"],"mappings":"AACA,SAASA,iBAAT,QAAkC,gBAAlC;AAEA,MAAMC,WAAW,GAAG;AAClBC,EAAAA,IAAI,EAAE,cADY;AAElBC,EAAAA,GAAG,EAAE,EAFa;AAGlBC,EAAAA,YAAY,EAAE;AACZC,IAAAA,WAAW,EAAE;AADD,GAHI;AAMlBC,EAAAA,UAAU,EAAE;AACVC,IAAAA,YAAY,EAAE;AACZC,MAAAA,IAAI,EAAEC,MADM;AAEZC,MAAAA,OAAO,EAAE;AAFG,KADJ;AAKVC,IAAAA,UAAU,EAAE;AACVH,MAAAA,IAAI,EAAEC,MADI;AAEVC,MAAAA,OAAO,EAAE,IAFC;;AAGVE,MAAAA,QAAQ,CAACC,QAAD,EAAmB;AACzB;AACA,YAAIA,QAAQ,IAAI,KAAKC,UAAjB,IAA+BD,QAAQ,KAAK,KAAKC,UAAL,CAAgBC,YAAhB,CAA6B,IAA7B,CAAhD,EAAoF;AAClF,eAAKD,UAAL,CAAgBE,SAAhB,CAA0BC,MAA1B,CAAiC,IAAjC;AACA,eAAKH,UAAL,GAAkB,IAAlB;AACA,eAAKI,QAAL;AACD;AACF;;AAVS;AALF,GANM;;AAwBlBC,EAAAA,OAAO,GAAG;AACR,SAAKd,WAAL,GAAmB,IAAIe,GAAJ,EAAnB;AACA,SAAKC,OAAL,CAAaC,gBAAb,CAA8B,UAA9B,EAA0C,MAAM;AAAA;;AAC9C,UAAI,CAACC,MAAM,CAACC,QAAP,CAAgBC,QAAhB,CAAyB,KAAKJ,OAA9B,CAAL,EAA6C;AAC7C,+BAAKP,UAAL,sEAAiBE,SAAjB,CAA2BU,gBAA3B;AACD,KAHD;AAID,GA9BiB;;AA+Bl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WADF","sourcesContent":["import type { SearchQuery } from '../libs/interfaces';\nimport { searchInResources } from '../libs/filter';\n\nconst FilterMixin = {\n name: 'filter-mixin',\n use: [],\n initialState: {\n searchCount: null,\n },\n attributes: {\n searchFields: {\n type: String,\n default: null\n },\n filteredBy: {\n type: String,\n default: null,\n callback(newValue: string) {\n // if we change search form, re-populate\n if (newValue && this.searchForm && newValue !== this.searchForm.getAttribute('id')) {\n this.searchForm.component.detach(this);\n this.searchForm = null;\n this.populate();\n }\n }\n }\n },\n created() {\n this.searchCount = new Map();\n this.element.addEventListener('populate', () => {\n if (!window.document.contains(this.element)) return;\n this.searchForm?.component.updateAutoRanges();\n })\n },\n attached(): void {\n this.listPostProcessors.push(this.filterCallback.bind(this));\n },\n get filters(): SearchQuery {\n return this.searchForm?.component.value ?? {};\n },\n set filters(filters) {\n this.searchForm.component.value = filters;\n this.filterList();\n },\n async filterCallback(resources: object[], listPostProcessors: Function[], div: HTMLElement, context: string): Promise<void> {\n if (this.filteredBy || this.searchFields) {\n if (!this.searchCount.has(context)) this.searchCount.set(context, 1);\n if (!this.searchForm) await this.createFilter(context);\n const filteredResources = await searchInResources(\n resources,\n this.filters,\n this.fields,\n this.searchForm\n );\n resources =\tresources.filter((_v, index) => filteredResources[index]);\n }\n\n const nextProcessor = listPostProcessors.shift();\n if(nextProcessor) await nextProcessor(resources, listPostProcessors, div, context + (this.searchCount.get(context) || ''));\n },\n async filterList(context: string): Promise<void> {\n this.searchCount.set(context, this.searchCount.get(context) + 1);\n if (!this.resource) return;\n this.empty();\n await this.populate();\n },\n async getValuesOfField(field: string) {\n const arrayOfDataObjects = this.resource['ldp:contains'];\n const arrayOfDataIds: string[] = [];\n for (const obj of arrayOfDataObjects) {\n // for each element, if it's an object, catch all elements in 'ldp:contains' key\n const nextArrayOfObjects = await obj[field];\n if (!nextArrayOfObjects) continue;\n\n if (typeof nextArrayOfObjects !== \"object\") {\n console.warn(`The format value of ${field} is not suitable with auto-range-[field] attribute`);\n continue;\n }\n\n const nextArrayOfIds = nextArrayOfObjects['ldp:contains'];\n for (const obj of nextArrayOfIds) {\n // catch each element id\n arrayOfDataIds.push(obj['@id']);\n }\n if (nextArrayOfObjects['@type'] !== 'ldp:Container') {\n // if no element in 'ldp:contains', catch object id\n arrayOfDataIds.push(nextArrayOfObjects['@id']);\n }\n }\n return arrayOfDataIds;\n },\n async createFilter(context: string): Promise<void> {\n const filteredBy = this.filteredBy;\n if (filteredBy != null) {\n this.searchForm = document.getElementById(filteredBy)\n if (!this.searchForm) throw `#${filteredBy} is not in DOM`;\n } else {\n this.searchForm = document.createElement(`solid-form-search`);\n }\n this.searchForm.component.attach(this);\n this.searchForm.addEventListener('formChange', () => {\n this.filterList(context);\n });\n this.searchForm.toggleAttribute('naked', true);\n\n if (filteredBy) return;\n\n //pass attributes to search form\n const searchAttributes = Array.from((this.element as Element).attributes)\n .filter(attr => attr['name'].startsWith('search-'))\n .map(attr => ({\n name: attr['name'].replace('search-', ''),\n value: attr['value'],\n }));\n\n searchAttributes.forEach(({name, value}) => {\n this.searchForm.setAttribute(name, value);\n });\n\n this.element.insertBefore(this.searchForm, this.element.firstChild);\n await this.searchForm.component.populate();\n },\n}\n\nexport {\n FilterMixin\n}"]}
|