@data-client/rest 0.15.4 → 0.15.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/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # @data-client/rest
2
2
 
3
+ ## 0.15.5
4
+
5
+ ### Patch Changes
6
+
7
+ - [`e571bda`](https://github.com/reactive/data-client/commit/e571bdabd136fddee7aa414c91a775c5f66ce094) Thanks [@ntucker](https://github.com/ntucker)! - Add direct exports for schema classes from `@data-client/endpoint`
8
+
9
+ Schema classes (`Union`, `Invalidate`, `Collection`, `Query`, `Values`, `All`) can now be imported directly instead of requiring the `schema` namespace.
10
+
11
+ #### Before
12
+
13
+ ```ts
14
+ import { schema } from '@data-client/endpoint';
15
+ const myUnion = new schema.Union({ users: User, groups: Group }, 'type');
16
+ ```
17
+
18
+ #### After
19
+
20
+ ```ts
21
+ import { Union } from '@data-client/endpoint';
22
+ const myUnion = new Union({ users: User, groups: Group }, 'type');
23
+ ```
24
+
25
+ The `schema` namespace export remains available for backward compatibility.
26
+
27
+ - Updated dependencies [[`e571bda`](https://github.com/reactive/data-client/commit/e571bdabd136fddee7aa414c91a775c5f66ce094)]:
28
+ - @data-client/endpoint@0.15.5
29
+
3
30
  ## 0.15.4
4
31
 
5
32
  ### Patch Changes
package/README.md CHANGED
@@ -126,7 +126,7 @@ const deleteTodo = data => ctrl.fetch(TodoResource.delete, { id });
126
126
  ### [Programmatic queries](https://dataclient.io/rest/api/Query)
127
127
 
128
128
  ```tsx
129
- const queryRemainingTodos = new schema.Query(
129
+ const queryRemainingTodos = new Query(
130
130
  TodoResource.getList.schema,
131
131
  entries => entries.filter(todo => !todo.completed).length,
132
132
  );
@@ -136,7 +136,7 @@ const firstUserRemainingTodos = useQuery(queryRemainingTodos, { userId: 1 });
136
136
  ```
137
137
 
138
138
  ```typescript
139
- const groupTodoByUser = new schema.Query(
139
+ const groupTodoByUser = new Query(
140
140
  TodoResource.getList.schema,
141
141
  todos => Object.groupBy(todos, todo => todo.userId),
142
142
  );
@@ -1 +1 @@
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(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},t.apply(null,arguments)}function n(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var r=0;function i(e){return"__private_"+r+++"_"+e}function s(e){return!("function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}class o{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){e._hoistable&&!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]}schemaKey(){return this.isSingleSchema?this.schema.key:Object.values(this.schema).join(";")}normalizeValue(e,t,n,r,i){if(!e)return e;const s=this.isSingleSchema,o=s?this.schema:this.schema[this._schemaAttribute(e,t,n)];if(!o)return e;const a=i(o,e,t,n,r);return s||null==a?a:{id:a,schema:this._schemaAttribute(e,t,n)}}denormalizeValue(e,t){const n=this.isSingleSchema,r=!n&&e&&(s(e)?e.get("schema"):e.schema);if(!n&&!r){if("object"==typeof e&&null!==e){const n=this.inferSchema(e,void 0,void 0);if(n)return t(n,e)}return e}const i=n?void 0:s(e)?e.get("id"):e.id;return t(n?this.schema:this.schema[r],i||e)}}class a extends o{normalize(e,t,n,r,i,s){const o={},a=Object.keys(e);for(let t=0;t<a.length;t++){const n=a[t],s=e[n];null!=s&&(o[n]=this.normalizeValue(s,e,n,r,i))}return o}denormalize(e,t,n){const r={},i=Object.keys(e);for(let t=0;t<i.length;t++){const s=i[t],o=e[s],a=this.denormalizeValue(o,n);a&&"symbol"!=typeof a&&(r[s]=a)}return r}queryKey(e,t,n){}}const c=e=>void 0!==e&&"symbol"!=typeof e;class h extends o{normalize(e,t,n,r,i){const s=(e=>Array.isArray(e)?e:Object.keys(e).map((t=>e[t])))(e);return s.map((e=>this.normalizeValue(e,t,n,r,i)))}denormalize(e,t,n){return e.map?e.map((e=>this.denormalizeValue(e,n))).filter(c):e}queryKey(e,t,n){}toJSON(){return[this.schema]}}function u(e,n,r,i){if(s(n))return function(e,t,n){let r;const i=Object.keys(e).reduce(((t,i)=>{const s=`${i}`,o=n(e[s],t.get(s));return"symbol"==typeof o&&(r=o),t.has(s)?t.set(s,o):t}),t);return null!=r?r:i}(e,n,i);const o=t({},n),a=Object.keys(e);for(let t=0;t<a.length;t++){const n=a[t],r=i(e[n],o[n]);if(void 0!==o[n]&&(o[n]=r),"symbol"==typeof r)return r}return o}class f{constructor(e){this.schema=void 0,this.define(e)}define(e){this.schema=Object.keys(e).reduce(((n,r)=>{const i=e[r];return t({},n,{[r]:i})}),this.schema||{})}normalize(...e){return((e,n,r,i,s,o)=>{const a=t({},n),c=Object.keys(e);for(let t=0;t<c.length;t++){const r=c[t],i=o(e[r],n[r],n,r,s);void 0===i?delete a[r]:a[r]=i}return a})(this.schema,...e)}denormalize(e,t,n){return u(this.schema,e,0,n)}queryKey(e,t){return function(e,t,n){const r={},i=Object.keys(e);for(let s=0;s<i.length;s++){const o=i[s];r[o]=n(e[o],t)}return r}(this.schema,e,t)}}const l=(e,t)=>[...e,...t],m=(e,t)=>[...t,...e],d=(e,n)=>t({},e,n),p=(e,t)=>e.filter((e=>!t.some((t=>{return r=t,"object"==typeof(n=e)&&"object"==typeof r?n.id===r.id&&n.schema===r.schema:n===r;var n,r})))),y=e=>[...e],g=e=>t({},e);class v{addWith(e,t){return b(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,n){if(this.schema=Array.isArray(e)?new h(e[0]):e,n?"nestKey"in n?this.nestKey=n.nestKey:this.argsKey="argsKey"in n?n.argsKey:e=>t({},e):this.argsKey=e=>t({},e),this.key=function(e){if(e instanceof h)return`[${e.schemaKey()}]`;if(e instanceof a)return`{${e.schemaKey()}}`;return`(${e.schemaKey()})`}(this.schema),null!=n&&n.nonFilterArgumentKeys){const{nonFilterArgumentKeys:e}=n;"function"==typeof e?this.nonFilterArgumentKeys=e:e instanceof RegExp?this.nonFilterArgumentKeys=t=>e.test(t):this.nonFilterArgumentKeys=t=>e.includes(t)}else null!=n&&n.createCollectionFilter&&(this.createCollectionFilter=n.createCollectionFilter.bind(this));this.schema instanceof h?(this.createIfValid=y,this.push=b(this,l),this.unshift=b(this,m),this.remove=b(this,p)):e instanceof a&&(this.createIfValid=g,this.assign=b(this,d))}get cacheWith(){return this.schema.schema}toString(){return this.key}toJSON(){return{key:this.key,schema:this.schema.schema}}pk(e,t,n,r){const i=this.argsKey?this.argsKey(...r):this.nestKey(t,n);for(const e in i)["number","boolean"].includes(typeof i[e])&&(i[e]=`${i[e]}`);return function(e){const t=Object.keys(e).sort(),n={};for(const r of t)n[r]=e[r];return JSON.stringify(n)}(i)}normalize(e,t,n,r,i,s){const o=this.schema.normalize(e,t,n,r,i,s),a=this.pk(o,t,n,r);return s.mergeEntity(this,a,o),a}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}queryKey(e,t,n){if(this.argsKey){const t=this.pk(void 0,void 0,"",e);if(n.getEntity(this.key,t))return t}}denormalize(e,t,n){return this.schema.denormalize(e,t,n)}}function b(e,t,n){const r={merge:{value:t},normalize:{value:w},queryKey:{value:E}};return e.schema instanceof h&&(r.createIfValid={value:O},r.denormalize={value:x}),n&&(r.createCollectionFilter={value:n}),Object.create(e,r)}function E(){}function w(e,t,n,r,i,s){const o=this.schema.normalize(this.schema instanceof h&&!Array.isArray(e)?[e]:e,t,n,r,i,s),a=this.createCollectionFilter(...r),c=s.getEntities(this.key);if(c)for(const e of c.keys())a(JSON.parse(e))&&s.mergeEntity(this,e,o);return o}function O(e){return Array.isArray(e)?[...e]:t({},e)}function x(e,t,n){return Array.isArray(e)?this.schema.denormalize(e,t,n):this.schema.denormalize([e],t,n)[0]}function k(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}const A=["pk","schema","key"];function S(e,n={}){class r extends e{static toString(){return this.key}static toJSON(){return{key:this.key,schema:this.schema}}static pk(e,t,n,r){return this.prototype.pk.call(e,t,n,r)}static shouldUpdate(e,t,n,r){return!0}static shouldReorder(e,t,n,r){return t.fetchedAt<e.fetchedAt}static merge(e,n){return t({},e,n)}static mergeWithStore(e,t,n,r){return this.shouldUpdate(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,n,r,i){return t({},e)}static normalize(e,t,n,r,i,s){const o=this.process(e,t,n,r);let a;if(void 0===o)return a=`${this.pk(e,t,n,r)}`,s.invalidate(this,a),a;if(a=this.pk(o,t,n,r),a=void 0===a||""===a||"undefined"===a?`MISS-${Math.random()}`:`${a}`,s.checkLoop(this.key,a,e))return a;!function(e){if(e){const t=new Error(e);throw t.status=400,t}}(this.validate(o));const c=Object.keys(this.schema);for(let e=0;e<c.length;e++){const t=c[e];Object.hasOwn(o,t)&&(o[t]=i(this.schema[t],o[t],o,t,r))}return s.mergeEntity(this,a,o),a}static validate(e){}static queryKey(e,t,n){if(!e[0])return;const r=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 i=(s=t[0],o=e.indexes,o?o.find((e=>Object.hasOwn(s,e))):void 0);var s,o;if(!i)return;const a=t[0][i];return n.getIndex(e.key,i,a)}(this,e,n);return r&&n.getEntity(this.key,r)?r:void 0}static denormalize(e,t,n){if("symbol"==typeof e)return e;for(const t of Object.keys(this.schema)){const r=n(this.schema[t],e[t]);if("symbol"==typeof r){if(this.defaults[t])return r;e[t]=void 0}else e[t]=r}return e}static get defaults(){return Object.hasOwn(this,"__defaults")||Object.defineProperty(this,"__defaults",{value:new this,writable:!0,configurable:!0}),this.__defaults}}const i=k(n,A);if(Object.assign(r,i),"schema"in n?r.schema=n.schema:e.schema||(r.schema={}),"pk"in n?"function"==typeof n.pk?r.prototype.pk=function(e,t){return n.pk(this,e,t)}:r.prototype.pk=function(){return this[n.pk]}:"function"!=typeof e.prototype.pk&&(r.prototype.pk=function(){return this.id}),"key"in n)Object.defineProperty(r,"key",{value:n.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 o=function(){return"EntityMixin"===this.name?e.name:this.name},a="undefined"!=typeof document&&document.CLS_MANGLE?function(){return null==document.CLS_MANGLE||document.CLS_MANGLE(this),Object.defineProperty(r,"key",{get:o,set:s,enumerable:!0,configurable:!0}),o.call(this)}:o;Object.defineProperty(r,"key",{get:a,set:s,enumerable:!0,configurable:!0})}return r}var j=Object.freeze({__proto__:null,All:class extends h{constructor(e,t){super(e,t)}normalize(e,t,n,r,i){super.normalize(e,t,n,r,i)}queryKey(e,t,n){if(this.isSingleSchema){const e=n.getEntities(this.schema.key);return e?[...e.keys()]:n.INVALID}let r=!1;const i=Object.values(this.schema).flatMap((e=>{const t=n.getEntities(e.key);if(!t)return[];r=!0;const i=[];for(const[n,r]of t.entries())r&&"symbol"!=typeof r&&i.push({id:e.pk(r,void 0,n,[]),schema:this.getSchemaAttribute(r,void 0,n)});return i}));return r?i:n.INVALID}},Array:h,Collection:v,Entity:S,EntityMixin:S,Invalidate:class extends o{constructor(e,t){super(e,t)}get key(){return this.schemaKey()}normalize(e,t,n,r,i,s){const o=this.inferSchema(e,t,n);if(!o)return e;let a;if("string"==typeof e||"number"==typeof e)a=e;else{const i=o.process(e,t,n,r);a=o.pk(null!=i?i:e,t,n,r)}return a=`${a}`,s.invalidate(o,a),this.isSingleSchema?a:{id:a,schema:this.getSchemaAttribute(e,t,n)}}queryKey(e,t,n){}denormalize(e,t,n){return this.denormalizeValue(e,n)}_denormalizeNullable(){return{}}_normalizeNullable(){return{}}},Object:f,Query:class{constructor(e,t){this.schema=e,this.process=t}normalize(...e){return this.schema.normalize(...e)}denormalize(e,t,n){const r=n(this.schema,e);return"symbol"==typeof r?r:this.process(r,...t)}queryKey(e,t){return t(this.schema,e)}},Union:class extends o{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t),this._hoistable=!0}normalize(e,t,n,r,i){return this.normalizeValue(e,t,n,r,i)}denormalize(e,t,n){return this.denormalizeValue(e,n)}queryKey(e,t){if(!e[0])return;const n=this.getSchemaAttribute(e[0],void 0,""),r=this.schema[n];if(r){const i=t(r,e);if(void 0===i)return;return{id:i,schema:n}}for(const n in this.schema){const r=t(this.schema[n],e);if(void 0!==r)return{id:r,schema:n}}}},Values:a});const _=class{};class P extends(S(_)){static process(e,t,n,r){return super.process(e,t,n,r)}}var R;const T="undefined"!=typeof document;let C=T&&!(null!=(R=document.querySelector("meta[http-equiv='Content-Security-Policy']"))&&R.getAttribute("content"));try{C||Function()}catch(e){C=!0,T&&console.error("Content Security Policy: The previous CSP log can be safely ignored - @data-client/endpoint will use setPrototypeOf instead")}var z;class $ extends Function{constructor(e,t){let n,r;return C?(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)}}z=$,(()=>{if("undefined"!=typeof document&&document.FUNC_MANGLE){const e=z.prototype.key;z.prototype.key=function(...t){return null==document.FUNC_MANGLE||document.FUNC_MANGLE(this),this.prototype.key=e,e.call(this,...t)}}})();const K=$;function N(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,s="";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));s+=e[a++]}else s+=e[a++]+e[a++];if(i)throw new TypeError("Unbalanced pattern at ".concat(n));if(!s)throw new TypeError("Missing pattern at ".concat(n));t.push({type:"PATTERN",index:n,value:s}),n=a}else{for(var o="",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;o+=e[a++]}if(!o)throw new TypeError("Missing parameter name at ".concat(n));t.push({type:"NAME",index:n,value:o}),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,s=t.delimiter,o=void 0===s?"/#?":s,a=[],c=0,h=0,u="",f=function(e){if(h<n.length&&n[h].type===e)return n[h++].value},l=function(e){var t=f(e);if(void 0!==t)return t;var r=n[h],i=r.type,s=r.index;throw new TypeError("Unexpected ".concat(i," at ").concat(s,", expected ").concat(e))},m=function(){for(var e,t="";e=f("CHAR")||f("ESCAPED_CHAR");)t+=e;return t},d=function(e){var t=a[a.length-1],n=e||(t&&"string"==typeof t?t:"");if(t&&!n)throw new TypeError('Must have text between two parameters, missing text after "'.concat(t.name,'"'));return!n||function(e){for(var t=0,n=o;t<n.length;t++){var r=n[t];if(e.indexOf(r)>-1)return!0}return!1}(n)?"[^".concat(M(o),"]+?"):"(?:(?!".concat(M(n),")[^").concat(M(o),"])+?")};h<n.length;){var p=f("CHAR"),y=f("NAME"),g=f("PATTERN");if(y||g){var v=p||"";-1===i.indexOf(v)&&(u+=v,v=""),u&&(a.push(u),u=""),a.push({name:y||c++,prefix:v,suffix:"",pattern:g||d(v),modifier:f("MODIFIER")||""})}else{var b=p||f("ESCAPED_CHAR");if(b)u+=b;else if(u&&(a.push(u),u=""),f("OPEN")){v=m();var E=f("NAME")||"",w=f("PATTERN")||"",O=m();l("CLOSE"),a.push({name:E||(w?c++:""),pattern:E&&!w?d(v):w,prefix:v,suffix:O,modifier:f("MODIFIER")||""})}else l("END")}}return a}function I(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,s=t.validate,o=void 0===s||s,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 s=e[r];if("string"!=typeof s){var c=t?t[s.name]:void 0,h="?"===s.modifier||"*"===s.modifier,u="*"===s.modifier||"+"===s.modifier;if(Array.isArray(c)){if(!u)throw new TypeError('Expected "'.concat(s.name,'" to not repeat, but got an array'));if(0===c.length){if(h)continue;throw new TypeError('Expected "'.concat(s.name,'" to not be empty'))}for(var f=0;f<c.length;f++){var l=i(c[f],s);if(o&&!a[r].test(l))throw new TypeError('Expected all "'.concat(s.name,'" to match "').concat(s.pattern,'", but got "').concat(l,'"'));n+=s.prefix+l+s.suffix}}else if("string"!=typeof c&&"number"!=typeof c){if(!h){var m=u?"an array":"a string";throw new TypeError('Expected "'.concat(s.name,'" to be ').concat(m))}}else{l=i(String(c),s);if(o&&!a[r].test(l))throw new TypeError('Expected "'.concat(s.name,'" to match "').concat(s.pattern,'", but got "').concat(l,'"'));n+=s.prefix+l+s.suffix}}else n+=s}return n}}(N(e,t),t)}function M(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function F(e){return e&&e.sensitive?"":"i"}function L(e,t,n){return function(e,t,n){void 0===n&&(n={});for(var r=n.strict,i=void 0!==r&&r,s=n.start,o=void 0===s||s,a=n.end,c=void 0===a||a,h=n.encode,u=void 0===h?function(e){return e}:h,f=n.delimiter,l=void 0===f?"/#?":f,m=n.endsWith,d="[".concat(M(void 0===m?"":m),"]|$"),p="[".concat(M(l),"]"),y=o?"^":"",g=0,v=e;g<v.length;g++){var b=v[g];if("string"==typeof b)y+=M(u(b));else{var E=M(u(b.prefix)),w=M(u(b.suffix));if(b.pattern)if(E||w)if("+"===b.modifier||"*"===b.modifier){var O="*"===b.modifier?"?":"";y+="(?:".concat(E,"((?:").concat(b.pattern,")(?:").concat(w).concat(E,"(?:").concat(b.pattern,"))*)").concat(w,")").concat(O)}else y+="(?:".concat(E,"(").concat(b.pattern,")").concat(w,")").concat(b.modifier);else{if("+"===b.modifier||"*"===b.modifier)throw new TypeError('Can not repeat "'.concat(b.name,'" without a prefix and suffix'));y+="(".concat(b.pattern,")").concat(b.modifier)}else y+="(?:".concat(E).concat(w,")").concat(b.modifier)}}if(c)i||(y+="".concat(p,"?")),y+=n.endsWith?"(?=".concat(d,")"):"$";else{var x=e[e.length-1],k="string"==typeof x?p.indexOf(x[x.length-1])>-1:void 0===x;i||(y+="(?:".concat(p,"(?=").concat(d,"))?")),k||(y+="(?=".concat(p,"|").concat(d,")"))}return new RegExp(y,F(n))}(N(e,n),0,n)}function q(e,t,n){return e instanceof RegExp?function(e){return e}(e):Array.isArray(e)?function(e,t,n){var r=e.map((function(e){return q(e,t,n).source}));return new RegExp("(?:".concat(r.join("|"),")"),F(n))}(e,t,n):L(e,0,n)}function U(e,n){if("object"!=typeof e||void 0===e||Array.isArray(e))return;if(e instanceof v)return n(e);const r=t({},e instanceof f?e.schema:e);for(const e in r){if(!r[e])continue;const t=U(r[e],n);if(t)return t}}function V(e,n){if("object"!=typeof e||void 0===e)return e;if(e instanceof v)return n(e);const r=t({},e instanceof f?e.schema:e);for(const e in r)r[e]&&(r[e]=V(r[e],n));return r}Object.hasOwn=Object.hasOwn||function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};class D extends Error{constructor(e){super(`${e.url}: ${e.statusText||`Status not 'ok': ${e.status}`}`),this.name="NetworkError",this.status=e.status,this.response=e}}function W(e,t){const n=new Set(e),r=[...e];for(const e of t)n.has(e)||r.push(e);return r}const H=new Map;function G(e){return H.has(e)||H.set(e,I(e,{encode:encodeURIComponent,validate:!1})),H.get(e)}const J=new Map;function B(e){return J.has(e)||J.set(e,new Set(N(e).map((e=>"string"==typeof e?e:`${e.name}`)))),J.get(e)}const Q=Object.prototype,X=Object.getPrototypeOf;var Y=i("hasBody");class Z extends ${constructor(e){var t;super(null!=(t=e.fetch)?t:async function(...e){const t=n(this,Y)[Y]&&e.length<2?{}:e[0]||{},r=n(this,Y)[Y]?e[e.length-1]:void 0;return this.fetchResponse(this.url(t),await this.getRequestInit(r)).then((e=>this.parseResponse(e))).then((t=>this.process(t,...e)))},e),Object.defineProperty(this,Y,{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=""),n(this,Y)[Y]=!("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(n(this,Y)[Y]&&e.length<2?{}:e[0]||{})}`}url(e={}){const t=G(this.path)(e),n=B(this.path),r={};return Object.keys(e).forEach((t=>{n.has(t)||(r[t]=e[t])})),Object.keys(r).length?`${this.urlPrefix}${t}?${this.searchToString(r)}`:`${this.urlPrefix}${t}`}searchToString(e){return function(e){const t=new URLSearchParams(e);return t.sort(),t.toString()}(e)}getHeaders(e){return e}async getRequestInit(e){const n=null!==(r=e)&&"object"==typeof r&&X(r)===Q;var r;n&&(e=JSON.stringify(e));const i=t({},this.requestInit,{method:this.method,signal:this.signal,body:e});return e&&!n||(i.headers=t({"Content-Type":"application/json"},i.headers)),i.headers=await this.getHeaders(i.headers),i}fetchResponse(e,t){return fetch(e,t).then((e=>{if(!e.ok)throw new D(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!==Z.prototype.process)return t;const n=new D(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 q(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 n extends this.constructor{}return Object.assign(n.prototype,this),new n(t({fetch:this.fetch},e))}paginated(e){if("string"==typeof e){const n=e;e=e=>{let r=t({},(function(e){if(null==e)throw new TypeError("Cannot destructure "+e)}(e),e));return delete r[n],[r]}}let n=!1;const r=V(this.schema,(t=>(n=!0,function(e,t){return Object.create(t,{name:{value:`Pagination(${t.schema})`},merge:{value:W},pk:{value:function(n,r,i,s){return t.pk.call(this,n,r,i,e(...s))}}})}(e,t))));if(!n)throw new Error("Missing Collection");const i=this;return this.extend({schema:r,key(...t){return i.key.call(this,...e(...t))},name:this.name+".getPage"})}get getPage(){return this.paginated(this.paginationField)}get push(){return this.extend({method:"POST",schema:U(this.schema,(e=>e.push)),name:this.name+".create"})}get unshift(){return this.extend({method:"POST",schema:U(this.schema,(e=>e.unshift)),name:this.name+".create"})}get assign(){return this.extend({method:"POST",schema:U(this.schema,(e=>e.assign)),name:this.name+".create"})}get remove(){return this.extend({method:"PATCH",schema:U(this.schema,(e=>e.remove)),name:this.name+".remove"})}}const ee=["path","schema","Endpoint","Collection","optimistic","paginationField"],{Invalidate:te,Collection:ne}=j;function re(e){let{path:n,schema:r,Endpoint:i=Z,Collection:s=ne,optimistic:o,paginationField:a}=e,c=k(e,ee);const h=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),u=e=>`${null==r?void 0:r.name}.${e}`;function f(e,t,n){e[t]=e[t].extend(n)}const l=t({},c),m=t({},c),d=new i(t({},c,{path:n,schema:r,name:u("get")}));o&&(l.getOptimisticResponse=ie,m.getOptimisticResponse=function(e){return function(n,r,i){const s=n.get(e,r);if(!s)throw n.abort;return t({},r,s,oe(i))}}(r));const p=new i(t({},l,{paginationField:a,path:h,schema:new s([r]),name:u("getList")}));return{get:d,getList:p,create:p.push.extend({name:u("create")}),update:new i(t({},l,{path:n,schema:r,method:"PUT",name:u("update")})),partialUpdate:new i(t({},m,{path:n,schema:r,method:"PATCH",name:u("partialUpdate")})),delete:new i(t({},l,{path:n,schema:r.process||r._hoistable?new te(r):r,method:"DELETE",name:u("delete"),process:(e,t)=>e&&Object.keys(e).length?e:t,getOptimisticResponse:o?se:void 0})),extend(...e){if("string"==typeof e[0]){const[n,r]=e;if(n in this){const e=t({},this);return f(e,n,r),e}return t({},this,{[n]:this.get.extend(r)})}if("function"==typeof e[0]){return t({},this,e[0](this))}const n=e[0],r=t({},this);for(const e in n)f(r,e,n[e]);return r}}}function ie(e,n,r){return t({},n,oe(r))}function se(e,t){return t}function oe(e){return e instanceof FormData?Object.fromEntries(e.entries()):e}e.Endpoint=$,e.Entity=P,e.EntityMixin=S,e.ExtendableEndpoint=K,e.NetworkError=D,e.RestEndpoint=Z,e.createResource=re,e.getUrlBase=G,e.getUrlTokens=B,e.hookifyResource=function(e,t){const n={};return Object.keys(e).forEach((r=>{const i=e[r];var s;void 0!==i.extend&&(n[`use${s=r,s.charAt(0).toUpperCase()+s.slice(1)}`]=()=>{const e=t();return i.extend({requestInit:e})})})),n},e.resource=re,e.schema=j,e.validateRequired=function(e,t){let n="";if(Object.keys(t).some((t=>!Object.hasOwn(e,t)&&(n=t,!0))))return`Missing key ${n}`}}));
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(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},t.apply(null,arguments)}function n(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var r=0;function i(e){return"__private_"+r+++"_"+e}function s(e){return!("function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}class o{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){e._hoistable&&!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]}schemaKey(){return this.isSingleSchema?this.schema.key:Object.values(this.schema).join(";")}normalizeValue(e,t,n,r,i){if(!e)return e;const s=this.isSingleSchema,o=s?this.schema:this.schema[this._schemaAttribute(e,t,n)];if(!o)return e;const a=i(o,e,t,n,r);return s||null==a?a:{id:a,schema:this._schemaAttribute(e,t,n)}}denormalizeValue(e,t){const n=this.isSingleSchema,r=!n&&e&&(s(e)?e.get("schema"):e.schema);if(!n&&!r){if("object"==typeof e&&null!==e){const n=this.inferSchema(e,void 0,void 0);if(n)return t(n,e)}return e}const i=n?void 0:s(e)?e.get("id"):e.id;return t(n?this.schema:this.schema[r],i||e)}}class a extends o{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t),this._hoistable=!0}normalize(e,t,n,r,i){return this.normalizeValue(e,t,n,r,i)}denormalize(e,t,n){return this.denormalizeValue(e,n)}queryKey(e,t){if(!e[0])return;const n=this.getSchemaAttribute(e[0],void 0,""),r=this.schema[n];if(r){const i=t(r,e);if(void 0===i)return;return{id:i,schema:n}}for(const n in this.schema){const r=t(this.schema[n],e);if(void 0!==r)return{id:r,schema:n}}}}class c extends o{normalize(e,t,n,r,i,s){const o={},a=Object.keys(e);for(let t=0;t<a.length;t++){const n=a[t],s=e[n];null!=s&&(o[n]=this.normalizeValue(s,e,n,r,i))}return o}denormalize(e,t,n){const r={},i=Object.keys(e);for(let t=0;t<i.length;t++){const s=i[t],o=e[s],a=this.denormalizeValue(o,n);a&&"symbol"!=typeof a&&(r[s]=a)}return r}queryKey(e,t,n){}}const h=e=>void 0!==e&&"symbol"!=typeof e;class u extends o{normalize(e,t,n,r,i){const s=(e=>Array.isArray(e)?e:Object.keys(e).map((t=>e[t])))(e);return s.map((e=>this.normalizeValue(e,t,n,r,i)))}denormalize(e,t,n){return e.map?e.map((e=>this.denormalizeValue(e,n))).filter(h):e}queryKey(e,t,n){}toJSON(){return[this.schema]}}class l extends u{constructor(e,t){super(e,t)}normalize(e,t,n,r,i){super.normalize(e,t,n,r,i)}queryKey(e,t,n){if(this.isSingleSchema){const e=n.getEntities(this.schema.key);return e?[...e.keys()]:n.INVALID}let r=!1;const i=Object.values(this.schema).flatMap((e=>{const t=n.getEntities(e.key);if(!t)return[];r=!0;const i=[];for(const[n,r]of t.entries())r&&"symbol"!=typeof r&&i.push({id:e.pk(r,void 0,n,[]),schema:this.getSchemaAttribute(r,void 0,n)});return i}));return r?i:n.INVALID}}function f(e,n,r,i){if(s(n))return function(e,t,n){let r;const i=Object.keys(e).reduce(((t,i)=>{const s=`${i}`,o=n(e[s],t.get(s));return"symbol"==typeof o&&(r=o),t.has(s)?t.set(s,o):t}),t);return null!=r?r:i}(e,n,i);const o=t({},n),a=Object.keys(e);for(let t=0;t<a.length;t++){const n=a[t],r=i(e[n],o[n]);if(void 0!==o[n]&&(o[n]=r),"symbol"==typeof r)return r}return o}class m{constructor(e){this.schema=void 0,this.define(e)}define(e){this.schema=Object.keys(e).reduce(((n,r)=>{const i=e[r];return t({},n,{[r]:i})}),this.schema||{})}normalize(...e){return((e,n,r,i,s,o)=>{const a=t({},n),c=Object.keys(e);for(let t=0;t<c.length;t++){const r=c[t],i=o(e[r],n[r],n,r,s);void 0===i?delete a[r]:a[r]=i}return a})(this.schema,...e)}denormalize(e,t,n){return f(this.schema,e,0,n)}queryKey(e,t){return function(e,t,n){const r={},i=Object.keys(e);for(let s=0;s<i.length;s++){const o=i[s];r[o]=n(e[o],t)}return r}(this.schema,e,t)}}let d=class extends o{constructor(e,t){super(e,t)}get key(){return this.schemaKey()}normalize(e,t,n,r,i,s){const o=this.inferSchema(e,t,n);if(!o)return e;let a;if("string"==typeof e||"number"==typeof e)a=e;else{const i=o.process(e,t,n,r);a=o.pk(null!=i?i:e,t,n,r)}return a=`${a}`,s.invalidate(o,a),this.isSingleSchema?a:{id:a,schema:this.getSchemaAttribute(e,t,n)}}queryKey(e,t,n){}denormalize(e,t,n){return this.denormalizeValue(e,n)}_denormalizeNullable(){return{}}_normalizeNullable(){return{}}};const p=(e,t)=>[...e,...t],y=(e,t)=>[...t,...e],g=(e,n)=>t({},e,n),v=(e,t)=>e.filter((e=>!t.some((t=>{return r=t,"object"==typeof(n=e)&&"object"==typeof r?n.id===r.id&&n.schema===r.schema:n===r;var n,r})))),b=e=>[...e],E=e=>t({},e);class w{addWith(e,t){return O(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,n){if(this.schema=Array.isArray(e)?new u(e[0]):e,n?"nestKey"in n?this.nestKey=n.nestKey:this.argsKey="argsKey"in n?n.argsKey:e=>t({},e):this.argsKey=e=>t({},e),this.key=function(e){if(e instanceof u)return`[${e.schemaKey()}]`;if(e instanceof c)return`{${e.schemaKey()}}`;return`(${e.schemaKey()})`}(this.schema),null!=n&&n.nonFilterArgumentKeys){const{nonFilterArgumentKeys:e}=n;"function"==typeof e?this.nonFilterArgumentKeys=e:e instanceof RegExp?this.nonFilterArgumentKeys=t=>e.test(t):this.nonFilterArgumentKeys=t=>e.includes(t)}else null!=n&&n.createCollectionFilter&&(this.createCollectionFilter=n.createCollectionFilter.bind(this));this.schema instanceof u?(this.createIfValid=b,this.push=O(this,p),this.unshift=O(this,y),this.remove=O(this,v)):e instanceof c&&(this.createIfValid=E,this.assign=O(this,g))}get cacheWith(){return this.schema.schema}toString(){return this.key}toJSON(){return{key:this.key,schema:this.schema.schema}}pk(e,t,n,r){const i=this.argsKey?this.argsKey(...r):this.nestKey(t,n);for(const e in i)["number","boolean"].includes(typeof i[e])&&(i[e]=`${i[e]}`);return function(e){const t=Object.keys(e).sort(),n={};for(const r of t)n[r]=e[r];return JSON.stringify(n)}(i)}normalize(e,t,n,r,i,s){const o=this.schema.normalize(e,t,n,r,i,s),a=this.pk(o,t,n,r);return s.mergeEntity(this,a,o),a}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}queryKey(e,t,n){if(this.argsKey){const t=this.pk(void 0,void 0,"",e);if(n.getEntity(this.key,t))return t}}denormalize(e,t,n){return this.schema.denormalize(e,t,n)}}function O(e,t,n){const r={merge:{value:t},normalize:{value:k},queryKey:{value:x}};return e.schema instanceof u&&(r.createIfValid={value:A},r.denormalize={value:S}),n&&(r.createCollectionFilter={value:n}),Object.create(e,r)}function x(){}function k(e,t,n,r,i,s){const o=this.schema.normalize(this.schema instanceof u&&!Array.isArray(e)?[e]:e,t,n,r,i,s),a=this.createCollectionFilter(...r),c=s.getEntities(this.key);if(c)for(const e of c.keys())a(JSON.parse(e))&&s.mergeEntity(this,e,o);return o}function A(e){return Array.isArray(e)?[...e]:t({},e)}function S(e,t,n){return Array.isArray(e)?this.schema.denormalize(e,t,n):this.schema.denormalize([e],t,n)[0]}function j(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}const _=["pk","schema","key"];function P(e,n={}){class r extends e{static toString(){return this.key}static toJSON(){return{key:this.key,schema:this.schema}}static pk(e,t,n,r){return this.prototype.pk.call(e,t,n,r)}static shouldUpdate(e,t,n,r){return!0}static shouldReorder(e,t,n,r){return t.fetchedAt<e.fetchedAt}static merge(e,n){return t({},e,n)}static mergeWithStore(e,t,n,r){return this.shouldUpdate(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,n,r,i){return t({},e)}static normalize(e,t,n,r,i,s){const o=this.process(e,t,n,r);let a;if(void 0===o)return a=`${this.pk(e,t,n,r)}`,s.invalidate(this,a),a;if(a=this.pk(o,t,n,r),a=void 0===a||""===a||"undefined"===a?`MISS-${Math.random()}`:`${a}`,s.checkLoop(this.key,a,e))return a;!function(e){if(e){const t=new Error(e);throw t.status=400,t}}(this.validate(o));const c=Object.keys(this.schema);for(let e=0;e<c.length;e++){const t=c[e];Object.hasOwn(o,t)&&(o[t]=i(this.schema[t],o[t],o,t,r))}return s.mergeEntity(this,a,o),a}static validate(e){}static queryKey(e,t,n){if(!e[0])return;const r=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 i=(s=t[0],o=e.indexes,o?o.find((e=>Object.hasOwn(s,e))):void 0);var s,o;if(!i)return;const a=t[0][i];return n.getIndex(e.key,i,a)}(this,e,n);return r&&n.getEntity(this.key,r)?r:void 0}static denormalize(e,t,n){if("symbol"==typeof e)return e;for(const t of Object.keys(this.schema)){const r=n(this.schema[t],e[t]);if("symbol"==typeof r){if(this.defaults[t])return r;e[t]=void 0}else e[t]=r}return e}static get defaults(){return Object.hasOwn(this,"__defaults")||Object.defineProperty(this,"__defaults",{value:new this,writable:!0,configurable:!0}),this.__defaults}}const i=j(n,_);if(Object.assign(r,i),"schema"in n?r.schema=n.schema:e.schema||(r.schema={}),"pk"in n?"function"==typeof n.pk?r.prototype.pk=function(e,t){return n.pk(this,e,t)}:r.prototype.pk=function(){return this[n.pk]}:"function"!=typeof e.prototype.pk&&(r.prototype.pk=function(){return this.id}),"key"in n)Object.defineProperty(r,"key",{value:n.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 o=function(){return"EntityMixin"===this.name?e.name:this.name},a="undefined"!=typeof document&&document.CLS_MANGLE?function(){return null==document.CLS_MANGLE||document.CLS_MANGLE(this),Object.defineProperty(r,"key",{get:o,set:s,enumerable:!0,configurable:!0}),o.call(this)}:o;Object.defineProperty(r,"key",{get:a,set:s,enumerable:!0,configurable:!0})}return r}class R{constructor(e,t){this.schema=e,this.process=t}normalize(...e){return this.schema.normalize(...e)}denormalize(e,t,n){const r=n(this.schema,e);return"symbol"==typeof r?r:this.process(r,...t)}queryKey(e,t){return t(this.schema,e)}}var T=Object.freeze({__proto__:null,All:l,Array:u,Collection:w,Entity:P,EntityMixin:P,Invalidate:d,Object:m,Query:R,Union:a,Values:c});const C=class{};class z extends(P(C)){static process(e,t,n,r){return super.process(e,t,n,r)}}var $;const K="undefined"!=typeof document;let N=K&&!(null!=($=document.querySelector("meta[http-equiv='Content-Security-Policy']"))&&$.getAttribute("content"));try{N||Function()}catch(e){N=!0,K&&console.error("Content Security Policy: The previous CSP log can be safely ignored - @data-client/endpoint will use setPrototypeOf instead")}var I;class M 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=M,(()=>{if("undefined"!=typeof document&&document.FUNC_MANGLE){const e=I.prototype.key;I.prototype.key=function(...t){return null==document.FUNC_MANGLE||document.FUNC_MANGLE(this),this.prototype.key=e,e.call(this,...t)}}})();const F=M;function L(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,s="";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));s+=e[a++]}else s+=e[a++]+e[a++];if(i)throw new TypeError("Unbalanced pattern at ".concat(n));if(!s)throw new TypeError("Missing pattern at ".concat(n));t.push({type:"PATTERN",index:n,value:s}),n=a}else{for(var o="",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;o+=e[a++]}if(!o)throw new TypeError("Missing parameter name at ".concat(n));t.push({type:"NAME",index:n,value:o}),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,s=t.delimiter,o=void 0===s?"/#?":s,a=[],c=0,h=0,u="",l=function(e){if(h<n.length&&n[h].type===e)return n[h++].value},f=function(e){var t=l(e);if(void 0!==t)return t;var r=n[h],i=r.type,s=r.index;throw new TypeError("Unexpected ".concat(i," at ").concat(s,", expected ").concat(e))},m=function(){for(var e,t="";e=l("CHAR")||l("ESCAPED_CHAR");)t+=e;return t},d=function(e){var t=a[a.length-1],n=e||(t&&"string"==typeof t?t:"");if(t&&!n)throw new TypeError('Must have text between two parameters, missing text after "'.concat(t.name,'"'));return!n||function(e){for(var t=0,n=o;t<n.length;t++){var r=n[t];if(e.indexOf(r)>-1)return!0}return!1}(n)?"[^".concat(q(o),"]+?"):"(?:(?!".concat(q(n),")[^").concat(q(o),"])+?")};h<n.length;){var p=l("CHAR"),y=l("NAME"),g=l("PATTERN");if(y||g){var v=p||"";-1===i.indexOf(v)&&(u+=v,v=""),u&&(a.push(u),u=""),a.push({name:y||c++,prefix:v,suffix:"",pattern:g||d(v),modifier:l("MODIFIER")||""})}else{var b=p||l("ESCAPED_CHAR");if(b)u+=b;else if(u&&(a.push(u),u=""),l("OPEN")){v=m();var E=l("NAME")||"",w=l("PATTERN")||"",O=m();f("CLOSE"),a.push({name:E||(w?c++:""),pattern:E&&!w?d(v):w,prefix:v,suffix:O,modifier:l("MODIFIER")||""})}else f("END")}}return a}function U(e,t){return function(e,t){void 0===t&&(t={});var n=V(t),r=t.encode,i=void 0===r?function(e){return e}:r,s=t.validate,o=void 0===s||s,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 s=e[r];if("string"!=typeof s){var c=t?t[s.name]:void 0,h="?"===s.modifier||"*"===s.modifier,u="*"===s.modifier||"+"===s.modifier;if(Array.isArray(c)){if(!u)throw new TypeError('Expected "'.concat(s.name,'" to not repeat, but got an array'));if(0===c.length){if(h)continue;throw new TypeError('Expected "'.concat(s.name,'" to not be empty'))}for(var l=0;l<c.length;l++){var f=i(c[l],s);if(o&&!a[r].test(f))throw new TypeError('Expected all "'.concat(s.name,'" to match "').concat(s.pattern,'", but got "').concat(f,'"'));n+=s.prefix+f+s.suffix}}else if("string"!=typeof c&&"number"!=typeof c){if(!h){var m=u?"an array":"a string";throw new TypeError('Expected "'.concat(s.name,'" to be ').concat(m))}}else{f=i(String(c),s);if(o&&!a[r].test(f))throw new TypeError('Expected "'.concat(s.name,'" to match "').concat(s.pattern,'", but got "').concat(f,'"'));n+=s.prefix+f+s.suffix}}else n+=s}return n}}(L(e,t),t)}function q(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function V(e){return e&&e.sensitive?"":"i"}function D(e,t,n){return function(e,t,n){void 0===n&&(n={});for(var r=n.strict,i=void 0!==r&&r,s=n.start,o=void 0===s||s,a=n.end,c=void 0===a||a,h=n.encode,u=void 0===h?function(e){return e}:h,l=n.delimiter,f=void 0===l?"/#?":l,m=n.endsWith,d="[".concat(q(void 0===m?"":m),"]|$"),p="[".concat(q(f),"]"),y=o?"^":"",g=0,v=e;g<v.length;g++){var b=v[g];if("string"==typeof b)y+=q(u(b));else{var E=q(u(b.prefix)),w=q(u(b.suffix));if(b.pattern)if(E||w)if("+"===b.modifier||"*"===b.modifier){var O="*"===b.modifier?"?":"";y+="(?:".concat(E,"((?:").concat(b.pattern,")(?:").concat(w).concat(E,"(?:").concat(b.pattern,"))*)").concat(w,")").concat(O)}else y+="(?:".concat(E,"(").concat(b.pattern,")").concat(w,")").concat(b.modifier);else{if("+"===b.modifier||"*"===b.modifier)throw new TypeError('Can not repeat "'.concat(b.name,'" without a prefix and suffix'));y+="(".concat(b.pattern,")").concat(b.modifier)}else y+="(?:".concat(E).concat(w,")").concat(b.modifier)}}if(c)i||(y+="".concat(p,"?")),y+=n.endsWith?"(?=".concat(d,")"):"$";else{var x=e[e.length-1],k="string"==typeof x?p.indexOf(x[x.length-1])>-1:void 0===x;i||(y+="(?:".concat(p,"(?=").concat(d,"))?")),k||(y+="(?=".concat(p,"|").concat(d,")"))}return new RegExp(y,V(n))}(L(e,n),0,n)}function W(e,t,n){return e instanceof RegExp?function(e){return e}(e):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("|"),")"),V(n))}(e,t,n):D(e,0,n)}function H(e,n){if("object"!=typeof e||void 0===e||Array.isArray(e))return;if(e instanceof w)return n(e);const r=t({},e instanceof m?e.schema:e);for(const e in r){if(!r[e])continue;const t=H(r[e],n);if(t)return t}}function G(e,n){if("object"!=typeof e||void 0===e)return e;if(e instanceof w)return n(e);const r=t({},e instanceof m?e.schema:e);for(const e in r)r[e]&&(r[e]=G(r[e],n));return r}Object.hasOwn=Object.hasOwn||function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};class J extends Error{constructor(e){super(`${e.url}: ${e.statusText||`Status not 'ok': ${e.status}`}`),this.name="NetworkError",this.status=e.status,this.response=e}}function B(e,t){const n=new Set(e),r=[...e];for(const e of t)n.has(e)||r.push(e);return r}const Q=new Map;function X(e){return Q.has(e)||Q.set(e,U(e,{encode:encodeURIComponent,validate:!1})),Q.get(e)}const Y=new Map;function Z(e){return Y.has(e)||Y.set(e,new Set(L(e).map((e=>"string"==typeof e?e:`${e.name}`)))),Y.get(e)}const ee=Object.prototype,te=Object.getPrototypeOf;var ne=i("hasBody");class re extends M{constructor(e){var t;super(null!=(t=e.fetch)?t:async function(...e){const t=n(this,ne)[ne]&&e.length<2?{}:e[0]||{},r=n(this,ne)[ne]?e[e.length-1]:void 0;return this.fetchResponse(this.url(t),await this.getRequestInit(r)).then((e=>this.parseResponse(e))).then((t=>this.process(t,...e)))},e),Object.defineProperty(this,ne,{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=""),n(this,ne)[ne]=!("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(n(this,ne)[ne]&&e.length<2?{}:e[0]||{})}`}url(e={}){const t=X(this.path)(e),n=Z(this.path),r={};return Object.keys(e).forEach((t=>{n.has(t)||(r[t]=e[t])})),Object.keys(r).length?`${this.urlPrefix}${t}?${this.searchToString(r)}`:`${this.urlPrefix}${t}`}searchToString(e){return function(e){const t=new URLSearchParams(e);return t.sort(),t.toString()}(e)}getHeaders(e){return e}async getRequestInit(e){const n=null!==(r=e)&&"object"==typeof r&&te(r)===ee;var r;n&&(e=JSON.stringify(e));const i=t({},this.requestInit,{method:this.method,signal:this.signal,body:e});return e&&!n||(i.headers=t({"Content-Type":"application/json"},i.headers)),i.headers=await this.getHeaders(i.headers),i}fetchResponse(e,t){return fetch(e,t).then((e=>{if(!e.ok)throw new J(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!==re.prototype.process)return t;const n=new J(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 n extends this.constructor{}return Object.assign(n.prototype,this),new n(t({fetch:this.fetch},e))}paginated(e){if("string"==typeof e){const n=e;e=e=>{let r=t({},(function(e){if(null==e)throw new TypeError("Cannot destructure "+e)}(e),e));return delete r[n],[r]}}let n=!1;const r=G(this.schema,(t=>(n=!0,function(e,t){return Object.create(t,{name:{value:`Pagination(${t.schema})`},merge:{value:B},pk:{value:function(n,r,i,s){return t.pk.call(this,n,r,i,e(...s))}}})}(e,t))));if(!n)throw new Error("Missing Collection");const i=this;return this.extend({schema:r,key(...t){return i.key.call(this,...e(...t))},name:this.name+".getPage"})}get getPage(){return this.paginated(this.paginationField)}get push(){return this.extend({method:"POST",schema:H(this.schema,(e=>e.push)),name:this.name+".create"})}get unshift(){return this.extend({method:"POST",schema:H(this.schema,(e=>e.unshift)),name:this.name+".create"})}get assign(){return this.extend({method:"POST",schema:H(this.schema,(e=>e.assign)),name:this.name+".create"})}get remove(){return this.extend({method:"PATCH",schema:H(this.schema,(e=>e.remove)),name:this.name+".remove"})}}const ie=["path","schema","Endpoint","Collection","optimistic","paginationField"],{Invalidate:se,Collection:oe}=T;function ae(e){let{path:n,schema:r,Endpoint:i=re,Collection:s=oe,optimistic:o,paginationField:a}=e,c=j(e,ie);const h=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),u=e=>`${null==r?void 0:r.name}.${e}`;function l(e,t,n){e[t]=e[t].extend(n)}const f=t({},c),m=t({},c),d=new i(t({},c,{path:n,schema:r,name:u("get")}));o&&(f.getOptimisticResponse=ce,m.getOptimisticResponse=function(e){return function(n,r,i){const s=n.get(e,r);if(!s)throw n.abort;return t({},r,s,ue(i))}}(r));const p=new i(t({},f,{paginationField:a,path:h,schema:new s([r]),name:u("getList")}));return{get:d,getList:p,create:p.push.extend({name:u("create")}),update:new i(t({},f,{path:n,schema:r,method:"PUT",name:u("update")})),partialUpdate:new i(t({},m,{path:n,schema:r,method:"PATCH",name:u("partialUpdate")})),delete:new i(t({},f,{path:n,schema:r.process||r._hoistable?new se(r):r,method:"DELETE",name:u("delete"),process:(e,t)=>e&&Object.keys(e).length?e:t,getOptimisticResponse:o?he:void 0})),extend(...e){if("string"==typeof e[0]){const[n,r]=e;if(n in this){const e=t({},this);return l(e,n,r),e}return t({},this,{[n]:this.get.extend(r)})}if("function"==typeof e[0]){return t({},this,e[0](this))}const n=e[0],r=t({},this);for(const e in n)l(r,e,n[e]);return r}}}function ce(e,n,r){return t({},n,ue(r))}function he(e,t){return t}function ue(e){return e instanceof FormData?Object.fromEntries(e.entries()):e}e.All=l,e.Collection=w,e.Endpoint=M,e.Entity=z,e.EntityMixin=P,e.ExtendableEndpoint=F,e.Invalidate=d,e.NetworkError=J,e.Query=R,e.RestEndpoint=re,e.Union=a,e.Values=c,e.createResource=ae,e.getUrlBase=X,e.getUrlTokens=Z,e.hookifyResource=function(e,t){const n={};return Object.keys(e).forEach((r=>{const i=e[r];var s;void 0!==i.extend&&(n[`use${s=r,s.charAt(0).toUpperCase()+s.slice(1)}`]=()=>{const e=t();return i.extend({requestInit:e})})})),n},e.resource=ae,e.schema=T,e.validateRequired=function(e,t){let n="";if(Object.keys(t).some((t=>!Object.hasOwn(e,t)&&(n=t,!0))))return`Missing key ${n}`}}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@data-client/rest",
3
- "version": "0.15.4",
3
+ "version": "0.15.5",
4
4
  "description": "Quickly define typed REST resources and endpoints",
5
5
  "homepage": "https://dataclient.io/rest",
6
6
  "repository": {
@@ -135,7 +135,7 @@
135
135
  "license": "Apache-2.0",
136
136
  "dependencies": {
137
137
  "@babel/runtime": "^7.20.0",
138
- "@data-client/endpoint": "^0.15.4",
138
+ "@data-client/endpoint": "^0.15.5",
139
139
  "path-to-regexp": "^6.3.0"
140
140
  },
141
141
  "devDependencies": {
@@ -1,4 +1,4 @@
1
- import { Entity, schema } from '@data-client/endpoint';
1
+ import { Entity, schema, Collection } from '@data-client/endpoint';
2
2
  import { useController } from '@data-client/react';
3
3
  import { useSuspense } from '@data-client/react';
4
4
  import { CacheProvider } from '@data-client/react';
@@ -50,7 +50,7 @@ const getArticleList = new RestEndpoint({
50
50
  path: '/article-paginated',
51
51
  schema: {
52
52
  nextPage: '',
53
- data: { results: new schema.Collection([PaginatedArticle]) },
53
+ data: { results: new Collection([PaginatedArticle]) },
54
54
  },
55
55
  method: 'GET',
56
56
  });
@@ -64,7 +64,7 @@ const getArticleList2 = new RestEndpoint({
64
64
  name: 'get',
65
65
  schema: {
66
66
  nextPage: '',
67
- data: { results: new schema.Collection([PaginatedArticle]) },
67
+ data: { results: new Collection([PaginatedArticle]) },
68
68
  },
69
69
  method: 'GET',
70
70
  });
@@ -83,7 +83,7 @@ const getArticleList3 = new RestEndpoint({
83
83
  path: '/article-paginated',
84
84
  schema: {
85
85
  nextPage: '',
86
- data: { results: new schema.Collection([PaginatedArticle]) },
86
+ data: { results: new Collection([PaginatedArticle]) },
87
87
  },
88
88
  method: 'GET',
89
89
  searchParams: {} as { group: string | number },
@@ -100,7 +100,7 @@ const getNextPage3 = getArticleList3.getPage;
100
100
  path: '/article-paginated',
101
101
  schema: {
102
102
  nextPage: '',
103
- data: { results: new schema.Collection([PaginatedArticle]) },
103
+ data: { results: new Collection([PaginatedArticle]) },
104
104
  },
105
105
  method: 'GET',
106
106
  });
@@ -119,7 +119,7 @@ const getNextPage3 = getArticleList3.getPage;
119
119
  path: '/article-paginated',
120
120
  schema: {
121
121
  nextPage: '',
122
- data: { results: new schema.Collection([PaginatedArticle]) },
122
+ data: { results: new Collection([PaginatedArticle]) },
123
123
  },
124
124
  method: 'GET',
125
125
  searchParams: {} as { group: string | number },
@@ -1,4 +1,10 @@
1
- import { Entity, PolymorphicInterface, schema } from '@data-client/endpoint';
1
+ import {
2
+ Entity,
3
+ PolymorphicInterface,
4
+ schema,
5
+ Union,
6
+ Query,
7
+ } from '@data-client/endpoint';
2
8
  import type { DefaultArgs } from '@data-client/endpoint';
3
9
  import {
4
10
  CacheProvider,
@@ -946,10 +952,7 @@ describe('resource()', () => {
946
952
  readonly content: string = '';
947
953
  readonly type = 'post' as const;
948
954
  }
949
- const FeedUnion = new schema.Union(
950
- { post: FeedPost, link: FeedLink },
951
- 'type',
952
- );
955
+ const FeedUnion = new Union({ post: FeedPost, link: FeedLink }, 'type');
953
956
  const FeedResource = resource({
954
957
  path: 'http\\://test.com/feed/:id',
955
958
  schema: FeedUnion,
@@ -1303,7 +1306,7 @@ describe('resource()', () => {
1303
1306
  searchParams: {} as { userId?: string | number } | undefined,
1304
1307
  });
1305
1308
 
1306
- const queryRemainingTodos = new schema.Query(
1309
+ const queryRemainingTodos = new Query(
1307
1310
  TodoResource.getList.schema,
1308
1311
  entries => entries.filter(todo => !todo.completed).length,
1309
1312
  );