@data-client/rest 0.9.3 → 0.9.5
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/README.md +85 -54
- package/dist/index.umd.min.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
#
|
|
1
|
+
# TypeScript HTTP definitions
|
|
2
2
|
|
|
3
3
|
[](https://circleci.com/gh/reactive/data-client)
|
|
4
4
|
[](https://app.codecov.io/gh/reactive/data-client?branch=master)
|
|
@@ -8,93 +8,126 @@
|
|
|
8
8
|
[](http://makeapullrequest.com)
|
|
9
9
|
[](https://discord.gg/35nb8Mz)
|
|
10
10
|
|
|
11
|
-
Extensible CRUD patterns for REST APIs.
|
|
12
|
-
|
|
13
11
|
<div align="center">
|
|
14
12
|
|
|
15
|
-
**[📖Read The Docs](https://dataclient.io/rest)** | [🎮Github Demo](https://stackblitz.com/github/reactive/data-client/tree/master/examples/github-app?file=src%2Fresources%2FIssue.tsx)
|
|
13
|
+
**[📖Read The Docs](https://dataclient.io/rest)** | [🎮Todo Demo](https://stackblitz.com/github/reactive/data-client/tree/master/examples/todo-app?file=src%2Fresources%2FTodoResource.ts) | [🎮Github Demo](https://stackblitz.com/github/reactive/data-client/tree/master/examples/github-app?file=src%2Fresources%2FIssue.tsx)
|
|
16
14
|
|
|
17
15
|
</div>
|
|
18
16
|
|
|
19
|
-
|
|
17
|
+
## RestEndpoint
|
|
18
|
+
|
|
19
|
+
Simplify TypeScript fetch functions with [RestEndpoint](https://dataclient.io/rest/api/RestEndpoint)
|
|
20
20
|
|
|
21
21
|
```typescript
|
|
22
|
-
|
|
22
|
+
const getTodo = new RestEndpoint({
|
|
23
|
+
urlPrefix: 'https://jsonplaceholder.typicode.com',
|
|
24
|
+
path: '/todos/:id',
|
|
25
|
+
});
|
|
26
|
+
```
|
|
23
27
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
+
[RestEndpoint](https://dataclient.io/rest/api/RestEndpoint) infers [path-to-regex](https://github.com/pillarjs/path-to-regexp#compile-reverse-path-to-regexp)
|
|
29
|
+
argument types, enabling enforcement of function calls
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
// signature requires id!
|
|
33
|
+
const todo = await getTodo({ id: 5 });
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
It automatically handles REST concepts like JSON serialization, consolidated error handling and more.
|
|
37
|
+
|
|
38
|
+
## Resources
|
|
39
|
+
|
|
40
|
+
Simplify related CRUD endpoints with [Resources](https://dataclient.io/rest/api/createResource)
|
|
28
41
|
|
|
42
|
+
[Resources](https://dataclient.io/rest/api/createResource) are a collection of `methods` for a given `data model`.
|
|
43
|
+
|
|
44
|
+
[Entities](https://dataclient.io/rest/api/Entity) and [Schemas](https://dataclient.io/concepts/normalization) declaratively define the _data model_.
|
|
45
|
+
[RestEndpoints](https://dataclient.io/rest/api/RestEndpoint) are the [_methods_](<https://en.wikipedia.org/wiki/Method_(computer_programming)>) on
|
|
46
|
+
that data.
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
class Todo extends Entity {
|
|
50
|
+
id = 0;
|
|
51
|
+
userId = 0;
|
|
52
|
+
title = '';
|
|
53
|
+
completed = false;
|
|
29
54
|
pk() {
|
|
30
|
-
return this.id
|
|
55
|
+
return `${this.id}`;
|
|
31
56
|
}
|
|
32
57
|
}
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
58
|
+
const TodoResource = createResource({
|
|
59
|
+
urlPrefix: 'https://jsonplaceholder.typicode.com',
|
|
60
|
+
path: '/todos/:id',
|
|
61
|
+
searchParams: {} as { userId?: string | number },
|
|
62
|
+
schema: Todo,
|
|
63
|
+
paginationField: 'page',
|
|
36
64
|
});
|
|
37
65
|
```
|
|
38
66
|
|
|
39
|
-
[
|
|
40
|
-
[createResource](https://dataclient.io/rest/api/createResource) creates a [collection](https://dataclient.io/rest/api/createResource#members)
|
|
41
|
-
of six [RestEndpoints](https://dataclient.io/rest/api/RestEndpoint)
|
|
67
|
+
One Resource defines [seven endpoints](https://dataclient.io/rest/api/createResource#members):
|
|
42
68
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
69
|
+
```typescript
|
|
70
|
+
// GET https://jsonplaceholder.typicode.com/todos/5
|
|
71
|
+
let todo5 = await TodoResource.get({ id: 5 });
|
|
46
72
|
|
|
47
|
-
|
|
73
|
+
// GET https://jsonplaceholder.typicode.com/todos
|
|
74
|
+
const todoList = await TodoResource.getList();
|
|
48
75
|
|
|
49
|
-
|
|
76
|
+
// GET https://jsonplaceholder.typicode.com/todos?userId=1
|
|
77
|
+
const userOneTodos = await TodoResource.getList({ userId: 1 });
|
|
50
78
|
|
|
51
|
-
|
|
79
|
+
// POST https://jsonplaceholder.typicode.com/todos
|
|
80
|
+
const newTodo = await TodoResource.getList.push({ title: 'my todo' });
|
|
52
81
|
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
const articles = useSuspense(ArticleResource.getList);
|
|
56
|
-
```
|
|
82
|
+
// POST https://jsonplaceholder.typicode.com/todos?userId=1
|
|
83
|
+
const newUserOneTodo = await TodoResource.getList.push({ userId: 1 }, { title: 'my todo' });
|
|
57
84
|
|
|
58
|
-
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
},
|
|
85
|
+
// GET https://jsonplaceholder.typicode.com/todos?userId=1&page=2
|
|
86
|
+
const nextPageOfTodos = await TodoResource.getList.getPage({ userId: 1, page: 2 });
|
|
87
|
+
|
|
88
|
+
// PUT https://jsonplaceholder.typicode.com/todos/5
|
|
89
|
+
todo5 = await TodoResource.update({ id: 5 }, { title: 'my todo' });
|
|
90
|
+
|
|
91
|
+
// PATCH https://jsonplaceholder.typicode.com/todos/5
|
|
92
|
+
todo5 = await TodoResource.partialUpdate({ id: 5 }, { title: 'my todo' });
|
|
93
|
+
|
|
94
|
+
// DELETE https://jsonplaceholder.typicode.com/todos/5
|
|
95
|
+
await TodoResource.delete({ id: 5 });
|
|
63
96
|
```
|
|
64
97
|
|
|
65
|
-
|
|
98
|
+
## Free React Integration
|
|
99
|
+
|
|
100
|
+
No need for any custom hooks. All endpoints are 100% compatible with [Reactive Data Client](https://dataclient.io)
|
|
101
|
+
|
|
102
|
+
### [Rendering](https://dataclient.io/docs/getting-started/data-dependency)
|
|
66
103
|
|
|
67
104
|
```typescript
|
|
68
|
-
const
|
|
69
|
-
const
|
|
70
|
-
const partialUpdateArticle = data =>
|
|
71
|
-
ctrl.fetch(ArticleResource.partialUpdate, { id }, data);
|
|
72
|
-
const createArticle = data => ctrl.fetch(ArticleResource.getList.push, data);
|
|
73
|
-
const deleteArticle = data => ctrl.fetch(ArticleResource.delete, { id });
|
|
105
|
+
const todo = useSuspense(TodoResource.get, { id: 5 });
|
|
106
|
+
const todoList = useSuspense(TodoResource.getList);
|
|
74
107
|
```
|
|
75
108
|
|
|
76
|
-
###
|
|
109
|
+
### [Mutations](https://dataclient.io/docs/getting-started/mutations)
|
|
77
110
|
|
|
78
111
|
```typescript
|
|
79
|
-
const
|
|
80
|
-
const
|
|
112
|
+
const ctrl = useController();
|
|
113
|
+
const updateTodo = data => ctrl.fetch(TodoResource.update, { id }, data);
|
|
114
|
+
const partialUpdateTodo= data =>
|
|
115
|
+
ctrl.fetch(TodoResource.partialUpdate, { id }, data);
|
|
116
|
+
const addTodoToEnd = data => ctrl.fetch(TodoResource.getList.push, data);
|
|
117
|
+
const addTodoToBeginning = data => ctrl.fetch(TodoResource.getList.unshift, data);
|
|
118
|
+
const deleteTodo = data => ctrl.fetch(TodoResource.delete, { id });
|
|
81
119
|
```
|
|
82
120
|
|
|
83
121
|
### [Programmatic queries](https://dataclient.io/rest/api/Query)
|
|
84
122
|
|
|
85
123
|
```tsx
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
(entries
|
|
89
|
-
const sorted = [...entries].sort((a, b) => a.title.localeCompare(b.title));
|
|
90
|
-
if (asc) return sorted;
|
|
91
|
-
return sorted.reverse();
|
|
92
|
-
},
|
|
124
|
+
const queryRemainingTodos = new Query(
|
|
125
|
+
TodoResource.getList,
|
|
126
|
+
(entries) => entries.filter((todo) => !todo.completed).length,
|
|
93
127
|
);
|
|
94
128
|
|
|
95
|
-
const
|
|
96
|
-
const
|
|
97
|
-
const articlesDescending = useCache(sortedArticles, { asc: false });
|
|
129
|
+
const allRemainingTodos = useCache(queryRemainingTodos);
|
|
130
|
+
const firstUserRemainingTodos = useCache(queryRemainingTodos, { userId: 1 });
|
|
98
131
|
```
|
|
99
132
|
|
|
100
133
|
### TypeScript requirements
|
|
@@ -102,8 +135,6 @@ const articlesDescending = useCache(sortedArticles, { asc: false });
|
|
|
102
135
|
TypeScript is optional, but will only work with 4.0 or above. 4.1 is needed for stronger types as it
|
|
103
136
|
supports inferring argument types from the path templates.
|
|
104
137
|
|
|
105
|
-
Version 5.x can be used for older TypeScript versions.
|
|
106
|
-
|
|
107
138
|
### Prior Art
|
|
108
139
|
|
|
109
140
|
- [Backbone Model](https://backbonejs.org/#Model)
|
package/dist/index.umd.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@data-client/endpoint")):"function"==typeof define&&define.amd?define(["exports","@data-client/endpoint"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Rest={},e.endpoint)}(this,(function(e,t){"use strict";function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function r(e,t){return e(t={exports:{}},t.exports),t.exports}var i=n(r((function(e){e.exports=function(e){if(null==e)throw new TypeError("Cannot destructure "+e)},e.exports.__esModule=!0,e.exports.default=e.exports}))),o=n(r((function(e){e.exports=function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e},e.exports.__esModule=!0,e.exports.default=e.exports}))),s=n(r((function(e){var t=0;e.exports=function(e){return"__private_"+t+++"_"+e},e.exports.__esModule=!0,e.exports.default=e.exports})));function a(e,t){void 0===t&&(t={});for(var n=function(e){for(var t=[],n=0;n<e.length;){var r=e[n];if("*"!==r&&"+"!==r&&"?"!==r)if("\\"!==r)if("{"!==r)if("}"!==r)if(":"!==r)if("("!==r)t.push({type:"CHAR",index:n,value:e[n++]});else{var i=1,o="";if("?"===e[a=n+1])throw new TypeError('Pattern cannot start with "?" at '.concat(a));for(;a<e.length;)if("\\"!==e[a]){if(")"===e[a]){if(0==--i){a++;break}}else if("("===e[a]&&(i++,"?"!==e[a+1]))throw new TypeError("Capturing groups are not allowed at ".concat(a));o+=e[a++]}else o+=e[a++]+e[a++];if(i)throw new TypeError("Unbalanced pattern at ".concat(n));if(!o)throw new TypeError("Missing pattern at ".concat(n));t.push({type:"PATTERN",index:n,value:o}),n=a}else{for(var s="",a=n+1;a<e.length;){var c=e.charCodeAt(a);if(!(c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||95===c))break;s+=e[a++]}if(!s)throw new TypeError("Missing parameter name at ".concat(n));t.push({type:"NAME",index:n,value:s}),n=a}else t.push({type:"CLOSE",index:n,value:e[n++]});else t.push({type:"OPEN",index:n,value:e[n++]});else t.push({type:"ESCAPED_CHAR",index:n++,value:e[n++]});else t.push({type:"MODIFIER",index:n,value:e[n++]})}return t.push({type:"END",index:n,value:""}),t}(e),r=t.prefixes,i=void 0===r?"./":r,o="[^".concat(u(t.delimiter||"/#?"),"]+?"),s=[],a=0,c=0,f="",h=function(e){if(c<n.length&&n[c].type===e)return n[c++].value},p=function(e){var t=h(e);if(void 0!==t)return t;var r=n[c],i=r.type,o=r.index;throw new TypeError("Unexpected ".concat(i," at ").concat(o,", expected ").concat(e))},d=function(){for(var e,t="";e=h("CHAR")||h("ESCAPED_CHAR");)t+=e;return t};c<n.length;){var l=h("CHAR"),m=h("NAME"),g=h("PATTERN");if(m||g){var v=l||"";-1===i.indexOf(v)&&(f+=v,v=""),f&&(s.push(f),f=""),s.push({name:m||a++,prefix:v,suffix:"",pattern:g||o,modifier:h("MODIFIER")||""})}else{var x=l||h("ESCAPED_CHAR");if(x)f+=x;else if(f&&(s.push(f),f=""),h("OPEN")){v=d();var y=h("NAME")||"",O=h("PATTERN")||"",E=d();p("CLOSE"),s.push({name:y||(O?a++:""),pattern:y&&!O?o:O,prefix:v,suffix:E,modifier:h("MODIFIER")||""})}else p("END")}}return s}function c(e,t){return function(e,t){void 0===t&&(t={});var n=f(t),r=t.encode,i=void 0===r?function(e){return e}:r,o=t.validate,s=void 0===o||o,a=e.map((function(e){if("object"==typeof e)return new RegExp("^(?:".concat(e.pattern,")$"),n)}));return function(t){for(var n="",r=0;r<e.length;r++){var o=e[r];if("string"!=typeof o){var c=t?t[o.name]:void 0,u="?"===o.modifier||"*"===o.modifier,f="*"===o.modifier||"+"===o.modifier;if(Array.isArray(c)){if(!f)throw new TypeError('Expected "'.concat(o.name,'" to not repeat, but got an array'));if(0===c.length){if(u)continue;throw new TypeError('Expected "'.concat(o.name,'" to not be empty'))}for(var h=0;h<c.length;h++){var p=i(c[h],o);if(s&&!a[r].test(p))throw new TypeError('Expected all "'.concat(o.name,'" to match "').concat(o.pattern,'", but got "').concat(p,'"'));n+=o.prefix+p+o.suffix}}else if("string"!=typeof c&&"number"!=typeof c){if(!u){var d=f?"an array":"a string";throw new TypeError('Expected "'.concat(o.name,'" to be ').concat(d))}}else{p=i(String(c),o);if(s&&!a[r].test(p))throw new TypeError('Expected "'.concat(o.name,'" to match "').concat(o.pattern,'", but got "').concat(p,'"'));n+=o.prefix+p+o.suffix}}else n+=o}return n}}(a(e,t),t)}function u(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function f(e){return e&&e.sensitive?"":"i"}function h(e,t,n){return function(e,t,n){void 0===n&&(n={});for(var r=n.strict,i=void 0!==r&&r,o=n.start,s=void 0===o||o,a=n.end,c=void 0===a||a,h=n.encode,p=void 0===h?function(e){return e}:h,d=n.delimiter,l=void 0===d?"/#?":d,m=n.endsWith,g="[".concat(u(void 0===m?"":m),"]|$"),v="[".concat(u(l),"]"),x=s?"^":"",y=0,O=e;y<O.length;y++){var E=O[y];if("string"==typeof E)x+=u(p(E));else{var b=u(p(E.prefix)),w=u(p(E.suffix));if(E.pattern)if(t&&t.push(E),b||w)if("+"===E.modifier||"*"===E.modifier){var j="*"===E.modifier?"?":"";x+="(?:".concat(b,"((?:").concat(E.pattern,")(?:").concat(w).concat(b,"(?:").concat(E.pattern,"))*)").concat(w,")").concat(j)}else x+="(?:".concat(b,"(").concat(E.pattern,")").concat(w,")").concat(E.modifier);else"+"===E.modifier||"*"===E.modifier?x+="((?:".concat(E.pattern,")").concat(E.modifier,")"):x+="(".concat(E.pattern,")").concat(E.modifier);else x+="(?:".concat(b).concat(w,")").concat(E.modifier)}}if(c)i||(x+="".concat(v,"?")),x+=n.endsWith?"(?=".concat(g,")"):"$";else{var P=e[e.length-1],R="string"==typeof P?v.indexOf(P[P.length-1])>-1:void 0===P;i||(x+="(?:".concat(v,"(?=").concat(g,"))?")),R||(x+="(?=".concat(v,"|").concat(g,")"))}return new RegExp(x,f(n))}(a(e,n),t,n)}function p(e,t,n){return e instanceof RegExp?function(e,t){if(!t)return e;for(var n=/\((?:\?<(.*?)>)?(?!\?)/g,r=0,i=n.exec(e.source);i;)t.push({name:i[1]||r++,prefix:"",suffix:"",modifier:"",pattern:""}),i=n.exec(e.source);return e}(e,t):Array.isArray(e)?function(e,t,n){var r=e.map((function(e){return p(e,t,n).source}));return new RegExp("(?:".concat(r.join("|"),")"),f(n))}(e,t,n):h(e,t,n)}function d(e,n){if("object"!=typeof e||void 0===e||Array.isArray(e))return;if(e instanceof t.schema.Collection)return n(e);const r=Object.assign({},e instanceof t.schema.Object?e.schema:e);for(const e in r){if(!r[e])continue;const t=d(r[e],n);if(t)return t}}function l(e,n){if("object"!=typeof e||void 0===e)return e;if(e instanceof t.schema.Collection)return n(e);const r=Object.assign({},e instanceof t.schema.Object?e.schema:e);for(const e in r)r[e]&&(r[e]=l(r[e],n));return r}class m extends Error{constructor(e){super(e.statusText||`Network response not 'ok': ${e.status}`),this.name="NetworkError",this.status=e.status,this.response=e}}function g(e,t){const n=new Set(e),r=[...e];for(const e of t)n.has(e)||r.push(e);return r}const v=Object.create(null);const x=Object.create(null);const y=Object.prototype,O=Object.getPrototypeOf;var E=s("hasBody");class b extends t.Endpoint{constructor(e){var t;super(null!=(t=e.fetch)?t:async function(...e){const t=o(this,E)[E]&&e.length<2?{}:e[0]||{},n=o(this,E)[E]?e[e.length-1]:void 0;return this.fetchResponse(this.url(t),await this.getRequestInit(n)).then((e=>this.parseResponse(e))).then((t=>this.process(t,...e)))},e),Object.defineProperty(this,E,{writable:!0,value:void 0}),(!("sideEffect"in this)||"method"in e&&!("sideEffect"in e))&&(this.sideEffect="GET"!==e.method&&void 0!==e.method||void 0),void 0===this.method&&(this.method=this.sideEffect?"POST":"GET"),void 0===this.urlPrefix&&(this.urlPrefix=""),o(this,E)[E]=!("body"in this&&void 0===this.body||["GET","DELETE"].includes(this.method)),Object.defineProperty(this,"name",{get(){return"__name"in this?this.__name:this.urlPrefix+this.path}})}key(...e){return`${this.method} ${this.url(o(this,E)[E]&&e.length<2?{}:e[0]||{})}`}url(e={}){const t=((n=this.path)in v||(v[n]=c(n,{encode:encodeURIComponent,validate:!1})),v[n])(e);var n;const r=function(e){return e in x||(x[e]=new Set(a(e).map((e=>"string"==typeof e?e:`${e.name}`)))),x[e]}(this.path),i={};return Object.keys(e).forEach((t=>{r.has(t)||(i[t]=e[t])})),Object.keys(i).length?`${this.urlPrefix}${t}?${function(e){const t=new URLSearchParams(e);return t.sort(),t.toString()}(i)}`:`${this.urlPrefix}${t}`}getHeaders(e){return e}async getRequestInit(e){const t=null!==(n=e)&&"object"==typeof n&&O(n)===y;var n;t&&(e=JSON.stringify(e));const r=Object.assign({},this.requestInit,{method:this.method,signal:this.signal,body:e});return e&&!t||(r.headers=Object.assign({"Content-Type":"application/json"},r.headers)),r.headers=await this.getHeaders(r.headers),r}fetchResponse(e,t){return fetch(e,t).then((e=>{if(!e.ok)throw new m(e);return e})).catch((e=>{throw e instanceof TypeError&&(e.status=500),e}))}parseResponse(e){var t;return 204===e.status?Promise.resolve(null):null!=(t=e.headers.get("content-type"))&&t.includes("json")?e.json().catch((e=>{throw e.status=400,e})):e.text().then((t=>{if(["string","undefined"].includes(typeof this.schema)||null===this.schema||this.process!==b.prototype.process)return t;const n=new m(e);throw n.status=404,n.message=`Unexpected text response for schema ${this.schema}`,n}))}process(e){return e}errorPolicy(e){return e.status>=500?"soft":void 0}get pathRegex(){return p(this.path)}testKey(e){const t=this.method+" "+this.urlPrefix;if(!e.startsWith(t))return!1;let n=e.lastIndexOf("?");return-1===n&&(n=void 0),this.pathRegex.test(e.substring(t.length,n))}extend(e){class t extends this.constructor{}return Object.assign(t.prototype,this),new t(Object.assign({fetch:this.fetch},e))}paginated(e){if("string"==typeof e){const t=e;e=e=>{let n=Object.assign({},(i(e),e));return delete n[t],[n]}}let t=!1;const n=l(this.schema,(n=>(t=!0,function(e,t){return Object.create(t,{name:{value:`Pagination(${t.schema})`},merge:{value:g},pk:{value:function(n,r,i,o){return t.pk.call(this,n,r,i,e(...o))}}})}(e,n))));if(!t)throw new Error("Missing Collection");const r=this;return this.extend({schema:n,key(...t){return r.key.call(this,...e(...t))},name:this.name+".getPage"})}get getPage(){return this.paginated(this.paginationField)}get push(){return this.extend({method:"POST",schema:d(this.schema,(e=>e.push)),name:this.name+".create"})}get unshift(){return this.extend({method:"POST",schema:d(this.schema,(e=>e.unshift)),name:this.name+".create"})}get assign(){return this.extend({method:"POST",schema:d(this.schema,(e=>e.assign)),name:this.name+".create"})}}var w=n(r((function(e){e.exports=function(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(i[n]=e[n]);return i},e.exports.__esModule=!0,e.exports.default=e.exports})));const j=["path","schema","Endpoint","Collection","optimistic","paginationField"],{Invalidate:P,Collection:R}=t.schema;function T(e,t,n){return Object.assign({},t,C(n))}function A(e,t){return t}function C(e){return e instanceof FormData?Object.fromEntries(e.entries()):e}Object.hasOwn=Object.hasOwn||function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},e.NetworkError=m,e.RestEndpoint=b,e.createResource=function(e){let{path:n,schema:r,Endpoint:i=b,Collection:o=R,optimistic:s,paginationField:a}=e,c=w(e,j);const u=function(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error("Resource path requires at least one :parameter");let n=e.substring(0,t);return"/"===n[n.length-1]&&(n=n.substring(0,n.length-1)),n}(n),f=e=>`${null==r?void 0:r.name}.${e}`;function h(e,t,n){e[t]=e[t].extend(n)}const p=Object.assign({},c),d=Object.assign({},c),l=new i(Object.assign({},c,{path:n,schema:r,name:f("get")}));var m;s&&(p.getOptimisticResponse=T,d.getOptimisticResponse=(m=l,function(e,n,r){const{data:i}=e.getResponse(m,n);if(!i)throw new t.AbortOptimistic;return Object.assign({},n,i,C(r))}));const g=new i(Object.assign({},p,{paginationField:a,path:u,schema:new o([r]),name:f("getList")}));return{get:l,getList:g,create:g.push.extend({name:f("create")}),update:new i(Object.assign({},p,{path:n,schema:r,method:"PUT",name:f("update")})),partialUpdate:new i(Object.assign({},d,{path:n,schema:r,method:"PATCH",name:f("partialUpdate")})),delete:new i(Object.assign({},p,{path:n,schema:r.process?new P(r):r,method:"DELETE",name:f("delete"),process:(e,t)=>e&&Object.keys(e).length?e:t,getOptimisticResponse:s?A:void 0})),extend(...e){if("string"==typeof e[0]){const[t,n]=e;if(t in this){const e=Object.assign({},this);return h(e,t,n),e}return Object.assign({},this,{[t]:this.get.extend(n)})}if("function"==typeof e[0]){const t=e[0](this);return Object.assign({},this,t)}const t=e[0],n=Object.assign({},this);for(const e in t)h(n,e,t[e]);return n}}},e.hookifyResource=function(e,t){const n={};return Object.keys(e).forEach((r=>{const i=e[r];var o;void 0!==i.extend&&(n[`use${o=r,o.charAt(0).toUpperCase()+o.slice(1)}`]=()=>{const e=t();return i.extend({requestInit:e})})})),n},Object.keys(t).forEach((function(n){"default"===n||e.hasOwnProperty(n)||Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[n]}})})),Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Rest={})}(this,(function(e){"use strict";function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e,t){return e(t={exports:{}},t.exports),t.exports}var r=t(n((function(e){e.exports=function(e){if(null==e)throw new TypeError("Cannot destructure "+e)},e.exports.__esModule=!0,e.exports.default=e.exports}))),s=t(n((function(e){e.exports=function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e},e.exports.__esModule=!0,e.exports.default=e.exports}))),i=t(n((function(e){var t=0;e.exports=function(e){return"__private_"+t+++"_"+e},e.exports.__esModule=!0,e.exports.default=e.exports})));function o(e){return!("function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}class c{constructor(e,t){this.schema=void 0,t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){"_schemaAttribute"in e&&!this._schemaAttribute?(this.schema=e.schema,this._schemaAttribute=e._schemaAttribute):this.schema=e}getSchemaAttribute(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)}inferSchema(e,t,n){if(this.isSingleSchema)return this.schema;const r=this.getSchemaAttribute(e,t,n);return this.schema[r]}normalizeValue(e,t,n,r,s,i,o,c){if(!e)return e;const a=this.inferSchema(e,t,n);if(!a)return e;const h=r(e,t,n,a,s,i,o,c);return this.isSingleSchema||null==h?h:{id:h,schema:this.getSchemaAttribute(e,t,n)}}denormalizeValue(e,t){const n=!this.isSingleSchema&&(o(e)?e.get("schema"):e.schema);if(!this.isSingleSchema&&!n)return e;return t((this.isSingleSchema?void 0:o(e)?e.get("id"):e.id)||e,this.isSingleSchema?this.schema:this.schema[n])}}class a extends c{normalize(e,t,n,r,s,i,o,c){return Object.keys(e).reduce(((t,n,a)=>{const h=e[n];return null!=h?Object.assign({},t,{[n]:this.normalizeValue(h,e,n,r,s,i,o,c)}):t}),{})}denormalize(e,t,n){return Object.keys(e).reduce(((t,r)=>{const s=e[r],i=this.denormalizeValue(s,n);return i&&"symbol"!=typeof i?Object.assign({},t,{[r]:i}):t}),{})}infer(e,t,n){}}const h=e=>void 0!==e&&"symbol"!=typeof e;class u extends c{normalize(e,t,n,r,s,i,o,c){const a=(e=>Array.isArray(e)?e:Object.keys(e).map((t=>e[t])))(e);return a.map(((e,a)=>this.normalizeValue(e,t,n,r,s,i,o,c))).filter((e=>null!=e))}denormalize(e,t,n){return e.map?e.map((e=>this.denormalizeValue(e,n))).filter(h):e}infer(e,t,n,r){}toJSON(){return[this.schema]}}function f(e,t,n,r){if(o(t))return function(e,t,n){var r;let s;const i=Object.keys(e).reduce(((t,r)=>{const i=`${r}`,o=n(t.get(i),e[i]);return"symbol"==typeof o&&(s=o),t.has(i)?t.set(i,o):t}),t);return null!=(r=s)?r:i}(e,t,r);const s=Object.assign({},t);for(const t of Object.keys(e)){const n=r(s[t],e[t]);if(void 0!==s[t]&&(s[t]=n),"symbol"==typeof n)return n}return s}class l{constructor(e){this.schema=void 0,this.define(e)}define(e){this.schema=Object.keys(e).reduce(((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})}),this.schema||{})}normalize(...e){return((e,t,n,r,s,i,o,c,a)=>{const h=Object.assign({},t);return Object.keys(e).forEach((n=>{const r=e[n],u=s(t[n],t,n,r,i,o,c,a);null==u?delete h[n]:h[n]=u})),h})(this.schema,...e)}denormalize(e,t,n){return f(this.schema,e,0,n)}infer(e,t,n,r){return function(e,t,n,r,s){const i={};return Object.keys(e).forEach((o=>{i[o]=r(e[o],t,n,s)})),i}(this.schema,e,t,n,r)}}const p=Symbol("INVALID");const d=Symbol("create"),m=(e,t)=>[...e,...t],y=(e,t)=>[...t,...e],g=(e,t)=>Object.assign({},e,t),b=e=>[...e],v=e=>Object.assign({},e);class O{addWith(e,t){return x(this,e,t)}createCollectionFilter(...e){return t=>Object.entries(t).every((([t,n])=>{var r;return this.nonFilterArgumentKeys(t)||`${e[0][t]}`===n||`${null==(r=e[1])?void 0:r[t]}`===n}))}nonFilterArgumentKeys(e){return e.startsWith("order")}constructor(e,t){if(this.schema=Array.isArray(e)?new u(e[0]):e,t?"nestKey"in t?this.nestKey=t.nestKey:this.argsKey="argsKey"in t?t.argsKey:e=>Object.assign({},e):this.argsKey=e=>Object.assign({},e),this.key=`COLLECT:${this.schema.constructor.name}(${this.schema.schema.key})`,null!=t&&t.nonFilterArgumentKeys){const{nonFilterArgumentKeys:e}=t;"function"==typeof e?this.nonFilterArgumentKeys=e:e instanceof RegExp?this.nonFilterArgumentKeys=t=>e.test(t):this.nonFilterArgumentKeys=t=>e.includes(t)}else null!=t&&t.createCollectionFilter&&(this.createCollectionFilter=t.createCollectionFilter.bind(this));this.schema instanceof u?(this.createIfValid=b,this.push=x(this,m),this.unshift=x(this,y)):e instanceof a&&(this.createIfValid=v,this.assign=x(this,g))}get cacheWith(){return this.schema.schema}toJSON(){return{name:`Collection(${this.schema.schema.name})`,schema:this.schema.schema.toJSON(),key:this.key}}pk(e,t,n,r){const s=this.argsKey?this.argsKey(...r):this.nestKey(t,n);for(const e in s)"string"!=typeof s[e]&&void 0!==s[e]&&(s[e]=`${s[e]}`);return function(e){const t=Object.keys(e).sort(),n={};for(const r of t)n[r]=e[r];return JSON.stringify(n)}(s)}normalize(e,t,n,r,s,i,o,c){const a=this.schema.normalize(e,t,n,r,s,i,o,c),h=this.pk(a,t,n,c);return s(this,a,h),h}merge(e,t){return t}shouldReorder(e,t,n,r){return t.fetchedAt<e.fetchedAt}mergeWithStore(e,t,n,r){return this.shouldReorder(e,t,n,r)?this.merge(r,n):this.merge(n,r)}mergeMetaWithStore(e,t,n,r){return this.shouldReorder(e,t,n,r)?e:t}infer(e,t,n,r){if(this.argsKey){var s;const t=this.pk(void 0,void 0,"",e);if(null!=(s=r[this.key])&&s[t])return t}}denormalize(e,t,n){return this.schema.denormalize(e,t,n)}}function x(e,t,n){const r={merge:{value:t},normalize:{value:E},infer:{value:j}};return e.schema instanceof u&&(r.createIfValid={value:k},r.denormalize={value:w}),n&&(r.createCollectionFilter={value:n}),Object.create(e,r)}function j(){}function E(e,t,n,r,s,i,o,c){i[d]={};const a=this.schema.normalize(this.schema instanceof u&&!Array.isArray(e)?[e]:e,t,n,r,s,i,o,c),h=this.createCollectionFilter(...c);return o[this.key]&&Object.keys(o[this.key]).forEach((e=>{h(JSON.parse(e))&&s(this,a,e)})),a}function k(e){return Array.isArray(e)?[...e]:Object.assign({},e)}function w(e,t,n){return Array.isArray(e)?this.schema.denormalize(e,t,n):this.schema.denormalize([e],t,n)[0]}var S=t(n((function(e){e.exports=function(e,t){if(null==e)return{};var n,r,s={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(s[n]=e[n]);return s},e.exports.__esModule=!0,e.exports.default=e.exports})));const A=["pk","schema","key"];function _(e,t={}){class n extends e{static toString(){return this.key}static toJSON(){return{name:this.name,schema:this.schema,key:this.key}}static pk(e,t,n,r){return this.prototype.pk.call(e,t,n,r)}static useIncoming(e,t,n,r){return!0}static shouldReorder(e,t,n,r){return t.fetchedAt<e.fetchedAt}static merge(e,t){return Object.assign({},e,t)}static mergeWithStore(e,t,n,r){return this.useIncoming(e,t,n,r)?typeof r!=typeof n?r:this.shouldReorder(e,t,n,r)?this.merge(r,n):this.merge(n,r):n}static mergeMetaWithStore(e,t,n,r){return this.shouldReorder(e,t,n,r)?e:t}static fromJS(e={}){const t=new this(e);return Object.assign(t,e),t}static createIfValid(e){if(!this.validate(e))return this.fromJS(e)}static process(e,t,n,r){return Object.assign({},e)}static normalize(e,t,n,r,s,i,o,c){const a=this.process(e,t,n,c);let h=this.pk(a,t,n,c);void 0!==h&&""!==h&&"undefined"!==h||(h=`MISS-${Math.random()}`);const u=this.key;if(u in i||(i[u]={}),h in i[u]||(i[u][h]=[]),i[u][h].some((t=>t===e)))return h;return function(e){if(e){const t=new Error(e);throw t.status=400,t}}(this.validate(a)),i[u][h].push(e),Object.keys(this.schema).forEach((e=>{if(Object.hasOwn(a,e)){const t=this.schema[e];a[e]=r(a[e],a,e,t,s,i,o,c)}})),s(this,a,h),h}static validate(e){}static infer(e,t,n,r){var s;if(!e[0])return;const i=function(e,t,n){if(["string","number"].includes(typeof t[0]))return`${t[0]}`;const r=e.pk(t[0],void 0,"",t);if(void 0!==r&&""!==r)return r;const s=function(e,t){return t?t.find((t=>Object.hasOwn(e,t))):void 0}(t[0],e.indexes);if(s&&n[e.key]){return n[e.key][s][t[0][s]]}}(this,e,t);return null!=(s=r[this.key])&&s[i]?i:void 0}static denormalize(e,t,n){if("symbol"==typeof e)return e;for(const t of Object.keys(this.schema)){const r=this.schema[t],s=n(e[t],r);if("symbol"==typeof s){if(this.defaults[t])return s;e[t]=void 0}else e[t]=s}return e}static get defaults(){return Object.hasOwn(this,"__defaults")||Object.defineProperty(this,"__defaults",{value:new this,writable:!0,configurable:!0}),this.__defaults}}const r=S(t,A);if(Object.assign(n,r),"schema"in t?n.schema=t.schema:e.schema||(n.schema={}),"pk"in t?"function"==typeof t.pk?n.prototype.pk=function(e,n){return t.pk(this,e,n)}:n.prototype.pk=function(){return this[t.pk]}:"function"!=typeof e.prototype.pk&&(n.prototype.pk=function(){return this.id}),"key"in t)Object.defineProperty(n,"key",{value:t.key,configurable:!0,writable:!0,enumerable:!0});else if(!("key"in e)){function s(e){Object.defineProperty(this,"key",{value:e,writable:!0,enumerable:!0,configurable:!0})}const i=function(){return"EntityMixin"===this.name?e.name:this.name},o="undefined"!=typeof document&&document.CLS_MANGLE?function(){return null==document.CLS_MANGLE||document.CLS_MANGLE(this),Object.defineProperty(n,"key",{get:i,set:s,enumerable:!0,configurable:!0}),i.call(this)}:i;Object.defineProperty(n,"key",{get:o,set:s,enumerable:!0,configurable:!0})}return n}var P=Object.freeze({__proto__:null,Union:class extends c{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,n,r,s,i,o,c){return this.normalizeValue(e,t,n,r,s,i,o,c)}denormalize(e,t,n){return this.denormalizeValue(e,n)}infer(e,t,n,r){if(!e[0])return;const s=this.getSchemaAttribute(e[0],void 0,""),i=this.schema[s];return void 0!==i?{id:n(i,e,t,r),schema:s}:void 0}},Values:a,Array:u,All:class extends u{constructor(e,t){super(e,t)}normalize(e,t,n,r,s,i,o,c){super.normalize(e,t,n,r,s,i,o,c)}infer(e,t,n,r){if(this.isSingleSchema){const e=r[this.schema.key];if(void 0===e)return;return Object.values(e).map((e=>e&&this.schema.pk(e)))}let s=!1;const i=Object.values(this.schema).flatMap((e=>r[e.key]?(s=!0,Object.values(r[e.key]).map((t=>({id:t&&e.pk(t),schema:this.getSchemaAttribute(t,void 0,void 0)})))):[]));if(s)return i}},Object:l,Invalidate:class{constructor(e){this._entity=e}get key(){return this._entity.key}normalize(e,t,n,r,s,i,o,c){const a=this._entity.process(e,t,n,c),h=this._entity.pk(a,t,n,c);return s(this,p,h),h}merge(e,t){return t}mergeWithStore(e,t,n,r){return this.merge(n,r)}mergeMetaWithStore(e,t,n,r){return t}infer(e,t,n){}denormalize(e,t,n){return n(e,this._entity)}_denormalizeNullable(){return{}}_normalizeNullable(){return{}}},Collection:O,Entity:_});const R=class{};class C extends(_(R)){static process(e,t,n,r){return super.process(e,t,n,r)}}var T;const z="undefined"!=typeof document;let N=z&&!(null!=(T=document.querySelector("meta[http-equiv='Content-Security-Policy']"))&&T.getAttribute("content"));try{N||Function()}catch(e){N=!0,z&&console.error("Content Security Policy: The previous CSP log can be safely ignored - @data-client/endpoint will use setPrototypeOf instead")}var $;class I extends Function{constructor(e,t){let n,r;return N?(n=(...e)=>n.fetch(...e),Object.setPrototypeOf(n,new.target.prototype)):(super("return arguments.callee.fetch.apply(arguments.callee, arguments)"),n=this),e&&(n.fetch=e),t&&"name"in t||!e||!e.name||"anonymous"===e.name||(r=e.name),Object.defineProperty(n,"name",{get(){return r||this.__name},set(e){this.__name=e}}),Object.assign(n,t),n}key(...e){return`${this.name} ${JSON.stringify(e)}`}testKey(e){return e.startsWith(this.name)}bind(e,...t){const n=this.fetch,r=this.key;return this.extend({fetch(){return n.apply(null!=e?e:this,t)},key(){return r.apply(this,t)}})}extend(e){class t extends this.constructor{}return Object.assign(t.prototype,this),new t(e.fetch,e)}}$=I,(()=>{if("undefined"!=typeof document&&document.FUNC_MANGLE){const e=$.prototype.key;$.prototype.key=function(...t){return null==document.FUNC_MANGLE||document.FUNC_MANGLE(this),this.prototype.key=e,e.call(this,...t)}}})();const M=I;class F extends Error{}function K(e,t){void 0===t&&(t={});for(var n=function(e){for(var t=[],n=0;n<e.length;){var r=e[n];if("*"!==r&&"+"!==r&&"?"!==r)if("\\"!==r)if("{"!==r)if("}"!==r)if(":"!==r)if("("!==r)t.push({type:"CHAR",index:n,value:e[n++]});else{var s=1,i="";if("?"===e[c=n+1])throw new TypeError('Pattern cannot start with "?" at '.concat(c));for(;c<e.length;)if("\\"!==e[c]){if(")"===e[c]){if(0==--s){c++;break}}else if("("===e[c]&&(s++,"?"!==e[c+1]))throw new TypeError("Capturing groups are not allowed at ".concat(c));i+=e[c++]}else i+=e[c++]+e[c++];if(s)throw new TypeError("Unbalanced pattern at ".concat(n));if(!i)throw new TypeError("Missing pattern at ".concat(n));t.push({type:"PATTERN",index:n,value:i}),n=c}else{for(var o="",c=n+1;c<e.length;){var a=e.charCodeAt(c);if(!(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||95===a))break;o+=e[c++]}if(!o)throw new TypeError("Missing parameter name at ".concat(n));t.push({type:"NAME",index:n,value:o}),n=c}else t.push({type:"CLOSE",index:n,value:e[n++]});else t.push({type:"OPEN",index:n,value:e[n++]});else t.push({type:"ESCAPED_CHAR",index:n++,value:e[n++]});else t.push({type:"MODIFIER",index:n,value:e[n++]})}return t.push({type:"END",index:n,value:""}),t}(e),r=t.prefixes,s=void 0===r?"./":r,i="[^".concat(D(t.delimiter||"/#?"),"]+?"),o=[],c=0,a=0,h="",u=function(e){if(a<n.length&&n[a].type===e)return n[a++].value},f=function(e){var t=u(e);if(void 0!==t)return t;var r=n[a],s=r.type,i=r.index;throw new TypeError("Unexpected ".concat(s," at ").concat(i,", expected ").concat(e))},l=function(){for(var e,t="";e=u("CHAR")||u("ESCAPED_CHAR");)t+=e;return t};a<n.length;){var p=u("CHAR"),d=u("NAME"),m=u("PATTERN");if(d||m){var y=p||"";-1===s.indexOf(y)&&(h+=y,y=""),h&&(o.push(h),h=""),o.push({name:d||c++,prefix:y,suffix:"",pattern:m||i,modifier:u("MODIFIER")||""})}else{var g=p||u("ESCAPED_CHAR");if(g)h+=g;else if(h&&(o.push(h),h=""),u("OPEN")){y=l();var b=u("NAME")||"",v=u("PATTERN")||"",O=l();f("CLOSE"),o.push({name:b||(v?c++:""),pattern:b&&!v?i:v,prefix:y,suffix:O,modifier:u("MODIFIER")||""})}else f("END")}}return o}function L(e,t){return function(e,t){void 0===t&&(t={});var n=U(t),r=t.encode,s=void 0===r?function(e){return e}:r,i=t.validate,o=void 0===i||i,c=e.map((function(e){if("object"==typeof e)return new RegExp("^(?:".concat(e.pattern,")$"),n)}));return function(t){for(var n="",r=0;r<e.length;r++){var i=e[r];if("string"!=typeof i){var a=t?t[i.name]:void 0,h="?"===i.modifier||"*"===i.modifier,u="*"===i.modifier||"+"===i.modifier;if(Array.isArray(a)){if(!u)throw new TypeError('Expected "'.concat(i.name,'" to not repeat, but got an array'));if(0===a.length){if(h)continue;throw new TypeError('Expected "'.concat(i.name,'" to not be empty'))}for(var f=0;f<a.length;f++){var l=s(a[f],i);if(o&&!c[r].test(l))throw new TypeError('Expected all "'.concat(i.name,'" to match "').concat(i.pattern,'", but got "').concat(l,'"'));n+=i.prefix+l+i.suffix}}else if("string"!=typeof a&&"number"!=typeof a){if(!h){var p=u?"an array":"a string";throw new TypeError('Expected "'.concat(i.name,'" to be ').concat(p))}}else{l=s(String(a),i);if(o&&!c[r].test(l))throw new TypeError('Expected "'.concat(i.name,'" to match "').concat(i.pattern,'", but got "').concat(l,'"'));n+=i.prefix+l+i.suffix}}else n+=i}return n}}(K(e,t),t)}function D(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function U(e){return e&&e.sensitive?"":"i"}function V(e,t,n){return function(e,t,n){void 0===n&&(n={});for(var r=n.strict,s=void 0!==r&&r,i=n.start,o=void 0===i||i,c=n.end,a=void 0===c||c,h=n.encode,u=void 0===h?function(e){return e}:h,f=n.delimiter,l=void 0===f?"/#?":f,p=n.endsWith,d="[".concat(D(void 0===p?"":p),"]|$"),m="[".concat(D(l),"]"),y=o?"^":"",g=0,b=e;g<b.length;g++){var v=b[g];if("string"==typeof v)y+=D(u(v));else{var O=D(u(v.prefix)),x=D(u(v.suffix));if(v.pattern)if(t&&t.push(v),O||x)if("+"===v.modifier||"*"===v.modifier){var j="*"===v.modifier?"?":"";y+="(?:".concat(O,"((?:").concat(v.pattern,")(?:").concat(x).concat(O,"(?:").concat(v.pattern,"))*)").concat(x,")").concat(j)}else y+="(?:".concat(O,"(").concat(v.pattern,")").concat(x,")").concat(v.modifier);else"+"===v.modifier||"*"===v.modifier?y+="((?:".concat(v.pattern,")").concat(v.modifier,")"):y+="(".concat(v.pattern,")").concat(v.modifier);else y+="(?:".concat(O).concat(x,")").concat(v.modifier)}}if(a)s||(y+="".concat(m,"?")),y+=n.endsWith?"(?=".concat(d,")"):"$";else{var E=e[e.length-1],k="string"==typeof E?m.indexOf(E[E.length-1])>-1:void 0===E;s||(y+="(?:".concat(m,"(?=").concat(d,"))?")),k||(y+="(?=".concat(m,"|").concat(d,")"))}return new RegExp(y,U(n))}(K(e,n),t,n)}function W(e,t,n){return e instanceof RegExp?function(e,t){if(!t)return e;for(var n=/\((?:\?<(.*?)>)?(?!\?)/g,r=0,s=n.exec(e.source);s;)t.push({name:s[1]||r++,prefix:"",suffix:"",modifier:"",pattern:""}),s=n.exec(e.source);return e}(e,t):Array.isArray(e)?function(e,t,n){var r=e.map((function(e){return W(e,t,n).source}));return new RegExp("(?:".concat(r.join("|"),")"),U(n))}(e,t,n):V(e,t,n)}function J(e,t){if("object"!=typeof e||void 0===e||Array.isArray(e))return;if(e instanceof O)return t(e);const n=Object.assign({},e instanceof l?e.schema:e);for(const e in n){if(!n[e])continue;const r=J(n[e],t);if(r)return r}}function G(e,t){if("object"!=typeof e||void 0===e)return e;if(e instanceof O)return t(e);const n=Object.assign({},e instanceof l?e.schema:e);for(const e in n)n[e]&&(n[e]=G(n[e],t));return n}class H extends Error{constructor(e){super(e.statusText||`Network response not 'ok': ${e.status}`),this.name="NetworkError",this.status=e.status,this.response=e}}function q(e,t){const n=new Set(e),r=[...e];for(const e of t)n.has(e)||r.push(e);return r}const Q=Object.create(null);const B=Object.create(null);const Y=Object.prototype,X=Object.getPrototypeOf;var Z=i("hasBody");class ee extends I{constructor(e){var t;super(null!=(t=e.fetch)?t:async function(...e){const t=s(this,Z)[Z]&&e.length<2?{}:e[0]||{},n=s(this,Z)[Z]?e[e.length-1]:void 0;return this.fetchResponse(this.url(t),await this.getRequestInit(n)).then((e=>this.parseResponse(e))).then((t=>this.process(t,...e)))},e),Object.defineProperty(this,Z,{writable:!0,value:void 0}),(!("sideEffect"in this)||"method"in e&&!("sideEffect"in e))&&(this.sideEffect="GET"!==e.method&&void 0!==e.method||void 0),void 0===this.method&&(this.method=this.sideEffect?"POST":"GET"),void 0===this.urlPrefix&&(this.urlPrefix=""),s(this,Z)[Z]=!("body"in this&&void 0===this.body||["GET","DELETE"].includes(this.method)),Object.defineProperty(this,"name",{get(){return"__name"in this?this.__name:this.urlPrefix+this.path}})}key(...e){return`${this.method} ${this.url(s(this,Z)[Z]&&e.length<2?{}:e[0]||{})}`}url(e={}){const t=((n=this.path)in Q||(Q[n]=L(n,{encode:encodeURIComponent,validate:!1})),Q[n])(e);var n;const r=function(e){return e in B||(B[e]=new Set(K(e).map((e=>"string"==typeof e?e:`${e.name}`)))),B[e]}(this.path),s={};return Object.keys(e).forEach((t=>{r.has(t)||(s[t]=e[t])})),Object.keys(s).length?`${this.urlPrefix}${t}?${function(e){const t=new URLSearchParams(e);return t.sort(),t.toString()}(s)}`:`${this.urlPrefix}${t}`}getHeaders(e){return e}async getRequestInit(e){const t=null!==(n=e)&&"object"==typeof n&&X(n)===Y;var n;t&&(e=JSON.stringify(e));const r=Object.assign({},this.requestInit,{method:this.method,signal:this.signal,body:e});return e&&!t||(r.headers=Object.assign({"Content-Type":"application/json"},r.headers)),r.headers=await this.getHeaders(r.headers),r}fetchResponse(e,t){return fetch(e,t).then((e=>{if(!e.ok)throw new H(e);return e})).catch((e=>{throw e instanceof TypeError&&(e.status=500),e}))}parseResponse(e){var t;return 204===e.status?Promise.resolve(null):null!=(t=e.headers.get("content-type"))&&t.includes("json")?e.json().catch((e=>{throw e.status=400,e})):e.text().then((t=>{if(["string","undefined"].includes(typeof this.schema)||null===this.schema||this.process!==ee.prototype.process)return t;const n=new H(e);throw n.status=404,n.message=`Unexpected text response for schema ${this.schema}`,n}))}process(e){return e}errorPolicy(e){return e.status>=500?"soft":void 0}get pathRegex(){return W(this.path)}testKey(e){const t=this.method+" "+this.urlPrefix;if(!e.startsWith(t))return!1;let n=e.lastIndexOf("?");return-1===n&&(n=void 0),this.pathRegex.test(e.substring(t.length,n))}extend(e){class t extends this.constructor{}return Object.assign(t.prototype,this),new t(Object.assign({fetch:this.fetch},e))}paginated(e){if("string"==typeof e){const t=e;e=e=>{let n=Object.assign({},(r(e),e));return delete n[t],[n]}}let t=!1;const n=G(this.schema,(n=>(t=!0,function(e,t){return Object.create(t,{name:{value:`Pagination(${t.schema})`},merge:{value:q},pk:{value:function(n,r,s,i){return t.pk.call(this,n,r,s,e(...i))}}})}(e,n))));if(!t)throw new Error("Missing Collection");const s=this;return this.extend({schema:n,key(...t){return s.key.call(this,...e(...t))},name:this.name+".getPage"})}get getPage(){return this.paginated(this.paginationField)}get push(){return this.extend({method:"POST",schema:J(this.schema,(e=>e.push)),name:this.name+".create"})}get unshift(){return this.extend({method:"POST",schema:J(this.schema,(e=>e.unshift)),name:this.name+".create"})}get assign(){return this.extend({method:"POST",schema:J(this.schema,(e=>e.assign)),name:this.name+".create"})}}const te=["path","schema","Endpoint","Collection","optimistic","paginationField"],{Invalidate:ne,Collection:re}=P;function se(e,t,n){return Object.assign({},t,oe(n))}function ie(e,t){return t}function oe(e){return e instanceof FormData?Object.fromEntries(e.entries()):e}Object.hasOwn=Object.hasOwn||function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},e.AbortOptimistic=F,e.Endpoint=I,e.Entity=C,e.ExtendableEndpoint=M,e.INVALID=p,e.Index=class{constructor(e,t){this.schema=e,t&&(this.key=t)}key(e){return JSON.stringify(e)}},e.NetworkError=H,e.Query=class{constructor(e,t){this.sideEffect=void 0,this.schema=this.createQuerySchema(e),t?this.process=t:this.process||(this.process=e=>e)}key(...e){return`QUERY ${JSON.stringify(e)}`}createQuerySchema(e){const t=Object.create(e);return t.denormalize=({args:t,input:n},r,s)=>{if(void 0===n)return;const i=e.denormalize(n,t,s);return"symbol"==typeof i?void 0:this.process(i,...t)},t.infer=(t,n,r,s)=>({args:t,input:r(e,t,n,s)}),t}},e.RestEndpoint=ee,e.createResource=function(e){let{path:t,schema:n,Endpoint:r=ee,Collection:s=re,optimistic:i,paginationField:o}=e,c=S(e,te);const a=function(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error("Resource path requires at least one :parameter");let n=e.substring(0,t);return"/"===n[n.length-1]&&(n=n.substring(0,n.length-1)),n}(t),h=e=>`${null==n?void 0:n.name}.${e}`;function u(e,t,n){e[t]=e[t].extend(n)}const f=Object.assign({},c),l=Object.assign({},c),p=new r(Object.assign({},c,{path:t,schema:n,name:h("get")}));var d;i&&(f.getOptimisticResponse=se,l.getOptimisticResponse=(d=p,function(e,t,n){const{data:r}=e.getResponse(d,t);if(!r)throw new F;return Object.assign({},t,r,oe(n))}));const m=new r(Object.assign({},f,{paginationField:o,path:a,schema:new s([n]),name:h("getList")}));return{get:p,getList:m,create:m.push.extend({name:h("create")}),update:new r(Object.assign({},f,{path:t,schema:n,method:"PUT",name:h("update")})),partialUpdate:new r(Object.assign({},l,{path:t,schema:n,method:"PATCH",name:h("partialUpdate")})),delete:new r(Object.assign({},f,{path:t,schema:n.process?new ne(n):n,method:"DELETE",name:h("delete"),process:(e,t)=>e&&Object.keys(e).length?e:t,getOptimisticResponse:i?ie:void 0})),extend(...e){if("string"==typeof e[0]){const[t,n]=e;if(t in this){const e=Object.assign({},this);return u(e,t,n),e}return Object.assign({},this,{[t]:this.get.extend(n)})}if("function"==typeof e[0]){const t=e[0](this);return Object.assign({},this,t)}const t=e[0],n=Object.assign({},this);for(const e in t)u(n,e,t[e]);return n}}},e.hookifyResource=function(e,t){const n={};return Object.keys(e).forEach((r=>{const s=e[r];var i;void 0!==s.extend&&(n[`use${i=r,i.charAt(0).toUpperCase()+i.slice(1)}`]=()=>{const e=t();return s.extend({requestInit:e})})})),n},e.schema=P,e.validateRequired=function(e,t){let n="";if(Object.keys(t).some((t=>!Object.hasOwn(e,t)&&(n=t,!0))))return`Missing key ${n}`},Object.defineProperty(e,"__esModule",{value:!0})}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@data-client/rest",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.5",
|
|
4
4
|
"description": "Endpoints for REST APIs",
|
|
5
5
|
"homepage": "https://dataclient.io/rest",
|
|
6
6
|
"repository": {
|
|
@@ -124,7 +124,7 @@
|
|
|
124
124
|
"license": "Apache-2.0",
|
|
125
125
|
"dependencies": {
|
|
126
126
|
"@babel/runtime": "^7.17.0",
|
|
127
|
-
"@data-client/endpoint": "^0.9.
|
|
127
|
+
"@data-client/endpoint": "^0.9.4",
|
|
128
128
|
"path-to-regexp": "^6.2.1"
|
|
129
129
|
},
|
|
130
130
|
"devDependencies": {
|