@we-debug/compiler-core 0.0.0-stage → 0.51.0

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 ADDED
@@ -0,0 +1,20 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # [0.51.0](https://github.com/dlhandsome/we-debug/compare/v0.50.0...v0.51.0) (2026-12-01)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **compiler-core:** harden UI plugin compilation ([ecad19d](https://github.com/dlhandsome/we-debug/commit/ecad19d4c749eeca69562f67841b9c511700b262))
12
+ * **compiler-core:** 增量注入时保证清单顺序并为已有标签补 generic ([08a0eb7](https://github.com/dlhandsome/we-debug/commit/08a0eb79c67a7b0516061328f34d3ffb2e51124e))
13
+ * **compiler-core:** 恢复 beforeInit 在插件注册前执行的顺序 ([0c10c90](https://github.com/dlhandsome/we-debug/commit/0c10c90c8441e04d054db953e19dc2d464256f3c))
14
+ * **gulp-tool:** 初始化钩子沿用流中的首个文件 ([8e0fe23](https://github.com/dlhandsome/we-debug/commit/8e0fe2320c392647e7833a4ef1f7634c2b4400d8))
15
+
16
+
17
+ ### Features
18
+
19
+ * **compiler:** let UI plugin panels fill the debug panel body ([a7af2b4](https://github.com/dlhandsome/we-debug/commit/a7af2b43671b0aeaac9674da5e4242a04edfed5a))
20
+ * **compiler-core:** 支持 UI 插件发现、宿主与清单生成 ([32bf67b](https://github.com/dlhandsome/we-debug/commit/32bf67be331822eef263f070a6a42a3bec9449a0))
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Sail
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @we-debug/compiler-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ we-debug 编译注入核心逻辑,由 [`@we-debug/cli`](../cli) 与 [`@we-debug/gulp-tool`](../gulp-tool) 共用。一般不需要直接依赖本包。
4
+
5
+ 如需在自定义构建流程中逐文件注入,可以直接使用 `Injector`:
6
+
7
+ ```javascript
8
+ const { Injector, VirtualFile } = require('@we-debug/compiler-core');
9
+
10
+ const injector = new Injector({ baseDir: 'src' });
11
+ injector.init();
12
+
13
+ const file = new VirtualFile({ base: injector.options.baseDir, path: absPath, contents: buffer });
14
+ injector.transform(file);
15
+ ```
@@ -0,0 +1,6 @@
1
+ export declare const PLUGIN_NAME = "@we-debug/compiler-core";
2
+ export declare const TRANSFORM_EXTNAMES: string[];
3
+ export declare const HOST_COMPONENT_NAME = "we-debug-host";
4
+ export declare const HOST_DIR = "we-debug-host";
5
+ export declare const GENERIC_NAME = "plugin-host";
6
+ export declare const DEFAULT_NPM_DIRNAME = "miniprogram_npm";
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_NPM_DIRNAME = exports.GENERIC_NAME = exports.HOST_DIR = exports.HOST_COMPONENT_NAME = exports.TRANSFORM_EXTNAMES = exports.PLUGIN_NAME = void 0;
4
+ exports.PLUGIN_NAME = '@we-debug/compiler-core';
5
+ exports.TRANSFORM_EXTNAMES = ['.wxml', '.json', '.js'];
6
+ exports.HOST_COMPONENT_NAME = 'we-debug-host';
7
+ exports.HOST_DIR = 'we-debug-host';
8
+ exports.GENERIC_NAME = 'plugin-host';
9
+ exports.DEFAULT_NPM_DIRNAME = 'miniprogram_npm';
package/dist/file.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { IFile } from './types';
4
+ export declare class VirtualFile implements IFile {
5
+ cwd: string;
6
+ base: string;
7
+ path: string;
8
+ contents: Buffer | null;
9
+ constructor(options: {
10
+ cwd?: string;
11
+ base: string;
12
+ path: string;
13
+ contents: Buffer | null;
14
+ });
15
+ get relative(): string;
16
+ get dirname(): string;
17
+ get basename(): string;
18
+ get stem(): string;
19
+ get extname(): string;
20
+ isNull(): boolean;
21
+ isBuffer(): boolean;
22
+ isDirectory(): boolean;
23
+ }
package/dist/file.js ADDED
@@ -0,0 +1,61 @@
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.VirtualFile = void 0;
7
+ var path_1 = __importDefault(require("path"));
8
+ var VirtualFile = (function () {
9
+ function VirtualFile(options) {
10
+ this.cwd = options.cwd || process.cwd();
11
+ this.base = options.base;
12
+ this.path = options.path;
13
+ this.contents = options.contents;
14
+ }
15
+ Object.defineProperty(VirtualFile.prototype, "relative", {
16
+ get: function () {
17
+ return path_1.default.relative(this.base, this.path);
18
+ },
19
+ enumerable: false,
20
+ configurable: true
21
+ });
22
+ Object.defineProperty(VirtualFile.prototype, "dirname", {
23
+ get: function () {
24
+ return path_1.default.dirname(this.path);
25
+ },
26
+ enumerable: false,
27
+ configurable: true
28
+ });
29
+ Object.defineProperty(VirtualFile.prototype, "basename", {
30
+ get: function () {
31
+ return path_1.default.basename(this.path);
32
+ },
33
+ enumerable: false,
34
+ configurable: true
35
+ });
36
+ Object.defineProperty(VirtualFile.prototype, "stem", {
37
+ get: function () {
38
+ return path_1.default.basename(this.path, this.extname);
39
+ },
40
+ enumerable: false,
41
+ configurable: true
42
+ });
43
+ Object.defineProperty(VirtualFile.prototype, "extname", {
44
+ get: function () {
45
+ return path_1.default.extname(this.path);
46
+ },
47
+ enumerable: false,
48
+ configurable: true
49
+ });
50
+ VirtualFile.prototype.isNull = function () {
51
+ return this.contents === null;
52
+ };
53
+ VirtualFile.prototype.isBuffer = function () {
54
+ return Buffer.isBuffer(this.contents);
55
+ };
56
+ VirtualFile.prototype.isDirectory = function () {
57
+ return false;
58
+ };
59
+ return VirtualFile;
60
+ }());
61
+ exports.VirtualFile = VirtualFile;
@@ -0,0 +1,8 @@
1
+ export * from './types';
2
+ export { Injector, IResolvedCompilerOption, resolveCompilerOption, getEntryRequire } from './injector';
3
+ export { VirtualFile } from './file';
4
+ export { PluginHost } from './plugin';
5
+ export { getAbsolutePath, toPosix, lookupPages, belongsPage, belongsApp, hitPageFilter, hitExclude } from './utils';
6
+ export { PLUGIN_NAME, TRANSFORM_EXTNAMES } from './constants';
7
+ export { IUIFile, IUIPlugin, IUIComponent, IUIDiscoverOption, discoverUIPlugins, generateUIFiles, getPluginPagePaths } from './ui';
8
+ export { HOST_COMPONENT_NAME, HOST_DIR, GENERIC_NAME, DEFAULT_NPM_DIRNAME } from './constants';
package/dist/index.js ADDED
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.DEFAULT_NPM_DIRNAME = exports.GENERIC_NAME = exports.HOST_DIR = exports.HOST_COMPONENT_NAME = exports.getPluginPagePaths = exports.generateUIFiles = exports.discoverUIPlugins = exports.TRANSFORM_EXTNAMES = exports.PLUGIN_NAME = exports.hitExclude = exports.hitPageFilter = exports.belongsApp = exports.belongsPage = exports.lookupPages = exports.toPosix = exports.getAbsolutePath = exports.PluginHost = exports.VirtualFile = exports.getEntryRequire = exports.resolveCompilerOption = exports.Injector = void 0;
18
+ __exportStar(require("./types"), exports);
19
+ var injector_1 = require("./injector");
20
+ Object.defineProperty(exports, "Injector", { enumerable: true, get: function () { return injector_1.Injector; } });
21
+ Object.defineProperty(exports, "resolveCompilerOption", { enumerable: true, get: function () { return injector_1.resolveCompilerOption; } });
22
+ Object.defineProperty(exports, "getEntryRequire", { enumerable: true, get: function () { return injector_1.getEntryRequire; } });
23
+ var file_1 = require("./file");
24
+ Object.defineProperty(exports, "VirtualFile", { enumerable: true, get: function () { return file_1.VirtualFile; } });
25
+ var plugin_1 = require("./plugin");
26
+ Object.defineProperty(exports, "PluginHost", { enumerable: true, get: function () { return plugin_1.PluginHost; } });
27
+ var utils_1 = require("./utils");
28
+ Object.defineProperty(exports, "getAbsolutePath", { enumerable: true, get: function () { return utils_1.getAbsolutePath; } });
29
+ Object.defineProperty(exports, "toPosix", { enumerable: true, get: function () { return utils_1.toPosix; } });
30
+ Object.defineProperty(exports, "lookupPages", { enumerable: true, get: function () { return utils_1.lookupPages; } });
31
+ Object.defineProperty(exports, "belongsPage", { enumerable: true, get: function () { return utils_1.belongsPage; } });
32
+ Object.defineProperty(exports, "belongsApp", { enumerable: true, get: function () { return utils_1.belongsApp; } });
33
+ Object.defineProperty(exports, "hitPageFilter", { enumerable: true, get: function () { return utils_1.hitPageFilter; } });
34
+ Object.defineProperty(exports, "hitExclude", { enumerable: true, get: function () { return utils_1.hitExclude; } });
35
+ var constants_1 = require("./constants");
36
+ Object.defineProperty(exports, "PLUGIN_NAME", { enumerable: true, get: function () { return constants_1.PLUGIN_NAME; } });
37
+ Object.defineProperty(exports, "TRANSFORM_EXTNAMES", { enumerable: true, get: function () { return constants_1.TRANSFORM_EXTNAMES; } });
38
+ var ui_1 = require("./ui");
39
+ Object.defineProperty(exports, "discoverUIPlugins", { enumerable: true, get: function () { return ui_1.discoverUIPlugins; } });
40
+ Object.defineProperty(exports, "generateUIFiles", { enumerable: true, get: function () { return ui_1.generateUIFiles; } });
41
+ Object.defineProperty(exports, "getPluginPagePaths", { enumerable: true, get: function () { return ui_1.getPluginPagePaths; } });
42
+ var constants_2 = require("./constants");
43
+ Object.defineProperty(exports, "HOST_COMPONENT_NAME", { enumerable: true, get: function () { return constants_2.HOST_COMPONENT_NAME; } });
44
+ Object.defineProperty(exports, "HOST_DIR", { enumerable: true, get: function () { return constants_2.HOST_DIR; } });
45
+ Object.defineProperty(exports, "GENERIC_NAME", { enumerable: true, get: function () { return constants_2.GENERIC_NAME; } });
46
+ Object.defineProperty(exports, "DEFAULT_NPM_DIRNAME", { enumerable: true, get: function () { return constants_2.DEFAULT_NPM_DIRNAME; } });
@@ -0,0 +1,37 @@
1
+ import { PluginHost } from './plugin';
2
+ import { IUIFile, IUIPlugin } from './ui';
3
+ import { FilterOption, ICompilerOption, ICompilerPluginOption, IFile } from './types';
4
+ export interface IResolvedCompilerOption {
5
+ baseDir: string;
6
+ wxml: NonNullable<ICompilerOption['wxml']>;
7
+ filter: FilterOption | FilterOption[];
8
+ compName: string;
9
+ compPath: string;
10
+ entryFile: string;
11
+ plugins: ICompilerPluginOption[];
12
+ uiPlugins?: string[];
13
+ autoDiscoverUIPlugins: boolean;
14
+ npmDirname: string;
15
+ projectDir: string;
16
+ }
17
+ export declare function resolveCompilerOption(options?: ICompilerOption): IResolvedCompilerOption;
18
+ export declare const getEntryRequire: (entryFile: string) => string;
19
+ export declare class Injector {
20
+ private rawOptions;
21
+ readonly options: IResolvedCompilerOption;
22
+ plugin: PluginHost;
23
+ pages: string[];
24
+ uiPlugins: IUIPlugin[];
25
+ injectedPages: string[];
26
+ injectedAppJson: boolean;
27
+ injectedAppScript: boolean;
28
+ constructor(rawOptions?: ICompilerOption);
29
+ init(file?: IFile): void;
30
+ adoptInitState(source: Injector): void;
31
+ getUIFiles(): IUIFile[];
32
+ private withGenericHost;
33
+ transform(file: IFile): IFile;
34
+ private parseWxml;
35
+ private parseJson;
36
+ private parseScript;
37
+ }
@@ -0,0 +1,197 @@
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
+ exports.Injector = exports.getEntryRequire = exports.resolveCompilerOption = void 0;
18
+ var fs_1 = __importDefault(require("fs"));
19
+ var path_1 = __importDefault(require("path"));
20
+ var plugin_1 = require("./plugin");
21
+ var file_1 = require("./file");
22
+ var constants_1 = require("./constants");
23
+ var utils_1 = require("./utils");
24
+ var ui_1 = require("./ui");
25
+ function resolveCompilerOption(options) {
26
+ if (options === void 0) { options = {}; }
27
+ var baseDir = (0, utils_1.getAbsolutePath)(options.baseDir || 'src');
28
+ var compPath = options.compPath || '@we-debug/miniprogram/index/index';
29
+ var entryFile = options.entryFile || 'we-debug/index.js';
30
+ var isModule = compPath.indexOf('@we-debug/core') === 0;
31
+ if (!isModule && path_1.default.isAbsolute(compPath)) {
32
+ compPath = (0, utils_1.toPosix)(path_1.default.relative(baseDir, compPath));
33
+ }
34
+ if (path_1.default.isAbsolute(entryFile)) {
35
+ entryFile = (0, utils_1.toPosix)(path_1.default.relative(baseDir, entryFile));
36
+ }
37
+ return {
38
+ baseDir: baseDir,
39
+ wxml: options.wxml || (function (props) { return "<we-debug useCustomMask=\"{{".concat(props.useCustomMask, "}}\" />"); }),
40
+ filter: options.filter || '',
41
+ compName: options.compName || 'we-debug',
42
+ compPath: compPath,
43
+ entryFile: entryFile,
44
+ plugins: options.plugins || [],
45
+ uiPlugins: options.uiPlugins,
46
+ autoDiscoverUIPlugins: options.autoDiscoverUIPlugins !== false,
47
+ npmDirname: options.npmDirname || constants_1.DEFAULT_NPM_DIRNAME,
48
+ projectDir: (0, utils_1.getAbsolutePath)(options.projectDir || process.cwd())
49
+ };
50
+ }
51
+ exports.resolveCompilerOption = resolveCompilerOption;
52
+ var getEntryRequire = function (entryFile) { return "require('".concat(entryFile, "')"); };
53
+ exports.getEntryRequire = getEntryRequire;
54
+ var hasComponentTag = function (code, compName) {
55
+ var name = compName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
56
+ return new RegExp("<".concat(name, "(?=[\\s/>])")).test(code);
57
+ };
58
+ var Injector = (function () {
59
+ function Injector(rawOptions) {
60
+ if (rawOptions === void 0) { rawOptions = {}; }
61
+ this.rawOptions = rawOptions;
62
+ this.plugin = new plugin_1.PluginHost();
63
+ this.pages = [];
64
+ this.uiPlugins = [];
65
+ this.injectedPages = [];
66
+ this.injectedAppJson = false;
67
+ this.injectedAppScript = false;
68
+ this.options = resolveCompilerOption(rawOptions);
69
+ }
70
+ Injector.prototype.init = function (file) {
71
+ var _a = this.options, baseDir = _a.baseDir, plugins = _a.plugins;
72
+ var appJsonPath = path_1.default.join(baseDir, 'app.json');
73
+ if (!fs_1.default.existsSync(appJsonPath)) {
74
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] app.json not found in ").concat(baseDir, ", please check baseDir"));
75
+ }
76
+ var lifecycleFile = file ||
77
+ new file_1.VirtualFile({ base: baseDir, path: appJsonPath, contents: fs_1.default.readFileSync(appJsonPath) });
78
+ this.plugin.execLifecycle('beforeInit', lifecycleFile);
79
+ try {
80
+ this.pages = (0, utils_1.lookupPages)(baseDir);
81
+ }
82
+ catch (e) {
83
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] look up pages failed, please check your configure: ").concat(e));
84
+ }
85
+ var _b = this.options, projectDir = _b.projectDir, uiPlugins = _b.uiPlugins, autoDiscoverUIPlugins = _b.autoDiscoverUIPlugins;
86
+ this.uiPlugins = (0, ui_1.discoverUIPlugins)({ projectDir: projectDir, uiPlugins: uiPlugins, autoDiscoverUIPlugins: autoDiscoverUIPlugins });
87
+ this.plugin.initPlugin(plugins, __assign(__assign({}, this.rawOptions), { baseDir: baseDir, pages: this.pages, projectDir: projectDir }));
88
+ this.plugin.execLifecycle('onInit', lifecycleFile);
89
+ };
90
+ Injector.prototype.adoptInitState = function (source) {
91
+ this.pages = source.pages;
92
+ this.uiPlugins = source.uiPlugins;
93
+ this.plugin = source.plugin;
94
+ };
95
+ Injector.prototype.getUIFiles = function () {
96
+ return (0, ui_1.generateUIFiles)(this.uiPlugins, this.options.npmDirname);
97
+ };
98
+ Injector.prototype.withGenericHost = function (wxml) {
99
+ if (!this.uiPlugins.length)
100
+ return wxml;
101
+ var name = this.options.compName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
102
+ return wxml.replace(new RegExp("<".concat(name, "(?=[\\s/>])")), "$& generic:".concat(constants_1.GENERIC_NAME, "=\"").concat(constants_1.HOST_COMPONENT_NAME, "\""));
103
+ };
104
+ Injector.prototype.transform = function (file) {
105
+ if (file.isNull())
106
+ return file;
107
+ switch (file.extname) {
108
+ case '.wxml':
109
+ this.parseWxml(file);
110
+ break;
111
+ case '.json':
112
+ this.parseJson(file);
113
+ break;
114
+ case '.js':
115
+ this.parseScript(file);
116
+ break;
117
+ default:
118
+ break;
119
+ }
120
+ return file;
121
+ };
122
+ Injector.prototype.parseWxml = function (file) {
123
+ var _a = this.options, filter = _a.filter, wxml = _a.wxml, compName = _a.compName;
124
+ this.plugin.execLifecycle('wxml', file);
125
+ if (filter && (0, utils_1.hitPageFilter)(filter, (0, utils_1.toPosix)(file.path)))
126
+ return;
127
+ if (!(0, utils_1.belongsPage)(file.path, this.pages))
128
+ return;
129
+ this.plugin.execLifecycle('beforeInsertWxml', file);
130
+ var code = String(file.contents);
131
+ if (!hasComponentTag(code, compName)) {
132
+ var injectWxml = typeof wxml === 'function' ? wxml({ useCustomMask: code.indexOf('<page-container') > -1 }) : wxml;
133
+ code += this.withGenericHost(injectWxml);
134
+ file.contents = Buffer.from(code);
135
+ this.injectedPages.push((0, utils_1.toPosix)(path_1.default.relative(this.options.baseDir, file.path)).replace(/\.wxml$/, ''));
136
+ }
137
+ else if (this.uiPlugins.length && code.indexOf("generic:".concat(constants_1.GENERIC_NAME, "=")) === -1) {
138
+ code = this.withGenericHost(code);
139
+ file.contents = Buffer.from(code);
140
+ }
141
+ this.plugin.execLifecycle('afterInsertWxml', file);
142
+ };
143
+ Injector.prototype.parseJson = function (file) {
144
+ var _a = this.options, baseDir = _a.baseDir, compName = _a.compName, compPath = _a.compPath;
145
+ this.plugin.execLifecycle('json', file);
146
+ if (!(0, utils_1.belongsApp)(file.path, baseDir))
147
+ return;
148
+ var json;
149
+ try {
150
+ json = JSON.parse(String(file.contents));
151
+ }
152
+ catch (e) {
153
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] parse ").concat(file.path, " failed: ").concat(e));
154
+ }
155
+ json.usingComponents = json.usingComponents || {};
156
+ json.usingComponents[compName] = compPath;
157
+ if (this.uiPlugins.length) {
158
+ json.usingComponents[constants_1.HOST_COMPONENT_NAME] = "/".concat(constants_1.HOST_DIR, "/index");
159
+ json.pages = json.pages || [];
160
+ (0, ui_1.getPluginPagePaths)(this.uiPlugins, this.options.npmDirname).forEach(function (p) {
161
+ if (json.pages.indexOf(p) === -1)
162
+ json.pages.push(p);
163
+ });
164
+ }
165
+ file.contents = Buffer.from(JSON.stringify(json, null, 2));
166
+ this.injectedAppJson = true;
167
+ };
168
+ Injector.prototype.parseScript = function (file) {
169
+ var _a = this.options, baseDir = _a.baseDir, entryFile = _a.entryFile;
170
+ this.plugin.execLifecycle('script', file);
171
+ if (!(0, utils_1.belongsApp)(file.path, baseDir) && file.relative !== 'app.js')
172
+ return;
173
+ this.plugin.execLifecycle('beforeInsertScript', file);
174
+ var code = String(file.contents);
175
+ var entryRequire = (0, exports.getEntryRequire)(entryFile);
176
+ var injectedCode = code;
177
+ if (this.uiPlugins.length) {
178
+ var manifestRequire = "require('./".concat(constants_1.HOST_DIR, "/manifest.js')");
179
+ if (injectedCode.indexOf(manifestRequire) === -1) {
180
+ injectedCode = "".concat(manifestRequire, "\n").concat(injectedCode);
181
+ }
182
+ if (injectedCode.indexOf(entryRequire) === -1) {
183
+ injectedCode = injectedCode.replace(manifestRequire, "".concat(manifestRequire, "\n").concat(entryRequire));
184
+ }
185
+ }
186
+ else if (injectedCode.indexOf(entryRequire) === -1) {
187
+ injectedCode = "".concat(entryRequire, "\n").concat(injectedCode);
188
+ }
189
+ if (injectedCode !== code) {
190
+ file.contents = Buffer.from(injectedCode);
191
+ this.injectedAppScript = true;
192
+ }
193
+ this.plugin.execLifecycle('afterInsertScript', file);
194
+ };
195
+ return Injector;
196
+ }());
197
+ exports.Injector = Injector;
@@ -0,0 +1,10 @@
1
+ import { IRegistration, ICompilerPluginOption, IPlugin, ICompilerPluginPackageOption, IFile, Lifecycle, Meta } from './types';
2
+ export declare class PluginHost implements IPlugin {
3
+ lifecycles: IRegistration[];
4
+ meta: Meta;
5
+ getLifecycles(): IRegistration[];
6
+ register(options: IRegistration): void;
7
+ execLifecycle(lifetime: Lifecycle, file: IFile): void;
8
+ loadPlugin(pkg: ICompilerPluginPackageOption): any;
9
+ initPlugin(packages: ICompilerPluginOption[], meta: Meta): void;
10
+ }
package/dist/plugin.js ADDED
@@ -0,0 +1,54 @@
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.PluginHost = void 0;
7
+ var path_1 = __importDefault(require("path"));
8
+ var module_1 = require("module");
9
+ var constants_1 = require("./constants");
10
+ var PluginHost = (function () {
11
+ function PluginHost() {
12
+ this.lifecycles = [];
13
+ this.meta = {
14
+ pages: []
15
+ };
16
+ }
17
+ PluginHost.prototype.getLifecycles = function () {
18
+ return this.lifecycles;
19
+ };
20
+ PluginHost.prototype.register = function (options) {
21
+ this.lifecycles.push(options);
22
+ };
23
+ PluginHost.prototype.execLifecycle = function (lifetime, file) {
24
+ var _this = this;
25
+ this.lifecycles.forEach(function (i) {
26
+ var lifecycle = i[lifetime];
27
+ if (typeof lifecycle === 'function') {
28
+ lifecycle.call(_this, file);
29
+ }
30
+ });
31
+ };
32
+ PluginHost.prototype.loadPlugin = function (pkg) {
33
+ if (typeof pkg === 'function') {
34
+ return pkg;
35
+ }
36
+ var mod = (0, module_1.createRequire)(path_1.default.join(this.meta.projectDir || process.cwd(), 'noop.js'))(pkg);
37
+ return typeof mod === 'function' ? mod : mod.default;
38
+ };
39
+ PluginHost.prototype.initPlugin = function (packages, meta) {
40
+ var _this = this;
41
+ this.meta = meta;
42
+ packages.forEach(function (p) {
43
+ try {
44
+ var fn = _this.loadPlugin(p.package);
45
+ fn.call(_this, _this, p.options || {});
46
+ }
47
+ catch (e) {
48
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] load package ").concat(p.package, " error: ").concat(e));
49
+ }
50
+ });
51
+ };
52
+ return PluginHost;
53
+ }());
54
+ exports.PluginHost = PluginHost;
@@ -0,0 +1,77 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ export interface IAnyObject {
4
+ [key: string]: any;
5
+ }
6
+ export declare namespace WechatMiniprogram {
7
+ type AppJsonSubpage = {
8
+ root: string;
9
+ pages: string[];
10
+ };
11
+ type AppJsonSubpages = AppJsonSubpage[];
12
+ interface IAppJson {
13
+ pages: string[];
14
+ subpackages?: AppJsonSubpages;
15
+ subPackages?: AppJsonSubpages;
16
+ }
17
+ }
18
+ export interface IFile {
19
+ cwd: string;
20
+ base: string;
21
+ path: string;
22
+ contents: Buffer | null;
23
+ readonly relative: string;
24
+ readonly dirname: string;
25
+ readonly basename: string;
26
+ readonly stem: string;
27
+ readonly extname: string;
28
+ isNull(): boolean;
29
+ isBuffer(): boolean;
30
+ isDirectory(): boolean;
31
+ }
32
+ export type ProcessDefine = (file: IFile, encoding?: string) => IFile | void;
33
+ export interface IRegistration {
34
+ pluginName: string;
35
+ beforeInit?: ProcessDefine;
36
+ onInit?: ProcessDefine;
37
+ wxml?: ProcessDefine;
38
+ beforeInsertWxml?: ProcessDefine;
39
+ afterInsertWxml?: ProcessDefine;
40
+ json?: ProcessDefine;
41
+ script?: ProcessDefine;
42
+ beforeInsertScript?: ProcessDefine;
43
+ afterInsertScript?: ProcessDefine;
44
+ }
45
+ export type Lifecycle = Exclude<keyof IRegistration, 'pluginName'>;
46
+ export type FilterOption = string | Function | RegExp;
47
+ export type Meta<T extends IAnyObject = IAnyObject> = ICompilerOption<T> & {
48
+ pages: string[];
49
+ };
50
+ export interface IPlugin<T extends IAnyObject = IAnyObject> {
51
+ lifecycles: IRegistration[];
52
+ meta: Meta<T>;
53
+ register(options: IRegistration): void;
54
+ getLifecycles(): IRegistration[];
55
+ execLifecycle(lifetime: Lifecycle, file: IFile): void;
56
+ }
57
+ export type ICompilerPluginPackage<T extends IAnyObject = IAnyObject> = (register: IPlugin, options: T) => void;
58
+ export type ICompilerPluginPackageOption<T extends IAnyObject = IAnyObject> = string | ICompilerPluginPackage<T>;
59
+ export interface ICompilerPluginOption<T extends IAnyObject = IAnyObject> {
60
+ package: ICompilerPluginPackageOption<T>;
61
+ options?: T;
62
+ }
63
+ export interface ICompilerOption<T extends IAnyObject = IAnyObject> {
64
+ baseDir?: string;
65
+ wxml?: string | ((props: {
66
+ useCustomMask: boolean;
67
+ }) => string);
68
+ filter?: FilterOption | FilterOption[];
69
+ compName?: string;
70
+ compPath?: string;
71
+ entryFile?: string;
72
+ plugins?: ICompilerPluginOption<T>[];
73
+ uiPlugins?: string[];
74
+ autoDiscoverUIPlugins?: boolean;
75
+ npmDirname?: string;
76
+ projectDir?: string;
77
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/dist/ui.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ export interface IUIComponent {
4
+ name: string;
5
+ path: string;
6
+ id: string;
7
+ tag: string;
8
+ }
9
+ export interface IUIPlugin {
10
+ name: string;
11
+ miniprogramDir: string;
12
+ components: IUIComponent[];
13
+ pages: string[];
14
+ }
15
+ export interface IUIFile {
16
+ relative: string;
17
+ contents?: Buffer;
18
+ sourcePath?: string;
19
+ }
20
+ export interface IUIDiscoverOption {
21
+ projectDir: string;
22
+ uiPlugins?: string[];
23
+ autoDiscoverUIPlugins: boolean;
24
+ }
25
+ export declare function discoverUIPlugins(option: IUIDiscoverOption): IUIPlugin[];
26
+ export declare function getPluginPagePaths(plugins: IUIPlugin[], npmDirname: string): string[];
27
+ export declare function generateUIFiles(plugins: IUIPlugin[], npmDirname: string): IUIFile[];
package/dist/ui.js ADDED
@@ -0,0 +1,185 @@
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
+ exports.generateUIFiles = exports.getPluginPagePaths = exports.discoverUIPlugins = void 0;
18
+ var fs_1 = __importDefault(require("fs"));
19
+ var path_1 = __importDefault(require("path"));
20
+ var constants_1 = require("./constants");
21
+ var PANEL_CLASS = 'wedebug-panel';
22
+ var utils_1 = require("./utils");
23
+ var readJson = function (file) { return JSON.parse(fs_1.default.readFileSync(file, 'utf-8')); };
24
+ function normalizeRelative(value) {
25
+ return (0, utils_1.toPosix)(value)
26
+ .replace(/^(?:\.\/|\/)+/, '')
27
+ .replace(/\/+$/, '');
28
+ }
29
+ function normalizeDeclared(value, packageName) {
30
+ var normalized = normalizeRelative(value);
31
+ if (normalized.split('/').indexOf('..') > -1) {
32
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] ").concat(packageName, ": declared path \"").concat(value, "\" contains .."));
33
+ }
34
+ return normalized;
35
+ }
36
+ function findPackageDir(name, fromDir) {
37
+ var dir = fromDir;
38
+ for (;;) {
39
+ var candidate = path_1.default.join(dir, 'node_modules', name);
40
+ if (fs_1.default.existsSync(path_1.default.join(candidate, 'package.json')))
41
+ return candidate;
42
+ var parent = path_1.default.dirname(dir);
43
+ if (parent === dir)
44
+ return '';
45
+ dir = parent;
46
+ }
47
+ }
48
+ function getCandidateNames(option) {
49
+ var names = [];
50
+ if (option.uiPlugins) {
51
+ names = option.uiPlugins;
52
+ }
53
+ else if (option.autoDiscoverUIPlugins) {
54
+ var pkgFile = path_1.default.join(option.projectDir, 'package.json');
55
+ if (fs_1.default.existsSync(pkgFile)) {
56
+ var pkg = readJson(pkgFile);
57
+ names = Object.keys(__assign(__assign({}, (pkg.dependencies || {})), (pkg.devDependencies || {})));
58
+ }
59
+ }
60
+ return names.filter(function (name, index) { return names.indexOf(name) === index; });
61
+ }
62
+ function discoverUIPlugins(option) {
63
+ var explicit = !!option.uiPlugins;
64
+ var plugins = [];
65
+ var index = 0;
66
+ getCandidateNames(option)
67
+ .slice()
68
+ .sort()
69
+ .forEach(function (name) {
70
+ var dir = findPackageDir(name, option.projectDir);
71
+ if (!dir) {
72
+ if (explicit)
73
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] UI plugin ").concat(name, " not found in node_modules"));
74
+ return;
75
+ }
76
+ var pkg = readJson(path_1.default.join(dir, 'package.json'));
77
+ if (!pkg.wedebug) {
78
+ if (explicit)
79
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] ").concat(name, " has no \"wedebug\" field in package.json"));
80
+ return;
81
+ }
82
+ var hasComponents = Object.keys(pkg.wedebug.components || {}).length > 0;
83
+ var hasPages = (pkg.wedebug.pages || []).length > 0;
84
+ if (!explicit && !hasComponents && !hasPages)
85
+ return;
86
+ var miniprogramDir = path_1.default.join(dir, pkg.miniprogram || '');
87
+ var declared = pkg.wedebug.components || {};
88
+ var components = Object.keys(declared).map(function (c) {
89
+ var p = normalizeDeclared(declared[c], name);
90
+ if (!fs_1.default.existsSync(path_1.default.join(miniprogramDir, "".concat(p, ".json")))) {
91
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] ").concat(name, ": component \"").concat(c, "\" not found at ").concat(p, ".json"));
92
+ }
93
+ var id = "c".concat(index);
94
+ var tag = "wdp-".concat(index, "-").concat(c.toLowerCase().replace(/[^a-z0-9-]/g, '-'));
95
+ index++;
96
+ return { name: c, path: p, id: id, tag: tag };
97
+ });
98
+ var pages = (pkg.wedebug.pages || []).map(function (p) { return normalizeDeclared(p, name); });
99
+ pages.forEach(function (p) {
100
+ if (!fs_1.default.existsSync(path_1.default.join(miniprogramDir, "".concat(p, ".js")))) {
101
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] ").concat(name, ": page \"").concat(p, "\" not found at ").concat(p, ".js"));
102
+ }
103
+ });
104
+ plugins.push({ name: name, miniprogramDir: miniprogramDir, components: components, pages: pages });
105
+ });
106
+ return plugins;
107
+ }
108
+ exports.discoverUIPlugins = discoverUIPlugins;
109
+ function getPluginPagePaths(plugins, npmDirname) {
110
+ var pages = [];
111
+ var npmDir = normalizeRelative(npmDirname);
112
+ plugins.forEach(function (p) { return p.pages.forEach(function (page) { return pages.push("".concat(npmDir, "/").concat(p.name, "/").concat(page)); }); });
113
+ return pages;
114
+ }
115
+ exports.getPluginPagePaths = getPluginPagePaths;
116
+ function walkFiles(dir, files) {
117
+ if (files === void 0) { files = []; }
118
+ fs_1.default.readdirSync(dir, { withFileTypes: true }).forEach(function (entry) {
119
+ var abs = path_1.default.join(dir, entry.name);
120
+ if (entry.isDirectory() && entry.name !== 'node_modules' && entry.name !== '.git')
121
+ walkFiles(abs, files);
122
+ else if (entry.isFile() && !/\.d\.ts$/.test(entry.name))
123
+ files.push(abs);
124
+ });
125
+ return files;
126
+ }
127
+ function generateUIFiles(plugins, npmDirname) {
128
+ if (!plugins.length)
129
+ return [];
130
+ npmDirname = normalizeRelative(npmDirname);
131
+ var usingComponents = {};
132
+ var manifest = {
133
+ npmDirname: npmDirname,
134
+ packages: {}
135
+ };
136
+ var all = [];
137
+ plugins.forEach(function (p) {
138
+ var components = {};
139
+ p.components.forEach(function (c) {
140
+ usingComponents[c.tag] = "/".concat(npmDirname, "/").concat(p.name, "/").concat(c.path);
141
+ components[c.name] = c.id;
142
+ all.push(c);
143
+ });
144
+ manifest.packages[p.name] = { components: components, pages: p.pages };
145
+ });
146
+ var node = function (c, condition, props, className) {
147
+ if (className === void 0) { className = ''; }
148
+ return " <".concat(c.tag).concat(className ? " class=\"".concat(className, "\"") : '', " wx:if=\"{{").concat(condition, "}}\" props=\"{{").concat(props, "}}\" data-id=\"").concat(c.id, "\" bind:close=\"onClose\" />");
149
+ };
150
+ var wxml = ["<block wx:if=\"{{mode === 'panel'}}\">"]
151
+ .concat(all.map(function (c) { return node(c, "active.componentId === '".concat(c.id, "'"), 'active.props', PANEL_CLASS); }))
152
+ .concat(['</block>', '<block wx:else>'])
153
+ .concat(all.map(function (c) { return node(c, "overlays.".concat(c.id), "overlays.".concat(c.id, ".props")); }))
154
+ .concat(['</block>', ''])
155
+ .join('\n');
156
+ var files = [
157
+ {
158
+ relative: "".concat(constants_1.HOST_DIR, "/index.json"),
159
+ contents: Buffer.from(JSON.stringify({ component: true, usingComponents: usingComponents }, null, 2))
160
+ },
161
+ { relative: "".concat(constants_1.HOST_DIR, "/index.wxml"), contents: Buffer.from(wxml) },
162
+ {
163
+ relative: "".concat(constants_1.HOST_DIR, "/index.wxss"),
164
+ contents: Buffer.from(".".concat(PANEL_CLASS, " { display: block; height: 100%; }\n"))
165
+ },
166
+ {
167
+ relative: "".concat(constants_1.HOST_DIR, "/index.js"),
168
+ contents: Buffer.from("Component({ behaviors: [require('@we-debug/miniprogram/host-behavior')] });\n")
169
+ },
170
+ {
171
+ relative: "".concat(constants_1.HOST_DIR, "/manifest.js"),
172
+ contents: Buffer.from("require('@we-debug/miniprogram').registerUIManifest(".concat(JSON.stringify(manifest, null, 2), ");\n"))
173
+ }
174
+ ];
175
+ plugins.forEach(function (p) {
176
+ walkFiles(p.miniprogramDir).forEach(function (abs) {
177
+ files.push({
178
+ relative: (0, utils_1.toPosix)(path_1.default.join(npmDirname, p.name, path_1.default.relative(p.miniprogramDir, abs))),
179
+ sourcePath: abs
180
+ });
181
+ });
182
+ });
183
+ return files;
184
+ }
185
+ exports.generateUIFiles = generateUIFiles;
@@ -0,0 +1,8 @@
1
+ import { FilterOption } from './types';
2
+ export declare const getAbsolutePath: (p: string, src?: string) => string;
3
+ export declare const toPosix: (p: string) => string;
4
+ export declare function lookupPages(projectDir: string): string[];
5
+ export declare function belongsPage(fullPath: string, pages?: string[]): boolean;
6
+ export declare function belongsApp(fullPath: string, projectDir: string): boolean;
7
+ export declare function hitPageFilter(filter: FilterOption | FilterOption[], pathStr: string): boolean;
8
+ export declare function hitExclude(exclude: FilterOption[], relativePosix: string): boolean;
package/dist/utils.js ADDED
@@ -0,0 +1,55 @@
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.hitExclude = exports.hitPageFilter = exports.belongsApp = exports.belongsPage = exports.lookupPages = exports.toPosix = exports.getAbsolutePath = void 0;
7
+ var fs_1 = __importDefault(require("fs"));
8
+ var path_1 = __importDefault(require("path"));
9
+ var getAbsolutePath = function (p, src) {
10
+ return path_1.default.isAbsolute(p) ? p : path_1.default.resolve(src || process.cwd(), p);
11
+ };
12
+ exports.getAbsolutePath = getAbsolutePath;
13
+ var toPosix = function (p) { return p.split(path_1.default.sep).join('/'); };
14
+ exports.toPosix = toPosix;
15
+ function lookupPages(projectDir) {
16
+ var appPath = path_1.default.join(projectDir, 'app.json');
17
+ var appJson = JSON.parse(fs_1.default.readFileSync(appPath, 'utf-8'));
18
+ var subpackages = appJson.subpackages || appJson.subPackages || [];
19
+ var pages = (appJson.pages || []).map(function (p) { return path_1.default.resolve(projectDir, p); });
20
+ subpackages.forEach(function (sub) {
21
+ sub.pages.forEach(function (p) {
22
+ pages.push(path_1.default.resolve(projectDir, sub.root, p));
23
+ });
24
+ });
25
+ return pages;
26
+ }
27
+ exports.lookupPages = lookupPages;
28
+ function belongsPage(fullPath, pages) {
29
+ if (pages === void 0) { pages = []; }
30
+ var file = path_1.default.parse(fullPath);
31
+ return pages.indexOf(path_1.default.join(file.dir, file.name)) > -1;
32
+ }
33
+ exports.belongsPage = belongsPage;
34
+ function belongsApp(fullPath, projectDir) {
35
+ var file = path_1.default.parse(fullPath);
36
+ return path_1.default.join(projectDir, 'app') === path_1.default.join(file.dir, file.name);
37
+ }
38
+ exports.belongsApp = belongsApp;
39
+ function hitPageFilter(filter, pathStr) {
40
+ var list = Array.isArray(filter) ? filter : [filter];
41
+ return list.some(function (item) {
42
+ return (typeof item === 'function' && !item(pathStr)) ||
43
+ (typeof item === 'string' && !!item && pathStr.indexOf(item) >= 0) ||
44
+ (item instanceof RegExp && item.test(pathStr));
45
+ });
46
+ }
47
+ exports.hitPageFilter = hitPageFilter;
48
+ function hitExclude(exclude, relativePosix) {
49
+ return exclude.some(function (item) {
50
+ return (typeof item === 'function' && !!item(relativePosix)) ||
51
+ (typeof item === 'string' && !!item && relativePosix.indexOf(item) >= 0) ||
52
+ (item instanceof RegExp && item.test(relativePosix));
53
+ });
54
+ }
55
+ exports.hitExclude = hitExclude;
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@we-debug/compiler-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.51.0",
4
+ "description": "we-debug compiler core, shared by @we-debug/cli and @we-debug/gulp-tool",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "scripts": {
14
+ "test": "node test/injector.test.js && node test/ui.test.js"
15
+ },
16
+ "keywords": [
17
+ "we-debug",
18
+ "miniprogram",
19
+ "compiler"
20
+ ],
21
+ "author": {
22
+ "name": "dlhandsome"
23
+ },
24
+ "license": "MIT",
25
+ "engines": {
26
+ "node": ">=14.14.0"
27
+ },
28
+ "gitHead": "22641ac4972a154619c6dc8f44b1bfdcbb92c8eb"
29
+ }