@morphql/core 0.1.11 → 0.1.13
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/dist/index.cjs +28 -47
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +28 -47
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,27 +1,7 @@
|
|
|
1
|
-
'use strict';var chevrotain=require('chevrotain'),fastXmlParser=require('fast-xml-parser'),gt=require('papaparse'),Ct=require('js-beautify');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var gt__default=/*#__PURE__*/_interopDefault(gt);var Ct__default=/*#__PURE__*/_interopDefault(Ct);var At=chevrotain.createToken({name:"WhiteSpace",pattern:/\s+/,group:chevrotain.Lexer.SKIPPED}),Ut=chevrotain.createToken({name:"LineComment",pattern:/\/\/[^\n\r]*/,group:chevrotain.Lexer.SKIPPED}),Tt=chevrotain.createToken({name:"BlockComment",pattern:/\/\*[\s\S]*?\*\//,group:chevrotain.Lexer.SKIPPED}),h=chevrotain.createToken({name:"Identifier",pattern:/[a-zA-Z_$][a-zA-Z0-9_.[\]]*/}),C=chevrotain.createToken({name:"QuotedIdentifier",pattern:/`([^`\\]|\\.)*`/}),L=chevrotain.createToken({name:"From",pattern:/from/i,longer_alt:h}),N=chevrotain.createToken({name:"To",pattern:/to/i,longer_alt:h}),R=chevrotain.createToken({name:"Transform",pattern:/transform/i,longer_alt:h}),B=chevrotain.createToken({name:"Set",pattern:/set/i,longer_alt:h}),M=chevrotain.createToken({name:"Section",pattern:/section/i,longer_alt:h}),I=chevrotain.createToken({name:"Multiple",pattern:/multiple/i,longer_alt:h}),q=chevrotain.createToken({name:"Clone",pattern:/clone/i,longer_alt:h}),P=chevrotain.createToken({name:"Delete",pattern:/delete/i,longer_alt:h}),w=chevrotain.createToken({name:"Define",pattern:/define/i,longer_alt:h}),k=chevrotain.createToken({name:"Modify",pattern:/modify/i,longer_alt:h}),O=chevrotain.createToken({name:"If",pattern:/if/i,longer_alt:h}),z=chevrotain.createToken({name:"Else",pattern:/else/i,longer_alt:h}),_=chevrotain.createToken({name:"True",pattern:/true/i,longer_alt:h}),j=chevrotain.createToken({name:"False",pattern:/false/i,longer_alt:h}),F=chevrotain.createToken({name:"Null",pattern:/null/i,longer_alt:h}),x=chevrotain.createToken({name:"Return",pattern:/return/i,longer_alt:h}),D=chevrotain.createToken({name:"Unsafe",pattern:/unsafe/i,longer_alt:h}),W=chevrotain.createToken({name:"EqualsEquals",pattern:/==/}),Y=chevrotain.createToken({name:"EqualsEqualsEquals",pattern:/===/}),G=chevrotain.createToken({name:"NotEquals",pattern:/!=/}),Q=chevrotain.createToken({name:"NotEqualsEquals",pattern:/!==/}),J=chevrotain.createToken({name:"LessThanOrEqual",pattern:/<=/}),V=chevrotain.createToken({name:"GreaterThanOrEqual",pattern:/>=/}),K=chevrotain.createToken({name:"LessThan",pattern:/</}),Z=chevrotain.createToken({name:"GreaterThan",pattern:/>/}),H=chevrotain.createToken({name:"And",pattern:/&&/}),X=chevrotain.createToken({name:"Or",pattern:/\|\|/}),tt=chevrotain.createToken({name:"Not",pattern:/!/}),y=chevrotain.createToken({name:"Equals",pattern:/=/}),et=chevrotain.createToken({name:"Plus",pattern:/\+/}),b=chevrotain.createToken({name:"Minus",pattern:/-/}),rt=chevrotain.createToken({name:"Times",pattern:/\*/}),st=chevrotain.createToken({name:"Divide",pattern:/\//}),c=chevrotain.createToken({name:"LParen",pattern:/\(/}),f=chevrotain.createToken({name:"RParen",pattern:/\)/}),S=chevrotain.createToken({name:"Comma",pattern:/,/}),it=chevrotain.createToken({name:"StringLiteral",pattern:/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/}),nt=chevrotain.createToken({name:"NumericLiteral",pattern:/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/}),at=[At,Ut,Tt,L,N,R,B,M,I,q,P,w,k,O,z,_,j,F,x,D,Y,W,Q,G,J,V,H,X,y,K,Z,tt,et,b,rt,st,c,f,S,it,nt,C,h],mt=new chevrotain.Lexer(at);var ot=class extends chevrotain.CstParser{constructor(){super(at),this.performSelfAnalysis();}query=this.RULE("query",()=>{this.CONSUME(L),this.SUBRULE(this.typeFormat,{LABEL:"sourceType"}),this.CONSUME(N),this.SUBRULE1(this.typeFormat,{LABEL:"targetType"}),this.OPTION(()=>{this.CONSUME(R),this.OPTION1(()=>{this.CONSUME(D);}),this.MANY(()=>{this.SUBRULE(this.action);});});});typeFormat=this.RULE("typeFormat",()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"name"}),this.OPTION(()=>{this.CONSUME(c),this.MANY_SEP({SEP:S,DEF:()=>{this.SUBRULE(this.typeFormatParameter,{LABEL:"params"});}}),this.CONSUME(f);});});typeFormatParameter=this.RULE("typeFormatParameter",()=>{this.OR([{GATE:()=>this.LA(2).tokenType===y,ALT:()=>this.SUBRULE(this.namedParameter)},{ALT:()=>this.SUBRULE(this.literal)}]);});namedParameter=this.RULE("namedParameter",()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"key"}),this.CONSUME(y),this.SUBRULE(this.literal,{LABEL:"value"});});anyIdentifier=this.RULE("anyIdentifier",()=>{this.OR([{ALT:()=>this.CONSUME(h)},{ALT:()=>this.CONSUME(C)}]);});literal=this.RULE("literal",()=>{this.OR([{ALT:()=>this.CONSUME(it)},{ALT:()=>this.CONSUME(nt)},{ALT:()=>this.CONSUME(_)},{ALT:()=>this.CONSUME(j)},{ALT:()=>this.CONSUME(F)}]);});action=this.RULE("action",()=>{this.OR([{ALT:()=>this.SUBRULE(this.setRule)},{ALT:()=>this.SUBRULE(this.modifyRule)},{ALT:()=>this.SUBRULE(this.sectionRule)},{ALT:()=>this.SUBRULE(this.cloneRule)},{ALT:()=>this.SUBRULE(this.deleteRule)},{ALT:()=>this.SUBRULE(this.ifAction)},{ALT:()=>this.SUBRULE(this.defineRule)},{ALT:()=>this.SUBRULE(this.returnRule)}]);});returnRule=this.RULE("returnRule",()=>{this.CONSUME(x),this.SUBRULE(this.expression,{LABEL:"expr"});});deleteRule=this.RULE("deleteRule",()=>{this.CONSUME(P),this.SUBRULE(this.anyIdentifier,{LABEL:"field"});});ifAction=this.RULE("ifAction",()=>{this.CONSUME(O),this.CONSUME(c),this.SUBRULE(this.expression,{LABEL:"condition"}),this.CONSUME(f),this.CONSUME2(c),this.MANY(()=>{this.SUBRULE(this.action,{LABEL:"thenActions"});}),this.CONSUME2(f),this.OPTION(()=>{this.CONSUME(z),this.CONSUME3(c),this.MANY2(()=>{this.SUBRULE2(this.action,{LABEL:"elseActions"});}),this.CONSUME3(f);});});cloneRule=this.RULE("cloneRule",()=>{this.CONSUME(q),this.OPTION(()=>{this.CONSUME(c),this.MANY_SEP({SEP:S,DEF:()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"fields"});}}),this.CONSUME(f);});});setRule=this.RULE("setRule",()=>{this.CONSUME(B),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(y),this.SUBRULE(this.expression,{LABEL:"right"});});modifyRule=this.RULE("modifyRule",()=>{this.CONSUME(k),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(y),this.SUBRULE(this.expression,{LABEL:"right"});});expression=this.RULE("expression",()=>{this.SUBRULE(this.logicalOr);});logicalOr=this.RULE("logicalOr",()=>{this.SUBRULE(this.logicalAnd,{LABEL:"lhs"}),this.MANY(()=>{this.CONSUME(X),this.SUBRULE1(this.logicalAnd,{LABEL:"rhs"});});});logicalAnd=this.RULE("logicalAnd",()=>{this.SUBRULE(this.comparison,{LABEL:"lhs"}),this.MANY(()=>{this.CONSUME(H),this.SUBRULE1(this.comparison,{LABEL:"rhs"});});});comparison=this.RULE("comparison",()=>{this.SUBRULE(this.addition,{LABEL:"lhs"}),this.OPTION(()=>{this.OR([{ALT:()=>this.CONSUME(W,{LABEL:"ops"})},{ALT:()=>this.CONSUME(Y,{LABEL:"ops"})},{ALT:()=>this.CONSUME(G,{LABEL:"ops"})},{ALT:()=>this.CONSUME(Q,{LABEL:"ops"})},{ALT:()=>this.CONSUME(J,{LABEL:"ops"})},{ALT:()=>this.CONSUME(V,{LABEL:"ops"})},{ALT:()=>this.CONSUME(K,{LABEL:"ops"})},{ALT:()=>this.CONSUME(Z,{LABEL:"ops"})}]),this.SUBRULE1(this.addition,{LABEL:"rhs"});});});addition=this.RULE("addition",()=>{this.SUBRULE(this.multiplication,{LABEL:"lhs"}),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(et,{LABEL:"ops"})},{ALT:()=>this.CONSUME(b,{LABEL:"ops"})}]),this.SUBRULE1(this.multiplication,{LABEL:"rhs"});});});multiplication=this.RULE("multiplication",()=>{this.SUBRULE(this.unaryExpression,{LABEL:"lhs"}),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(rt,{LABEL:"ops"})},{ALT:()=>this.CONSUME(st,{LABEL:"ops"})}]),this.SUBRULE1(this.unaryExpression,{LABEL:"rhs"});});});unaryExpression=this.RULE("unaryExpression",()=>{this.OPTION(()=>{this.OR([{ALT:()=>this.CONSUME(b,{LABEL:"sign"})},{ALT:()=>this.CONSUME(tt,{LABEL:"sign"})}]);}),this.SUBRULE(this.atomic);});atomic=this.RULE("atomic",()=>{this.OR([{ALT:()=>this.SUBRULE(this.literal)},{GATE:()=>this.LA(2).tokenType===c,ALT:()=>this.SUBRULE(this.functionCall)},{ALT:()=>this.SUBRULE(this.anyIdentifier)},{ALT:()=>{this.CONSUME(c),this.SUBRULE(this.expression),this.CONSUME(f);}}]);});functionCall=this.RULE("functionCall",()=>{this.OR([{ALT:()=>this.CONSUME(h,{LABEL:"name"})},{ALT:()=>this.CONSUME(O,{LABEL:"name"})}]),this.CONSUME(c),this.MANY_SEP({SEP:S,DEF:()=>{this.SUBRULE(this.expression,{LABEL:"args"});}}),this.CONSUME(f);});sectionRule=this.RULE("sectionRule",()=>{this.CONSUME(M),this.OPTION(()=>{this.CONSUME(I);}),this.SUBRULE(this.anyIdentifier,{LABEL:"sectionName"}),this.CONSUME(c),this.OPTION1(()=>{this.CONSUME(L,{LABEL:"subqueryFrom"}),this.SUBRULE(this.typeFormat,{LABEL:"subquerySourceType"}),this.CONSUME(N,{LABEL:"subqueryTo"}),this.SUBRULE1(this.typeFormat,{LABEL:"subqueryTargetType"}),this.OPTION2(()=>{this.CONSUME(R,{LABEL:"subqueryTransform"});});}),this.MANY(()=>{this.SUBRULE(this.action);}),this.CONSUME(f),this.OPTION3(()=>{this.CONSUME1(L,{LABEL:"followFrom"}),this.SUBRULE2(this.anyIdentifier,{LABEL:"followPath"});});});defineRule=this.RULE("defineRule",()=>{this.CONSUME(w),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(y),this.SUBRULE(this.expression,{LABEL:"right"});})},d=new ot;var ft={substring:s=>{if(s.length<2)throw new Error("substring() requires at least 2 arguments (string, start, [length])");let[t,e,r]=s;return r!==void 0?`String(${t}).slice(${e}, (${e}) + (${r}))`:`String(${t}).slice(${e})`},if:s=>{if(s.length!==3)throw new Error("if() requires exactly 3 arguments (condition, trueValue, falseValue)");let[t,e,r]=s;return `((${t}) ? (${e}) : (${r}))`},text:s=>{if(s.length!==1)throw new Error("text() requires exactly 1 argument (string or number)");let[t]=s;return `String(${t})`},replace:s=>{if(s.length!==3)throw new Error("replace() requires exactly 3 arguments (string, search, replacement)");let[t,e,r]=s;return `String(${t}).replace(${e}, ${r})`},number:s=>{if(s.length!==1)throw new Error("number() requires exactly 1 argument (string)");let[t]=s;return `Number(${t})`},extractnumber:s=>{if(s.length!==1)throw new Error("extractNumber() requires exactly 1 argument (string)");let[t]=s;return `(() => { const match = String(${t}).match(/\\d+(\\.\\d+)?/); return match ? Number(match[0]) : null; })()`},uppercase:s=>{if(s.length!==1)throw new Error("uppercase() requires exactly 1 argument (string)");let[t]=s;return `String(${t}).toUpperCase()`},lowercase:s=>{if(s.length!==1)throw new Error("lowercase() requires exactly 1 argument (string)");let[t]=s;return `String(${t}).toLowerCase()`},xmlnode:s=>{if(s.length<1)throw new Error("xmlnode() requires at least 1 argument (string)");let t=s[0],e=[...s.slice(1)],r="";if(e.length>0){let i=[...e];i=[...Array(Math.ceil(i.length/2))].map(()=>i.splice(0,2)).map(([a,o])=>{let p=a;return a.startsWith('"')||a.startsWith("'")?p=`"$${a.slice(1,-1)}"`:p=`["$"+${a}]`,`${p}:${o||"null"}`}),r=","+i.join(",");}else return t;return `{_:${t}${r}}`},split:s=>{if(s.length<1)throw new Error("split() requires at least 1 argument (string)");let[t,e,r]=s,n=e!==void 0?e:'""',i=r!==void 0?`, ${r}`:"";return `String(${t}).split(${n}${i})`},to_base64:s=>{if(s.length!==1)throw new Error("to_base64() requires exactly 1 argument (string)");let[t]=s;return `(typeof btoa === 'function' ? btoa(unescape(encodeURIComponent(String(${t})))) : Buffer.from(String(${t}), 'utf-8').toString('base64'))`},from_base64:s=>{if(s.length!==1)throw new Error("from_base64() requires exactly 1 argument (string)");let[t]=s;return `(typeof atob === 'function' ? decodeURIComponent(escape(atob(String(${t})))) : Buffer.from(String(${t}), 'base64').toString('utf-8'))`},aslist:s=>{if(s.length!==1)throw new Error("aslist() requires exactly 1 argument");let[t]=s;return `(Array.isArray(${t}) ? ${t} : (${t} == null ? [] : [${t}]))`},spreadsheet:s=>{if(s.length!==1)throw new Error("spreadsheet() requires exactly 1 argument");let[t]=s;return `((data)=>{
|
|
2
|
-
const spreadsheet = Array.isArray(data) ? data : (data == null ? [] : [data]);
|
|
3
|
-
const out = [];
|
|
4
|
-
const titles = [];
|
|
5
|
-
let keys = [];
|
|
6
|
-
for (let i = 0; i < spreadsheet.length; i++) {
|
|
7
|
-
const line = spreadsheet[i];
|
|
8
|
-
if (!line || typeof line !== 'object') continue;
|
|
9
|
-
if (i === 0) {
|
|
10
|
-
keys = Object.keys(line);
|
|
11
|
-
for (const k of keys) titles.push(line[k]);
|
|
12
|
-
} else {
|
|
13
|
-
const tempLine = {};
|
|
14
|
-
for (let j = 0; j < keys.length; j++) {
|
|
15
|
-
tempLine[titles[j]] = line[keys[j]];
|
|
16
|
-
}
|
|
17
|
-
out.push(tempLine);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return out;
|
|
21
|
-
})(${t})`}};var A=class{sourceRoot={type:"object",properties:{}};targetRoot={type:"object",properties:{}};sourceStack=[this.sourceRoot];targetStack=[this.targetRoot];getCurrentSource(){return this.sourceStack[this.sourceStack.length-1]}getCurrentTarget(){return this.targetStack[this.targetStack.length-1]}recordAccess(t,e="any",r=false){let n=r?this.getCurrentTarget():this.getCurrentSource();this.setInNode(n,t,e);}recordAssignment(t,e="any"){this.setInNode(this.getCurrentTarget(),t,e);}recordClone(t){let e=this.getCurrentTarget();t?t.forEach(r=>{this.setInNode(this.getCurrentSource(),r,"any"),this.setInNode(e,r,"any");}):e.isOpen=true;}recordDelete(t){let e=this.getCurrentTarget();this.deleteInNode(e,t);}pushSection(t,e,r){e!=="parent"&&this.setInNode(this.getCurrentSource(),e,r?"array":"object");let n={type:r?"array":"object"};r?n.items={type:"object",properties:{}}:n.properties={};let i={type:"object",properties:{}};this.setInNodeExplicit(this.getCurrentTarget(),t,n),this.targetStack.push(r?n.items:n),this.sourceStack.push(i);}popSection(t,e){let r=this.sourceStack.pop();this.targetStack.pop();let n=this.getCurrentSource();if(t!=="parent"){let i=this.getOrSetNode(n,t,e?"array":"object"),a=e?i.items:i;a&&(a.properties||(a.properties={}),Object.assign(a.properties,r.properties||{}));}else n.properties||(n.properties={}),Object.assign(n.properties,r.properties||{});}setInNode(t,e,r){let n=e.split("."),i=t;for(let a=0;a<n.length;a++){let o=n[a];i.properties||(i.properties={}),a===n.length-1?i.properties[o]||(i.properties[o]={type:r},r==="object"?i.properties[o].properties={}:r==="array"&&(i.properties[o].items={type:"object",properties:{}})):(i.properties[o]||(i.properties[o]={type:"object",properties:{}}),i=i.properties[o]);}}setInNodeExplicit(t,e,r){let n=e.split("."),i=t;for(let a=0;a<n.length;a++){let o=n[a];i.properties||(i.properties={}),a===n.length-1?i.properties[o]=r:(i.properties[o]||(i.properties[o]={type:"object",properties:{}}),i=i.properties[o]);}}deleteInNode(t,e){let r=e.split("."),n=t;for(let i=0;i<r.length;i++){if(!n.properties)return;if(i===r.length-1)delete n.properties[r[i]];else if(n=n.properties[r[i]],!n)return}}getOrSetNode(t,e,r){let n=e.split("."),i=t;for(let a=0;a<n.length;a++){let o=n[a],u=a===n.length-1?r:"object";i.properties||(i.properties={}),i.properties[o]||(i.properties[o]={type:u},u==="object"?i.properties[o].properties={}:u==="array"&&(i.properties[o].items={type:"object",properties:{}})),i=i.properties[o];}return i}getResult(){return {source:this.sourceRoot,target:this.targetRoot}}};var Ot=d.getBaseCstVisitorConstructor(),lt=class extends Ot{readFrom="source";scopeStack=[];safeMode=true;isAnalyzing=false;tracker=new A;lastInferredType="any";constructor(){super(),this.validateVisitor();}visitWithContext(t,e){let r=this.readFrom;this.readFrom=e.readFrom;let n=this.visit(t);return this.readFrom=r,n}query(t){this.isAnalyzing&&(this.tracker=new A);let e=this.visit(t.sourceType),r=this.visit(t.targetType),n=!!t.Unsafe;this.safeMode=!n,this.scopeStack.push({format:r.name,options:r.options,isSerializationScope:true});let i=t.action?t.action.map(m=>this.visit(m)):[];this.scopeStack.pop(),t.Transform||i.push("Object.assign(target, source);");let a=e.name,o=r.name,p=JSON.stringify(e.options),u=JSON.stringify(r.options),g=i.some(m=>typeof m=="string"&&m.trim().startsWith("return "));return {code:`
|
|
1
|
+
'use strict';var chevrotain=require('chevrotain'),fastXmlParser=require('fast-xml-parser'),ft=require('papaparse'),vt=require('js-beautify');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ft__default=/*#__PURE__*/_interopDefault(ft);var vt__default=/*#__PURE__*/_interopDefault(vt);var Lt=chevrotain.createToken({name:"WhiteSpace",pattern:/\s+/,group:chevrotain.Lexer.SKIPPED}),St=chevrotain.createToken({name:"LineComment",pattern:/\/\/[^\n\r]*/,group:chevrotain.Lexer.SKIPPED}),At=chevrotain.createToken({name:"BlockComment",pattern:/\/\*[\s\S]*?\*\//,group:chevrotain.Lexer.SKIPPED}),u=chevrotain.createToken({name:"Identifier",pattern:/[a-zA-Z_$][a-zA-Z0-9_.[\]]*/}),v=chevrotain.createToken({name:"QuotedIdentifier",pattern:/`([^`\\]|\\.)*`/}),A=chevrotain.createToken({name:"From",pattern:/from/i,longer_alt:u}),T=chevrotain.createToken({name:"To",pattern:/to/i,longer_alt:u}),R=chevrotain.createToken({name:"Transform",pattern:/transform/i,longer_alt:u}),$=chevrotain.createToken({name:"Set",pattern:/set/i,longer_alt:u}),C=chevrotain.createToken({name:"Section",pattern:/section/i,longer_alt:u}),B=chevrotain.createToken({name:"Multiple",pattern:/multiple/i,longer_alt:u}),M=chevrotain.createToken({name:"Clone",pattern:/clone/i,longer_alt:u}),I=chevrotain.createToken({name:"Delete",pattern:/delete/i,longer_alt:u}),w=chevrotain.createToken({name:"Define",pattern:/define/i,longer_alt:u}),k=chevrotain.createToken({name:"Modify",pattern:/modify/i,longer_alt:u}),b=chevrotain.createToken({name:"If",pattern:/if/i,longer_alt:u}),q=chevrotain.createToken({name:"Else",pattern:/else/i,longer_alt:u}),P=chevrotain.createToken({name:"True",pattern:/true/i,longer_alt:u}),_=chevrotain.createToken({name:"False",pattern:/false/i,longer_alt:u}),j=chevrotain.createToken({name:"Null",pattern:/null/i,longer_alt:u}),z=chevrotain.createToken({name:"Return",pattern:/return/i,longer_alt:u}),F=chevrotain.createToken({name:"Unsafe",pattern:/unsafe/i,longer_alt:u}),x=chevrotain.createToken({name:"EqualsEquals",pattern:/==/}),D=chevrotain.createToken({name:"EqualsEqualsEquals",pattern:/===/}),W=chevrotain.createToken({name:"NotEquals",pattern:/!=/}),Y=chevrotain.createToken({name:"NotEqualsEquals",pattern:/!==/}),G=chevrotain.createToken({name:"LessThanOrEqual",pattern:/<=/}),J=chevrotain.createToken({name:"GreaterThanOrEqual",pattern:/>=/}),Q=chevrotain.createToken({name:"LessThan",pattern:/</}),V=chevrotain.createToken({name:"GreaterThan",pattern:/>/}),Z=chevrotain.createToken({name:"And",pattern:/&&/}),K=chevrotain.createToken({name:"Or",pattern:/\|\|/}),H=chevrotain.createToken({name:"Not",pattern:/!/}),d=chevrotain.createToken({name:"Equals",pattern:/=/}),X=chevrotain.createToken({name:"Plus",pattern:/\+/}),O=chevrotain.createToken({name:"Minus",pattern:/-/}),tt=chevrotain.createToken({name:"Times",pattern:/\*/}),et=chevrotain.createToken({name:"Divide",pattern:/\//}),g=chevrotain.createToken({name:"LParen",pattern:/\(/}),y=chevrotain.createToken({name:"RParen",pattern:/\)/}),U=chevrotain.createToken({name:"Comma",pattern:/,/}),rt=chevrotain.createToken({name:"StringLiteral",pattern:/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/}),st=chevrotain.createToken({name:"NumericLiteral",pattern:/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/}),it=[Lt,St,At,A,T,R,$,C,B,M,I,w,k,b,q,P,_,j,z,F,D,x,Y,W,G,J,Z,K,d,Q,V,H,X,O,tt,et,g,y,U,rt,st,v,u],ht=new chevrotain.Lexer(it);var nt=class extends chevrotain.CstParser{constructor(){super(it),this.performSelfAnalysis();}query=this.RULE("query",()=>{this.CONSUME(A),this.SUBRULE(this.typeFormat,{LABEL:"sourceType"}),this.CONSUME(T),this.SUBRULE1(this.typeFormat,{LABEL:"targetType"}),this.OPTION(()=>{this.CONSUME(R),this.OPTION1(()=>{this.CONSUME(F);}),this.MANY(()=>{this.SUBRULE(this.action);});});});typeFormat=this.RULE("typeFormat",()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"name"}),this.OPTION(()=>{this.CONSUME(g),this.MANY_SEP({SEP:U,DEF:()=>{this.SUBRULE(this.typeFormatParameter,{LABEL:"params"});}}),this.CONSUME(y);});});typeFormatParameter=this.RULE("typeFormatParameter",()=>{this.OR([{GATE:()=>this.LA(2).tokenType===d,ALT:()=>this.SUBRULE(this.namedParameter)},{ALT:()=>this.SUBRULE(this.literal)}]);});namedParameter=this.RULE("namedParameter",()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"key"}),this.CONSUME(d),this.SUBRULE(this.literal,{LABEL:"value"});});anyIdentifier=this.RULE("anyIdentifier",()=>{this.OR([{ALT:()=>this.CONSUME(u)},{ALT:()=>this.CONSUME(v)}]);});literal=this.RULE("literal",()=>{this.OR([{ALT:()=>this.CONSUME(rt)},{ALT:()=>this.CONSUME(st)},{ALT:()=>this.CONSUME(P)},{ALT:()=>this.CONSUME(_)},{ALT:()=>this.CONSUME(j)}]);});action=this.RULE("action",()=>{this.OR([{ALT:()=>this.SUBRULE(this.setRule)},{ALT:()=>this.SUBRULE(this.modifyRule)},{ALT:()=>this.SUBRULE(this.sectionRule)},{ALT:()=>this.SUBRULE(this.cloneRule)},{ALT:()=>this.SUBRULE(this.deleteRule)},{ALT:()=>this.SUBRULE(this.ifAction)},{ALT:()=>this.SUBRULE(this.defineRule)},{ALT:()=>this.SUBRULE(this.returnRule)}]);});returnRule=this.RULE("returnRule",()=>{this.CONSUME(z),this.SUBRULE(this.expression,{LABEL:"expr"});});deleteRule=this.RULE("deleteRule",()=>{this.CONSUME(I),this.SUBRULE(this.anyIdentifier,{LABEL:"field"});});ifAction=this.RULE("ifAction",()=>{this.CONSUME(b),this.CONSUME(g),this.SUBRULE(this.expression,{LABEL:"condition"}),this.CONSUME(y),this.CONSUME2(g),this.MANY(()=>{this.SUBRULE(this.action,{LABEL:"thenActions"});}),this.CONSUME2(y),this.OPTION(()=>{this.CONSUME(q),this.CONSUME3(g),this.MANY2(()=>{this.SUBRULE2(this.action,{LABEL:"elseActions"});}),this.CONSUME3(y);});});cloneRule=this.RULE("cloneRule",()=>{this.CONSUME(M),this.OPTION(()=>{this.CONSUME(g),this.MANY_SEP({SEP:U,DEF:()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"fields"});}}),this.CONSUME(y);});});setRule=this.RULE("setRule",()=>{this.CONSUME($),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(d),this.SUBRULE(this.expression,{LABEL:"right"});});modifyRule=this.RULE("modifyRule",()=>{this.CONSUME(k),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(d),this.SUBRULE(this.expression,{LABEL:"right"});});expression=this.RULE("expression",()=>{this.SUBRULE(this.logicalOr);});logicalOr=this.RULE("logicalOr",()=>{this.SUBRULE(this.logicalAnd,{LABEL:"lhs"}),this.MANY(()=>{this.CONSUME(K),this.SUBRULE1(this.logicalAnd,{LABEL:"rhs"});});});logicalAnd=this.RULE("logicalAnd",()=>{this.SUBRULE(this.comparison,{LABEL:"lhs"}),this.MANY(()=>{this.CONSUME(Z),this.SUBRULE1(this.comparison,{LABEL:"rhs"});});});comparison=this.RULE("comparison",()=>{this.SUBRULE(this.addition,{LABEL:"lhs"}),this.OPTION(()=>{this.OR([{ALT:()=>this.CONSUME(x,{LABEL:"ops"})},{ALT:()=>this.CONSUME(D,{LABEL:"ops"})},{ALT:()=>this.CONSUME(W,{LABEL:"ops"})},{ALT:()=>this.CONSUME(Y,{LABEL:"ops"})},{ALT:()=>this.CONSUME(G,{LABEL:"ops"})},{ALT:()=>this.CONSUME(J,{LABEL:"ops"})},{ALT:()=>this.CONSUME(Q,{LABEL:"ops"})},{ALT:()=>this.CONSUME(V,{LABEL:"ops"})}]),this.SUBRULE1(this.addition,{LABEL:"rhs"});});});addition=this.RULE("addition",()=>{this.SUBRULE(this.multiplication,{LABEL:"lhs"}),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(X,{LABEL:"ops"})},{ALT:()=>this.CONSUME(O,{LABEL:"ops"})}]),this.SUBRULE1(this.multiplication,{LABEL:"rhs"});});});multiplication=this.RULE("multiplication",()=>{this.SUBRULE(this.unaryExpression,{LABEL:"lhs"}),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(tt,{LABEL:"ops"})},{ALT:()=>this.CONSUME(et,{LABEL:"ops"})}]),this.SUBRULE1(this.unaryExpression,{LABEL:"rhs"});});});unaryExpression=this.RULE("unaryExpression",()=>{this.OPTION(()=>{this.OR([{ALT:()=>this.CONSUME(O,{LABEL:"sign"})},{ALT:()=>this.CONSUME(H,{LABEL:"sign"})}]);}),this.SUBRULE(this.atomic);});atomic=this.RULE("atomic",()=>{this.OR([{ALT:()=>this.SUBRULE(this.literal)},{GATE:()=>this.LA(2).tokenType===g,ALT:()=>this.SUBRULE(this.functionCall)},{ALT:()=>this.SUBRULE(this.anyIdentifier)},{ALT:()=>{this.CONSUME(g),this.SUBRULE(this.expression),this.CONSUME(y);}}]);});functionCall=this.RULE("functionCall",()=>{this.OR([{ALT:()=>this.CONSUME(u,{LABEL:"name"})},{ALT:()=>this.CONSUME(b,{LABEL:"name"})}]),this.CONSUME(g),this.MANY_SEP({SEP:U,DEF:()=>{this.SUBRULE(this.expression,{LABEL:"args"});}}),this.CONSUME(y);});sectionRule=this.RULE("sectionRule",()=>{this.CONSUME(C),this.OPTION(()=>{this.CONSUME(B);}),this.SUBRULE(this.anyIdentifier,{LABEL:"sectionName"}),this.CONSUME(g),this.OPTION1(()=>{this.CONSUME(A,{LABEL:"subqueryFrom"}),this.SUBRULE(this.typeFormat,{LABEL:"subquerySourceType"}),this.CONSUME(T,{LABEL:"subqueryTo"}),this.SUBRULE1(this.typeFormat,{LABEL:"subqueryTargetType"}),this.OPTION2(()=>{this.CONSUME(R,{LABEL:"subqueryTransform"});});}),this.MANY(()=>{this.SUBRULE(this.action);}),this.CONSUME(y),this.OPTION3(()=>{this.CONSUME1(A,{LABEL:"followFrom"}),this.SUBRULE(this.expression,{LABEL:"followExpr"});});});defineRule=this.RULE("defineRule",()=>{this.CONSUME(w),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(d),this.SUBRULE(this.expression,{LABEL:"right"});})},E=new nt;var ut={substring:r=>{if(r.length<2)throw new Error("substring() requires at least 2 arguments (string, start, [length])");let[t,e,s]=r;return s!==void 0?`String(${t}).slice(${e}, (${e}) + (${s}))`:`String(${t}).slice(${e})`},if:r=>{if(r.length!==3)throw new Error("if() requires exactly 3 arguments (condition, trueValue, falseValue)");let[t,e,s]=r;return `((${t}) ? (${e}) : (${s}))`},text:r=>{if(r.length!==1)throw new Error("text() requires exactly 1 argument (string or number)");let[t]=r;return `String(${t})`},replace:r=>{if(r.length!==3)throw new Error("replace() requires exactly 3 arguments (string, search, replacement)");let[t,e,s]=r;return `String(${t}).replace(${e}, ${s})`},number:r=>{if(r.length!==1)throw new Error("number() requires exactly 1 argument (string)");let[t]=r;return `Number(${t})`},extractnumber:r=>{if(r.length!==1)throw new Error("extractNumber() requires exactly 1 argument (string)");let[t]=r;return `(() => { const match = String(${t}).match(/\\d+(\\.\\d+)?/); return match ? Number(match[0]) : null; })()`},uppercase:r=>{if(r.length!==1)throw new Error("uppercase() requires exactly 1 argument (string)");let[t]=r;return `String(${t}).toUpperCase()`},lowercase:r=>{if(r.length!==1)throw new Error("lowercase() requires exactly 1 argument (string)");let[t]=r;return `String(${t}).toLowerCase()`},xmlnode:r=>{if(r.length<1)throw new Error("xmlnode() requires at least 1 argument (string)");let[t,...e]=r,s=e.join(", ");return `env.functions.xmlnode(${t}${s?", "+s:""})`},split:r=>{if(r.length<1)throw new Error("split() requires at least 1 argument (string)");let[t,e,s]=r,n=e!==void 0?e:'""',i=s!==void 0?`, ${s}`:"";return `String(${t}).split(${n}${i})`},to_base64:r=>{if(r.length!==1)throw new Error("to_base64() requires exactly 1 argument (string)");let[t]=r;return `env.functions.to_base64(${t})`},from_base64:r=>{if(r.length!==1)throw new Error("from_base64() requires exactly 1 argument (string)");let[t]=r;return `env.functions.from_base64(${t})`},aslist:r=>{if(r.length!==1)throw new Error("aslist() requires exactly 1 argument");let[t]=r;return `env.functions.aslist(${t})`},spreadsheet:r=>{if(r.length!==1)throw new Error("spreadsheet() requires exactly 1 argument");let[t]=r;return `env.functions.spreadsheet(${t})`},unpack:r=>{if(r.length<2)throw new Error("unpack() requires at least 2 arguments (string, fieldSpec1, [fieldSpec2, ...])");let[t,...e]=r;e.forEach(n=>{let i=n.replace(/^["']|["']$/g,""),a=i.split(":");if(a.length<3)throw new Error(`Invalid field spec for unpack(): ${i}. Expected "name:start:length[:modifier]"`);let[o,h,p]=a;if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new Error(`Invalid field name in unpack() spec: "${o}". Must be a valid JavaScript identifier.`);let c=parseInt(h,10),f=parseInt(p,10);if(isNaN(c)||isNaN(f))throw new Error(`Invalid character positions in unpack() spec: ${i}`)});let s=e.join(", ");return `env.functions.unpack(${t}, ${s})`},pack:r=>{if(r.length<2)throw new Error("pack() requires at least 2 arguments (object, fieldSpec1, [fieldSpec2, ...])");let[t,...e]=r;e.forEach(n=>{let i=n.replace(/^["']|["']$/g,""),a=i.split(":");if(a.length<3)throw new Error(`Invalid field spec for pack(): ${i}. Expected "name:start:length[:modifier]"`);let[o,h,p]=a;if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new Error(`Invalid field name in pack() spec: "${o}". Must be a valid JavaScript identifier.`);let c=parseInt(h,10),f=parseInt(p,10);if(isNaN(c)||isNaN(f))throw new Error(`Invalid character positions in pack() spec: ${i}`)});let s=e.join(", ");return `env.functions.pack(${t}, ${s})`},concat:r=>`env.functions.concat(${r.join(", ")})`};var L=class{sourceRoot={type:"object",properties:{}};targetRoot={type:"object",properties:{}};sourceStack=[this.sourceRoot];targetStack=[this.targetRoot];getCurrentSource(){return this.sourceStack[this.sourceStack.length-1]}getCurrentTarget(){return this.targetStack[this.targetStack.length-1]}recordAccess(t,e="any",s=false){let n=s?this.getCurrentTarget():this.getCurrentSource();this.setInNode(n,t,e);}recordAssignment(t,e="any"){this.setInNode(this.getCurrentTarget(),t,e);}recordClone(t){let e=this.getCurrentTarget();t?t.forEach(s=>{this.setInNode(this.getCurrentSource(),s,"any"),this.setInNode(e,s,"any");}):e.isOpen=true;}recordDelete(t){let e=this.getCurrentTarget();this.deleteInNode(e,t);}pushSection(t,e,s){e!=="parent"&&this.setInNode(this.getCurrentSource(),e,s?"array":"object");let n={type:s?"array":"object"};s?n.items={type:"object",properties:{}}:n.properties={};let i={type:"object",properties:{}};this.setInNodeExplicit(this.getCurrentTarget(),t,n),this.targetStack.push(s?n.items:n),this.sourceStack.push(i);}popSection(t,e){let s=this.sourceStack.pop();this.targetStack.pop();let n=this.getCurrentSource();if(t!=="parent"){let i=this.getOrSetNode(n,t,e?"array":"object"),a=e?i.items:i;a&&(a.properties||(a.properties={}),Object.assign(a.properties,s.properties||{}));}else n.properties||(n.properties={}),Object.assign(n.properties,s.properties||{});}setInNode(t,e,s){let n=e.split("."),i=t;for(let a=0;a<n.length;a++){let o=n[a];i.properties||(i.properties={}),a===n.length-1?(!i.properties[o]||i.properties[o].type==="any")&&(i.properties[o]={type:s},s==="object"?i.properties[o].properties={}:s==="array"&&(i.properties[o].items={type:"object",properties:{}})):(i.properties[o]||(i.properties[o]={type:"object",properties:{}}),i=i.properties[o]);}}setInNodeExplicit(t,e,s){let n=e.split("."),i=t;for(let a=0;a<n.length;a++){let o=n[a];i.properties||(i.properties={}),a===n.length-1?i.properties[o]=s:(i.properties[o]||(i.properties[o]={type:"object",properties:{}}),i=i.properties[o]);}}deleteInNode(t,e){let s=e.split("."),n=t;for(let i=0;i<s.length;i++){if(!n.properties)return;if(i===s.length-1)delete n.properties[s[i]];else if(n=n.properties[s[i]],!n)return}}getOrSetNode(t,e,s){let n=e.split("."),i=t;for(let a=0;a<n.length;a++){let o=n[a],p=a===n.length-1?s:"object";i.properties||(i.properties={}),i.properties[o]||(i.properties[o]={type:p},p==="object"?i.properties[o].properties={}:p==="array"&&(i.properties[o].items={type:"object",properties:{}})),i=i.properties[o];}return i}getResult(){return {source:this.sourceRoot,target:this.targetRoot}}};var Tt=E.getBaseCstVisitorConstructor(),at=class extends Tt{readFrom="source";scopeStack=[];safeMode=true;isAnalyzing=false;tracker=new L;lastInferredType="any";constructor(){super(),this.validateVisitor();}reset(){this.readFrom="source",this.scopeStack=[],this.tracker=new L,this.lastInferredType="any";}visitWithContext(t,e){let s=this.readFrom;this.readFrom=e.readFrom;try{return this.visit(t)}finally{this.readFrom=s;}}query(t){this.reset(),this.isAnalyzing&&(this.tracker=new L);let e=this.visit(t.sourceType),s=this.visit(t.targetType),n=!!t.Unsafe;this.safeMode=!n,this.scopeStack.push({format:s.name,options:s.options,isSerializationScope:true});try{let i=t.action?t.action.map(m=>this.visit(m)):[];t.Transform||i.push("Object.assign(target, source);");let a=e.name,o=s.name,h=JSON.stringify(e.options),p=JSON.stringify(s.options),c=i.some(m=>typeof m=="string"&&m.trim().startsWith("return "));return {code:`
|
|
22
2
|
return function(input, env) {
|
|
23
3
|
// 1. Parse Input
|
|
24
|
-
const source = env.parse('${a}', input, ${
|
|
4
|
+
const source = env.parse('${a}', input, ${h});
|
|
25
5
|
const _rootSource = source;
|
|
26
6
|
|
|
27
7
|
// 2. Transform
|
|
@@ -31,54 +11,55 @@
|
|
|
31
11
|
`)}
|
|
32
12
|
|
|
33
13
|
// 3. Serialize Output
|
|
34
|
-
${
|
|
14
|
+
${c?"":`return env.serialize('${o}', target, ${p});`}
|
|
35
15
|
}
|
|
36
|
-
`,sourceType:e,targetType:
|
|
16
|
+
`,sourceType:e,targetType:s,analysis:this.isAnalyzing?this.tracker.getResult():void 0}}finally{this.scopeStack.pop();}}typeFormat(t){let e=this.visit(t.name),s={params:[]};return t.params&&t.params.forEach(n=>{let i=this.visit(n);typeof i=="object"&&"key"in i?s[i.key]=this.parseLiteral(i.value):s.params.push(this.parseLiteral(i));}),{name:e.name,options:s}}typeFormatParameter(t){if(t.namedParameter)return this.visit(t.namedParameter);if(t.literal)return this.visit(t.literal)}namedParameter(t){let e=this.visit(t.key).name,s=this.visit(t.value);return {key:e,value:s}}parseLiteral(t){if(t==="true")return true;if(t==="false")return false;if(t==="null")return null;if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);let e=Number(t);return isNaN(e)?t:e}genAccess(t,e,s=false){let n=this.safeMode&&!s?"?.":".";return e.quoted||e.name.includes("-")&&!e.name.includes(".")&&!e.name.includes("[")?`${t}${this.safeMode&&!s?"?.":""}["${e.name}"]`:`${t}${n}${e.name}`}anyIdentifier(t){if(t.Identifier)return {name:t.Identifier[0].image,quoted:false};if(t.QuotedIdentifier)return {name:t.QuotedIdentifier[0].image.slice(1,-1).replace(/\\(.)/g,"$1"),quoted:true}}literal(t){if(t.StringLiteral)return this.lastInferredType="string",t.StringLiteral[0].image;if(t.NumericLiteral)return this.lastInferredType="number",t.NumericLiteral[0].image;if(t.True)return this.lastInferredType="boolean","true";if(t.False)return this.lastInferredType="boolean","false";if(t.Null)return this.lastInferredType="null","null"}action(t){if(t.setRule)return this.visit(t.setRule);if(t.modifyRule)return this.visit(t.modifyRule);if(t.sectionRule)return this.visit(t.sectionRule);if(t.cloneRule)return this.visit(t.cloneRule);if(t.ifAction)return this.visit(t.ifAction);if(t.deleteRule)return this.visit(t.deleteRule);if(t.defineRule)return this.visit(t.defineRule);if(t.returnRule)return this.visit(t.returnRule)}deleteRule(t){let e=this.visit(t.field);return this.isAnalyzing&&this.tracker.recordDelete(e.name),`delete ${this.genAccess("target",e,true)};`}ifAction(t){let e=this.visit(t.condition),s=t.thenActions?t.thenActions.map(i=>this.visit(i)).join(`
|
|
37
17
|
`):"",n=t.elseActions?`else { ${t.elseActions.map(i=>this.visit(i)).join(`
|
|
38
18
|
`)} }`:"";return `if (${e}) {
|
|
39
|
-
${
|
|
40
|
-
} ${n}`}cloneRule(t){if(t.fields){let e=t.fields.map(
|
|
41
|
-
`)}return this.isAnalyzing&&this.tracker.recordClone(),"Object.assign(target, source);"}setRule(t){let e=this.visit(t.left);this.lastInferredType="any";let
|
|
42
|
-
if (${
|
|
43
|
-
${n} = ${
|
|
44
|
-
const subSource = env.parse('${
|
|
19
|
+
${s}
|
|
20
|
+
} ${n}`}cloneRule(t){if(t.fields){let e=t.fields.map(s=>this.visit(s));return this.isAnalyzing&&this.tracker.recordClone(e.map(s=>s.name)),e.map(s=>`${this.genAccess("target",s,true)} = ${this.genAccess("source",s)};`).join(`
|
|
21
|
+
`)}return this.isAnalyzing&&this.tracker.recordClone(),"Object.assign(target, source);"}setRule(t){let e=this.visit(t.left);this.lastInferredType="any";let s=this.visit(t.right);return this.isAnalyzing&&this.tracker.recordAssignment(e.name,this.lastInferredType),`${this.genAccess("target",e,true)} = ${s};`}modifyRule(t){let e=this.visit(t.left);this.lastInferredType="any";let s=this.visitWithContext(t.right,{readFrom:"target"});return this.isAnalyzing&&this.tracker.recordAssignment(e.name,this.lastInferredType),`${this.genAccess("target",e,true)} = ${s};`}defineRule(t){let e=this.visit(t.left);this.lastInferredType="any";let s=this.visit(t.right);return this.isAnalyzing&&this.tracker.recordAssignment(e.name,this.lastInferredType),`${this.genAccess("source",e,true)} = ${s};`}returnRule(t){let e=this.visitWithContext(t.expr,{readFrom:"target"}),s=this.scopeStack[this.scopeStack.length-1];if(s&&s.isSerializationScope){let n=JSON.stringify(s.options);return `return env.serialize('${s.format}', ${e}, ${n});`}return `return ${e};`}expression(t){return this.visit(t.logicalOr)}logicalOr(t){let e=this.visit(t.lhs);if(t.rhs&&t.rhs.length>0){this.lastInferredType="boolean";for(let s=0;s<t.rhs.length;s++){let n=this.visit(t.rhs[s]);e=`${e} || ${n}`;}}return e}logicalAnd(t){let e=this.visit(t.lhs);if(t.rhs&&t.rhs.length>0){this.lastInferredType="boolean";for(let s=0;s<t.rhs.length;s++){let n=this.visit(t.rhs[s]);e=`${e} && ${n}`;}}return e}comparison(t){let e=this.visit(t.lhs);if(t.rhs){this.lastInferredType="boolean";let s=t.ops[0].image,n=this.visit(t.rhs[0]);e=`${e} ${s} ${n}`;}return e}addition(t){let e=this.visit(t.lhs),s=this.lastInferredType,n=e;if(t.rhs&&t.rhs.length>0){let i=s==="string",a=s==="number";for(let o=0;o<t.rhs.length;o++){let h=t.ops[o].image,p=this.visit(t.rhs[o]);this.lastInferredType==="string"&&(i=true),this.lastInferredType!=="number"&&(a=false),n=`${n} ${h} ${p}`;}i?this.lastInferredType="string":a?this.lastInferredType="number":this.lastInferredType="any";}else this.lastInferredType=s;return n}multiplication(t){let e=this.visit(t.lhs);if(t.rhs&&t.rhs.length>0){this.lastInferredType="number";for(let s=0;s<t.rhs.length;s++){let n=t.ops[s].image,i=this.visit(t.rhs[s]);e=`${e} ${n} ${i}`;}}return e}unaryExpression(t){let e=this.visit(t.atomic);if(t.sign){let s=t.sign[0].image;return s==="!"&&(this.lastInferredType="boolean"),s==="-"&&(this.lastInferredType="number"),`${s}${e}`}return e}atomic(t){if(t.literal)return this.visit(t.literal);if(t.functionCall)return this.visit(t.functionCall);if(t.anyIdentifier){this.lastInferredType="any";let e=this.visit(t.anyIdentifier);if(["true","false","null"].includes(e.name)&&!e.quoted)return e.name;if(!e.quoted){if(e.name.startsWith("source.")||e.name.startsWith("source["))return this.isAnalyzing&&this.tracker.recordAccess(e.name.substring(7),"any",false),e.name;if(e.name.startsWith("target.")||e.name.startsWith("target["))return this.isAnalyzing&&this.tracker.recordAccess(e.name.substring(7),"any",true),e.name;if(e.name==="target")return "target";if(e.name==="source")return "source";if(e.name==="_source"||e.name.startsWith("_source.")||e.name.startsWith("_source["))return this.isAnalyzing&&this.tracker.recordAccess(e.name.substring(7)||"","any",false),`_rootSource${e.name.substring(7)}`;if(e.name==="_target"||e.name.startsWith("_target.")||e.name.startsWith("_target["))return this.isAnalyzing&&this.tracker.recordAccess(e.name.substring(7)||"","any",true),`_rootTarget${e.name.substring(7)}`}return this.isAnalyzing&&this.tracker.recordAccess(e.name,"any",this.readFrom==="target"),this.genAccess(this.readFrom,e)}if(t.expression)return `(${this.visit(t.expression)})`}functionCall(t){let e=t.name[0].image,s=(e.startsWith("`")?e.slice(1,-1):e).toLowerCase(),n=t.args?t.args.map(a=>this.visit(a)):[],i=ut[s];if(i)return ["substring","text","replace","uppercase","lowercase","to_base64","from_base64"].includes(s)?this.lastInferredType="string":["number","extractnumber"].includes(s)?this.lastInferredType="number":["aslist"].includes(s)?this.lastInferredType="array":s==="asobject"&&(this.lastInferredType="object"),i(n);throw new Error(`Unknown function: ${e}`)}sectionRule(t){let e=this.visit(t.sectionName),s=e.name,n=this.genAccess("target",e,true),i,a;if(t.followExpr){let p=this.visit(t.followExpr),c=p.replace(/\?\./g,".");c==="source.parent"||c==="this.source.parent"||c===`${this.readFrom.replace(/\?\./g,".")}.parent`?(i="source",a="parent"):(i=p,a=i);}else i=this.genAccess("source",e),a=e.name;let o=!!t.Multiple;if(!!t.subqueryFrom){let p=this.visit(t.subquerySourceType),c=this.visit(t.subqueryTargetType);this.scopeStack.push({format:c.name,options:c.options,isSerializationScope:true});try{let f=!!t.subqueryTransform,m=t.action?t.action.map(Et=>this.visit(Et)):[];f||m.push("Object.assign(target, source);");let pt=JSON.stringify(p.options),ct=JSON.stringify(c.options);return o?`
|
|
22
|
+
if (${i} && Array.isArray(${i})) {
|
|
23
|
+
${n} = ${i}.map(item => {
|
|
24
|
+
const subSource = env.parse('${p.name}', item, ${pt});
|
|
45
25
|
const source = subSource;
|
|
46
26
|
const target = {};
|
|
47
|
-
${
|
|
27
|
+
${m.join(`
|
|
48
28
|
`)}
|
|
49
|
-
return env.serialize('${
|
|
29
|
+
return env.serialize('${c.name}', target, ${ct});
|
|
50
30
|
});
|
|
51
31
|
}
|
|
52
|
-
|
|
53
|
-
if (${
|
|
32
|
+
`:`
|
|
33
|
+
if (${i}) {
|
|
54
34
|
${n} = (function(innerSource) {
|
|
55
|
-
const subSource = env.parse('${
|
|
35
|
+
const subSource = env.parse('${p.name}', innerSource, ${pt});
|
|
56
36
|
const source = subSource;
|
|
57
37
|
const target = {};
|
|
58
|
-
${
|
|
38
|
+
${m.join(`
|
|
59
39
|
`)}
|
|
60
|
-
return env.serialize('${
|
|
61
|
-
})(${
|
|
40
|
+
return env.serialize('${c.name}', target, ${ct});
|
|
41
|
+
})(${i});
|
|
62
42
|
}
|
|
63
|
-
|
|
64
|
-
if (${
|
|
65
|
-
${n} = ${
|
|
43
|
+
`}finally{this.scopeStack.pop();}}this.scopeStack.push({format:"object",options:{},isSerializationScope:false});try{let p=a;p!=="parent"&&(p=p.replace(/^source\??\./,"").replace(/^this\.source\??\./,"").replace(/\?\./g,".")),this.isAnalyzing&&this.tracker.pushSection(s,p,o);try{let c=t.action?t.action.map(f=>this.visit(f)):[];return o?`
|
|
44
|
+
if (${i} && Array.isArray(${i})) {
|
|
45
|
+
${n} = ${i}.map(item => {
|
|
66
46
|
const source = item;
|
|
67
47
|
const target = {};
|
|
68
|
-
${
|
|
48
|
+
${c.join(`
|
|
69
49
|
`)}
|
|
70
50
|
return target;
|
|
71
51
|
});
|
|
72
52
|
}
|
|
73
|
-
|
|
74
|
-
if (${
|
|
53
|
+
`:`
|
|
54
|
+
if (${i}) {
|
|
75
55
|
${n} = (function(innerSource) {
|
|
76
56
|
const source = innerSource;
|
|
77
57
|
const target = {};
|
|
78
|
-
${
|
|
58
|
+
${c.join(`
|
|
79
59
|
`)}
|
|
80
60
|
return target;
|
|
81
|
-
})(${
|
|
61
|
+
})(${i});
|
|
82
62
|
}
|
|
83
|
-
|
|
63
|
+
`}finally{this.isAnalyzing&&this.tracker.popSection(p,o);}}finally{this.scopeStack.pop();}}},ot=new at;var gt={};function S(r,t){gt[r.toLowerCase()]=t;}function lt(r){let t=gt[r.toLowerCase()];if(!t)throw new Error(`No adapter found for format: ${r}`);return t}function bt(r){let t="";for(;r>=0;)t=String.fromCharCode(r%26+65)+t,r=Math.floor(r/26)-1;return t}S("json",{parse:r=>typeof r!="string"?r:JSON.parse(r),serialize:r=>JSON.stringify(r,null,2)});var Ot=new fastXmlParser.XMLBuilder({ignoreAttributes:false,attributeNamePrefix:"$",textNodeName:"_",format:true});S("xml",{parse:(r,t)=>typeof r!="string"?r:new fastXmlParser.XMLParser({ignoreAttributes:false,removeNSPrefix:true,...t}).parse(r),serialize:(r,t)=>{let e=t?.rootGenerated??t?.params?.[0]??"root";return (t?new fastXmlParser.XMLBuilder({ignoreAttributes:false,attributeNamePrefix:"$",textNodeName:"_",format:true,...t}):Ot).build({[e]:r})}});S("csv",{parse:(r,t)=>{if(typeof r!="string")return r;let e=t?.delimiter??t?.params?.[0]??",";return {rows:ft__default.default.parse(r,{delimiter:e,skipEmptyLines:true,...t}).data.map(i=>{let a={};return Array.isArray(i)&&i.forEach((o,h)=>{a[bt(h)]=o;}),a})}},serialize:(r,t)=>{if(!r||!Array.isArray(r.rows))return "";let e=t?.delimiter??t?.params?.[0]??",",s=r.rows.map(n=>Object.keys(n).filter(a=>/^[A-Z]+$/.test(a)).sort((a,o)=>a.length!==o.length?a.length-o.length:a.localeCompare(o)).map(a=>n[a]));return ft__default.default.unparse(s,{delimiter:e,...t})}});S("object",{parse:r=>r,serialize:r=>r});S("plaintext",{parse:(r,t)=>{if(typeof r!="string")return r;let e=t?.separator??t?.params?.[0]??/\r?\n/;return {rows:r.split(e).filter(s=>s.length>0)}},serialize:(r,t)=>{if(!r||!Array.isArray(r.rows))return "";let e=t?.separator??t?.params?.[0]??`
|
|
64
|
+
`;return r.rows.join(e)}});var yt={spreadsheet:r=>{let t=Array.isArray(r)?r:r==null?[]:[r];if(!Array.isArray(r)&&r&&typeof r=="object"&&Array.isArray(r.rows)&&(t=r.rows),t.length===0)return [];let e=[],s=[],n=[];for(let i=0;i<t.length;i++){let a=t[i];if(!(!a||typeof a!="object"))if(i===0){n=Object.keys(a);for(let o of n)s.push(String(a[o]));}else {let o={};for(let h=0;h<n.length;h++){let p=n[h],c=s[h];o[c]=a[p];}e.push(o);}}return e},aslist:r=>Array.isArray(r)?r:r==null?[]:[r],to_base64:r=>{let t=String(r);return typeof btoa=="function"?btoa(unescape(encodeURIComponent(t))):Buffer.from(t,"utf-8").toString("base64")},from_base64:r=>{let t=String(r);return typeof atob=="function"?decodeURIComponent(escape(atob(t))):Buffer.from(t,"base64").toString("utf-8")},xmlnode:(r,...t)=>{if(t.length>0){let e=[];for(let i=0;i<t.length;i+=2)e.push([t[i],t[i+1]]);let s=e.map(([i,a])=>[`$${i}`,a]),n=Object.fromEntries(s);return {_:r,...n}}return r},unpack:(r,...t)=>{let e=String(r||""),s={};for(let n of t){let i=n.split(":");if(i.length<3)continue;let[a,o,h,p]=i,c=parseInt(o,10),f=parseInt(h,10);if(isNaN(c)||isNaN(f))continue;let m=e.substring(c,c+f);p!=="raw"&&(m=m.trim()),s[a]=m;}return s},pack:(r,...t)=>{let e=r||{},s=t.map(a=>{let o=a.split(":");if(o.length<3)return null;let[h,p,c,f]=o;return {name:h,start:parseInt(p,10),length:parseInt(c,10),left:f==="left"}}).filter(a=>a!==null),n=s.reduce((a,o)=>Math.max(a,o.start+o.length),0),i=" ".repeat(n);for(let a of s){let o=String(e[a.name]??""),p=(a.left?o.padStart(a.length):o.padEnd(a.length)).substring(0,a.length);i=i.substring(0,a.start)+p+i.substring(a.start+a.length);}return i},concat:(...r)=>r.reduce((t,e)=>t.concat(Array.isArray(e)?e:e==null?[]:[e]),[])};async function te(r,t){if(t?.cache){let c=await t.cache.retrieve(r);if(c)return dt(c)}let e=ht.tokenize(r);if(e.errors.length>0)throw new Error(`Lexing errors: ${e.errors[0].message}`);E.input=e.tokens;let s=E.query();if(E.errors.length>0)throw new Error(`Parsing errors: ${E.errors[0].message}`);ot.isAnalyzing=!!t?.analyze;let{code:n,analysis:i,sourceType:a,targetType:o}=ot.visit(s),h=vt__default.default.js(n,{indent_size:2,space_in_empty_paren:true,end_with_newline:true});t?.cache&&await t.cache.save(r,h);let p=dt(h);return i&&(i.sourceFormat=a.name,i.targetFormat=o.name,p.analysis=i),p}function dt(r){let e=new Function(r)(),s={parse:(i,a,o)=>lt(i).parse(a,o),serialize:(i,a,o)=>lt(i).serialize(a,o),functions:yt},n=(i=>e(i,s));return n.code=r,n}function ee(r,...t){return r.reduce((e,s,n)=>e+s+(t[n]??""),"")}function re(r){return `Hello, ${r}! The Morph engine is ready.`}exports.compile=te;exports.getAdapter=lt;exports.greet=re;exports.morphQL=ee;exports.registerAdapter=S;//# sourceMappingURL=index.cjs.map
|
|
84
65
|
//# sourceMappingURL=index.cjs.map
|