kristianmandrup / schema-to-yup

Schema to Yup validation
Other
281 stars 51 forks source link

Syntax error when using Jest #101

Closed strmer15 closed 2 years ago

strmer15 commented 2 years ago

I just upgraded to the newest version of schema-to-yup, 1.11.4, from 1.11.2, and encountered the following error whenever I run my React component unit tests:

    SyntaxError: Unexpected token '.'

      21 |   useState,
      22 | } from 'react'
    > 23 | import { buildYup } from 'schema-to-yup'
         | ^
      24 | import { getClient } from '../../../client'
      25 |
      26 | const client = getClient()

      at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/components/MyCompnent.tsx:23:1)

I'm running React 17.0.2, Jest 27.4.7, Node 12.22.8, and Typescript 4.4.4 - this is a CRA-app that I've ejected. When the test fails it also prints this out at the top:

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/strmer15/work/my-app/node_modules/schema-to-yup/dist/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){var t=require("yup"),e=require("uniq"),s=require("dashify"),r=require("uppercamelcase");function n(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(s){if("default"!==s){var r=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,r.get?r:{enumerable:!0,get:function(){return t[s]}})}}),e.default=t,e}var a=/*#__PURE__*/i(t),o=/*#__PURE__*/n(e),h=/*#__PURE__*/n(s),c=/*#__PURE__*/n(r);const l={getProps:t=>t&&t.properties,getType:t=>t&&t.type,getName:t=>t&&(t.name||t.title),getConstraints:t=>t,isString:t=>t&&"string"===t.type,isArray:t=>t&&"array"===t.type,isInteger:t=>t&&("integer"===t.type||"int"===t.type),isBoolean:t=>t&&"boolean"===t.type,hasDateFormat:t=>t&&["date","date-time"].find(e=>e===t.format),isDate:t=>t&&"string"===t.type&&l.hasDateFormat(t.format),isNumber:t=>t&&("number"===t.type||l.isInteger(t)),isObject:t=>t&&"object"===t.type,isRequired:t=>t&&t.required},u={getProps:t=>t.properties,getType:t=>t.type,getName:t=>t.name||t.title,getConstraints:t=>t,isString:t=>"string"===t.type&&!u.hasDateFormat(t),isArray:t=>"array"===t.type,isBoolean:t=>"boolean"===t.type,isInteger:t=>"integer"===t.type,hasDateFormat:t=>["date","date-time"].includes(t?.value?.format),isDate:t=>"string"===t.type&&u.hasDateFormat(t),isNumber:t=>"number"===t.type||u.isInteger(t),isObject:t=>"object"===t.type,isRequired:t=>t.required},d={getProps:t=>t&&t.fields,getType:t=>t&&t.type,getName:t=>t&&(t.name||t.title),getConstraints:t=>t,isString:t=>t&&"string"===t.type,isArray:t=>t&&"array"===t.type,isInteger:t=>t&&"int"===t.type,isFloat:t=>t&&"float"===t.type,isDouble:t=>t&&"double"===t.type,isBoolean:t=>t&&"boolean"===t.type,isDate:t=>t&&"int"===t.type&&"date"===t.logicalType,isNumber:t=>t&&(d.isInteger(t)||d.isFloat(t)||d.isDouble(t)),isObject:t=>t&&"record"===t.type,isRequired:t=>t&&t.required},p={"json-schema":l,"type-def":u,avro:d};class m extends class{constructor(t={}){this.config=t;const{log:e,error:s}=t,r=t.enable||{};!0===t.logging&&(r.log=!0),!1===t.logging&&(r.log=!1),this.enable=r,this.log="function"==typeof e?e:console.log,this.err="function"==typeof s?s:console.error}error(t){var e=[].slice.call(arguments,1);if(!1!==this.enable.error&&this.err)throw e&&e.length?this.err(t,...e):this.err(t),t}warn(t){this.enable.warn&&this.logInfo("WARNING: "+t,...[].slice.call(arguments,1))}logInfo(t){var e=[].slice.call(arguments,1);this.enable.log&&this.log&&(e&&e.length?this.log(t,...e):this.log(t))}}{constructor(t={}){super(t)}isNothing(t){return null==t}isPresent(t){return!this.isNothing(t)}toNumber(t){return Number(t)}isNumberLike(t){return!isNaN(this.toNumber(t))}isObjectType(t){return t===Object(t)}isArrayType(t){return Array.isArray(t)}isNumberType(t){return!isNaN(t)}isStringType(t){return"string"==typeof t}isFunctionType(t){return"function"==typeof t}isDateType(t){return t instanceof Date}}class g{constructor(t,e){this.schemaParserMap=t,this.name=e}lookup(t=this.name){return this.schemaParserMap[t]}build(){const t=this.lookup();if(t.extends){const e=this.extend(t.extends);if(e)return e}return t}extend(t){const e=this.lookup(t);e&&(entry={...e,...this.lookup()})}}class y extends m{constructor(t={}){super(t);const e=(t.createSchemaParserBuilder||new g(t.schemaParserMap||p,t.schemaType||"json-schema")).build();this.config={...e,...t}}createSchemaParserBuilder(t,e){return new SchemaParserBuilder(t,e)}}function f(t){return t===Object(t)}class b{constructor(t,e={}){this.whenEntryObj=t;const{schema:s,properties:r,config:n,key:i,when:a,type:o}=e;this.schema=s,this.when=a,this.properties=r||{},this.key=i,this.type=o,this.config=n}validateAndConfigure(t){if(!f(t=t||this.whenEntryObj))return this.warn("invalid or missing when entry constraint object",t),!1;const e=Object.keys(t);return e.length<2?(this.warn(`validateAndConfigure: when entry constraint must have at least 2 keys: ${e}`,t),!1):this.hasKey(e,"is")?!!this.hasKey(e,"then")||(this.warn(`validateAndConfigure: when entry constraint missing 'then' or 'else' constraint: ${e}`,t),!1):(this.warn(`validateAndConfigure: when entry constraint missing 'is' constraint: ${e}`,t),!1)}createYupSchemaEntry(t){return this.config.createYupSchemaEntry(t)}createValue(t,e){return"string"==typeof t&&(t={[t]:!0}),f(t)||this.error(`createValue: ${e} must be a schema object`),{key:this.key,type:this.type,...t}}createEntryOpts(t,e){const s=this.createValue(t,e);return{schema:this.schema,properties:this.properties,key:this.key,type:this.type,value:s,config:this.config}}createEntry(t,e){const s=this.createEntryOpts(t,e);return this.createYupSchemaEntry(s)}hasKey(t,e){return t.find(t=>t===e)}hasAnyKey(t,e){return t.find(t=>e.includes(t))}whenEntryFor(t,e,s){if(s=s||e,"string"==typeof t&&(t={[t]:!0}),!f(t))throw`whenEntryFor: Invalid when object ${t}`;const r={...t[s]};return delete t[s],r?(t[e]=this.createEntry(r,e),t):t}calcEntryObj(){let t={...this.whenEntryObj};return t=this.whenEntryFor(t,"then"),"otherwise"in t&&(t=this.whenEntryFor(t,"otherwise")),"else"in t&&(t=this.whenEntryFor(t,"else")),t}get entryObj(){return this.validateAndConfigure()&&this.calcEntryObj()}warn(t,e){console.error("[WhenEntry] WARNING",t,e)}error(t,e){throw console.error("[WhenEntry] ERROR",t,e),t}}function v(t){return t===Object(t)}class C{constructor(t={}){const{type:e,key:s,value:r,when:n,schema:i,properties:a,config:o}=t;this.opts=t,this.when=n,this.key=s,this.type=e,this.value=r,this.schema=i,this.properties=a,this.config=o,this.validate()}validate(){"string"!=typeof this.type&&this.error(`validate: invalid or mising type: ${this.type}`,this.opts),v(this.when)||this.error(`validate: invalid or mising when: ${this.when}`,this.opts)}validateAndConfigure(t){if(!v(t=t||this.when))return this.warn("invalid or missing when constraint",t),!1;const e=Object.keys(t);return e.length<1?(this.warn(`when constraint must have at least 1 key: ${e}`,t),!1):(this.whenKeys=e,!0)}createWhenEntry(t,e){return((t,e={})=>new b(t,e))(t,e)}accumulate(t,e){let s=this.when[e];if(!v(s))return this.warn(`invalid when entry constraint object ${s} for ${e}`),t;const r={type:this.type,key:this.key,schema:this.schema,properties:this.properties,config:this.config},{entryObj:n}=this.createWhenEntry(s,r);return n?t=Object.assign(t,n):t}get constraintObj(){return this.whenKeys?this.whenKeys.reduce(this.accumulate.bind(this),{}):{}}get keyVal(){const t=this.whenKeys||[];return 1===t.length?t[0]:t}get constraintValue(){return!!this.keyVal&&[this.keyVal,this.constraintObj]}get constraint(){return this.validateAndConfigure()&&this.constraintValue}warn(t,e){console.error("[WhenCondition] WARNING",t,e)}error(t,e){throw console.error("[WhenCondition] ERROR",t,e),t}}const w=t=>new C(t);class E extends m{constructor(t,e={}){super(e),this.typeHandler=t,this.builder=t.builder,this.constraintsAdded={},this.delegators.map(e=>{this[e]=t[e]})}get delegators(){return["errMessages","base","key","type","constraints","errorMessageHandler","logInfo","warn"]}build(t,e={}){let{constraintName:s,constraintValue:r,propValue:n,method:i,yup:a,value:o,values:h,errName:c}=e;if(a=a||this.base,r=this.getFirstValue([r,n,this.constraints[t]]),s=s||t,i=i||s,this.idObj={propName:t,method:i,key:this.key},this.logDetailed("build",e,{resolved:{constraintValue:r,constraintName:s}}),this.isNothing(r))return this.warn("no prop value",{constraintValue:r}),!1;const l=this.aliasMap[i]||i;if(!a[l])return this.warn(`Yup has no such API method: ${l}`),!1;const u=a[l].bind(a),d=this.valErrMessage(s),p=c&&this.valErrMessage(c),m={constraintName:s,yup:a,constraintFn:u,errFn:d||p},g=["multiValueConstraint","presentConstraintValue","nonPresentConstraintValue"];let y;for(let t of g)if(y=this[t].bind(this)(this.getFirstValue([o,h]),m),y)break;return y?(this.base=y,y):(this.warn("buildConstraint: missing value or values options"),!1)}getFirstValue(t){const e=this.isPresent.bind(this);return t.filter(e)[0]}nonPresentConstraintValue(t,{constraintName:e,constraintFn:s,errFn:r}){if(!this.isPresent(t))return this.logInfo("nonPresentConstraintValue",{constraintValue:t}),this.onConstraintAdded({method:"nonPresentConstraintValue",name:e}),s(r)}presentConstraintValue(t,{constraintName:e,constraintFn:s,errFn:r}){if(this.isPresent(t))return this.logInfo("presentConstraintValue",{constraintName:e,constraintValue:t}),this.onConstraintAdded({method:"presentConstraintValue",name:e,value:t}),this.isNoValueConstraint(e)?(this.logInfo("isNoValueConstraint",{constraintName:e}),s(r)):(this.logInfo("presentConstraintValue: apply validator function",{constraintName:e,constraintValue:t}),s(t,r));this.logInfo("presentConstraintValue: value not present",{constraintName:e,constraintValue:t})}multiValueConstraint(t,{constraintFn:e,constraintName:s,errFn:r}){if(this.isPresent(t)){if(this.logInfo("multiValueConstraint",{constraintName:s,values:t}),Array.isArray(t))return this.onConstraintAdded({method:"multiValueConstraint",name:s,value:t}),this.logInfo("multiValueConstraint: apply validator function",{constraintName:s,value:t}),this.callConstraintFn(e,s,t,r);this.warn("buildConstraint: values option must be an array of arguments")}}callConstraintFn(t,e,s,r){return this.isMultiArgsCall(e)?t(...s,r):t(s,r)}isMultiArgsCall(t){return this.multiArgsValidatorMethods[t]}get multiArgsValidatorMethods(){return this.config.multiArgsValidatorMethods||{when:!0}}isNoValueConstraint(t){return this.noValueConstraints.includes(t)}get noValueConstraints(){return["required","email","url","format"]}addValueConstraint(t,{constraintName:e,errName:s}={}){return this.addConstraint(t,{constraintName:e,value:!0,errName:s})}addConstraint(t,e){const s=this.build(t,e);return!!s&&(this.typeHandler.base=s,s)}onConstraintAdded({method:t,name:e,value:s}){if(this.constraintsAdded[e]=s,this.builder)return this.builder.onConstraintAdded({type:this.type,method:t,name:e,value:s}),this.typeHandler;this.logInfo("no builder set to notify in ConstraintBuilder")}get constraintsMap(){return{simple:["required","notRequired","nullable"],value:["default","strict"]}}logDetailed(t){const e=this.idObj,s=this.config.logDetailed||[];s.length&&s.find(t=>!(t.key&&e.key!==t.key||t.propName&&e.propName!==t.propName||t.method&&e.method!==t.method))&&this.logInfo(t,e,...[].slice.call(arguments,1))}valErrMessage(t){return this.errorMessageHandler.valErrMessage(t)}get aliasMap(){return{oneOf:"oneOf",enum:"oneOf",anyOf:"oneOf"}}}class N extends m{constructor(t,e={}){super(e),this.typeHandler=t,this.constraints=t.constraints,this.errMessages=t.errMessages,this.key=t.key,this.type=t.type}valErrMessage(t){const{constraints:e}=this,s=this.errMessageFor(t);return"function"==typeof s?s(e):s}errMessageFor(t){const{errMessages:e,key:s}=this,r=e[s];return r?r[t]:e[`$${t}`]}}class x extends Error{}class T extends y{constructor(t={}){super(t.config),this.init(t)}init(t){let{schema:e,key:s,value:r,config:n,entryHandler:i}=t;n=n||{},e=e||{},this.validateOnCreate(s,r,t),this.opts=t,this.entryHandler=i,this.validator=this.getValidator(),this.key=s,this.schema=e,this.properties=e.properties||{},this.value=r,this.constraints=this.getConstraints(),this.format=r.format||this.constraints.format,this.config=n||{},this.type=this.baseType,this.mixedConfig=this.config.mixedEnabled||{},this.typeConfig=this.config[this.type]||{},this.errMessages=n.errMessages||{},this.configureTypeConfig(),this.constraintsAdded={},this.base=this.getBase()}get builder(){return this.entryHandler&&this.entryHandler.builder}getBase(){return this.customBaseValidator||this.validatorInstance}get customBaseValidator(){return this.config.validatorFor&&this.config.validatorFor(this.type)}getValidator(){return this.opts.validator||this.config.validator||this.builder&&this.builder.validator||a}get baseType(){return"mixed"}get validatorInstance(){return this.validator.mixed()}configureTypeConfig(){this.typeConfig.enabled||this.typeConfig.extends||this.typeConfig.convert&&(this.typeConfig.extends=Object.keys(this.typeConfig.convert))}isRequired(t){return!0===(t=t||this.value).required}get mode(){return this.config.mode||{}}get disableFlags(){return[!1,"disabled","no","off"]}get enableFlags(){return[!0,"enabled","yes","on"]}disabledMode(t){const e=this.mode[t];return!!this.disableFlags.find(t=>e===t)}enabledMode(t){const e=this.mode[t];return!!this.enableFlags.find(t=>e===t)}get shouldPreProcessValue(){return!this.disabledMode("notRequired")}preProcessedConstraintValue(t){return this.shouldPreProcessValue?this.isRequired(t)?t:{...t,notRequired:!0}:t}set value(t){this._value=this.preProcessedConstraintValue(t)}get value(){return this._value}initHelpers(){const{config:t}=this;this.errorMessageHandler=(this.config.createErrorMessageHandler||this.createErrorMessageHandler)(this,t),this.constraintBuilder=(this.config.createConstraintBuilder||this.createConstraintBuilder)(this,t),this.rebind("addConstraint","addValueConstraint")}createConstraintBuilder(t,e={}){return new E(t,e)}createErrorMessageHandler(t,e={}){return new N(t,e)}rebind(){[].slice.call(arguments).map(t=>{const e=this[t];this[t]=this.isFunctionType(e)?e.bind(this):e})}validateOnCreate(t,e,s){t||this.error(`create: missing key ${JSON.stringify(s)}`),e||this.error(`create: missing value ${JSON.stringify(s)}`)}get mixedEnabled(){return this.mixedConfig.enabled||["oneOf","notOneOf","when","nullable","isType","label","refValueFor"]}get typeEnabled(){return[]}get $typeExtends(){if(Array.isArray(this.typeConfig.extends))return o.default([...this.typeConfig.extends,...this.typeEnabled])}get configuredTypeEnabled(){return Array.isArray(this.typeConfig.enabled)?this.typeConfig.enabled:this.typeEnabled}get $typeEnabled(){return this.$typeExtends||this.configuredTypeEnabled}get enabled(){return[...this.mixedEnabled,...this.$typeEnabled]}convertEnabled(){this.enabled.map(t=>{const e=this.convertFnFor(t);e&&e(this)})}convertFnFor(t){return this.customConvertFnFor(t,this)||this.builtInConvertFnFor(t)}customConvertFnFor(t){return(this.typeConfig.convert||{})[t]}builtInConvertFnFor(t){return this[t].bind(this)}getConstraints(){return this.config.getConstraints(this.value)}createSchemaEntry(){return this.convert().base}convert(){return this.initHelpers(),this.addMappedConstraints(),this.convertEnabled(),this}apply(t){var e=[].slice.call(arguments,1);if("string"!=typeof t)throw new TypeError("[Mixed] apply must take a method name available on the validator instance as first argument");return this.base=e&&e.length&&this.base[t](...e)||this.base,this}addValueConstraint(t,e){const s=this.constraintBuilder.addValueConstraint(t,e);if(s){const{base:t}=s;this.base=t}return this}addConstraint(t,e){if(!this.constraintBuilder)throw new Error(`[YupMixed] addConstraint: Missing constraintBuilder in ${this.constructor.name}`);const s=this.constraintBuilder.addConstraint(t,e);return s&&(this.base=s),this}addMappedConstraints(){const t=Object.keys(this.constraintsMap),e=this.addMappedConstraint.bind(this);return t.map(e),this}addMappedConstraint(t){const{constraintsMap:e}=this,s=this["value"===t?"addValueConstraint":"addConstraint"];e[t].map(t=>{s(t)})}get constraintsMap(){return{simple:["required","notRequired","nullable"],value:["default","strict"]}}refValueFor(){let t=this.constraints.refValueFor;return this.isNothing(t)?this:(this.logInfo("refValueFor",{propRefName:t}),this.apply("when",(e,s)=>e?s.required().oneOf([a.ref(t)]):s))}oneOf(){let t=this.constraints.enum||this.constraints.oneOf||this.constraints.anyOf;if(this.isNothing(t))return this;t=Array.isArray(t)?t:[t];const e=["oneOf","enum","anyOf"].find(t=>void 0!==this.constraints[t]);return this.addConstraint(e,{values:t})}notOneOf(){const{not:t,notOneOf:e}=this.constraints;let s=e||t&&(t.enum||t.oneOf);return this.isNothing(s)?this:(s=Array.isArray(s)?s:[s],this.addConstraint("notOneOf",{values:s}))}valErrMessage(t){return this.errorMessageHandler.valErrMessage(t)}createWhenConditionFor(t){return(this.config.createWhenCondition||w)({key:this.key,type:this.type,value:this.value,schema:this.schema,properties:this.properties,config:this.config,when:t})}label(){const t=this.value,e=t.title||t.label;return this.base=e&&this.base.label(e)||this.base,this}when(){const t=this.constraints.when;if((e=t)!==Object(e))return this;var e;const{constraint:s}=this.createWhenConditionFor(t);return s?(this.logInfo(`Adding when constraint for ${this.key}`,s),this.addConstraint("when",{values:s,errName:"when"}),this):(this.warn(`Invalid when constraint for: ${t}`),this)}isType(){return this.addConstraint("isType",{value:this.constraints.isType,errName:"notOneOf"}),this}nullable(){const{nullable:t,isNullable:e}=this.constraints;return this.addConstraint("nullable",{value:t||e,errName:"notOneOf"}),this}message(){return config.messages[this.key]||config.messages[this.type]||{}}errMessage(t="default"){return this.message[t]||"error"}toValidJSONSchema(){}normalize(){}deNormalize(){}errorMsg(t){this.throwError(t)}error(t,e){const s=[`[${t}]`,e].join(" ");this.errorMsg(s)}throwError(t){throw t}}const O=["oneOf","enum","required","notRequired","minDate","min","maxDate","max","trim","lowercase","uppercase","email","url","minLength","maxLength","pattern","matches","regex","integer","positive","minimum","maximum"],M={errMessages:(t=O)=>t.reduce((t,e)=>(t[e]=({key:t,value:e})=>`${t}: invalid for ${e.name||e.title}`,t),{})};class V extends T{constructor(t){super(t),this.type=this.baseType,this.base=this.validatorInstance,this.createYupSchemaEntry=this.config.createYupSchemaEntry}get baseType(){return"array"}get validatorInstance(){return this.validator.array()}static create(t){return new V(t)}convert(){return super.convert(),this}get typeEnabled(){return["maxItems","minItems","ensureItems","compact","itemsOf"]}ensureItems(){return this.addConstraint("ensure")}compact(){return this.addConstraint("compact")}itemsOf(){const{items:t,itemsOf:e}=this.constraints,s=t||e||this.constraints.of;if(!this.isNothing(s))if(Array.isArray(s))this.error("itemsOf","does not (yet) support an Array of schemas");else if(this.isObjectType(s)){if(this.createYupSchemaEntry){try{const t=this.createYupSchemaEntry({key:this.key,value:s,config:this.config});return this.addConstraint("of",{constraintValue:t,propValue:s})}catch(t){this.error("itemsOf: Error",t)}return this}this.warn("missing createYupSchemaEntry in config, needed for recursive validation")}else this.error("itemsOf","must be a schema object, was "+typeof s)}maxItems(){const{maxItems:t,max:e}=this.constraints,s=t||e;if(!this.isNumberType(s))return this;if(!this.isValidSize(s))return this.handleInvalidSize("maxItems",s);const r=s&&this.base.max(s);return this.base=r||this.base,this}minItems(){const{minItems:t,min:e}=this.constraints,s=t||e;if(!this.isNumberType(s))return this;if(!this.isValidSize(s))return this.handleInvalidSize("minItems",s);const r=s&&this.base.min(s);return this.base=r||this.base,this}$items(){return this}$additionalItems(){return this}$uniqueItems(){return this}$contains(){return this}handleInvalidSize(t,e){const s=`invalid array size constraint for ${t}, was ${e}. Must be a number >= 0`;return this.config.warnOnInvalid?(this.warn(s),this):(this.error(s,e),this)}isValidSize(t){return this.isNumberType(t)&&t>=0}}class k extends y{constructor(t){super(t)}isArray(t){return this.config.isArray||this.error("ArrayHandler: mising isArray in config",this.config),this.config.isArray(t)}handle(t){return this.isArray(t)&&V.create(t).createSchemaEntry()}}function S(t,e={}){return t&&new k(e).handle(t)}class I extends T{constructor(t){super(t),this.type=this.baseType,this.base=this.validatorInstance}get baseType(){return"boolean"}get validatorInstance(){return this.validator.boolean()}static create(t){return new I(t)}}class j{constructor(t){this.config=t}isBoolean(t){return this.config.isBoolean(t)}handle(t){return this.isBoolean(t)&&I.create(t).createSchemaEntry()}}function A(t,e={}){return t&&new j(e).handle(t)}class F extends m{constructor(t,e){super(t.config),this.map=e||this.$map||{},this.typeHandler=t,this.delegates.map(e=>{const s=t[e];s||this.error(`missing delegate: ${e}`,{typeHandler:t}),this[e]=this.isFunctionType(s)?s.bind(t):s})}isStringType(t){return"string"==typeof t}get delegates(){return["constraints","addConstraint","constraintsAdded"]}add(){const t=this.map;Object.keys(t).map(e=>{const s=this.entryNames(t[e]);this.addConstraints(e,s)})}entryNames(t){return Array.isArray(t)?t:[t]}addConstraints(t,e=[]){return e.map(e=>{const s=this.validateAndTransform(e);this.addConstraint(e,{method:t,value:s})}),this}validateAndTransform(t){const e=this.constraints[t];return this.validate(e),this.transform(e)}invalidMsg(t,e){return`invalid constraint for ${t}, was ${e}.`}get explainConstraintValidMsg(){return""}invalidConstraintMsg(t,e){return[this.invalidMsg(t,e),this.explainConstraintValidMsg].join("\n")}validate(t){return this.isNothing(t)?this:this.isValidConstraint(t)?void 0:this.handleInvalidConstraint(name,t)}isValidConstraint(t){return!0}handleInvalidConstraint(t,e){const s=this.invalidConstraintMsg(t,e);return this.config.warnOnInvalid?(this.warn(s),this):(this.error(s,e),this)}}class D extends F{constructor(t){super(t)}transform(t){return this.typeHandler.toNumber(t)}isValidConstraint(t){return this.typeHandler.isNumberLike(t)}get explainConstraintValidMsg(){return"Must be a number or convertible to a number"}}class P extends D{constructor(t){super(t)}get $map(){return{moreThan:["exclusiveMinimum","moreThan"],lessThan:["exclusiveMaximum","lessThan"],max:["maximum","max"],min:["minimum","min"]}}}class $ extends y{constructor(t,e){super(e),this.obj=t}isValid(){return!1}verify(){return this.isPresent(this.obj)&&this.isValid(this.obj)}}class H extends ${constructor(t,e){super(t,e)}isValid(){return this.config.isNumber(this.obj)}}const R=(t,e={})=>function(t,e){return new H(t,e)}(t,e).verify();function Y(t,e={}){return R(t,e)&&function(t){return q.schemaEntryFor(t)}(t)}class q extends T{constructor(t){super(t),this.type=this.baseType,this.base=this.validatorInstance,this.rangeConstraint=new P(this)}get baseType(){return this.normalizeNumType(this.opts.type)}get validatorInstance(){return this.validator.number()}normalizeNumType(t){return"int"===t?"integer":t}static create(t){return new q(t)}static schemaEntryFor(t){return q.create(t).createSchemaEntry()}get typeEnabled(){return["range","posNeg","integer"]}convert(){return super.convert(),this}range(){this.rangeConstraint.add()}truncate(){return this.addConstraint("truncate")}round(){const{round:t}=this.constraints;if(this.isNothing(t))return this;const e=this.isStringType(t)?t:"round";return t&&this.base.round(e),this}posNeg(){this.positive(),this.negative()}integer(){return this.isInteger&&this.addConstraint("integer"),this}get isInteger(){return this.config.isInteger(this.type)}positive(){return this.addConstraint("positive")}negative(){return this.addConstraint("negative")}get isNegative(){const{exclusiveMaximum:t,negative:e}=this.constraints;return!!e||void 0!==t&&0===t}get isPositive(){const{exclusiveMinimum:t,positive:e}=this.constraints;return!!e||void 0!==t&&0===t}normalize(){this.constraints.maximum=this.constraints.maximum||this.constraints.max,this.constraints.minimum=this.constraints.minimum||this.constraints.min}}class B extends T{constructor(t){super(t),this.type=this.baseType,this.base=this.validatorInstance,this.properties=this.value.properties}get baseType(){return"object"}get validatorInstance(){return this.validator.object()}static create(t){return new B(t)}get typeEnabled(){return["noUnknown","camelCase","constantCase"]}convert(){if(!this.properties)return this;super.convert();const t=this.value,e=this.config;if(t){e.buildYup||this.error("convert","Missing buildYup function from config",e);const s=this.config.buildYup(t,e);this.base=s}return this}camelCase(){return this.addConstraint("camelCase")}constantCase(){return this.addConstraint("constantCase")}noUnknown(){const{noUnknown:t,propertyNames:e}=this.value,s=t||e,r=s&&this.base.noUnknown(s,this.valErrMessage("propertyNames")||this.valErrMessage("noUnknown"));return this.base=r||this.base,this}}const L=t=>t&&"object"===t.type;class z{constructor(t={}){(t=t||{}).isObject=t.isObject||L,this.config=t,this.schema=t.schema}isObject(t){return this.config.isObject(t.value)}handle(t){return this.isObject(t)&&B.create({...t,config:this.config}).createSchemaEntry()}}function K(t,e={}){return t&&new z(e).handle(t)}class U extends T{constructor(t){super(t),this.type=this.baseType,this.base=this.validatorInstance}get baseType(){return"string"}get validatorInstance(){return this.validator.string()}static create(t){return new U(t)}convert(){return super.convert(),this}get typeEnabled(){return["normalize","minLength","maxLength","pattern","lowercase","uppercase","email","url","genericFormat"]}trim(){return this.addConstraint("trim")}lowercase(){return this.addConstraint("lowercase")}uppercase(){return this.addConstraint("uppercase")}genericFormat(){1!=!this.config.format&&this.validator.prototype[this.format]&&this.addConstraint(this.format)}email(){if(!this.isEmail)return this;const t=this.constraintNameFor("email","format"),e="email";return this.addConstraint("email",{constraintValue:!0,constraintName:t,method:e,errName:e}),this}constraintNameFor(){return[].slice.call(arguments).find(t=>this.constraints[t])}get isEmail(){return this.constraints.email||"email"===this.format}url(){if(!this.isUrl)return this;const t=this.constraintNameFor("url","format");return this.addConstraint("url",{constraintValue:!0,constraintName:t,method:"url",errName:"url"}),this}get isUrl(){return this.constraints.url||"url"===this.format}minLength(){const{minLength:t}=this.constraints,e=this.valErrMessage("minLength")||this.valErrMessage("min"),s=t&&this.base.min(t,e);return this.base=s||this.base,this}maxLength(){const{maxLength:t}=this.constraints,e=this.valErrMessage("maxLength")||this.valErrMessage("max"),s=t&&this.base.max(t,e);return this.base=s||this.base,this}pattern(){const{pattern:t,flags:e}=this.constraints;if(!t)return this;const s=new RegExp(t,e),r=this.valErrMessage("pattern")||this.valErrMessage("matches")||this.valErrMessage("regex"),n=s&&this.base.matches(s,r);return this.base=n||this.base,this}normalize(){this.constraints.pattern=this.constraints.pattern||this.constraints.matches||this.constraints.regex,this.constraints.maxLength=this.constraints.maxLength||this.constraints.max,this.constraints.minLength=this.constraints.minLength||this.constraints.min}}class W{constructor(t){this.config=t}isString(t){return this.config.isString(t)}handle(t){return this.isString(t)&&U.create({config:this.config,...t}).createSchemaEntry()}}function _(t,e={}){return t&&new W(e).handle(t)}class J extends T{constructor(t){super(t),this.type=this.baseType,this.base=this.validatorInstance}get baseType(){return"date"}get validatorInstance(){return this.validator.date()}static create(t){return new J(t)}get typeEnabled(){return["minDate","maxDate"]}convert(){return super.convert(),this}toDate(t){return new Date(t)}isValidDateType(t){return this.isStringType(t)||this.isDateType(t)}isValidDate(t){return!!this.isValidDateType(t)&&(!this.isStringType(t)||Boolean(Date.parse(t)))}transformToDate(t){return this.isNumberType(t)?new Date(t):t}minDate(){const t=this.constraints.minDate||this.constraints.min;if(this.isNothing(t))return this;const e=this.transformToDate(t);if(!this.isValidDateType(e))return this.handleInvalidDate("minDate",e);const s=e&&this.base.min(this.toDate(e),this.valErrMessage("minDate")||this.valErrMessage("min"));return this.base=s||this.base,this}maxDate(){const t=this.constraints.maxDate||this.constraints.max;if(this.isNothing(t))return this;const e=this.transformToDate(t);if(!this.isValidDateType(e))return this.handleInvalidDate("maxDate",e);const s=e&&this.base.max(this.toDate(e),this.valErrMessage("maxDate")||this.valErrMessage("max"));return this.base=s||this.base,this}handleInvalidDate(t,e){const s=`invalid constraint for ${t}, was ${e}. Must be a number, string (valid date format) or a Date instance`;return this.config.warnOnInvalid?(this.warn(s),this):(this.error(s,e),this)}}class G{constructor(t){this.config=t}isDate(t){return this.config.isDate(t)}handle(t){return this.isDate(t)&&J.create(t).createSchemaEntry()}}function Q(t,e={}){return t&&new G(e).handle(t)}var X={__proto__:null,errValKeys:O,defaults:M,YupArray:V,toYupArray:S,YupBoolean:I,toYupBoolean:A,YupNumber:q,toYupNumberSchemaEntry:Y,toYupNumber:function(t,e={}){return R(t,e)&&function(t){return q.create(t)}(t)},YupObject:B,toYupObject:K,YupString:U,toYupString:_,YupDate:J,toYupDate:Q,YupMixed:T,ConvertYupSchemaError:x,Base:y};class Z extends Error{}class tt extends y{constructor(t,e,s){super(e);const{value:r,type:n,kind:i,name:a,key:o,schema:h,types:c}=t;this.entryHandler=s||t.entryHandler,this.opts=t,this.kind=i,this.value=r,this.schema=h,this.key=o,this.value=r||{},this.name=a,this.type=n,this.types=c}error(t,e){const{opts:s}=this;throw e?console.error(t,e,...s):console.error(t,...s),new Z(t)}resolve(){throw"Must be implemented by subclass"}get obj(){const{schema:t,key:e,value:s,type:r,kind:n,config:i,entryHandler:a}=this;return{schema:t,key:e,value:s,type:r,kind:n,config:i,entryHandler:a}}}class et extends tt{constructor(t,e,s){super(t,e,s)}resolve(){const{value:t}=this;if(!Array.isArray(t))return;const e=this.config.toMultiType;return e?e(this):void 0}}class st extends tt{constructor(t,e,s){super(t,e,s)}resolve(){const{value:t}=this;if(Array.isArray(t))return;const e=this.config.toSingleType;if(e)return e(this);const{obj:s,config:r,entryHandler:n}=this,i=Object.keys(this.types);let a;for(let t of i){const e=this.types[t];if(e&&(a=e(s,r,n)),a)break}return a}}const rt=(t,e,s)=>new nt(t,e,s);class nt extends tt{constructor(t,e,s){super(t,e,s),this.initResolvers()}initResolvers(){const{opts:t,config:e,entryHandler:s}=this,r=e.createMultiTypeResolver||this.createMultiTypeResolver.bind(this);this.multiTypeResolver=r(t,e,s);const n=e.createSingleTypeResolver||this.createSingleTypeResolver.bind(this);this.singleTypeResolver=n(t,e,s)}createMultiTypeResolver(){const{opts:t,config:e,entryHandler:s}=this;return new et(t,e,s)}createSingleTypeResolver(){const{opts:t,config:e,entryHandler:s}=this;return new st(t,e,s)}resolve(){return this.toMultiType()||this.toSingleType()||this.toDefaultEntry()}toMultiType(){return(this.config.toMultiType||this.singleTypeResolver.resolve.bind(this.singleTypeResolver))(this)}toSingleType(){return(this.config.toSingleType||this.singleTypeResolver.resolve.bind(this.singleTypeResolver))(this)}toDefaultEntry(){return this.defaultType()}defaultType(){this.error("toEntry: unknown type",this.type)}}class it extends Error{}class at extends y{constructor(t){super(t.config);const{schema:e,name:s,key:r,value:n,config:i,builder:a}=t;this.builder=a,this.opts=t,this.schema=e,this.key=r,this.value=n||{},this.config=i||{},this.name=s;const o=Array.isArray(n)?"array":n.type;this.kind="array"===o?"multi":"single",this.type=o,this.setTypeHandlers(),this.setPropertyHandler()}get validator(){return this.builder&&this.builder.validator}setPropertyHandler(){const{config:t}=this;this.propertyValueHandler=(t.createPropertyValueHandler||this.createPropertyValueHandler)(this.propertyHandlerOpts,t)}get propertyHandlerOpts(){const{types:t,value:e,name:s,key:r,type:n,kind:i,schema:a}=this;return{type:n,kind:i,types:t,value:e,name:s,key:r,schema:a,entryHandler:this}}createPropertyValueHandler(t,e){return rt(t,e,this)}get defaultTypeHandlerMap(){return{string:_,number:Y,boolean:A,array:S,object:K,date:Q}}setTypeHandlers(){this.types=this.config.types||this.typeHandlers}get typeHandlers(){return{...this.defaultTypeHandlerMap,...this.config.typeHandlers||{}}}isValidSchema(){const{type:t}=this;return this.isStringType(t)}error(t,e){const{opts:s}=this;throw e?console.error(t,e,...s):console.error(t,...s),new it(t)}toEntry(){if(!this.isValidSchema()){const t=JSON.stringify(this.schema);this.error(`Not a valid schema: type ${this.type} must be a string, was ${typeof this.type} ${t}`)}const{opts:t,config:e}=this;return this.propertyValueHandler.resolve(t,e)}}function ot(t={}){return new at(t).toEntry()}function ht(t,e={}){return new lt(t,{...e}).yupSchema}function ct(t){return t===Object(t)}class lt extends y{constructor(t,e={}){super(e),this.init(t,e)}init(t,e){e.buildYup=ht,e.createYupSchemaEntry=e.createYupSchemaEntry||ot,this.config=Object.assign(this.config,e),this.schema=t;const s=this.getType(t),r=this.getProps(t);if(this.type=s,this.properties=r,this.additionalProps=this.getAdditionalProperties(t),this.required=this.getRequired(t),this.setLocale(),("function"==typeof e.init?e.init:()=>{}).bind(this)(t,e),!function(t){return t&&"object"===t}(s))return void this.error(`invalid schema: must be type: "object", was type: ${s}`);if(!ct(r)){const t=JSON.stringify(i);return void this.error(`invalid schema: must have a properties object: ${t}`)}const n=this.getName(t),i=this.normalizeRequired(t),a=this.propsToShape({properties:i,name:n,config:e});this.shapeConfig=a,this.validSchema=!0}get validator(){return a}setLocale(){this.config.locale&&a.setLocale(this.config.locale)}getAdditionalProperties(t){return t.additionalProperties}getRequired(t){const{getRequired:e}=this.config;return e?e(t):t.required||[]}getProps(t){return this.config.getProps(t)}getType(t){return this.config.getType(t)}getName(t){return this.config.getName(t)}get yupSchema(){return a.object().shape(this.shapeConfig)}normalizeRequired(){const t={...this.properties},e=[...this.required]||[];return Object.keys(t).reduce((s,r)=>{const n=t[r],i=e.indexOf(r)>=0;return ct(n)?n.required=this.isRequired(n)||i:this.warn(`Bad value: ${n} must be an object`),s[r]=n,s},{})}isRequired(t){return this.config.isRequired(t)}propsToShape(t={}){const e=this.objPropsToShape(t);return this.objPropsShape=e,this.addPropsShape=this.additionalPropsToShape(t,e),e}additionalPropsToShape(t,e){return e}objPropsToShape({name:t}){const e={...this.properties};return Object.keys(e).reduce((s,r)=>{const n=this.propToYupSchemaEntry({name:t,key:r,value:e[r]});return this.logInfo("propsToShape",{key:r,yupSchemaEntry:n}),s[r]=n,s},{})}propToYupSchemaEntry({name:t,key:e,value:s={}}){return this.createYupSchemaEntry({schema:this.schema,name:t,key:e,value:s,config:this.config,builder:this})}createYupSchemaEntry(t={}){return this.config.createYupSchemaEntry(t)}onConstraintAdded(t){this.logInfo("Constraint Added",t)}}const ut={alphanumeric:{optsKey:"locale"},alpha:{optsKey:"locale"},ascii:{},byte:{},creditCard:{},currency:{opts:"currencyOpts"},dataUri:{},dateTime:{},date:{},domainName:{opts:"domainOpts"},hash:{opts:"hashAlgo"},hexColor:{},ipv4:{},ipv6:{},isbn:{},magnetUri:{},mimeType:{},mobilePhone:{},mongoId:{},postalCode:{},uuid:{}},dt={createValidatorName:(t,e)=>`is${t=(t=(t=c.default(t||e)).replace(/Uri$/,"URI")).replace(/Id$/,"ID")}`,createTestName:(t,e)=>h.default(t||e)},pt={isMagnetURI:(t,e)=>/magnet:\?xt=urn:[a-z0-9]+:[a-z0-9]{32}/i.test(t)};exports.ConstraintBuilder=E,exports.ErrorMessageHandler=N,exports.PropertyValueResolver=nt,exports.YupBuilder=lt,exports.YupSchemaEntry=at,exports.YupSchemaEntryError=it,exports.buildYup=ht,exports.createPropertyValueResolver=rt,exports.createYupSchemaEntry=ot,exports.extendYupApi=function({constraints:e,override:s=!1,validator:r,createValidatorName:n,createTestName:i}={}){if(!r)throw"extendYupApi: missing validator option";Array.isArray(e)&&(e=((t,e={})=>t.reduce((t,s)=>{if("string"!=typeof s&&!(s instanceof Object)){if(!1!==e.throws)throw`toConstraintsMap: invalid entry ${s}`;return t}if("string"==typeof s)t[name]={};else{if(!s.name){if(!1!==e.throws)throw`toConstraintsMap: invalid entry ${s} missing name`;return t}t[s.name]=s}return t},{}))(e)),e=s?e||ut:{...ut,...e||{}},n=n||dt.createValidatorName,i=i||dt.createTestName,Object.keys(e).map(s=>{let{testName:a,optsKey:o,validatorName:h,logging:c}=e[s];const l=n(h,s);a=i(a,s),t.addMethod(t.string,s,(e={})=>{const{message:n}=e,i=e[o];return t.string().test(a,n,t=>{const{path:e,createError:o}=this;let h=r[l];if(h=h||pt[l],"function"!=typeof h)throw Error("No method named ${validatorName} on validator");const u=h(t,i);return!0===c&&console.log("Yup validator bridge",{key:s,fullValidatorName:l,testName:a,value:t,valid:u}),u||o({path:e,message:n})})})})},exports.types=X;
kristianmandrup commented 2 years ago

