UNPKG

@har-sdk/openapi-sampler

Version:

[![Maintainability](https://api.codeclimate.com/v1/badges/4acaec95c82465cb2c3d/maintainability)](https://codeclimate.com/github/NeuraLegion/har-sdk/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/4acaec95c82465cb2c3d/test_coverage

3 lines (2 loc) 12.5 kB
var e,t;e=this,t=function(e,t,r){function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=a(t),i=a(r);const n=e=>e&&"object"==typeof e,l=(...e)=>e.reduce(((e,t)=>(Object.keys(t).forEach((r=>{const a=e[r],s=t[r];n(a)&&n(s)?e[r]=l(a,s):e[r]=s})),e)),Array.isArray(e[e.length-1])?[]:{}),o=e=>e[0],u=e=>void 0!==e.items;class m{constructor(e){this.traverse=e}sample(e,t,r){let a=e.minItems||1;u(e)&&Array.isArray(e.items)&&(a=Math.max(a,e.items.length));const s=[];if(!u(e))return s;for(let n=0;n<a;n++){const a=(i=n,u(e)&&Array.isArray(e.items)?e.items[i]||{}:u(e)?e.items:{});s.push(this.traverse.traverse(a,r,t).value)}var i;return s}}class h{sample(e){return!0}}class c{constructor(){this.EPS=.001}sample(e){const t="integer"===(e.type?e.type:"number"),r=this.getMinimum(e),a=this.getMaximum(e);let s,i=!1;return r?s=this.sampleUsingMinimum(r,t):a&&(i=!0,s=this.sampleUsingMaximum(a,t)),e.multipleOf&&(s=this.roundUp(null!=s?s:e.multipleOf,e.multipleOf),s=i?s-e.multipleOf:s),this.ensureBoundaries(null!=s?s:42,{minimum:r,maximum:a,schema:e})}sampleUsingMinimum(e,t){let r=e.value,a=e.exclusive;return t&&!Number.isInteger(r)&&(r=Math.ceil(r),a=!1),a?r+(t?1:this.EPS):r}sampleUsingMaximum(e,t){let r=e.value,a=e.exclusive;return t&&!Number.isInteger(r)&&(r=Math.floor(r),a=!1),a?r-(t?1:this.EPS):r}roundUp(e,t){return t&&e?Math.ceil(e/t)*t:0}ensureBoundaries(e,t){const{minimum:r,maximum:a,schema:s}=t;let i=!0;if(r&&(i=this.isValidMinimum(r,e)),a&&(i=this.isValidMaximum(a,e)),i&&s.multipleOf&&!Number.isInteger(e/s.multipleOf)&&(i=!1),!i)throw new Error(`Sample numeric cannot be generated by boundaries: ${this.formatConditions(t)}`);return e}isValidMinimum(e,t){return e.exclusive?t>e.value:t>=e.value}isValidMaximum(e,t){return e.exclusive?t<e.value:t<=e.value}formatConditions({minimum:e,maximum:t,schema:r}){let a="";return e&&(a+=`${e.value} ${e.exclusive?"<":"<="} `),a+="x",t&&(a+=` ${t.exclusive?"<":"<="} ${t.value}`),"multipleOf"in r&&(a+=`, multipleOf: ${r.multipleOf}`),a}getMinimum(e){var t;let r=null!==(t=e.minimum)&&void 0!==t?t:void 0,a=!!e.exclusiveMinimum;return"number"==typeof e.exclusiveMinimum&&(r=e.exclusiveMinimum,a=!0),void 0!==r?{value:r,exclusive:a}:void 0}getMaximum(e){var t;let r=null!==(t=e.maximum)&&void 0!==t?t:void 0,a=!!e.exclusiveMaximum;return"number"==typeof e.exclusiveMaximum&&(r=e.exclusiveMaximum,a=!0),void 0!==r?{value:r,exclusive:a}:void 0}}class p{sample(e){return null}}class d{constructor(e){this.traverse=e}sample(e,t,r){const a={};if(e&&"object"==typeof e.properties){const s=(Array.isArray(e.required)?e.required:[]).reduce(((e,t)=>(e[t]=!0,e)),{});Object.keys(e.properties).forEach((i=>{if((null==r?void 0:r.skipNonRequired)&&!s.hasOwnProperty(i))return;const n=this.traverse.traverse(e.properties[i],r,t);(null==r?void 0:r.skipReadOnly)&&n.readOnly||(null==r?void 0:r.skipWriteOnly)&&n.writeOnly||(a[i]=n.value)}))}return e&&"object"==typeof e.additionalProperties&&(a.property1=this.traverse.traverse(e.additionalProperties,r,t).value,a.property2=this.traverse.traverse(e.additionalProperties,r,t).value),a}}class v{constructor(){this.MAX_PATTERN_SAMPLE_LENGTH=500,this.stringFormats={email:()=>"jon.snow@targaryen.com","idn-email":()=>"джон.сноу@таргариен.укр",password:(e,t)=>this.adjustLength("p@$$w0rd",e,t),"date-time":()=>"2021-12-31T23:34:00Z",date:()=>"2021-12-31",time:()=>"23:34:00Z",duration:()=>"P3D",ipv4:()=>"208.67.222.222",ipv6:()=>"0000:0000:0000:0000:0000:ffff:d043:dcdc",hostname:()=>"brokencrystals.com","idn-hostname":()=>"сломанные-кристаллы.бел",iri:()=>"https://be.wikipedia.org/wiki/%D0%9A%D1%80%D1%8B%D1%88%D1%82%D0%B0%D0%BB%D1%96","iri-reference":()=>"/wiki/%D0%9A%D1%80%D1%8B%D1%88%D1%82%D0%B0%D0%BB%D1%96",uri:()=>"https://github.com/NeuraLegion/brokencrystals","uri-reference":()=>"../brokencrystals","uri-template":()=>"https://brokencrystals.com/api/file/{provider}",byte:()=>"ZHVtbXkgYmluYXJ5IHNhbXBsZQA=",binary:()=>"",base64:()=>"ZHVtbXkgYmluYXJ5IHNhbXBsZQA=",base64url:()=>"bG9yZW0",uuid:()=>"fbdf5a53-161e-4460-98ad-0e39408d8689","json-pointer":()=>"/json/pointer","relative-json-pointer":()=>"1/relative/json/pointer",regex:()=>"/regex/",pattern:(e,t,{pattern:r})=>this.patternSample(r,e,t),default:(e,t)=>this.adjustLength("lorem",e,t)}}sample(e){const t=["base64","base64url"].includes(e.contentEncoding)?e.contentEncoding:"application/octet-stream"===e.contentMediaType?"binary":e.format,r=e.pattern?"pattern":t||"default",a=this.stringFormats[r]||this.stringFormats.default,{minLength:s,maxLength:i}=e;return this.checkLength(a(s,i,e),r,s,i)}patternSample(e,t,r){this.assertLength(t,r);const a=new s.default(e);if(a.randInt=(e,t)=>Math.floor((e+t)/2),void 0!==t)return this.sampleWithMinLength(a,t,r);a.max=null!=r?r:a.max;const i=a.gen();return void 0!==r&&i.length>r&&this.hasInfiniteQuantifier(e)?this.sampleWithMaxLength(a,r):i}hasInfiniteQuantifier(e){const t="string"==typeof e?e:e.source;return/(\+|\*|\{\d*,\})/.test(t)}sampleWithMaxLength(e,t){let r="";for(let a=1;a<=Math.min(t,20)&&(e.max=Math.floor(t/a),r=e.gen(),!(r.length<=t));a++);return r}sampleWithMinLength(e,t,r){const a=e.randInt;e.max=t,e.randInt=(e,t)=>e;let s=e.gen();return e.randInt=a,s.length<t&&(e.max=2*t,s=this.adjustMaxLength(e.gen(),r)),s}checkLength(e,t,r,a){if(r&&e.length<r||a&&e.length>a){const e=[{key:"minLength",value:r},{key:"maxLength",value:a},{key:"format",value:t}].filter((e=>void 0!==e.value)).map((e=>`${e.key}=${e.value}`)).join(", ");throw new Error(`Sample string cannot be generated by boundaries: ${e}`)}return e}assertLength(e,t){const r=[{key:"minLength",value:e},{key:"maxLength",value:t}].filter((e=>!this.checkBoundary(e.value))).map((e=>`${e.key}=${e.value}`)).join(", ");if(r)throw new Error(`Sample string cannot be generated by boundaries: ${r}. Both minLength and maxLength must not exceed ${this.MAX_PATTERN_SAMPLE_LENGTH}`)}checkBoundary(e){return void 0===e||e<=this.MAX_PATTERN_SAMPLE_LENGTH}adjustLength(e,t,r){const a=t||0,s=r||e.length;return a>e.length?e.repeat(Math.trunc(a/e.length)+1).substring(0,a):e.substr(0,Math.min(Math.max(e.length,a),s))}adjustMaxLength(e,t){return t&&e.length>=t?e.substring(0,t):e}}var f;e.VendorExtensions=void 0,(f=e.VendorExtensions||(e.VendorExtensions={})).X_EXAMPLE="x-example",f.X_EXAMPLES="x-examples";class y{extract(t){return[t[e.VendorExtensions.X_EXAMPLE],t[e.VendorExtensions.X_EXAMPLES]].reduce(((e,r)=>e||this.findExampleByShape(r,t)),void 0)}findExampleByShape(e,t){const r=this.getExampleShape(t);return 0===r.objectKeys.length&&0===r.arrayDepth?e:this.traverse(e,r)}getExampleShape(e,t=0){return"items"in e?this.getExampleShape(e.items,1+t):{arrayDepth:t,objectKeys:"properties"in e&&e.properties?Object.keys(e.properties):[]}}traverse(e,t,r=[]){if(e&&"object"==typeof e)return t.arrayDepth>0&&Array.isArray(e)?this.traverseArray(e,t,r):Array.isArray(e)?void 0:this.traverseObject(e,t,r)}traverseArray(e,t,r){return t.arrayDepth>0&&Array.isArray(e)?(r.push(e),this.traverseArray([...e,void 0].shift(),{...t,arrayDepth:t.arrayDepth-1},r)):e&&(Array.isArray(e)||t.arrayDepth>0)?void 0:this.traverseObject(e,t,r)}traverseObject(e,t,r){const a=Object.keys(null!=e?e:{});return 0===t.arrayDepth&&a.every((e=>t.objectKeys.includes(e)))?r.length>0?r.shift():e:a.map((r=>this.traverse(e[r],t))).filter((e=>!!e)).shift()}}class x{constructor(e=new y){this.vendorExampleExtractor=e}extractFromExamples(e,t){let r=this.extractFromSchemaExamples(e);return r=void 0===r?this.extractFromVendorExamples(e,t):r,r}extractFromProperties(e){let t;return(e=>void 0!==e.default)(e)?t=e.default:void 0!==e.const?t=e.const:e.enum&&e.enum.length&&(t=o(e.enum)),t}extractFromSchemaExamples(e){return(e=>void 0!==e.example)(e)?e.example:void 0!==e.examples&&e.examples.length>0?o(e.examples):void 0}extractFromVendorExamples(e,{includeVendorExamples:t}){return t?this.vendorExampleExtractor.extract(e):void 0}}const g={multipleOf:"number",maximum:"number",exclusiveMaximum:"number",minimum:"number",exclusiveMinimum:"number",maxLength:"string",minLength:"string",pattern:"string",items:"array",maxItems:"array",minItems:"array",uniqueItems:"array",additionalItems:"array",maxProperties:"object",minProperties:"object",required:"object",additionalProperties:"object",properties:"object",patternProperties:"object",dependencies:"object"};class b{constructor(e=new x){this.sampleValueExtractor=e,this.NULL="null",this.refCache={},this.schemasStack=[]}get samplers(){return this._samplers}set samplers(e){this._samplers=e}clearCache(){this.refCache={},this.schemasStack=[]}traverse(e,t,r){var a,s;if(!this.samplers||0===this.samplers.size)throw Error("Samplers must be set");return this.checkIfCircleRef(e,t)?this.getReplacementForCircular(e):(this.pushSchemaStack(e),(e=>void 0!==e.$ref)(e)?this.inferRef(r,e,t):null!==(s=null!==(a=this.findSchemaExample(e,t))&&void 0!==a?a:this.tryTraverseSubSchema(e,t,r))&&void 0!==s?s:this.createSchemaExample(e,t,r))}createSchemaExample(e,t,r){const a=e.type;let s=this.sampleValueExtractor.extractFromProperties(e);s=void 0===s?this.createSampleValueFromInferredType(e,t,r):s,this.popSchemaStack();const{readOnly:i,writeOnly:n}=e;return{type:a,readOnly:i,writeOnly:n,value:s}}createSampleValueFromInferredType(e,t,r){var a;let s=e.type;Array.isArray(s)&&(s=null!==(a=s.find((e=>e!==this.NULL)))&&void 0!==a?a:s.find((e=>e===this.NULL))),s||(s=this.inferType(e));const i=this.samplers.get(s||this.NULL);let n;return i&&(n=i.sample(e,r,t)),n}tryTraverseSubSchema(e,t,r){var a,s;return null!==(s=null!==(a=this.tryTraverseAllOf(e,t,r))&&void 0!==a?a:this.tryTraverseOneOf(e,t,r))&&void 0!==s?s:this.tryTraverseAnyOf(e,t,r)}tryTraverseAllOf(e,t,r){if(e.allOf)return this.popSchemaStack(),this.allOfSample({...e,allOf:void 0},e.allOf,t,r)}tryTraverseOneOf(e,t,r){if(e.oneOf&&e.oneOf.length)return e.anyOf&&!t.quiet&&console.warn("oneOf and anyOf are not supported on the same level. Skipping anyOf"),this.popSchemaStack(),this.traverse(o(e.oneOf),t,r)}tryTraverseAnyOf(e,t,r){if(e.anyOf&&e.anyOf.length)return this.popSchemaStack(),this.traverse(o(e.anyOf),t,r)}findSchemaExample(e,t){const r=this.sampleValueExtractor.extractFromExamples(e,t);if(void 0!==r){const{type:t,readOnly:a,writeOnly:s}=e;return this.popSchemaStack(),{type:t,readOnly:a,writeOnly:s,value:r}}}pushSchemaStack(e){this.schemasStack.push(e)}checkIfCircleRef(e,t){return this.schemasStack.includes(e)&&this.schemasStack.length>t.maxSampleDepth}inferRef(e,t,r){if(!e)throw new Error("Your schema contains $ref. You must provide specification in the third parameter.");let a=decodeURIComponent(t.$ref);a.startsWith("#")&&(a=a.substring(1));const s=i.default.get(e,a);let n;return this.refCache[a]?n=this.getReplacementForCircular(s):(this.refCache[a]=!0,n=this.traverse(s,r,e),this.refCache[a]=!1),this.popSchemaStack(),n}getReplacementForCircular(e){const t=this.inferType(e);return{value:"object"===(r=t)?{}:"array"===r?[]:void 0};var r}popSchemaStack(){this.schemasStack.pop()}inferType(e){const t=Object.keys(g);for(let r=0;r<t.length;r++){const a=t[r],s=g[a];if(e[a])return s}return null}allOfSample(e,t,r,a){const s=this.traverse(e,r,a),i=[];for(const e of t){const{type:t,readOnly:n,writeOnly:l,value:o}=this.traverse(e,r,a);if(s.type&&t&&t!==s.type)throw new Error("allOf: schemas with different types can't be merged");s.type=s.type||t,s.readOnly=s.readOnly||n,s.writeOnly=s.writeOnly||l,null!=o&&i.push(o)}switch(s.type){case"object":s.value=l(s.value||{},...i);break;case"array":r.quiet||console.warn('OpenAPI Sampler: found allOf with "array" type. Result may be incorrect');const e=l(...t);s.value=this.traverse(e,r,a).value;break;default:const n=i[i.length-1];s.value=null!=n?n:s.value}return s}}const O=new Map;e.SAMPLER_MAP=O,e.sample=(e,t,r)=>{var a;const{skipReadOnly:s,maxSampleDepth:i}=null!=t?t:{},n={...t,maxSampleDepth:null!=i?i:1,skipReadOnly:null!=s&&s},l=new b;return O.set("boolean",new h),O.set("null",new p),O.set("array",new m(l)),O.set("integer",new c),O.set("number",new c),O.set("object",new d(l)),O.set("string",new v),l.samplers=O,l.clearCache(),null===(a=l.traverse(e,n,r))||void 0===a?void 0:a.value}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("randexp"),require("json-pointer")):"function"==typeof define&&define.amd?define(["exports","randexp","json-pointer"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@har-sdk/openapi-sampler"]={},e.RandExp,e.JsonPointer); //# sourceMappingURL=bundle.umd.js.map