@we-debug/gulp-tool 0.31.0 → 0.31.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,14 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [0.31.3](https://github.com/dlhandsome/we-debug/compare/v0.31.2...v0.31.3) (2024-01-16)
7
+
8
+ **Note:** Version bump only for package @we-debug/gulp-tool
9
+
10
+
11
+
12
+
13
+
6
14
  # [0.31.0](https://github.com/dlhandsome/we-debug/compare/v0.30.1...v0.31.0) (2024-01-03)
7
15
 
8
16
  **Note:** Version bump only for package @we-debug/gulp-tool
@@ -0,0 +1,2 @@
1
+ export declare function belongsPage(fullPath: string, pages?: string[]): boolean;
2
+ export declare function belongsApp(fullPath: string, projectDir: string): boolean;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.belongsApp = exports.belongsPage = void 0;
7
+ var path_1 = __importDefault(require("path"));
8
+ function belongsPage(fullPath, pages) {
9
+ if (pages === void 0) { pages = []; }
10
+ var file = path_1.default.parse(fullPath);
11
+ return pages.indexOf(path_1.default.join(file.dir, file.name)) > -1;
12
+ }
13
+ exports.belongsPage = belongsPage;
14
+ ;
15
+ function belongsApp(fullPath, projectDir) {
16
+ var file = path_1.default.parse(fullPath);
17
+ var app = path_1.default.format({ dir: projectDir, name: 'app' });
18
+ return app === path_1.default.join(file.dir, file.name);
19
+ }
20
+ exports.belongsApp = belongsApp;
21
+ ;
@@ -0,0 +1 @@
1
+ export declare const PLUGIN_NAME = "@we-debug/gulp-tool";
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PLUGIN_NAME = void 0;
4
+ exports.PLUGIN_NAME = '@we-debug/gulp-tool';
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ var path_1 = __importDefault(require("path"));
18
+ var lead_1 = __importDefault(require("lead"));
19
+ var pumpify_1 = __importDefault(require("pumpify"));
20
+ var through2_1 = __importDefault(require("through2"));
21
+ var plugin_error_1 = __importDefault(require("plugin-error"));
22
+ var lookup_1 = require("./lookup");
23
+ var belongs_1 = require("./belongs");
24
+ var path_2 = require("./path");
25
+ var plugin_1 = __importDefault(require("./plugin"));
26
+ var constants_1 = require("./constants");
27
+ var pages = [];
28
+ var hasInit = false;
29
+ function mpGlobalComp(options) {
30
+ if (options === void 0) { options = {}; }
31
+ var baseDir = options.baseDir || 'src';
32
+ var wxmlRaw = options.wxml || '<we-debug />';
33
+ var filter = options.filter || '';
34
+ var compName = options.compName || 'we-debug';
35
+ var compPath = options.compPath || '@we-debug/miniprogram/index/index';
36
+ var entryFile = options.entryFile || 'we-debug/index.js';
37
+ var plugins = options.plugins || [];
38
+ baseDir = (0, path_2.getAbsolutePath)(baseDir);
39
+ var isModule = compPath.indexOf('@we-debug/core') === 0;
40
+ if (!isModule && path_1.default.isAbsolute(compPath)) {
41
+ compPath = path_1.default.relative(baseDir, compPath);
42
+ }
43
+ if (path_1.default.isAbsolute(entryFile)) {
44
+ entryFile = path_1.default.relative(baseDir, entryFile);
45
+ }
46
+ function init() {
47
+ return through2_1.default.obj(function (file, encoding, callback) {
48
+ if (!hasInit) {
49
+ plugin_1.default.execLifecycle('beforeInit', file);
50
+ try {
51
+ pages = (0, lookup_1.lookupPages)(baseDir);
52
+ plugin_1.default.initPlugin(plugins, __assign(__assign({}, options), { pages: pages }));
53
+ }
54
+ catch (e) {
55
+ throw new plugin_error_1.default(constants_1.PLUGIN_NAME, 'look up pages failed, please check your configure');
56
+ }
57
+ hasInit = true;
58
+ plugin_1.default.execLifecycle('onInit', file);
59
+ }
60
+ callback(null, file);
61
+ });
62
+ }
63
+ function parseWxml() {
64
+ return through2_1.default.obj(function (file, encoding, callback) {
65
+ if (file.isNull())
66
+ return callback(null, file);
67
+ if (file.extname !== '.wxml')
68
+ return callback(null, file);
69
+ plugin_1.default.execLifecycle('wxml', file);
70
+ if (filter) {
71
+ var pathStr_1 = file.path.split(path_1.default.sep).join('/');
72
+ if (Array.isArray(filter)) {
73
+ var result = filter.some(function (item) {
74
+ return isDoFilter(item, pathStr_1);
75
+ });
76
+ if (result)
77
+ return callback(null, file);
78
+ }
79
+ else {
80
+ if (isDoFilter(filter, pathStr_1))
81
+ return callback(null, file);
82
+ }
83
+ }
84
+ if ((0, belongs_1.belongsPage)(file.path, pages)) {
85
+ plugin_1.default.execLifecycle('beforeInsertWxml', file);
86
+ var code = file.contents.toString();
87
+ code += wxmlRaw;
88
+ file.contents = Buffer.from(code);
89
+ plugin_1.default.execLifecycle('afterInsertWxml', file);
90
+ }
91
+ callback(null, file);
92
+ });
93
+ }
94
+ function isDoFilter(filter, path) {
95
+ return ((typeof filter === 'function' && !filter(path)) ||
96
+ (typeof filter === 'string' && path.indexOf(filter) >= 0) ||
97
+ (filter instanceof RegExp && filter.test(path)));
98
+ }
99
+ function parseJson() {
100
+ return through2_1.default.obj(function (file, encoding, callback) {
101
+ if (file.isNull())
102
+ return callback(null, file);
103
+ if (file.extname !== '.json')
104
+ return callback(null, file);
105
+ plugin_1.default.execLifecycle('json', file);
106
+ if ((0, belongs_1.belongsApp)(file.path, baseDir)) {
107
+ var code = file.contents.toString();
108
+ try {
109
+ var json = JSON.parse(code);
110
+ if (!json.usingComponents) {
111
+ json.usingComponents = {};
112
+ }
113
+ json.usingComponents[compName] = compPath;
114
+ code = JSON.stringify(json, null, 2);
115
+ }
116
+ catch (e) {
117
+ throw new plugin_error_1.default(constants_1.PLUGIN_NAME, e);
118
+ }
119
+ file.contents = Buffer.from(code);
120
+ }
121
+ callback(null, file);
122
+ });
123
+ }
124
+ function parseScript() {
125
+ return through2_1.default.obj(function (file, encoding, callback) {
126
+ if (file.isNull())
127
+ return callback(null, file);
128
+ if (file.extname !== '.js')
129
+ return callback(null, file);
130
+ plugin_1.default.execLifecycle('script', file);
131
+ if ((0, belongs_1.belongsApp)(file.path, baseDir) || file.relative === 'app.js') {
132
+ plugin_1.default.execLifecycle('beforeInsertScript', file);
133
+ var code = file.contents.toString();
134
+ code = "require('".concat(entryFile, "')\n") + code;
135
+ file.contents = Buffer.from(code);
136
+ plugin_1.default.execLifecycle('afterInsertScript', file);
137
+ }
138
+ callback(null, file);
139
+ });
140
+ }
141
+ var pipeline = [init(), parseWxml(), parseJson(), parseScript()];
142
+ return (0, lead_1.default)(new pumpify_1.default.obj(pipeline));
143
+ }
144
+ module.exports = mpGlobalComp;
@@ -0,0 +1 @@
1
+ export declare function lookupPages(projectDir: string): string[];
package/dist/lookup.js ADDED
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.lookupPages = void 0;
7
+ var path_1 = __importDefault(require("path"));
8
+ var path_2 = require("./path");
9
+ function lookupPages(projectDir) {
10
+ var pages = [];
11
+ var subpackages = [];
12
+ projectDir = (0, path_2.getAbsolutePath)(projectDir);
13
+ var appPath = path_1.default.format({
14
+ dir: projectDir,
15
+ name: 'app',
16
+ ext: '.json'
17
+ });
18
+ try {
19
+ var appJson = require(appPath);
20
+ pages = appJson.pages;
21
+ subpackages = appJson.subpackages || [];
22
+ pages = pages.map(function (p) {
23
+ return path_1.default.resolve(projectDir, p);
24
+ });
25
+ subpackages.forEach(function (sub) {
26
+ sub.pages.forEach(function (p) {
27
+ var relativePath = path_1.default.join(sub.root, p);
28
+ pages.push(path_1.default.resolve(projectDir, relativePath));
29
+ });
30
+ });
31
+ }
32
+ catch (err) {
33
+ throw new Error(err);
34
+ }
35
+ return pages;
36
+ }
37
+ exports.lookupPages = lookupPages;
38
+ ;
package/dist/path.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare const getAbsolutePath: (p: string, src?: string) => string;
package/dist/path.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getAbsolutePath = void 0;
7
+ var path_1 = __importDefault(require("path"));
8
+ var getAbsolutePath = function (p, src) { return (path_1.default.isAbsolute(p) ? p : path_1.default.resolve(src || process.cwd(), p)); };
9
+ exports.getAbsolutePath = getAbsolutePath;
@@ -0,0 +1,13 @@
1
+ /// <reference types="node" />
2
+ import { IRegistration, IPackageOption, IAnyObject, IPlugin, PackageParam } from './types';
3
+ declare class Plugin implements IPlugin {
4
+ lifecycles: IRegistration[];
5
+ meta: IAnyObject;
6
+ getLifecycles(): IRegistration[];
7
+ register(options: IRegistration): void;
8
+ execLifecycle(lifetime: keyof IRegistration, file: File): void;
9
+ loadPlugin(pkg: PackageParam): any;
10
+ initPlugin(packges: IPackageOption[], meta: IAnyObject): void;
11
+ }
12
+ declare const _default: Plugin;
13
+ export default _default;
package/dist/plugin.js ADDED
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ var plugin_error_1 = __importDefault(require("plugin-error"));
7
+ var PLUGIN_NAME = '@we-debug/gulp-tool';
8
+ var Plugin = (function () {
9
+ function Plugin() {
10
+ this.lifecycles = [];
11
+ this.meta = {};
12
+ }
13
+ Plugin.prototype.getLifecycles = function () {
14
+ return this.lifecycles;
15
+ };
16
+ Plugin.prototype.register = function (options) {
17
+ this.lifecycles.push(options);
18
+ };
19
+ Plugin.prototype.execLifecycle = function (lifetime, file) {
20
+ var _this = this;
21
+ this.lifecycles.forEach(function (i) {
22
+ var lifecycle = i[lifetime];
23
+ if (typeof lifecycle === 'function') {
24
+ lifecycle.call(_this, file);
25
+ }
26
+ });
27
+ };
28
+ Plugin.prototype.loadPlugin = function (pkg) {
29
+ if (typeof pkg === 'string') {
30
+ return require(pkg);
31
+ }
32
+ if (typeof pkg === 'function') {
33
+ return pkg;
34
+ }
35
+ };
36
+ Plugin.prototype.initPlugin = function (packges, meta) {
37
+ var _this = this;
38
+ this.meta = meta;
39
+ packges.map(function (p) {
40
+ try {
41
+ var fn = _this.loadPlugin(p.package);
42
+ fn.call(_this, _this, p.options);
43
+ }
44
+ catch (e) {
45
+ throw new plugin_error_1.default(PLUGIN_NAME, "load package ".concat(p.package, " error: ', ").concat(e));
46
+ }
47
+ });
48
+ };
49
+ return Plugin;
50
+ }());
51
+ exports.default = new Plugin();
@@ -0,0 +1,53 @@
1
+ /// <reference types="node" />
2
+ export interface IAnyObject {
3
+ [key: string]: any;
4
+ }
5
+ export declare namespace WechatMiniprogram {
6
+ type AppJsonSubpage = {
7
+ root: string;
8
+ pages: string[];
9
+ };
10
+ type AppJsonSubpages = AppJsonSubpage[];
11
+ interface IAppJson {
12
+ pages: string[];
13
+ subpackages?: AppJsonSubpages;
14
+ }
15
+ }
16
+ export type ProcessDefine = (file: File, encoding?: string) => File | void;
17
+ export interface IRegistration {
18
+ pluginName: string;
19
+ beforeInit?: ProcessDefine;
20
+ onInit?: ProcessDefine;
21
+ wxml?: ProcessDefine;
22
+ beforeInsertWxml?: ProcessDefine;
23
+ afterInsertWxml?: ProcessDefine;
24
+ json?: ProcessDefine;
25
+ script?: ProcessDefine;
26
+ beforeInsertScript?: ProcessDefine;
27
+ afterInsertScript?: ProcessDefine;
28
+ }
29
+ export type FilterOption = string | Function | RegExp;
30
+ export interface IPlugin {
31
+ lifecycles: IRegistration[];
32
+ meta: IAnyObject;
33
+ register(options: IRegistration): void;
34
+ getLifecycles(): IRegistration[];
35
+ execLifecycle(lifetime: keyof IRegistration, file: File): void;
36
+ loadPlugin(pkg: string | PackageFunc): void;
37
+ initPlugin(packges: IPackageOption[], meta: IAnyObject): void;
38
+ }
39
+ export type PackageFunc = (register: IPlugin, options: IAnyObject) => void;
40
+ export type PackageParam = string | PackageFunc;
41
+ export interface IPackageOption {
42
+ package: PackageParam;
43
+ options: IAnyObject;
44
+ }
45
+ export interface ICompilerOption {
46
+ baseDir?: string;
47
+ wxml?: string;
48
+ filter?: FilterOption;
49
+ compName?: string;
50
+ compPath?: string;
51
+ entryFile?: string;
52
+ plugins?: IPackageOption[];
53
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@we-debug/gulp-tool",
3
- "version": "0.31.0",
3
+ "version": "0.31.3",
4
4
  "description": "we-debug, gulp",
5
- "main": "index.js",
5
+ "main": "dist/index.js",
6
+ "types": "dist/types.d.ts",
6
7
  "directories": {
7
8
  "lib": "lib"
8
9
  },
@@ -18,6 +19,8 @@
18
19
  },
19
20
  "license": "MIT",
20
21
  "dependencies": {
22
+ "@types/pumpify": "^1.4.4",
23
+ "@types/through2": "^2.0.41",
21
24
  "crypto": "^1.0.1",
22
25
  "gogocode": "^1.0.55",
23
26
  "lead": "^1.0.0",
@@ -28,5 +31,5 @@
28
31
  "readme": "ERROR: No README data found!",
29
32
  "_id": "@we-debug/gulp-tool@0.1.3",
30
33
  "_commitid": "f35f53c",
31
- "gitHead": "346011b3a2557c10cd62ead041ba8482e81aa8e1"
34
+ "gitHead": "b6e97372d68b7e69e16d5750b6fcba79af802c60"
32
35
  }
@@ -1,11 +1,11 @@
1
- const path = require('path');
1
+ import path from 'path';
2
2
 
3
- exports.belongsPage = function (fullPath, pages = []) {
3
+ export function belongsPage (fullPath: string, pages: string[] = []) {
4
4
  const file = path.parse(fullPath);
5
5
  return pages.indexOf(path.join(file.dir, file.name)) > -1;
6
6
  };
7
7
 
8
- exports.belongsApp = function (fullPath, projectDir) {
8
+ export function belongsApp (fullPath: string, projectDir: string) {
9
9
  const file = path.parse(fullPath);
10
10
  const app = path.format({ dir: projectDir, name: 'app' });
11
11
  return app === path.join(file.dir, file.name);
@@ -0,0 +1 @@
1
+ export const PLUGIN_NAME = '@we-debug/gulp-tool';
@@ -1,24 +1,37 @@
1
- const path = require('path');
2
- const lead = require('lead');
3
- const pumpify = require('pumpify');
4
- const through = require('through2');
5
- const PluginError = require('plugin-error');
6
- const { lookupPages } = require('./lib/lookup');
7
- const { belongsPage, belongsApp } = require('./lib/belongs');
8
- const { getAbsolutePath } = require('./lib/path');
9
- const injectComponentId = require('./lib/inject-component-id');
10
- const plugin = require('./lib/plugin');
11
- const { PLUGIN_NAME } = require('./lib/constants');
12
-
13
- let pages = [];
14
-
15
- function mpGlobalComp(options = {}) {
1
+ import path from 'path';
2
+ import lead from 'lead';
3
+ import pumpify from 'pumpify';
4
+ import through from 'through2';
5
+ import PluginError from 'plugin-error';
6
+ import {
7
+ lookupPages
8
+ } from './lookup';
9
+ import {
10
+ belongsPage,
11
+ belongsApp
12
+ } from './belongs';
13
+ import {
14
+ getAbsolutePath
15
+ } from './path';
16
+ import plugin from './plugin';
17
+ import {
18
+ PLUGIN_NAME
19
+ } from './constants';
20
+ import {
21
+ FilterOption,
22
+ ICompilerOption
23
+ } from './types';
24
+
25
+ let pages: string[] = [];
26
+ let hasInit = false;
27
+
28
+ function mpGlobalComp(options: ICompilerOption = {}) {
16
29
  //
17
30
  let baseDir = options.baseDir || 'src';
18
31
  const wxmlRaw = options.wxml || '<we-debug />';
19
32
  const filter = options.filter || '';
20
33
  let compName = options.compName || 'we-debug';
21
- let compPath = options.compPath || '@we-debug/core/component/index/index';
34
+ let compPath = options.compPath || '@we-debug/miniprogram/index/index';
22
35
  let entryFile = options.entryFile || 'we-debug/index.js';
23
36
  const plugins = options.plugins || [];
24
37
 
@@ -35,11 +48,11 @@ function mpGlobalComp(options = {}) {
35
48
 
36
49
  /**
37
50
  * 初始化设置
38
- *
39
51
  */
40
52
  function init() {
53
+ // @ts-ignore
41
54
  return through.obj((file, encoding, callback) => {
42
- if (!mpGlobalComp.init) {
55
+ if (!hasInit) {
43
56
  // 执行 beforeInit 插件钩子
44
57
  plugin.execLifecycle('beforeInit', file);
45
58
 
@@ -49,7 +62,7 @@ function mpGlobalComp(options = {}) {
49
62
  } catch (e) {
50
63
  throw new PluginError(PLUGIN_NAME, 'look up pages failed, please check your configure');
51
64
  }
52
- mpGlobalComp.init = true;
65
+ hasInit = true;
53
66
  // 执行 onInit 插件钩子
54
67
  plugin.execLifecycle('onInit', file);
55
68
  }
@@ -57,7 +70,11 @@ function mpGlobalComp(options = {}) {
57
70
  });
58
71
  }
59
72
 
73
+ /**
74
+ * 解析 wxml
75
+ */
60
76
  function parseWxml() {
77
+ // @ts-ignore
61
78
  return through.obj((file, encoding, callback) => {
62
79
  if (file.isNull()) return callback(null, file);
63
80
 
@@ -100,7 +117,7 @@ function mpGlobalComp(options = {}) {
100
117
  * 是否需要过滤
101
118
  * @returns [Boolean] true-需要过滤;false-不需要过滤
102
119
  */
103
- function isDoFilter(filter, path) {
120
+ function isDoFilter(filter: FilterOption, path: string) {
104
121
  return (
105
122
  (typeof filter === 'function' && !filter(path)) ||
106
123
  (typeof filter === 'string' && path.indexOf(filter) >= 0) ||
@@ -110,9 +127,9 @@ function mpGlobalComp(options = {}) {
110
127
 
111
128
  /**
112
129
  * 处理 json
113
- *
114
130
  */
115
131
  function parseJson() {
132
+ // @ts-ignore
116
133
  return through.obj((file, encoding, callback) => {
117
134
  if (file.isNull()) return callback(null, file);
118
135
 
@@ -147,10 +164,9 @@ function mpGlobalComp(options = {}) {
147
164
 
148
165
  /**
149
166
  * 处理 js
150
- *
151
- * @returns
152
167
  */
153
168
  function parseScript() {
169
+ // @ts-ignore
154
170
  return through.obj((file, encoding, callback) => {
155
171
  if (file.isNull()) return callback(null, file);
156
172
 
@@ -177,9 +193,7 @@ function mpGlobalComp(options = {}) {
177
193
 
178
194
  const pipeline = [init(), parseWxml(), parseJson(), parseScript()];
179
195
 
180
- return lead(pumpify.obj(pipeline));
196
+ return lead(new pumpify.obj(pipeline));
181
197
  }
182
198
 
183
- mpGlobalComp.injectComponentId = injectComponentId;
184
-
185
199
  module.exports = mpGlobalComp;
@@ -1,15 +1,24 @@
1
- const path = require('path');
2
- const { getAbsolutePath } = require('./path');
3
-
4
- exports.lookupPages = function (projectDir) {
5
- let pages = [];
6
- let subpackages = [];
1
+ import path from 'path';
2
+ import {
3
+ getAbsolutePath
4
+ } from './path';
5
+ import {
6
+ WechatMiniprogram,
7
+ } from './types';
8
+
9
+ export function lookupPages (projectDir: string) {
10
+ let pages: string[] = [];
11
+ let subpackages: WechatMiniprogram.AppJsonSubpages = [];
7
12
 
8
13
  projectDir = getAbsolutePath(projectDir);
9
- const appPath = path.format({ dir: projectDir, name: 'app', ext: '.json' });
14
+ const appPath = path.format({
15
+ dir: projectDir,
16
+ name: 'app',
17
+ ext: '.json'
18
+ });
10
19
 
11
20
  try {
12
- const appJson = require(appPath);
21
+ const appJson: WechatMiniprogram.IAppJson = require(appPath);
13
22
 
14
23
  pages = appJson.pages;
15
24
  subpackages = appJson.subpackages || [];
package/src/path.ts ADDED
@@ -0,0 +1,4 @@
1
+ import path from 'path';
2
+
3
+ /** 获取绝对路径 */
4
+ export const getAbsolutePath = (p: string, src?: string): string => (path.isAbsolute(p) ? p : path.resolve(src || process.cwd(), p));
package/src/plugin.ts ADDED
@@ -0,0 +1,60 @@
1
+ import PluginError from 'plugin-error';
2
+ import {
3
+ IRegistration,
4
+ IPackageOption,
5
+ IAnyObject,
6
+ IPlugin,
7
+ PackageParam
8
+ } from './types';
9
+
10
+ const PLUGIN_NAME = '@we-debug/gulp-tool';
11
+
12
+ class Plugin implements IPlugin {
13
+ /** 子插件生命周期 */
14
+ lifecycles: IRegistration[] = [];
15
+ /** 插件元信息 */
16
+ meta: IAnyObject = {};
17
+
18
+ getLifecycles() {
19
+ return this.lifecycles;
20
+ }
21
+
22
+ register(options: IRegistration) {
23
+ this.lifecycles.push(options);
24
+ }
25
+
26
+ execLifecycle(lifetime: keyof IRegistration, file: File) {
27
+ this.lifecycles.forEach(i => {
28
+ const lifecycle = i[lifetime];
29
+ if (typeof lifecycle === 'function') {
30
+ lifecycle.call(this, file);
31
+ }
32
+ });
33
+ }
34
+
35
+ loadPlugin(pkg: PackageParam) {
36
+ if (typeof pkg === 'string') {
37
+ return require(pkg);
38
+ }
39
+
40
+ if (typeof pkg === 'function') {
41
+ return pkg;
42
+ }
43
+ }
44
+
45
+ initPlugin(packges: IPackageOption[], meta: IAnyObject) {
46
+ this.meta = meta;
47
+
48
+ packges.map(p => {
49
+ try {
50
+ // 加载插件
51
+ let fn = this.loadPlugin(p.package);
52
+ fn.call(this, this, p.options);
53
+ } catch (e) {
54
+ throw new PluginError(PLUGIN_NAME, `load package ${p.package} error: ', ${e}`);
55
+ }
56
+ });
57
+ }
58
+ }
59
+
60
+ export default new Plugin();
package/src/types.ts ADDED
@@ -0,0 +1,89 @@
1
+ export interface IAnyObject {
2
+ [key: string]: any;
3
+ }
4
+
5
+ export namespace WechatMiniprogram {
6
+ export type AppJsonSubpage = {
7
+ root: string;
8
+ pages: string[];
9
+ };
10
+ export type AppJsonSubpages = AppJsonSubpage[];
11
+
12
+ export interface IAppJson {
13
+ pages: string[];
14
+ subpackages?: AppJsonSubpages;
15
+ }
16
+ }
17
+
18
+ export type ProcessDefine = (file: File, encoding?: string) => File | void;
19
+
20
+ export interface IRegistration {
21
+ // 插件名称
22
+ pluginName: string;
23
+ // tool 初始化前执行
24
+ beforeInit?: ProcessDefine;
25
+ // tool 初始化时执行
26
+ onInit?: ProcessDefine;
27
+ // 检测到项目 wxml 文件后立即执行
28
+ wxml?: ProcessDefine;
29
+ // 插入 we-debug 片段之前执行
30
+ beforeInsertWxml?: ProcessDefine;
31
+ // 插入 we-debug 片段前执行
32
+ afterInsertWxml?: ProcessDefine;
33
+ // 检测到项目 json 文件后立即执行
34
+ json?: ProcessDefine;
35
+ // 检测到项目 js 文件后立即执行
36
+ script?: ProcessDefine;
37
+ // app.js 插入 we-debug import 片段前执行
38
+ beforeInsertScript?: ProcessDefine;
39
+ // app.js 插入 we-debug import 片段后执行
40
+ afterInsertScript?: ProcessDefine;
41
+ }
42
+
43
+ export type FilterOption = string | Function | RegExp;
44
+
45
+ export interface IPlugin {
46
+ /** 插件生命周期钩子声明 */
47
+ lifecycles: IRegistration[];
48
+ /** 插件元信息 */
49
+ meta: IAnyObject;
50
+ /** 注册插件 */
51
+ register(options: IRegistration): void;
52
+ /** 获取插件生命周期钩子声明 */
53
+ getLifecycles(): IRegistration[];
54
+ /** 执行插件生命周期钩子声明 */
55
+ execLifecycle(lifetime: keyof IRegistration, file: File): void;
56
+ /** 加载插件 */
57
+ loadPlugin(pkg: string | PackageFunc): void;
58
+ /** 初始化插件列表 */
59
+ initPlugin(packges: IPackageOption[], meta: IAnyObject): void;
60
+ }
61
+
62
+ export type PackageFunc = (register: IPlugin, options: IAnyObject) => void;
63
+
64
+ /**
65
+ * 插件
66
+ */
67
+ export type PackageParam = string | PackageFunc;
68
+
69
+ /**
70
+ * 插件参数
71
+ */
72
+ export interface IPackageOption {
73
+ package: PackageParam;
74
+ options: IAnyObject;
75
+ }
76
+
77
+ /**
78
+ * 编译函数入口参数
79
+ */
80
+ export interface ICompilerOption {
81
+ /** */
82
+ baseDir?: string;
83
+ wxml?: string;
84
+ filter?: FilterOption;
85
+ compName?: string;
86
+ compPath?: string;
87
+ entryFile?: string;
88
+ plugins?: IPackageOption[];
89
+ }
@@ -0,0 +1 @@
1
+ declare module 'lead';
package/lib/constants.js DELETED
@@ -1 +0,0 @@
1
- exports.PLUGIN_NAME = '@we-debug/gulp-tool';
package/lib/gogocode.js DELETED
@@ -1,61 +0,0 @@
1
- const setAttributeToAST = (ast, attrName, attrValue) => {
2
- if (!ast || typeof attrName !== 'string') {
3
- return;
4
- }
5
-
6
- // 如果属性存在,则直接修改属性
7
- let isModified = false;
8
- const attrs = ast.attr('content.attributes') || [];
9
- for (let i = 0; i < attrs.length; i++) {
10
- const attr = attrs[i];
11
- if (attr.key.content === attrName) {
12
- attr.value.content = attrValue;
13
- isModified = true;
14
- break;
15
- }
16
- }
17
-
18
- // 如果属性不存在,则新增属性
19
- if (!isModified) {
20
- attrs.push({
21
- key: {
22
- type: 'token:attribute-key',
23
- content: attrName
24
- },
25
- startWrapper: {
26
- type: 'token:attribute-value-wrapper-start',
27
- content: '"'
28
- },
29
- value: {
30
- type: 'token:attribute-value',
31
- content: attrValue
32
- },
33
- endWrapper: {
34
- type: 'token:attribute-value-wrapper-end',
35
- content: '"'
36
- }
37
- });
38
- }
39
- ast.attr('content.attributes', attrs);
40
- };
41
-
42
- const getAttributeValueWithAST = (ast, attrName) => {
43
- if (!ast || typeof attrName !== 'string') {
44
- return;
45
- }
46
-
47
- const attrs = ast.attr('content.attributes') || [];
48
- for (let i = 0; i < attrs.length; i++) {
49
- const attr = attrs[i];
50
- if (attr.key.content === attrName) {
51
- return attr.value.content;
52
- }
53
- }
54
-
55
- return;
56
- };
57
-
58
- module.exports = {
59
- setAttributeToAST,
60
- getAttributeValueWithAST
61
- };
@@ -1,92 +0,0 @@
1
- const lead = require('lead');
2
- const $ = require('gogocode');
3
- const pumpify = require('pumpify');
4
- const through = require('through2');
5
- const { md5 } = require('./md5');
6
- const { getAppJsonPath, getAbsoluteComponentPath } = require('./path');
7
- const { setAttributeToAST, getAttributeValueWithAST } = require('./gogocode');
8
-
9
- const PLUGIN_NAME = 'we-debug-record-playback';
10
- let componentsInAppJson = [];
11
-
12
- module.exports = function (options = {}) {
13
- const { baseDir } = options || {};
14
- if (typeof baseDir !== 'string' || !baseDir) {
15
- throw new Error(`[${PLUGIN_NAME}]请传入正确的baseDir,用于标识遍历的根目录。`);
16
- }
17
-
18
- let isInit = false;
19
-
20
- /** 初始化,获取app.json路径和所有页面路径 */
21
- const init = () =>
22
- through.obj((file, encoding, callback) => {
23
- if (!isInit) {
24
- try {
25
- parseAppJsonComponents();
26
- injectComponentId();
27
- } catch (e) {
28
- throw new Error(`[${PLUGIN_NAME}]遍历文件失败,请检查设置是否正确。`);
29
- }
30
- isInit = true;
31
- }
32
- callback(null, file);
33
- });
34
-
35
- /** 解析app.json中引用的组件 */
36
- const parseAppJsonComponents = () => {
37
- const appJsonPath = getAppJsonPath(baseDir);
38
-
39
- componentsInAppJson = require(appJsonPath).usingComponents || [];
40
- Object.getOwnPropertyNames(componentsInAppJson).forEach(componentName => {
41
- componentsInAppJson[componentName] = getAbsoluteComponentPath(
42
- componentsInAppJson[componentName],
43
- appJsonPath.slice(0, appJsonPath.lastIndexOf('/'))
44
- );
45
- });
46
- };
47
-
48
- /** 解析页面/页面中引用的组件 */
49
- const parseChildComponents = path => {
50
- const usingComponents = require(`${path}.json`).usingComponents || {};
51
- const componentsInJson = {};
52
- Object.getOwnPropertyNames(usingComponents).forEach(componentName => {
53
- componentsInJson[componentName] = getAbsoluteComponentPath(
54
- usingComponents[componentName],
55
- path.slice(0, path.lastIndexOf('/'))
56
- );
57
- });
58
- return componentsInJson;
59
- };
60
-
61
- const injectComponentId = () =>
62
- through.obj((file, encoding, callback) => {
63
- if (file.extname === '.wxml') {
64
- const gogo = $.loadFile(file.path, { parseOptions: { language: 'html' } });
65
- const path = file.path.slice(0, -5);
66
- const usingComponents = {
67
- ...(parseChildComponents(path) || {}),
68
- ...componentsInAppJson
69
- };
70
- Object.getOwnPropertyNames(usingComponents).forEach(component =>
71
- gogo
72
- .replace(`<${component} $$$0 />`, `<${component} $$$0></${component}>`)
73
- .find(`<${component}></${component}>`)
74
- .each(item => {
75
- if (typeof getAttributeValueWithAST(item, 'id') === 'undefined') {
76
- const itemString = item.generate();
77
- const id = md5(itemString);
78
- setAttributeToAST(item, 'id', id);
79
- }
80
- })
81
- );
82
- const res = gogo.generate();
83
- // eslint-disable-next-line no-param-reassign
84
- file.contents = Buffer.from(res);
85
- }
86
- callback(null, file);
87
- });
88
-
89
- const pipeline = [init(), injectComponentId()];
90
-
91
- return lead(pumpify.obj(pipeline));
92
- };
package/lib/md5.js DELETED
@@ -1,13 +0,0 @@
1
- const crypto = require('crypto');
2
-
3
- const md5 = src => {
4
- if (typeof src !== 'string') {
5
- return '';
6
- }
7
- const hash = crypto.createHash('md5');
8
- return hash.update(src).digest('hex');
9
- };
10
-
11
- module.exports = {
12
- md5
13
- };
package/lib/path.js DELETED
@@ -1,22 +0,0 @@
1
- const path = require('path');
2
-
3
- /** 获取绝对路径 */
4
- const getAbsolutePath = (p, src) => (path.isAbsolute(p) ? p : path.resolve(src || process.cwd(), p));
5
-
6
- /** 通过项目入口,获取app.json的绝对路径 */
7
- const getAppJsonPath = projectDir => {
8
- const projectDirAbsolute = getAbsolutePath(projectDir);
9
- return path.format({ dir: projectDirAbsolute, name: 'app', ext: '.json' });
10
- };
11
-
12
- /** 获取组件绝对路径 */
13
- const getAbsoluteComponentPath = (componentPath = '', baseDir = '') => {
14
- const isGlobalPath = componentPath[0] === '@';
15
- return isGlobalPath ? componentPath : getAbsolutePath(componentPath, baseDir);
16
- };
17
-
18
- module.exports = {
19
- getAbsolutePath,
20
- getAppJsonPath,
21
- getAbsoluteComponentPath
22
- };
package/lib/plugin.js DELETED
@@ -1,55 +0,0 @@
1
- const PluginError = require('plugin-error');
2
-
3
- const PLUGIN_NAME = '@we-debug/gulp-tool';
4
-
5
- class Plugin {
6
- /** 子插件生命周期 */
7
- lifecycles = [];
8
- /** 插件元信息 */
9
- meta = {};
10
-
11
- getLifecycles() {
12
- return this.lifecycles;
13
- }
14
-
15
- register(options) {
16
- this.lifecycles.push(options);
17
- }
18
-
19
- execLifecycle(lifetime, file) {
20
- this.lifecycles.forEach(i => {
21
- if (typeof i[lifetime] === 'function') {
22
- i[lifetime].call(this, file);
23
- }
24
- });
25
- }
26
-
27
- loadPlugin(pkg) {
28
- const pkgType = typeof pkg;
29
-
30
- switch (pkgType) {
31
- case 'function':
32
- // 函数直接返回
33
- return pkg;
34
- case 'string':
35
- // 字符串识别为 npm 包
36
- return require(pkg);
37
- }
38
- }
39
-
40
- initPlugin(packges, meta) {
41
- this.meta = meta;
42
-
43
- packges.map(p => {
44
- try {
45
- // 加载插件
46
- let fn = this.loadPlugin(p.package);
47
- fn.call(this, this, p.options);
48
- } catch (e) {
49
- throw new PluginError(PLUGIN_NAME, `load package ${p.package} error: ', ${e}`);
50
- }
51
- });
52
- }
53
- }
54
-
55
- module.exports = new Plugin();