xhs-mp-sketch-loader 2.0.4-beta.3 → 2.0.4

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +9 -9
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("./consts.js"),t=require("xhs-mp-pack"),r=require("xhs-mp-compiler-utils"),n=require("xhs-mp-ml-parser"),i=require("lodash");class o extends n.BaseValidator{constructor(e,t){super(),this.source=e,this.filePath=t}validateBase(e){if(n.isImport(e)||n.isTemplateConsume(e)||n.isTemplateDefine(e))throw new t.ParserError(e.start,"骨架文件:不支持 template、import 标签");if(n.isInclude(e))throw new t.ParserError(e.start,"骨架文件:不支持 include 标签");if(n.isSlotGet(e)||n.isSlotPass(e))throw new t.ParserError(e.start,"骨架文件:不支持 插槽 语法");if(n.isSJS(e))throw new t.ParserError(e.start,"骨架文件:不支持 sjs 标签")}validate(e){var t;this.validateBase(e),n.isLoopNode(e)&&this.validateLoop(e),n.isConditionNode(e)&&this.validateCondition(e),e.children.length&&(e.children.forEach((e=>{this.validate(e)})),(null===(t=e.children)||void 0===t?void 0:t.some(n.isConditionNode))&&this.validateConditionStack(e.children))}}class s{static addExpr(t){const r=i.last(s._list);if(r){r.exprs.push(t);const n=r.exprs.length-1;return t.loopContext.length?`${e.EXPR_TRY_CATCH}(${n}, { ${t.loopContext.join(",")}} )`:`${e.EXPR_TRY_CATCH}(${n})`}return""}static renderExpr(){var t;const r=i.last(s._list);if(!(null===(t=null==r?void 0:r.exprs)||void 0===t?void 0:t.length))return"";const n=r.exprs.map(((t,r)=>{let n="";return n=t.loopContext.length?`{\n const { ${t.loopContext.join(",")} } = ${e.EXPR_TRY_CATCH_CTX}\n return ${t.value};\n }\n `:`{ return ${t.value}; }`,{code:n,idx:r}})),o=i.groupBy(n,"code"),l=Object.keys(o).map((e=>`${o[e].map((({idx:e})=>`case ${e}:`)).join("")}${e}`)).join("\n");return`\n const ${e.EXPR_TRY_CATCH} = (${e.EXPR_TRY_CATCH_INDEX}, ${e.EXPR_TRY_CATCH_CTX}) => {\n try{\n switch(${e.EXPR_TRY_CATCH_INDEX}) {\n ${l} \n }\n }catch(error){\n // console.warn(\`[xhs warning]: \${error.message}\`)\n }\n }\n `}static addHelper(t){const r=i.last(s._list);if(r)switch(t){case e.HELPERS.RENDER_LIST:r.renderList=!0;break;case e.HELPERS.RENDER_COMMENT:r.renderComment=!0;break;case e.HELPERS.RENDER_ELEMENT:r.renderElement=!0;break;case e.HELPERS.RENDER_TEXT:r.renderText=!0}}static renderListHelper(){const t=i.last(s._list);return(null==t?void 0:t.renderList)?`const ${e.HELPERS.RENDER_LIST} = (list, renderItem) => {\n if(Array.isArray(list)){ return list.map(renderItem).filter(Boolean) }\n if(typeof list === 'object' && list != null ){ return Object.entries(list).map(([k, v]) => renderItem(v, k)).filter(Boolean) } \n if(typeof list === 'string'){ return list.split("").map(renderItem).filter(Boolean) } \n return []\n }`:""}static renderElementHelper(){const t=i.last(s._list);return(null==t?void 0:t.renderElement)?`const ${e.HELPERS.RENDER_ELEMENT} = (tagName, attributes, childNodes = []) => ({ type: ${e.NodeType.Element}, tagName, attributes, childNodes: childNodes.filter(Boolean) })`:""}static renderTextHelper(){const t=i.last(s._list);return(null==t?void 0:t.renderText)?`const ${e.HELPERS.RENDER_TEXT} = (textContent) => ({ type: ${e.NodeType.Text} , textContent })`:""}static renderCommentHelper(){const t=i.last(s._list);return(null==t?void 0:t.renderComment)?`const ${e.HELPERS.RENDER_COMMENT} = (textContent) => ({ type: ${e.NodeType.Comment} , textContent })`:""}static startHoisting(){s._list.push({exprs:[],renderComment:!1,renderElement:!1,renderList:!1,renderText:!1})}static popHoisting(){const e=[s.renderExpr(),s.renderCommentHelper(),s.renderTextHelper(),s.renderElementHelper(),s.renderListHelper()].filter(Boolean).join("\n");return s._list.pop(),e}static clear(){s._list=[]}}s._list=[];const l=["null","undefined","false","true","NaN","Number","Boolean","String","JSON"],a=["window","self","globalThis","this"],d=(r,i,o,d)=>{try{if("expression"===o||"text"===o){return("expression"===o?r.trim():r).split(/({{.*?}})/).filter(Boolean).map((t=>{var r,d;if(null===(r=n.matchMustache(t))||void 0===r?void 0:r.length){const r=t.replace(/{{(.*?)}}/g,((t,r)=>((t,r)=>{let i=!1;const o=new Set,d=n.parseExpression(t).map((t=>{var n,s;if("string"==typeof t)return t;const d=null===(n=t.source)||void 0===n?void 0:n.trim();return l.includes(d)?d:a.includes(d)?(i=!0,"({})"):(null===(s=r.loopContext)||void 0===s?void 0:s.includes(d))?(i=!0,o.add(d),d):(i=!0,`${e.SKETCH_CTX}.${d}`)})).join("");return i?s.addExpr({value:d,loopContext:[...o].sort()}):d})(r,i)));return`(${r})`}return"expression"===o?JSON.stringify(t):(d=t).includes("&")?JSON.stringify(n.decodeHtmlEntity(d,!1)):JSON.stringify(d)})).join("+")}}catch(e){const o=d instanceof n.XhsAttr?d.name:"";let s=e.message+`: \`${r}\``;throw o?(s=`${s} at attribute \`${o}\``,i instanceof n.XhsElement&&(s=`${s} in tag \`${i.name}\``)):d instanceof n.XhsText&&(s=`${s} at text block`),new t.ParserError((null==d?void 0:d.start)||(null==i?void 0:i.start)||0,s)}throw new Error(`${r} 未实现模式${o}`)};function c(e,t,r,i="expression"){var o;return(null===(o=n.matchMustache(t))||void 0===o?void 0:o.length)?d(t,e,i,r)||"":JSON.stringify(t)}class E{constructor(e){var t;this.filePath="",this.shortPath="",this.removeComentNode=!0,this.filePath=e.filePath,this.removeComentNode=null===(t=e.removeComentNode)||void 0===t||t,this.ast=e.ast}handleAttr(e){const t=[];return Object.values(e.attrsMap).forEach((r=>{const{name:i,value:o}=r;n.XhsOperations.includes(i)||("boolean"!=typeof o?t.push(`${JSON.stringify(i)}: ${c(e,o,r)}`):t.push(`${JSON.stringify(i)}: ${o}`))})),`{ ${t.filter(Boolean).join(",")} }`}renderFor(t){const{forBody:r,forItem:i,forIndex:o,forKey:l,forBodyAttr:a,forKeyAttr:d}=n.getLoop(t),E=c(t,r,a),p=i||"item",h=o||"index";if(n.isDefined(l)){let e="";e=l===p?p:l===h?h:(null==l?void 0:l.startsWith(`${p}.`))?l:["*this","*item",void 0].includes(l)?p:n.matchMustache(l)?l||'""':`${p}["${l}"]`,d&&(d.value=e)}return t.loopContext=[...t.loopContext,p,h],n.broadcastContext({nodes:t.children,loopContext:[p,h]}),s.addHelper(e.HELPERS.RENDER_LIST),`${e.HELPERS.RENDER_LIST}(\n ${E},\n (${p}, ${h}) => ${t.operation["xhs:if"]?this.renderIf(t):this.renderElement(t)}\n)`}renderIf(e){var t,r,i;const o=[e],s=null===(r=null===(t=e.parent)||void 0===t?void 0:t.children)||void 0===r?void 0:r.findIndex((t=>t===e));if(void 0!==s){const t=null===(i=e.parent)||void 0===i?void 0:i.children;if(t)for(let e=s+1;e<t.length;e++){const r=t[e];if(r.operation["xhs:elif"])o.push(r);else if(!r.is(n.ElementType.COMMENT)){if(r.operation["xhs:else"]){o.push(r);break}break}}}const l=!o.find((e=>e.operation["xhs:else"]));let a="";return o.forEach((t=>{const{ifState:r,elifState:i,elseState:o}=n.getCondition(t);if(n.isDefined(r)||n.isDefined(i)){const n=c(e,`${r||i}`,e.operation["xhs:if"]||e.operation["xhs:elif"]);a+=`${n} ? ${this.renderElement(t)} :`}else o&&(a+=this.renderElement(t))})),l&&(a+="null"),a}renderElement(t){const r=t.children.map((e=>this.renderNode(e))).filter(Boolean).join(",");let i=n.tagTransformMap[t.name]?`xhs-${t.name}`:t.name;return s.addHelper(e.HELPERS.RENDER_ELEMENT),`${e.HELPERS.RENDER_ELEMENT}('${i}', ${this.handleAttr(t)}, [${r}])`}renderNode(t){if(t.is(n.ElementType.COMMENT)&&!this.removeComentNode)return s.addHelper(e.HELPERS.RENDER_COMMENT),`${e.HELPERS.RENDER_COMMENT}(${JSON.stringify(t.content)})`;if(t.is(n.ElementType.Element)){if(i.isEmpty(t.operation))return this.renderElement(t);if(t.operation["xhs:for"])return this.renderFor(t);if(t.operation["xhs:if"])return this.renderIf(t)}else if(t.is(n.ElementType.TEXT)){const r=c(t,t.content,t,"text");return s.addHelper(e.HELPERS.RENDER_TEXT),`${e.HELPERS.RENDER_TEXT}(${r})`}return""}renderSketch(){s.startHoisting();const t=this.ast.children.map((e=>this.renderNode(e))).filter(Boolean);return`function(${e.SKETCH_CTX}){\n ${s.popHoisting()}\n return ([${t.join(",")}]).filter(Boolean)\n }`}}module.exports=function(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=this.async();try{const{resourcePath:l,_compiler:a,resourceQuery:d}=this,{miniprogramDir:c,appJSON:p={}}=(null==a?void 0:a.project)||{},h=r.getShortPath(c,l);t.initErrorContext(i,l),s.clear();const u=n.parseML(i,l);new o(i,l).validate(u);const f=new E({ast:u,filePath:l,shortPath:h});e(null,`export default ${f.renderSketch()}`)}catch(t){e(t)}}))};
1
+ "use strict";var e=require("./consts.js"),t=require("xhs-mp-pack"),r=require("xhs-mp-compiler-utils"),n=require("xhs-mp-ml-parser"),i=require("lodash");class o extends n.BaseValidator{constructor(e,t){super(),this.source=e,this.filePath=t}validateBase(e){if(n.isImport(e)||n.isTemplateConsume(e)||n.isTemplateDefine(e))throw new t.ParserError(e.start,"骨架文件:不支持 template、import 标签");if(n.isInclude(e))throw new t.ParserError(e.start,"骨架文件:不支持 include 标签");if(n.isSlotGet(e)||n.isSlotPass(e))throw new t.ParserError(e.start,"骨架文件:不支持 插槽 语法");if(n.isSJS(e))throw new t.ParserError(e.start,"骨架文件:不支持 sjs 标签")}validate(e){var t;this.validateBase(e),n.isLoopNode(e)&&this.validateLoop(e),n.isConditionNode(e)&&this.validateCondition(e),e.is(n.ElementType.Element)&&"block"===e.name&&n.sanitizeBlockAttributes(e),e.children.length&&(e.children.forEach((e=>{this.validate(e)})),(null===(t=e.children)||void 0===t?void 0:t.some(n.isConditionNode))&&this.validateConditionStack(e.children))}}class s{static addExpr(t){const r=i.last(s._list);if(r){r.exprs.push(t);const n=r.exprs.length-1;return t.loopContext.length?`${e.EXPR_TRY_CATCH}(${n}, { ${t.loopContext.join(",")}} )`:`${e.EXPR_TRY_CATCH}(${n})`}return""}static renderExpr(){var t;const r=i.last(s._list);if(!(null===(t=null==r?void 0:r.exprs)||void 0===t?void 0:t.length))return"";const n=r.exprs.map(((t,r)=>{let n="";return n=t.loopContext.length?`{\n const { ${t.loopContext.join(",")} } = ${e.EXPR_TRY_CATCH_CTX}\n return ${t.value};\n }\n `:`{ return ${t.value}; }`,{code:n,idx:r}})),o=i.groupBy(n,"code"),l=Object.keys(o).map((e=>`${o[e].map((({idx:e})=>`case ${e}:`)).join("")}${e}`)).join("\n");return`\n const ${e.EXPR_TRY_CATCH} = (${e.EXPR_TRY_CATCH_INDEX}, ${e.EXPR_TRY_CATCH_CTX}) => {\n try{\n switch(${e.EXPR_TRY_CATCH_INDEX}) {\n ${l} \n }\n }catch(error){\n // console.warn(\`[xhs warning]: \${error.message}\`)\n }\n }\n `}static addHelper(t){const r=i.last(s._list);if(r)switch(t){case e.HELPERS.RENDER_LIST:r.renderList=!0;break;case e.HELPERS.RENDER_COMMENT:r.renderComment=!0;break;case e.HELPERS.RENDER_ELEMENT:r.renderElement=!0;break;case e.HELPERS.RENDER_TEXT:r.renderText=!0}}static renderListHelper(){const t=i.last(s._list);return(null==t?void 0:t.renderList)?`const ${e.HELPERS.RENDER_LIST} = (list, renderItem) => {\n if(Array.isArray(list)){ return list.map(renderItem).filter(Boolean) }\n if(typeof list === 'object' && list != null ){ return Object.entries(list).map(([k, v]) => renderItem(v, k)).filter(Boolean) } \n if(typeof list === 'string'){ return list.split("").map(renderItem).filter(Boolean) } \n return []\n }`:""}static renderElementHelper(){const t=i.last(s._list);return(null==t?void 0:t.renderElement)?`const ${e.HELPERS.RENDER_ELEMENT} = (tagName, attributes, childNodes = []) => ({ type: ${e.NodeType.Element}, tagName, attributes, childNodes: childNodes.filter(Boolean) })`:""}static renderTextHelper(){const t=i.last(s._list);return(null==t?void 0:t.renderText)?`const ${e.HELPERS.RENDER_TEXT} = (textContent) => ({ type: ${e.NodeType.Text} , textContent })`:""}static renderCommentHelper(){const t=i.last(s._list);return(null==t?void 0:t.renderComment)?`const ${e.HELPERS.RENDER_COMMENT} = (textContent) => ({ type: ${e.NodeType.Comment} , textContent })`:""}static startHoisting(){s._list.push({exprs:[],renderComment:!1,renderElement:!1,renderList:!1,renderText:!1})}static popHoisting(){const e=[s.renderExpr(),s.renderCommentHelper(),s.renderTextHelper(),s.renderElementHelper(),s.renderListHelper()].filter(Boolean).join("\n");return s._list.pop(),e}static clear(){s._list=[]}}s._list=[];const l=["null","undefined","false","true","NaN","Number","Boolean","String","JSON"],a=["window","self","globalThis","this"],d=(r,i,o,d)=>{try{if("expression"===o||"text"===o){return("expression"===o?r.trim():r).split(/({{.*?}})/).filter(Boolean).map((t=>{var r,d;if(null===(r=n.matchMustache(t))||void 0===r?void 0:r.length){const r=t.replace(/{{(.*?)}}/g,((t,r)=>((t,r)=>{let i=!1;const o=new Set,d=n.parseExpression(t).map((t=>{var n,s;if("string"==typeof t)return t;const d=null===(n=t.source)||void 0===n?void 0:n.trim();return l.includes(d)?d:a.includes(d)?(i=!0,"({})"):(null===(s=r.loopContext)||void 0===s?void 0:s.includes(d))?(i=!0,o.add(d),d):(i=!0,`${e.SKETCH_CTX}.${d}`)})).join("");return i?s.addExpr({value:d,loopContext:[...o].sort()}):d})(r,i)));return`(${r})`}return"expression"===o?JSON.stringify(t):(d=t).includes("&")?JSON.stringify(n.decodeHtmlEntity(d,!1)):JSON.stringify(d)})).join("+")}}catch(e){const o=d instanceof n.XhsAttr?d.name:"";let s=e.message+`: \`${r}\``;throw o?(s=`${s} at attribute \`${o}\``,i instanceof n.XhsElement&&(s=`${s} in tag \`${i.name}\``)):d instanceof n.XhsText&&(s=`${s} at text block`),new t.ParserError((null==d?void 0:d.start)||(null==i?void 0:i.start)||0,s)}throw new Error(`${r} 未实现模式${o}`)};function c(e,t,r,i="expression"){var o;return(null===(o=n.matchMustache(t))||void 0===o?void 0:o.length)?d(t,e,i,r)||"":JSON.stringify(t)}class E{constructor(e){var t;this.filePath="",this.shortPath="",this.removeComentNode=!0,this.filePath=e.filePath,this.removeComentNode=null===(t=e.removeComentNode)||void 0===t||t,this.ast=e.ast}handleAttr(e){const t=[];return Object.values(e.attrsMap).forEach((r=>{const{name:i,value:o}=r;n.XhsOperations.includes(i)||("boolean"!=typeof o?t.push(`${JSON.stringify(i)}: ${c(e,o,r)}`):t.push(`${JSON.stringify(i)}: ${o}`))})),`{ ${t.filter(Boolean).join(",")} }`}renderFor(t){const{forBody:r,forItem:i,forIndex:o,forKey:l,forBodyAttr:a,forKeyAttr:d}=n.getLoop(t),E=c(t,r,a),p=i||"item",h=o||"index";if(n.isDefined(l)){let e="";e=l===p?p:l===h?h:(null==l?void 0:l.startsWith(`${p}.`))?l:["*this","*item",void 0].includes(l)?p:n.matchMustache(l)?l||'""':`${p}["${l}"]`,d&&(d.value=e)}return t.loopContext=[...t.loopContext,p,h],n.broadcastContext({nodes:t.children,loopContext:[p,h]}),s.addHelper(e.HELPERS.RENDER_LIST),`${e.HELPERS.RENDER_LIST}(\n ${E},\n (${p}, ${h}) => ${t.operation["xhs:if"]?this.renderIf(t):this.renderElement(t)}\n)`}renderIf(e){var t,r,i;const o=[e],s=null===(r=null===(t=e.parent)||void 0===t?void 0:t.children)||void 0===r?void 0:r.findIndex((t=>t===e));if(void 0!==s){const t=null===(i=e.parent)||void 0===i?void 0:i.children;if(t)for(let e=s+1;e<t.length;e++){const r=t[e];if(r.operation["xhs:elif"])o.push(r);else if(!r.is(n.ElementType.COMMENT)){if(r.operation["xhs:else"]){o.push(r);break}break}}}const l=!o.find((e=>e.operation["xhs:else"]));let a="";return o.forEach((t=>{const{ifState:r,elifState:i,elseState:o}=n.getCondition(t);if(n.isDefined(r)||n.isDefined(i)){const n=c(e,`${r||i}`,e.operation["xhs:if"]||e.operation["xhs:elif"]);a+=`${n} ? ${this.renderElement(t)} :`}else o&&(a+=this.renderElement(t))})),l&&(a+="null"),a}renderElement(t){const r=t.children.map((e=>this.renderNode(e))).filter(Boolean).join(",");let i=n.tagTransformMap[t.name]?`xhs-${t.name}`:t.name;return s.addHelper(e.HELPERS.RENDER_ELEMENT),`${e.HELPERS.RENDER_ELEMENT}('${i}', ${this.handleAttr(t)}, [${r}])`}renderNode(t){if(t.is(n.ElementType.COMMENT)&&!this.removeComentNode)return s.addHelper(e.HELPERS.RENDER_COMMENT),`${e.HELPERS.RENDER_COMMENT}(${JSON.stringify(t.content)})`;if(t.is(n.ElementType.Element)){if(i.isEmpty(t.operation))return this.renderElement(t);if(t.operation["xhs:for"])return this.renderFor(t);if(t.operation["xhs:if"])return this.renderIf(t)}else if(t.is(n.ElementType.TEXT)){const r=c(t,t.content,t,"text");return s.addHelper(e.HELPERS.RENDER_TEXT),`${e.HELPERS.RENDER_TEXT}(${r})`}return""}renderSketch(){s.startHoisting();const t=this.ast.children.map((e=>this.renderNode(e))).filter(Boolean);return`function(${e.SKETCH_CTX}){\n ${s.popHoisting()}\n return ([${t.join(",")}]).filter(Boolean)\n }`}}module.exports=function(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=this.async();try{const{resourcePath:l,_compiler:a,resourceQuery:d}=this,{miniprogramDir:c,appJSON:p={}}=(null==a?void 0:a.project)||{},h=r.getShortPath(c,l);t.initErrorContext(i,l),s.clear();const u=n.parseML(i,l);new o(i,l).validate(u);const m=new E({ast:u,filePath:l,shortPath:h});e(null,`export default ${m.renderSketch()}`)}catch(t){e(t)}}))};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xhs-mp-sketch-loader",
3
- "version": "2.0.4-beta.3",
3
+ "version": "2.0.4",
4
4
  "description": "sketch loader",
