youzanyun-devtool-worker
Version:
345 lines (344 loc) • 13.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const axios_1 = tslib_1.__importDefault(require("axios"));
const spring4js_nodejs_1 = require("spring4js-nodejs");
var deleteAndReplace = function (conf) {
var res = [];
for (var i = 0; i < conf.length; i++) {
var comp = conf[i];
if (!comp.isDelete) {
if (comp.replace && comp.replace.type) {
res.push({
type: comp.replace.type,
});
}
else {
if (comp.children) {
comp.children = deleteAndReplace(comp.children);
}
delete comp._isCustomComp;
res.push(comp);
}
}
}
return res;
};
let ActionH5PreviewEditorService = class ActionH5PreviewEditorService {
constructor() {
this.proxyConfig = null;
}
async start() {
const useProxy = this.configService.isUseProxy();
const host = this.configService.getProxyHost();
const port = this.configService.getProxyPort();
if (useProxy) {
this.proxyConfig = {
host,
port,
protocol: 'http:',
};
}
}
async processRequest(ctx, next) {
const { _yzy_preview_type_, pageName, nodeName, projectId, implId } = ctx.query;
const ignorePathArr = ['/ranta/configjs', '/wa/wecom-app/api'];
if (ctx.path === '/h5-extension-service/check-design') {
await this.h5ExtensionServicePageModify(ctx, next);
return true;
}
if (ignorePathArr.some((path) => ctx.path.includes(path))) {
return false;
}
if (_yzy_preview_type_ === 'h5-preview-editor' && pageName && nodeName) {
let setCookieObj = {
projectId,
nodeName,
implId,
};
Object.keys(setCookieObj).forEach((key) => {
ctx.cookies.set(key, setCookieObj[key], {
domain: '.youzan.com',
});
});
if (ctx.path === '/wscgoods/detail-api/init.jsonp') {
return false;
}
else if (ctx.path === '/wscgoods/detail-api/cloud.jsonp') {
await this.sandBoxPageModify(ctx, next);
}
else {
await this.pageModify(ctx, next);
}
return true;
}
else {
return false;
}
}
async getCachePreviewComps(params) {
try {
const { projectId, implId } = params;
const result = await this.h5ExtensionPreviewEditorService.getPreviewComps(projectId, implId);
return result || [];
}
catch (err) {
return [];
}
}
async getCachePreviewCompsV2(params) {
try {
const { projectId, implId } = params;
const result = await this.h5ExtensionPreviewEditorService.getPreviewComps(projectId, implId);
let design = result || [];
if (design && design.length) {
design = deleteAndReplace(design);
}
return design;
}
catch (err) {
return [];
}
}
async getLocalPageFile(params) {
try {
const result = await this.h5ExtensionService.getLocalPageFile(params);
return result || [];
}
catch (err) {
return [];
}
}
async h5ExtensionServicePageModify(ctx, next) {
const { callback, pageName } = ctx.query;
const implId = ctx.cookies.get('implId');
const projectId = ctx.cookies.get('projectId');
const nodeCode = ctx.cookies.get('nodeName');
const diyScript = await this.getLocalPageFile({
projectId,
nodeCode,
pageName,
});
const previewComps = await this.getCachePreviewComps({
projectId,
implId,
});
let design = [];
let extension = [];
if (previewComps && previewComps.length && previewComps[0].type === 'config') {
design = previewComps;
let isv = previewComps[0].script || { appName: 'local-test' };
let components = [];
let componentsMap = {};
let getComp = function (comps) {
comps.forEach(function (comp) {
var originName = comp.type;
var isReplace = false;
if (comp.replace && comp.replace.type) {
originName = comp.replace.type;
isReplace = true;
}
if (originName.match(/^cloud_/)) {
var targetName = isv.appName + '_' + originName;
if (!componentsMap[originName]) {
componentsMap[originName] = true;
components.push({
originName,
targetName,
});
}
if (isReplace) {
comp.replace.type = targetName;
}
else {
comp._isCustomComp = originName;
comp.type = targetName;
}
}
else {
if (comp.children) {
getComp(comp.children);
}
}
});
};
getComp(design);
extension.push({
name: isv.appName,
resouce: [diyScript],
components,
});
design = deleteAndReplace(design);
}
ctx.res.setHeader('Content-Type', 'text/javascript; charset=UTF-8');
ctx.body = `window['${callback}']({ type: 'replaceDesign',design: ${JSON.stringify(design)}, extension:${JSON.stringify(extension)}, useSandbox:true });`;
return;
}
async sandBoxPageModify(ctx, next) {
const { pageName, nodeName, projectId, workbenchId, refUrl, implId } = ctx.query;
let requestHeader = JSON.parse(JSON.stringify(ctx.headers));
requestHeader['accept-encoding'] = 'gzip, deflate';
const axiosConfig = {
method: ctx.method,
url: ctx.href,
headers: requestHeader,
data: ctx.isJsonHeader ? ctx.request.body : ctx.req,
responseType: 'text',
validateStatus: function (status) {
return true;
},
maxRedirects: 0,
};
if (this.proxyConfig) {
axiosConfig.proxy = this.proxyConfig;
}
let axiosRes = await axios_1.default.request(axiosConfig);
const diyScript = await this.getLocalPageFile({
projectId,
nodeCode: nodeName,
pageName,
});
const previewComps = await this.getCachePreviewCompsV2({
projectId,
implId,
});
let design = [];
if (previewComps && previewComps.length && previewComps[0].type === 'config') {
design = previewComps.slice(1);
}
const result = {
code: 0,
data: {
diyScript,
design,
diyConfig: { type: 'youzanyun', version: '2.0' },
},
msg: 'ok',
};
const resData = `/**/ typeof initGlobal === 'function' && initGlobal(${JSON.stringify(result)})`;
let header = JSON.parse(JSON.stringify(axiosRes.headers));
delete header['content-length'];
ctx.body = resData;
return;
}
async pageModify(ctx, next) {
const { pageName, nodeName, proPath, projectId, workbenchId, implId } = ctx.query;
let requestHeader = JSON.parse(JSON.stringify(ctx.headers));
requestHeader['accept-encoding'] = 'gzip, deflate';
const axiosConfig = {
method: ctx.method,
url: ctx.href,
headers: requestHeader,
data: ctx.isJsonHeader ? ctx.request.body : ctx.req,
responseType: 'text',
validateStatus: function (status) {
return true;
},
maxRedirects: 0,
};
if (this.proxyConfig) {
axiosConfig.proxy = this.proxyConfig;
}
let axiosRes = await axios_1.default.request(axiosConfig);
if (axiosRes.status < 200 || axiosRes.status >= 300 || pageName === 'goods-detail__v2') {
ctx.status = axiosRes.status;
let header = axiosRes.headers;
if (axiosRes.status === 302 && header.location) {
const currentQuery = `?_yzy_preview_type_=h5-preview-editor&pageName=${pageName}&nodeName=${nodeName}&implId=${implId}` +
`&projectId=${projectId}&workbenchId=${workbenchId}&`;
const reLocation = header.location;
const temp = reLocation.split('?');
const newLocation = temp[0] + currentQuery + temp.slice(1).join('?');
header.location = newLocation;
}
delete header['content-length'];
ctx.set(header);
ctx.body = axiosRes.data;
return;
}
const previewComps = await this.getCachePreviewCompsV2({
projectId,
implId,
});
const diyScript = await this.getLocalPageFile({
projectId,
nodeCode: nodeName,
pageName,
});
let design = `
if (!window._global) {
window._global = {design: []};
}
window._global.design = ${JSON.stringify(previewComps)};
`;
let mallCloudJsRepalce = `
<script src="${diyScript}"></script>
`;
let designUpdate = `
<script id="customScript">
${design}
</script>
`;
const content = axiosRes.data;
let finalContent = axiosRes.data;
const rantaTeeStartFlag = '<!-- ranta tee start-->';
const rantaTeeEndFlag = '<!-- ranta tee end -->';
if (content.indexOf(rantaTeeEndFlag) > -1) {
const rantaTeeStartIndex = content.indexOf(rantaTeeStartFlag);
finalContent =
content.substring(0, rantaTeeStartIndex) +
designUpdate +
content.substring(rantaTeeStartIndex);
const rantaTeeEndIndex = finalContent.indexOf(rantaTeeEndFlag);
finalContent =
finalContent.substring(0, rantaTeeEndIndex) +
mallCloudJsRepalce +
finalContent.substring(rantaTeeEndIndex);
}
else {
let newContentWithMallCloud = axiosRes.data;
if (mallCloudJsRepalce) {
const mallCloudJsReg = /<script src="https:\/\/file.yzcdn.cn\/mall-cloud\/\S*?"><\/script>/g;
let mallCloudJsIndex = -1;
let mallCloudJsMatches;
let matchMallCloudJsStr = '';
while ((mallCloudJsMatches = mallCloudJsReg.exec(content)) !== null) {
mallCloudJsIndex = mallCloudJsMatches.index;
matchMallCloudJsStr = mallCloudJsMatches[0];
}
const matchStrLength = matchMallCloudJsStr.length;
newContentWithMallCloud =
content.substring(0, mallCloudJsIndex) +
mallCloudJsRepalce +
content.substring(mallCloudJsIndex + matchStrLength);
}
const wscJsReg = /<script src="\S*?" charset="utf-8" onerror="_cdnFallback\(this\)[\s\S]*?><\/script>/g;
let wscJsIndex = -1;
let wscMatches;
while ((wscMatches = wscJsReg.exec(newContentWithMallCloud)) !== null) {
wscJsIndex = wscMatches.index;
}
finalContent =
newContentWithMallCloud.substring(0, wscJsIndex) +
designUpdate +
newContentWithMallCloud.substring(wscJsIndex);
}
let header = JSON.parse(JSON.stringify(axiosRes.headers));
delete header['content-length'];
ctx.set(header);
ctx.body = finalContent;
}
};
tslib_1.__decorate([
(0, spring4js_nodejs_1.Resource)()
], ActionH5PreviewEditorService.prototype, "configService", void 0);
tslib_1.__decorate([
(0, spring4js_nodejs_1.Resource)()
], ActionH5PreviewEditorService.prototype, "h5ExtensionService", void 0);
tslib_1.__decorate([
(0, spring4js_nodejs_1.Resource)()
], ActionH5PreviewEditorService.prototype, "h5ExtensionPreviewEditorService", void 0);
ActionH5PreviewEditorService = tslib_1.__decorate([
(0, spring4js_nodejs_1.Service)()
], ActionH5PreviewEditorService);
exports.default = ActionH5PreviewEditorService;