typizator
Version:
Runtime types and metadata schemas for Typescript
2 lines (1 loc) • 9.45 kB
JavaScript
var z="Not implemented",U=class extends Error{constructor(){super(z)}},G="Null not allowed",f=class extends Error{constructor(){super(G)}},Y="Integer out of bounds",g=class extends Error{constructor(){super(Y)}},q="Invalid number",h=class extends Error{constructor(){super(q)}},H="Invalid date",x=class extends Error{constructor(){super(H)}},Q="Invalid boolean",p=class extends Error{constructor(){super(Q)}},Z="Field missing",T=class extends Error{constructor(){super(Z)}},ee="JSON Array not found",b=class extends Error{constructor(){super(ee)}},te="The source is not an object",y=class extends Error{constructor(){super(te)}};import m from"json-bigint";var D=class{constructor(t){this.definition=t;this.get=t=>this.definition[t];this.forEach=t=>{Object.keys(this.definition).forEach(e=>t(e,this.definition[e]))};this.map=t=>Object.keys(this.definition).map(e=>t(e,this.definition[e]));this.filter=t=>Object.keys(this.definition).filter(e=>t(e,this.definition[e])).map(e=>({key:e,schema:this.definition[e]}))}get size(){return Object.keys(this.definition).length}},B=class{constructor(t,e=!0){this.notNullFlag=e;this.unbox=(t,e)=>{if(t===null||e?.keepNullString!==!0&&t==="null")throw new f;return this.#t(t,e)};this.extend=t=>{if(this.#e.dataType!=="object")throw new Error("Cannot extend non-object schema");return E({...this.#e.fields.definition,...t})};this.#e={...t.metadata,notNull:!0,optional:!1},this.#t=t.unbox}#e;#t;get metadata(){return this.#e}},O=class{constructor(t,e=!0){this.optionalFlag=e;this.unbox=(t,e)=>{if(!(!this.#e.hasDefaultRule&&(t===void 0||e?.keepUndefinedString===!1&&t==="undefined")))try{return this.#t(t,e)}catch(n){if(t===void 0)return;throw n}};this.extend=t=>{if(this.#e.dataType!=="object")throw new Error("Cannot extend non-object schema");return E({...this.#e.fields.definition,...t})};this.#e={...t.metadata,notNull:!1,optional:!0},this.#t=t.unbox}#e;#t;get metadata(){return this.#e}},F=class{constructor(t,e,n){this.condition=n;this.#a=void 0;this.unbox=(t,e)=>this.condition(t)?this.targetCheck(t):this.#t(t,e);this.#e=this.#e={...t.metadata,hasDefaultRule:!0},this.#t=t.unbox,this.targetCheck=typeof e=="function"?this.targetCheck=e:e instanceof Error?this.targetCheck=i=>{throw e}:i=>e}#e;#t;get metadata(){return this.#e}#a;get optional(){return this.#a||(this.#a=new O(this)),this.#a}},d=class{constructor(){this.unbox=(t,e)=>{if(t===null||e?.keepNullString!==!0&&t==="null")return null;if(t===void 0||e?.keepUndefinedString===!1&&t==="undefined")throw new T;return this.convert(t,e)};this.#e=void 0;this.#t=void 0;this.byDefault=(t,e=n=>n==null)=>new F(this,t,e)}#e;get notNull(){return this.#e||(this.#e=new B(this)),this.#e}#t;get optional(){return this.#t||(this.#t=new O(this)),this.#t}},L=a=>`{${a.map((t,e)=>`${t}:${S(e)}`).join(",")}}`,J=a=>a.metadata?.dataType!==void 0,ae=a=>a.metadata.dataType==="object",ne=a=>a.metadata.dataType==="array",re=a=>a.metadata.dataType==="dictionary",k=a=>J(a)?ae(a)?L(a.metadata.fields):ne(a)?`${S(a.metadata.elements)}[]`:re(a)?`{[string]:${S(a.metadata.values)}}`:a.metadata.dataType:L(new D(a)),S=a=>J(a)?`${k(a)}${a.metadata.notNull?".NN":a.metadata.optional?".OPT":""}${a.metadata.hasDefaultRule?".DEF":""}`:k(a),me={isRecursive:!0,metadata:{dataType:"recursive",notNull:!1,optional:!0},unbox:()=>{throw new Error("Recursive schema cannot be unboxed directly")}},v=class extends d{constructor(e){super();this.convert=(e,n)=>{let i=typeof e=="string"?m.parse(e):e,c={};return this._metadata.fields.forEach((r,s)=>{try{let o=i[r],l;if(s.metadata.dataType==="recursive"){if(o==null)return;l=this.unbox(o,n)}else l=s.unbox(o,n);if(l===void 0)return;c[r]=l}catch(o){let l=m.stringify(i[r]);throw new Error(`Unboxing ${r}, value: ${l}: ${o.message}`)}}),c};this.extend=e=>E({...this._metadata.fields.definition,...e});this._metadata={dataType:"object",fields:new D(e),notNull:!1,optional:!1}}get metadata(){return this._metadata}},A=class a{constructor(){this.#e={};this.getOrCreateObject=t=>{let e=S(t);return e.indexOf(".DEF")>0?new v(t):(this.#e[e]||(this.#e[e]=new v(t)),this.#e[e])}}#e;static#t=new a;static get instance(){return this.#t}},ie=A.instance,E=a=>ie.getOrCreateObject(a),N=class extends d{constructor(e){super();this.elements=e;this.convert=(e,n)=>{let i=typeof e=="string"?m.parse(e):e;if(!Array.isArray(i))throw new b;return i.map((c,r)=>{try{return this.elements.unbox(c,n)}catch(s){let o=m.stringify(c);throw new Error(`Unboxing array element ${r}, value: ${o}: ${s.message}`)}})}}get metadata(){return{dataType:"array",elements:this.elements,notNull:!1,optional:!1}}},M=class a{constructor(){this.#e={};this.getOrCreateArray=t=>{let e=S(t);return e.indexOf(".DEF")>0?new N(t):(this.#e[e]||(this.#e[e]=new N(t)),this.#e[e])}}#e;static#t=new a;static get instance(){return this.#t}},oe=M.instance,Se=a=>oe.getOrCreateArray(a),w=class extends d{constructor(e){super();this.values=e;this.convert=(e,n)=>{let i=typeof e=="string"?m.parse(e):e;if(typeof i!="object"||Array.isArray(i))throw new y;return Object.keys(i).reduce((c,r)=>{try{c[r]=this.values.unbox(i[r],n)}catch(s){let o=m.stringify(i[r]);throw new Error(`Unboxing dictionary element ${r}, value: ${o}: ${s.message}`)}return c},{})}}get metadata(){return{dataType:"dictionary",values:this.values,notNull:!1,optional:!1}}},j=class a{constructor(){this.#e={};this.getOrCreateDictionary=t=>{let e=S(t);return e.indexOf(".DEF")>0?new w(t):(this.#e[e]||(this.#e[e]=new w(t)),this.#e[e])}}#e;static#t=new a;static get instance(){return this.#t}},se=j.instance,he=a=>se.getOrCreateDictionary(a);var W=a=>a.replace(/[\.|,][0-9]*$/,""),u=a=>({dataType:a,notNull:!1,optional:!1}),I=class extends d{constructor(){super(...arguments);this._metadata=u("bigint");this.convert=e=>typeof e=="bigint"?e:BigInt(typeof e=="string"?W(e):typeof e=="number"?Math.floor(e):W(`${e}`))}get metadata(){return this._metadata}},Te=new I,$=class extends d{constructor(){super(...arguments);this._metadata=u("string");this.convert=e=>typeof e=="string"?e:`${e}`}get metadata(){return this._metadata}},be=new $,_=class extends d{constructor(e){super();this.convert=e=>{if(!this.values.includes(e))throw new Error(`Invalid value for literal type: ${e}, must be one of ${this.values.join("|")}`);return e};this.values=e,this._metadata=u(`literal(${e.join("|")})`)}get metadata(){return this._metadata}},ye=(...a)=>new _(a),R=class extends d{constructor(){super(...arguments);this._metadata=u("int");this.convert=e=>{let n=Number(e);if(Number.isNaN(n))throw new h;let i=Number.isInteger(n)?n:Math.floor(n);if(!Number.isSafeInteger(i))throw new g;return i}}get metadata(){return this._metadata}},De=new R,K=class extends d{constructor(){super(...arguments);this._metadata=u("float");this.convert=e=>{let n=Number(e);if(Number.isNaN(n))throw new h;return n}}get metadata(){return this._metadata}},Oe=new K,P=class extends d{constructor(){super(...arguments);this._metadata=u("date");this.convert=e=>{if(typeof e=="string"){let n=e===""?Date.now():Date.parse(e);if(Number.isNaN(n))throw new x;return new Date(n)}return e}}get metadata(){return this._metadata}},ve=new P,V=class extends d{constructor(){super(...arguments);this._metadata=u("bool");this.convert=e=>{if(typeof e=="string"){if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1;throw new p}if(typeof e=="number"){if(e===1)return!0;if(e===0)return!1;throw new p}return e}}get metadata(){return this._metadata}},Ne=new V;var Be=()=>!0;var C=class{constructor(t,e){this.extractMetadata=(t,e,n,i)=>{let c={};return Object.keys(t).forEach(r=>{let s=t[r];if(typeof s.args=="object")Object.keys(s).forEach(o=>{if(!["args","retVal","hidden"].includes(o))throw new Error(`Invalid field ${o} in ${e}/${r}`)}),c[r]={...t[r],name:r,path:`${n}${e}/${r}`,metadata:{dataType:"function",args:s.args,retVal:s.retVal,name:r,path:`${n}${e}/${r}`,hidden:s.hidden??i.hidden}};else{let o=this.extractMetadata(s,r,`${n}${e}/`,i);c[r]={...o.implementation,name:r,path:`${n}${e}/${r}`,metadata:o}}}),{dataType:"api",implementation:c,name:e,path:`${n}${e}`,hidden:i.hidden}};this._metadata=this.extractMetadata(t,"","",e)}get metadata(){return this._metadata}},Ae=(a,t={})=>new C(a,t);var X=a=>a.match(/(?:[^\s"']+|['"][^'"]*["'])+/g),ce=(a,t)=>{let e=a.split(/[\r\n]+/);for(;e.length>0&&e[0].trim().length===0;)e.shift();if(e.length===0)throw new Error("Table must have at least a header");let n=X(e[0]);return e.shift(),e.filter(i=>i.trim()!=="").map((i,c)=>{let r=X(i);return n.reduce((s,o,l)=>{if(!r[l])throw console.table(r),new Error(`Table column ${l+1} missing in row ${c+1}`);return s[o]=r[l]==="null"?null:r[l]==="undefined"?void 0:r[l].replace(/(^")|("$)/g,""),s},structuredClone(t)??{})})},je=(a,t,e)=>ce(t,e).map(n=>a.unbox(n,{keepNullString:!0,keepUndefinedString:!0}));export{Z as FIELD_MISSING,T as FieldMissingError,Y as INT_OUT_OF_BOUNDS,Q as INVALID_BOOLEAN,H as INVALID_DATE,q as INVALID_NUMBER,g as IntOutOfBoundsError,p as InvalidBooleanError,x as InvalidDateError,h as InvalidNumberError,b as JSONArrayNotFoundError,ee as JSON_ARRAY_NOT_FOUND,z as NOT_IMPLEMENTED,G as NULL_NOT_ALLOWED,U as NotImplementedError,f as NullNotAllowedError,te as SOURCE_IS_NOT_OBJECT,y as SourceNotObjectError,d as TypeSchema,Be as always,Ae as apiS,Se as arrayS,Te as bigintS,Ne as boolS,ve as dateS,he as dictionaryS,Oe as floatS,S as getSchemaSignature,De as intS,ye as literalS,E as objectS,me as recursiveS,be as stringS,je as tabularInput,ce as transformToArray};