5
5
  "category": "esm",
6
6
  "main": "./dist/index.js",
@@ -27,10 +27,10 @@
27
27
  "peerDependencies": {
28
28
  "@swc/core": "^1.3.83",
29
29
  "webpack": "^5.88.2",
30
- "xhs-mp-pack": "2.0.4-beta.3",
31
- "xhs-mp-compiler-utils": "2.0.4-beta.3",
32
- "xhs-mp-shared": "2.0.4-beta.3",
33
- "xhs-mp-ml-parser": "2.0.4-beta.3",
30
+ "xhs-mp-pack": "2.0.4",
31
+ "xhs-mp-compiler-utils": "2.0.4",
32
+ "xhs-mp-shared": "2.0.4",
33
+ "xhs-mp-ml-parser": "2.0.4",
34
34
  "postcss": "^8.2.15",
35
35
  "postcss-import": "^14.1.0",
36
36
  "postcss-prefix-selector": "^1.16.1",
@@ -56,10 +56,10 @@
56
56
  "tslib": "^2.6.2",
57
57
  "typescript": "^5.4.3",
58
58
  "webpack": "^5.88.2",
59
- "xhs-mp-pack": "2.0.4-beta.3",
60
- "xhs-mp-compiler-utils": "2.0.4-beta.3",
61
- "xhs-mp-shared": "2.0.4-beta.3",
62
- "xhs-mp-ml-parser": "2.0.4-beta.3",
59
+ "xhs-mp-pack": "2.0.4",
60
+ "xhs-mp-compiler-utils": "2.0.4",
61
+ "xhs-mp-shared": "2.0.4",
62
+ "xhs-mp-ml-parser": "2.0.4",
63
63
  "postcss": "^8.2.15",
64
64
  "postcss-import": "^14.1.0",
65
65
  "postcss-prefix-selector": "^1.16.1",