Try this:

https://dev.to/bytebodger/how-i-fixed-the-unexpected-token-error-in-jest-4o1j

https://stackoverflow.com/questions/51994111/jest-encountered-an-unexpected-token

For anyone using create-react-app, only certain jest configurations can be changed in package.json when using create-react-app.

I have issues with Jest picking up an internal library, Jest would display 'unexpected token' errors wherever I had my imports from this library.

To solve this, you can change your test script to the below: "test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",

strmer15 commented 2 years ago

Ah, ok - so maybe the newest version used some syntax that Jest is unable to transform correctly? I guess I can either try to explicitly ignore it or else I'll have to see if there's some kind of babel plugin I need to add. Thanks, for the help!

kristianmandrup commented 2 years ago

Let me know if you can make it work. I'd also suggest you clone the full repo and run the example in sample-runs as described at the top of the Readme (person schema). It references the distribution js file in dist/ directly. Not exactly sure why the lib suddenly breaks babel. Perhaps if I delete dist locally and publish the lib again it will generate a clean dist and deployment with no such issue.

strmer15 commented 2 years ago

FYI, I just upgraded to 1.11.5 and this seems to work correctly now, so not sure what happened 🤷

strmer15 commented 2 years ago

Actually, I thought that had fixed it, but it didn't - I ended up just using 'node_modules/(?!(schema-to-yup)/).+\\.(js|jsx|ts|tsx)$' in my transformIgnorePatterns and that did the trick.