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

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.
@@ -8,8 +8,8 @@ export declare class Hoisting {
8
8
  static addExpr(exp: Expr): string;
9
9
  static renderExpr(): string;
10
10
  static addHelper(key: HELPERS): void;
11
- static renderListHelper(): string;
12
- static renderElementHelper(): "" | "const _renderElement$_ = (tagName, attributes, childNodes) => ({ type: 2, tagName, attributes, childNodes })";
11
+ static renderListHelper(): "" | "const _renderList$_ = (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 }";
12
+ static renderElementHelper(): "" | "const _renderElement$_ = (tagName, attributes, childNodes = []) => ({ type: 2, tagName, attributes, childNodes: childNodes.filter(Boolean) })";
13
13
  static renderTextHelper(): "" | "const _renderText$_ = (textContent) => ({ type: 3 , textContent })";
14
14
  static renderCommentHelper(): "" | "const _renderComment$_ = (textContent) => ({ type: 5 , textContent })";
15
15
  static startHoisting(): void;
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"),o=require("lodash");class s{constructor(e,t){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){if(this.validateBase(e),n.isLoopNode(e))throw new t.ParserError(e.start,"骨架文件:暂不支持 循环控制 语法");if(n.isConditionNode(e))throw new t.ParserError(e.start,"骨架文件:暂不支持 条件控制 语法");e.children.length&&e.children.forEach((e=>{this.validate(e)}))}}class i{static addExpr(t){const r=o.last(i._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=o.last(i._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}})),s=o.groupBy(n,"code"),l=Object.keys(s).map((e=>`${s[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=o.last(i._list);if(r)switch(t){case e.HELPERS.RENDER_LIST:r.renderList=!0;break;case e.HELPERS.RENDER_COMMENT:r.renderComment;break;case e.HELPERS.RENDER_ELEMENT:r.renderElement=!0;break;case e.HELPERS.RENDER_TEXT:r.renderText=!0}}static renderListHelper(){const e=o.last(i._list);return null==e||e.renderList,""}static renderElementHelper(){const t=o.last(i._list);return e.NodeType.Element,(null==t?void 0:t.renderElement)?`const ${e.HELPERS.RENDER_ELEMENT} = (tagName, attributes, childNodes) => ({ type: ${e.NodeType.Element}, tagName, attributes, childNodes })`:""}static renderTextHelper(){const t=o.last(i._list);return(null==t?void 0:t.renderText)?`const ${e.HELPERS.RENDER_TEXT} = (textContent) => ({ type: ${e.NodeType.Text} , textContent })`:""}static renderCommentHelper(){const t=o.last(i._list);return(null==t?void 0:t.renderComment)?`const ${e.HELPERS.RENDER_COMMENT} = (textContent) => ({ type: ${e.NodeType.Comment} , textContent })`:""}static startHoisting(){i._list.push({exprs:[],renderComment:!1,renderElement:!1,renderList:!1,renderText:!1})}static popHoisting(){const e=[i.renderExpr(),i.renderCommentHelper(),i.renderTextHelper(),i.renderElementHelper(),i.renderListHelper()].filter(Boolean).join("\n");return i._list.pop(),e}static clear(){i._list=[]}}i._list=[];const l=["null","undefined","false","true","NaN","Number","Boolean","String","JSON"],a=["window","self","globalThis","this"],d=(r,o,s,d)=>{try{if("expression"===s||"text"===s){return("expression"===s?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 o=!1;const s=new Set,d=n.parseExpression(t).map((t=>{var n,i;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)?(o=!0,"({})"):(null===(i=r.loopContext)||void 0===i?void 0:i.includes(d))?(o=!0,s.add(d),d):(o=!0,`${e.SKETCH_CTX}.${d}`)})).join("");return o?i.addExpr({value:d,loopContext:[...s].sort()}):d})(r,o)));return`(${r})`}return"expression"===s?JSON.stringify(t):(d=t).includes("&")?JSON.stringify(n.decodeHtmlEntity(d,!1)):JSON.stringify(d)})).join("+")}}catch(e){const s=d instanceof n.XhsAttr?d.name:"";let i=e.message+`: \`${r}\``;throw s?(i=`${i} at attribute \`${s}\``,o instanceof n.XhsElement&&(i=`${i} in tag \`${o.name}\``)):d instanceof n.XhsText&&(i=`${i} at text block`),new t.ParserError((null==d?void 0:d.start)||(null==o?void 0:o.start)||0,i)}throw new Error(`${r} 未实现模式${s}`)};function E(e,t,r,o="expression"){var s;return(null===(s=n.matchMustache(t))||void 0===s?void 0:s.length)?d(t,e,o,r)||"":JSON.stringify(t)}class c{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:n,value:o}=r;"boolean"!=typeof o?t.push(`${JSON.stringify(n)}: ${E(e,o,r)}`):t.push(`${JSON.stringify(n)}: ${o}`)})),`{ ${t.filter(Boolean).join(",")} }`}renderFor(t){const{forBody:r,forItem:o,forIndex:s,forKey:l,forBodyAttr:a,forKeyAttr:d}=n.getLoop(t),c=E(t,r,a),p=o||"item",h=s||"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]}),i.addHelper(e.HELPERS.RENDER_LIST),`${e.HELPERS.RENDER_LIST}(\n ${c},\n (${p}, ${h}) => ${t.operation["xhs:if"]?this.renderIf(t):this.renderElement(t)}\n)`}renderIf(e){var t,r,o;const s=[e],i=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!==i){const t=null===(o=e.parent)||void 0===o?void 0:o.children;if(t)for(let e=i+1;e<t.length;e++){const r=t[e];if(r.operation["xhs:elif"])s.push(r);else if(!r.is(n.ElementType.COMMENT)){if(r.operation["xhs:else"]){s.push(r);break}break}}}const l=!s.find((e=>e.operation["xhs:else"]));let a="";return s.forEach((t=>{const{ifState:r,elifState:o,elseState:s}=n.getCondition(t);if(n.isDefined(r)||n.isDefined(o)){const n=E(e,`${r||o}`,e.operation["xhs:if"]||e.operation["xhs:elif"]);a+=`${n} ? ${this.renderElement(t)} :`}else s&&(a+=this.renderElement(t))})),l&&(a+="null"),a}renderElement(t){const r=t.children.map((e=>this.renderNode(e))).filter(Boolean).join(",");let o=n.tagTransformMap[t.name]?`xhs-${t.name}`:t.name;return i.addHelper(e.HELPERS.RENDER_ELEMENT),`${e.HELPERS.RENDER_ELEMENT}('${o}', ${this.handleAttr(t)}, [${r}])`}renderNode(t){if(t.is(n.ElementType.COMMENT)&&!this.removeComentNode)return i.addHelper(e.HELPERS.RENDER_COMMENT),`${e.HELPERS.RENDER_COMMENT}(${JSON.stringify(t.content)})`;if(t.is(n.ElementType.Element)){if(o.isEmpty(t.operation))return this.renderElement(t)}else if(t.is(n.ElementType.TEXT)){const r=E(t,t.content,t,"text");return i.addHelper(e.HELPERS.RENDER_TEXT),`${e.HELPERS.RENDER_TEXT}(${r})`}return""}renderSketch(){i.startHoisting();const e=this.ast.children.map((e=>this.renderNode(e))).filter(Boolean);return`{\n ${i.popHoisting()}\n return ([${e.join(",")}])\n }`}}module.exports=function(o){return e.__awaiter(this,void 0,void 0,(function*(){const l=this.async();try{const{resourcePath:a,_compiler:d,resourceQuery:E}=this,{miniprogramDir:p,appJSON:h={}}=(null==d?void 0:d.project)||{},u=r.getShortPath(p,a);t.initErrorContext(o,a),i.clear();const m=n.parseML(o,a);new s(o,a).validate(m);const f=new c({ast:m,filePath:a,shortPath:u}).renderSketch();l(null,`export default (${e.SKETCH_CTX}) => ${f}`)}catch(e){l(e)}}))};
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,5 +1,6 @@
1
1
  import { XhsNode } from "xhs-mp-ml-parser";
2
- export declare class Validator {
2
+ import { BaseValidator } from "xhs-mp-ml-parser";
3
+ export declare class Validator extends BaseValidator {
3
4
  source: string;
4
5
  filePath: string;
5
6
  constructor(source: string, filePath: string);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xhs-mp-sketch-loader",
3
- "version": "2.0.4-beta.2",
3
+ "version": "2.0.4-beta.3",
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.2",
31
- "xhs-mp-compiler-utils": "2.0.4-beta.2",
32
- "xhs-mp-shared": "2.0.4-beta.2",
33
- "xhs-mp-ml-parser": "2.0.4-beta.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",
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.2",
60
- "xhs-mp-compiler-utils": "2.0.4-beta.2",
61
- "xhs-mp-shared": "2.0.4-beta.2",
62
- "xhs-mp-ml-parser": "2.0.4-beta.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",
63
63
  "postcss": "^8.2.15",
64
64
  "postcss-import": "^14.1.0",
65
65
  "postcss-prefix-selector": "^1.16.1",