@we-debug/compiler-core 0.51.0 → 0.52.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 CHANGED
@@ -3,6 +3,37 @@
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.52.0](https://github.com/dlhandsome/we-debug/compare/v0.51.1...v0.52.0) (2026-12-02)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * resolve subpackage UI plugin host ([0c73838](https://github.com/dlhandsome/we-debug/commit/0c73838496548038dade71630038e7df09c5c10b))
12
+ * **cli:** transform TypeScript subpackage entries ([9db5e00](https://github.com/dlhandsome/we-debug/commit/9db5e00d2d69100128b4409d53bb4da0883720b8))
13
+ * **compiler:** relocate copied npm dependencies ([b45f345](https://github.com/dlhandsome/we-debug/commit/b45f345c2b8a1e0ca0a984616dd57ce7147f8e19))
14
+ * **compiler:** relocate gulp compiled entries ([52cc367](https://github.com/dlhandsome/we-debug/commit/52cc36716b02ffe85dfc50da31816d555bab965f))
15
+ * **compiler:** retain async subpackage modules ([85c500e](https://github.com/dlhandsome/we-debug/commit/85c500e14e06ae3ccaa5d6a0cc90b32f23574847))
16
+ * **compiler-core:** avoid duplicate index.js when generating npm main shim ([893df19](https://github.com/dlhandsome/we-debug/commit/893df19a5e15a9cacef0603d244ae81168ce93f8))
17
+ * **compiler-core:** make isInside path-normalized ([11c4613](https://github.com/dlhandsome/we-debug/commit/11c4613cf5ca338bf7493a76a193be8529bc3b19))
18
+ * **compiler-core:** validate subpackage root ([b685d0f](https://github.com/dlhandsome/we-debug/commit/b685d0f2a419fec8c31c156fa08570b60be2caab))
19
+ * **core:** detect subpackage root conflicts early ([d554694](https://github.com/dlhandsome/we-debug/commit/d554694cf618a7da9d8b40e59194013998d3d4c3))
20
+ * **core:** escape boot stub paths ([aed51b8](https://github.com/dlhandsome/we-debug/commit/aed51b8775ce4e4784db95f3993e0476fd0a6ea0))
21
+ * **core:** preflight mixed injection modes ([0d3c6ee](https://github.com/dlhandsome/we-debug/commit/0d3c6eeabbedd7dcf33e0f0118e4d5c0ca8a739c))
22
+ * **core:** reject mixed injection modes ([36f8510](https://github.com/dlhandsome/we-debug/commit/36f8510b6bffc9a4a2abe6a309b68b58e2052668))
23
+ * **core:** validate subpackage buffer size ([1873422](https://github.com/dlhandsome/we-debug/commit/187342227827065d54d911331f471310683fcaeb))
24
+
25
+
26
+ ### Features
27
+
28
+ * **compiler-core:** collect npm package outputs for subpackage ([28a1aed](https://github.com/dlhandsome/we-debug/commit/28a1aed5c603154f7f30a3b2c94c2377ac706b74))
29
+ * **compiler-core:** generate boot stub that buffers early network and error events ([60fed40](https://github.com/dlhandsome/we-debug/commit/60fed408457785be3208c89ccdcbb212a04ba994))
30
+ * **compiler-core:** relocate entry directory and rewrite module paths ([7aada14](https://github.com/dlhandsome/we-debug/commit/7aada14151061497de5201da59151d93e0c5fb51))
31
+ * **compiler-core:** support subpackage injection mode ([de1226e](https://github.com/dlhandsome/we-debug/commit/de1226ee86becb530760a4c8131244b19bc75bc6))
32
+
33
+
34
+
35
+
36
+
6
37
  # [0.51.0](https://github.com/dlhandsome/we-debug/compare/v0.50.0...v0.51.0) (2026-12-01)
7
38
 
8
39
 
@@ -4,3 +4,11 @@ export declare const HOST_COMPONENT_NAME = "we-debug-host";
4
4
  export declare const HOST_DIR = "we-debug-host";
5
5
  export declare const GENERIC_NAME = "plugin-host";
6
6
  export declare const DEFAULT_NPM_DIRNAME = "miniprogram_npm";
7
+ export declare const DEFAULT_SUBPACKAGE_ROOT = "we-debug-pkg";
8
+ export declare const DEFAULT_BOOT_BUFFER_SIZE = 200;
9
+ export declare const STUB_FILE = "we-debug-stub.js";
10
+ export declare const SUBPACKAGE_NPM_DIRNAME = "miniprogram_npm";
11
+ export declare const SUBPACKAGE_ENTRY_DIR = "entry";
12
+ export declare const PLACEHOLDER_PAGE = "placeholder/index";
13
+ export declare const WE_DEBUG_SCOPE = "@we-debug/";
14
+ export declare const COMPILER_PACKAGES: string[];
package/dist/constants.js CHANGED
@@ -1,9 +1,17 @@
1
1
  "use strict";
2
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;
3
+ exports.COMPILER_PACKAGES = exports.WE_DEBUG_SCOPE = exports.PLACEHOLDER_PAGE = exports.SUBPACKAGE_ENTRY_DIR = exports.SUBPACKAGE_NPM_DIRNAME = exports.STUB_FILE = exports.DEFAULT_BOOT_BUFFER_SIZE = exports.DEFAULT_SUBPACKAGE_ROOT = exports.DEFAULT_NPM_DIRNAME = exports.GENERIC_NAME = exports.HOST_DIR = exports.HOST_COMPONENT_NAME = exports.TRANSFORM_EXTNAMES = exports.PLUGIN_NAME = void 0;
4
4
  exports.PLUGIN_NAME = '@we-debug/compiler-core';
5
- exports.TRANSFORM_EXTNAMES = ['.wxml', '.json', '.js'];
5
+ exports.TRANSFORM_EXTNAMES = ['.wxml', '.json', '.js', '.ts'];
6
6
  exports.HOST_COMPONENT_NAME = 'we-debug-host';
7
7
  exports.HOST_DIR = 'we-debug-host';
8
8
  exports.GENERIC_NAME = 'plugin-host';
9
9
  exports.DEFAULT_NPM_DIRNAME = 'miniprogram_npm';
10
+ exports.DEFAULT_SUBPACKAGE_ROOT = 'we-debug-pkg';
11
+ exports.DEFAULT_BOOT_BUFFER_SIZE = 200;
12
+ exports.STUB_FILE = 'we-debug-stub.js';
13
+ exports.SUBPACKAGE_NPM_DIRNAME = 'miniprogram_npm';
14
+ exports.SUBPACKAGE_ENTRY_DIR = 'entry';
15
+ exports.PLACEHOLDER_PAGE = 'placeholder/index';
16
+ exports.WE_DEBUG_SCOPE = '@we-debug/';
17
+ exports.COMPILER_PACKAGES = ['@we-debug/cli', '@we-debug/gulp-tool', '@we-debug/compiler-core'];
@@ -0,0 +1,10 @@
1
+ export interface IEntryRelocation {
2
+ baseDir: string;
3
+ entryDir: string;
4
+ targetDir: string;
5
+ mainNpmDir: string;
6
+ subNpmDir: string;
7
+ packageNames?: string[];
8
+ }
9
+ export declare function relocatePath(r: IEntryRelocation, absPath: string): string;
10
+ export declare function rewriteRequires(r: IEntryRelocation, fromFile: string, code: string): string;
package/dist/entry.js ADDED
@@ -0,0 +1,40 @@
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.rewriteRequires = exports.relocatePath = void 0;
7
+ var path_1 = __importDefault(require("path"));
8
+ var utils_1 = require("./utils");
9
+ var SPECIFIER = /(\brequire\s*\(\s*|\bimport\s*\(\s*|\bfrom\s*|\bimport\s+)(['"])([^'"]+)\2/g;
10
+ function relocatePath(r, absPath) {
11
+ return (0, utils_1.isInside)(absPath, r.entryDir) ? path_1.default.join(r.targetDir, path_1.default.relative(r.entryDir, absPath)) : absPath;
12
+ }
13
+ exports.relocatePath = relocatePath;
14
+ function toSubNpm(r, target) {
15
+ if (!(0, utils_1.isInside)(target, r.mainNpmDir))
16
+ return target;
17
+ var relative = path_1.default.relative(r.mainNpmDir, target);
18
+ var segments = relative.split(path_1.default.sep);
19
+ var packageName = segments[0].charAt(0) === '@' ? segments.slice(0, 2).join('/') : segments[0];
20
+ if (packageName.indexOf('@we-debug/') !== 0 && (r.packageNames || []).indexOf(packageName) === -1)
21
+ return target;
22
+ return path_1.default.join(r.subNpmDir, relative);
23
+ }
24
+ function rewriteSpecifier(r, fromFile, spec) {
25
+ if (spec.charAt(0) === '/') {
26
+ return "/".concat((0, utils_1.toPosix)(path_1.default.relative(r.baseDir, toSubNpm(r, path_1.default.join(r.baseDir, spec)))));
27
+ }
28
+ if (spec.charAt(0) !== '.')
29
+ return spec;
30
+ var target = path_1.default.resolve(path_1.default.dirname(fromFile), spec);
31
+ if ((0, utils_1.isInside)(target, r.entryDir))
32
+ return spec;
33
+ return (0, utils_1.toRequirePath)(path_1.default.dirname(relocatePath(r, fromFile)), toSubNpm(r, target));
34
+ }
35
+ function rewriteRequires(r, fromFile, code) {
36
+ return code.replace(SPECIFIER, function (_match, prefix, quote, spec) {
37
+ return "".concat(prefix).concat(quote).concat(rewriteSpecifier(r, fromFile, spec)).concat(quote);
38
+ });
39
+ }
40
+ exports.rewriteRequires = rewriteRequires;
package/dist/index.d.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  export * from './types';
2
- export { Injector, IResolvedCompilerOption, resolveCompilerOption, getEntryRequire } from './injector';
2
+ export { Injector, IResolvedCompilerOption, IResolvedSubpackage, resolveCompilerOption, getEntryRequire, getStubRequire, getEntryDir } from './injector';
3
3
  export { VirtualFile } from './file';
4
4
  export { PluginHost } from './plugin';
5
- export { getAbsolutePath, toPosix, lookupPages, belongsPage, belongsApp, hitPageFilter, hitExclude } from './utils';
5
+ export { getAbsolutePath, toPosix, lookupPages, belongsPage, belongsApp, hitPageFilter, hitExclude, isInside, toRequirePath, findPackageDir, walkFiles } from './utils';
6
6
  export { PLUGIN_NAME, TRANSFORM_EXTNAMES } from './constants';
7
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';
8
+ export { collectNpmFiles } from './npm';
9
+ export { generateStub, IStubOption } from './stub';
10
+ export { IEntryRelocation, relocatePath, rewriteRequires } from './entry';
11
+ export { HOST_COMPONENT_NAME, HOST_DIR, GENERIC_NAME, DEFAULT_NPM_DIRNAME, DEFAULT_SUBPACKAGE_ROOT, STUB_FILE, SUBPACKAGE_NPM_DIRNAME } from './constants';
package/dist/index.js CHANGED
@@ -14,12 +14,14 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
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;
17
+ exports.SUBPACKAGE_NPM_DIRNAME = exports.STUB_FILE = exports.DEFAULT_SUBPACKAGE_ROOT = exports.DEFAULT_NPM_DIRNAME = exports.GENERIC_NAME = exports.HOST_DIR = exports.HOST_COMPONENT_NAME = exports.rewriteRequires = exports.relocatePath = exports.generateStub = exports.collectNpmFiles = exports.getPluginPagePaths = exports.generateUIFiles = exports.discoverUIPlugins = exports.TRANSFORM_EXTNAMES = exports.PLUGIN_NAME = exports.walkFiles = exports.findPackageDir = exports.toRequirePath = exports.isInside = exports.hitExclude = exports.hitPageFilter = exports.belongsApp = exports.belongsPage = exports.lookupPages = exports.toPosix = exports.getAbsolutePath = exports.PluginHost = exports.VirtualFile = exports.getEntryDir = exports.getStubRequire = exports.getEntryRequire = exports.resolveCompilerOption = exports.Injector = void 0;
18
18
  __exportStar(require("./types"), exports);
19
19
  var injector_1 = require("./injector");
20
20
  Object.defineProperty(exports, "Injector", { enumerable: true, get: function () { return injector_1.Injector; } });
21
21
  Object.defineProperty(exports, "resolveCompilerOption", { enumerable: true, get: function () { return injector_1.resolveCompilerOption; } });
22
22
  Object.defineProperty(exports, "getEntryRequire", { enumerable: true, get: function () { return injector_1.getEntryRequire; } });
23
+ Object.defineProperty(exports, "getStubRequire", { enumerable: true, get: function () { return injector_1.getStubRequire; } });
24
+ Object.defineProperty(exports, "getEntryDir", { enumerable: true, get: function () { return injector_1.getEntryDir; } });
23
25
  var file_1 = require("./file");
24
26
  Object.defineProperty(exports, "VirtualFile", { enumerable: true, get: function () { return file_1.VirtualFile; } });
25
27
  var plugin_1 = require("./plugin");
@@ -32,6 +34,10 @@ Object.defineProperty(exports, "belongsPage", { enumerable: true, get: function
32
34
  Object.defineProperty(exports, "belongsApp", { enumerable: true, get: function () { return utils_1.belongsApp; } });
33
35
  Object.defineProperty(exports, "hitPageFilter", { enumerable: true, get: function () { return utils_1.hitPageFilter; } });
34
36
  Object.defineProperty(exports, "hitExclude", { enumerable: true, get: function () { return utils_1.hitExclude; } });
37
+ Object.defineProperty(exports, "isInside", { enumerable: true, get: function () { return utils_1.isInside; } });
38
+ Object.defineProperty(exports, "toRequirePath", { enumerable: true, get: function () { return utils_1.toRequirePath; } });
39
+ Object.defineProperty(exports, "findPackageDir", { enumerable: true, get: function () { return utils_1.findPackageDir; } });
40
+ Object.defineProperty(exports, "walkFiles", { enumerable: true, get: function () { return utils_1.walkFiles; } });
35
41
  var constants_1 = require("./constants");
36
42
  Object.defineProperty(exports, "PLUGIN_NAME", { enumerable: true, get: function () { return constants_1.PLUGIN_NAME; } });
37
43
  Object.defineProperty(exports, "TRANSFORM_EXTNAMES", { enumerable: true, get: function () { return constants_1.TRANSFORM_EXTNAMES; } });
@@ -39,8 +45,18 @@ var ui_1 = require("./ui");
39
45
  Object.defineProperty(exports, "discoverUIPlugins", { enumerable: true, get: function () { return ui_1.discoverUIPlugins; } });
40
46
  Object.defineProperty(exports, "generateUIFiles", { enumerable: true, get: function () { return ui_1.generateUIFiles; } });
41
47
  Object.defineProperty(exports, "getPluginPagePaths", { enumerable: true, get: function () { return ui_1.getPluginPagePaths; } });
48
+ var npm_1 = require("./npm");
49
+ Object.defineProperty(exports, "collectNpmFiles", { enumerable: true, get: function () { return npm_1.collectNpmFiles; } });
50
+ var stub_1 = require("./stub");
51
+ Object.defineProperty(exports, "generateStub", { enumerable: true, get: function () { return stub_1.generateStub; } });
52
+ var entry_1 = require("./entry");
53
+ Object.defineProperty(exports, "relocatePath", { enumerable: true, get: function () { return entry_1.relocatePath; } });
54
+ Object.defineProperty(exports, "rewriteRequires", { enumerable: true, get: function () { return entry_1.rewriteRequires; } });
42
55
  var constants_2 = require("./constants");
43
56
  Object.defineProperty(exports, "HOST_COMPONENT_NAME", { enumerable: true, get: function () { return constants_2.HOST_COMPONENT_NAME; } });
44
57
  Object.defineProperty(exports, "HOST_DIR", { enumerable: true, get: function () { return constants_2.HOST_DIR; } });
45
58
  Object.defineProperty(exports, "GENERIC_NAME", { enumerable: true, get: function () { return constants_2.GENERIC_NAME; } });
46
59
  Object.defineProperty(exports, "DEFAULT_NPM_DIRNAME", { enumerable: true, get: function () { return constants_2.DEFAULT_NPM_DIRNAME; } });
60
+ Object.defineProperty(exports, "DEFAULT_SUBPACKAGE_ROOT", { enumerable: true, get: function () { return constants_2.DEFAULT_SUBPACKAGE_ROOT; } });
61
+ Object.defineProperty(exports, "STUB_FILE", { enumerable: true, get: function () { return constants_2.STUB_FILE; } });
62
+ Object.defineProperty(exports, "SUBPACKAGE_NPM_DIRNAME", { enumerable: true, get: function () { return constants_2.SUBPACKAGE_NPM_DIRNAME; } });
@@ -1,6 +1,11 @@
1
1
  import { PluginHost } from './plugin';
2
2
  import { IUIFile, IUIPlugin } from './ui';
3
+ import { IEntryRelocation } from './entry';
3
4
  import { FilterOption, ICompilerOption, ICompilerPluginOption, IFile } from './types';
5
+ export interface IResolvedSubpackage {
6
+ root: string;
7
+ bufferSize: number;
8
+ }
4
9
  export interface IResolvedCompilerOption {
5
10
  baseDir: string;
6
11
  wxml: NonNullable<ICompilerOption['wxml']>;
@@ -13,25 +18,45 @@ export interface IResolvedCompilerOption {
13
18
  autoDiscoverUIPlugins: boolean;
14
19
  npmDirname: string;
15
20
  projectDir: string;
21
+ subpackage: IResolvedSubpackage | null;
16
22
  }
23
+ export declare const getEntryDir: (entryFile: string) => string;
17
24
  export declare function resolveCompilerOption(options?: ICompilerOption): IResolvedCompilerOption;
18
25
  export declare const getEntryRequire: (entryFile: string) => string;
26
+ export declare const getStubRequire: () => string;
19
27
  export declare class Injector {
20
28
  private rawOptions;
21
29
  readonly options: IResolvedCompilerOption;
30
+ readonly relocation: IEntryRelocation | null;
22
31
  plugin: PluginHost;
23
32
  pages: string[];
24
33
  uiPlugins: IUIPlugin[];
34
+ subpackageNpmFiles: IUIFile[];
35
+ warnings: string[];
25
36
  injectedPages: string[];
26
37
  injectedAppJson: boolean;
27
38
  injectedAppScript: boolean;
28
39
  constructor(rawOptions?: ICompilerOption);
40
+ get uiNpmDirname(): string;
41
+ get hostDir(): string;
29
42
  init(file?: IFile): void;
30
43
  adoptInitState(source: Injector): void;
31
44
  getUIFiles(): IUIFile[];
45
+ getOutputFiles(): IUIFile[];
46
+ private getSubpackageNpmFiles;
47
+ resolveOutputPath(absPath: string): string;
48
+ checkMainNpm(dir: string): void;
49
+ private warn;
50
+ private getSubpackageEntry;
51
+ private getSubpackageEntryPath;
52
+ private getSubpackageNpmNames;
32
53
  private withGenericHost;
33
54
  transform(file: IFile): IFile;
55
+ private relocateEntryFile;
56
+ private checkMainPackageRequire;
34
57
  private parseWxml;
35
58
  private parseJson;
59
+ private addSubpackage;
36
60
  private parseScript;
61
+ private checkInjectionMode;
37
62
  }
package/dist/injector.js CHANGED
@@ -14,7 +14,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.Injector = exports.getEntryRequire = exports.resolveCompilerOption = void 0;
17
+ exports.Injector = exports.getStubRequire = exports.getEntryRequire = exports.resolveCompilerOption = exports.getEntryDir = void 0;
18
18
  var fs_1 = __importDefault(require("fs"));
19
19
  var path_1 = __importDefault(require("path"));
20
20
  var plugin_1 = require("./plugin");
@@ -22,18 +22,53 @@ var file_1 = require("./file");
22
22
  var constants_1 = require("./constants");
23
23
  var utils_1 = require("./utils");
24
24
  var ui_1 = require("./ui");
25
+ var npm_1 = require("./npm");
26
+ var stub_1 = require("./stub");
27
+ var entry_1 = require("./entry");
28
+ var normalizeEntry = function (entryFile) { return (0, utils_1.toPosix)(entryFile).replace(/^(?:\.\/|\/)+/, ''); };
29
+ var getEntryDir = function (entryFile) { return path_1.default.posix.dirname(normalizeEntry(entryFile)); };
30
+ exports.getEntryDir = getEntryDir;
31
+ function resolveSubpackage(value) {
32
+ if (!value)
33
+ return null;
34
+ var option = value === true ? {} : value;
35
+ var originalRoot = Object.prototype.hasOwnProperty.call(option, 'root') ? option.root : constants_1.DEFAULT_SUBPACKAGE_ROOT;
36
+ var root = (0, utils_1.toPosix)(originalRoot || '').replace(/^(?:\.\/|\/)+/, '').replace(/\/+$/, '');
37
+ var hasBufferSize = Object.prototype.hasOwnProperty.call(option, 'bufferSize');
38
+ var bufferSize = hasBufferSize ? option.bufferSize : constants_1.DEFAULT_BOOT_BUFFER_SIZE;
39
+ if (!root || root.split('/').some(function (segment) { return segment === '.' || segment === '..'; })) {
40
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] subpackage root must be a relative directory inside baseDir, got \"").concat(originalRoot, "\""));
41
+ }
42
+ if (!Number.isFinite(bufferSize) || bufferSize <= 0 || Math.floor(bufferSize) !== bufferSize) {
43
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] subpackage bufferSize must be a positive integer, got \"").concat(bufferSize, "\""));
44
+ }
45
+ return {
46
+ root: root,
47
+ bufferSize: bufferSize
48
+ };
49
+ }
25
50
  function resolveCompilerOption(options) {
26
51
  if (options === void 0) { options = {}; }
27
52
  var baseDir = (0, utils_1.getAbsolutePath)(options.baseDir || 'src');
28
- var compPath = options.compPath || '@we-debug/miniprogram/index/index';
53
+ var rawCompPath = options.compPath || '@we-debug/miniprogram/index/index';
54
+ var compPath = rawCompPath;
29
55
  var entryFile = options.entryFile || 'we-debug/index.js';
30
56
  var isModule = compPath.indexOf('@we-debug/core') === 0;
57
+ var subpackage = resolveSubpackage(options.subpackage);
31
58
  if (!isModule && path_1.default.isAbsolute(compPath)) {
32
59
  compPath = (0, utils_1.toPosix)(path_1.default.relative(baseDir, compPath));
33
60
  }
34
61
  if (path_1.default.isAbsolute(entryFile)) {
35
62
  entryFile = (0, utils_1.toPosix)(path_1.default.relative(baseDir, entryFile));
36
63
  }
64
+ if (subpackage) {
65
+ if ((0, exports.getEntryDir)(entryFile) === '.') {
66
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] subpackage mode requires entryFile to live in its own directory, got \"").concat(entryFile, "\""));
67
+ }
68
+ if (!path_1.default.isAbsolute(rawCompPath) && !/^[./]/.test(rawCompPath)) {
69
+ compPath = "/".concat(subpackage.root, "/").concat(constants_1.SUBPACKAGE_NPM_DIRNAME, "/").concat(rawCompPath);
70
+ }
71
+ }
37
72
  return {
38
73
  baseDir: baseDir,
39
74
  wxml: options.wxml || (function (props) { return "<we-debug useCustomMask=\"{{".concat(props.useCustomMask, "}}\" />"); }),
@@ -45,16 +80,32 @@ function resolveCompilerOption(options) {
45
80
  uiPlugins: options.uiPlugins,
46
81
  autoDiscoverUIPlugins: options.autoDiscoverUIPlugins !== false,
47
82
  npmDirname: options.npmDirname || constants_1.DEFAULT_NPM_DIRNAME,
48
- projectDir: (0, utils_1.getAbsolutePath)(options.projectDir || process.cwd())
83
+ projectDir: (0, utils_1.getAbsolutePath)(options.projectDir || process.cwd()),
84
+ subpackage: subpackage
49
85
  };
50
86
  }
51
87
  exports.resolveCompilerOption = resolveCompilerOption;
52
88
  var getEntryRequire = function (entryFile) { return "require('".concat(entryFile, "')"); };
53
89
  exports.getEntryRequire = getEntryRequire;
90
+ var getStubRequire = function () { return "require('./".concat(constants_1.STUB_FILE, "')"); };
91
+ exports.getStubRequire = getStubRequire;
54
92
  var hasComponentTag = function (code, compName) {
55
93
  var name = compName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
56
94
  return new RegExp("<".concat(name, "(?=[\\s/>])")).test(code);
57
95
  };
96
+ function createRelocation(o) {
97
+ if (!o.subpackage)
98
+ return null;
99
+ var rootDir = path_1.default.join(o.baseDir, o.subpackage.root);
100
+ return {
101
+ baseDir: o.baseDir,
102
+ entryDir: path_1.default.join(o.baseDir, (0, exports.getEntryDir)(o.entryFile)),
103
+ targetDir: path_1.default.join(rootDir, constants_1.SUBPACKAGE_ENTRY_DIR),
104
+ mainNpmDir: path_1.default.join(o.baseDir, o.npmDirname),
105
+ subNpmDir: path_1.default.join(rootDir, constants_1.SUBPACKAGE_NPM_DIRNAME),
106
+ packageNames: []
107
+ };
108
+ }
58
109
  var Injector = (function () {
59
110
  function Injector(rawOptions) {
60
111
  if (rawOptions === void 0) { rawOptions = {}; }
@@ -62,17 +113,40 @@ var Injector = (function () {
62
113
  this.plugin = new plugin_1.PluginHost();
63
114
  this.pages = [];
64
115
  this.uiPlugins = [];
116
+ this.subpackageNpmFiles = [];
117
+ this.warnings = [];
65
118
  this.injectedPages = [];
66
119
  this.injectedAppJson = false;
67
120
  this.injectedAppScript = false;
68
121
  this.options = resolveCompilerOption(rawOptions);
122
+ this.relocation = createRelocation(this.options);
69
123
  }
124
+ Object.defineProperty(Injector.prototype, "uiNpmDirname", {
125
+ get: function () {
126
+ var _a = this.options, subpackage = _a.subpackage, npmDirname = _a.npmDirname;
127
+ return subpackage ? "".concat(subpackage.root, "/").concat(constants_1.SUBPACKAGE_NPM_DIRNAME) : npmDirname;
128
+ },
129
+ enumerable: false,
130
+ configurable: true
131
+ });
132
+ Object.defineProperty(Injector.prototype, "hostDir", {
133
+ get: function () {
134
+ var subpackage = this.options.subpackage;
135
+ return subpackage ? "".concat(subpackage.root, "/").concat(constants_1.HOST_DIR) : constants_1.HOST_DIR;
136
+ },
137
+ enumerable: false,
138
+ configurable: true
139
+ });
70
140
  Injector.prototype.init = function (file) {
71
- var _a = this.options, baseDir = _a.baseDir, plugins = _a.plugins;
141
+ var _a = this.options, baseDir = _a.baseDir, plugins = _a.plugins, subpackage = _a.subpackage;
72
142
  var appJsonPath = path_1.default.join(baseDir, 'app.json');
73
143
  if (!fs_1.default.existsSync(appJsonPath)) {
74
144
  throw new Error("[".concat(constants_1.PLUGIN_NAME, "] app.json not found in ").concat(baseDir, ", please check baseDir"));
75
145
  }
146
+ var appScriptPath = path_1.default.join(baseDir, 'app.js');
147
+ if (fs_1.default.existsSync(appScriptPath)) {
148
+ this.checkInjectionMode(fs_1.default.readFileSync(appScriptPath, 'utf-8'));
149
+ }
76
150
  var lifecycleFile = file ||
77
151
  new file_1.VirtualFile({ base: baseDir, path: appJsonPath, contents: fs_1.default.readFileSync(appJsonPath) });
78
152
  this.plugin.execLifecycle('beforeInit', lifecycleFile);
@@ -82,21 +156,134 @@ var Injector = (function () {
82
156
  catch (e) {
83
157
  throw new Error("[".concat(constants_1.PLUGIN_NAME, "] look up pages failed, please check your configure: ").concat(e));
84
158
  }
159
+ if (subpackage) {
160
+ var appJson = JSON.parse(fs_1.default.readFileSync(appJsonPath, 'utf-8'));
161
+ var lists = [].concat(appJson.subpackages || [], appJson.subPackages || []);
162
+ var existing = lists.filter(function (s) { return s.root.replace(/\/+$/, '') === subpackage.root; })[0];
163
+ if (existing && (existing.pages || []).indexOf(constants_1.PLACEHOLDER_PAGE) === -1) {
164
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] subpackage root \"").concat(subpackage.root, "\" already exists in app.json"));
165
+ }
166
+ var rootDir_1 = path_1.default.join(baseDir, subpackage.root);
167
+ this.pages = this.pages.filter(function (p) { return !(0, utils_1.isInside)(p, rootDir_1); });
168
+ this.checkMainNpm(baseDir);
169
+ }
85
170
  var _b = this.options, projectDir = _b.projectDir, uiPlugins = _b.uiPlugins, autoDiscoverUIPlugins = _b.autoDiscoverUIPlugins;
86
171
  this.uiPlugins = (0, ui_1.discoverUIPlugins)({ projectDir: projectDir, uiPlugins: uiPlugins, autoDiscoverUIPlugins: autoDiscoverUIPlugins });
172
+ if (subpackage) {
173
+ var collected = (0, npm_1.collectNpmFilesWithNames)(this.getSubpackageNpmNames(), projectDir, this.uiNpmDirname);
174
+ this.subpackageNpmFiles = collected.files;
175
+ var packageNames_1 = collected.names.concat(this.uiPlugins.map(function (plugin) { return plugin.name; }));
176
+ this.relocation.packageNames = packageNames_1.filter(function (name, index) { return packageNames_1.indexOf(name) === index; });
177
+ }
87
178
  this.plugin.initPlugin(plugins, __assign(__assign({}, this.rawOptions), { baseDir: baseDir, pages: this.pages, projectDir: projectDir }));
88
179
  this.plugin.execLifecycle('onInit', lifecycleFile);
89
180
  };
90
181
  Injector.prototype.adoptInitState = function (source) {
91
182
  this.pages = source.pages;
92
183
  this.uiPlugins = source.uiPlugins;
184
+ this.subpackageNpmFiles = source.subpackageNpmFiles;
185
+ if (this.relocation && source.relocation) {
186
+ this.relocation.packageNames = source.relocation.packageNames;
187
+ }
93
188
  this.plugin = source.plugin;
94
189
  };
95
190
  Injector.prototype.getUIFiles = function () {
96
- return (0, ui_1.generateUIFiles)(this.uiPlugins, this.options.npmDirname);
191
+ return (0, ui_1.generateUIFiles)(this.uiPlugins, this.uiNpmDirname, this.hostDir);
192
+ };
193
+ Injector.prototype.getOutputFiles = function () {
194
+ var files = this.getUIFiles();
195
+ var subpackage = this.options.subpackage;
196
+ if (subpackage) {
197
+ var root = subpackage.root;
198
+ files.push.apply(files, this.getSubpackageNpmFiles());
199
+ var placeholderRequires = this.uiPlugins.length
200
+ ? ["require('../".concat(constants_1.HOST_DIR, "/manifest.js');")]
201
+ : [];
202
+ placeholderRequires.push("require('../".concat(this.getSubpackageEntryPath(), "');"), 'Page({});');
203
+ files.push({
204
+ relative: "".concat(root, "/").concat(constants_1.PLACEHOLDER_PAGE, ".js"),
205
+ contents: Buffer.from("".concat(placeholderRequires.join('\n'), "\n"))
206
+ }, { relative: "".concat(root, "/").concat(constants_1.PLACEHOLDER_PAGE, ".json"), contents: Buffer.from('{}\n') }, { relative: "".concat(root, "/").concat(constants_1.PLACEHOLDER_PAGE, ".wxml"), contents: Buffer.from('<view></view>\n') }, {
207
+ relative: constants_1.STUB_FILE,
208
+ contents: Buffer.from((0, stub_1.generateStub)({
209
+ entry: this.getSubpackageEntry(),
210
+ manifest: this.uiPlugins.length ? "./".concat(this.hostDir, "/manifest.js") : undefined,
211
+ bufferSize: subpackage.bufferSize
212
+ }))
213
+ });
214
+ }
215
+ var seen = {};
216
+ return files.filter(function (f) { return (seen[f.relative] ? false : (seen[f.relative] = true)); });
217
+ };
218
+ Injector.prototype.getSubpackageNpmFiles = function () {
219
+ var _this = this;
220
+ if (!this.options.subpackage || !this.uiPlugins.length)
221
+ return this.subpackageNpmFiles;
222
+ var relative = "".concat(this.uiNpmDirname, "/").concat(constants_1.WE_DEBUG_SCOPE, "miniprogram/index/index.json");
223
+ var source = this.subpackageNpmFiles.filter(function (file) { return file.relative === relative; })[0];
224
+ if (!source || !source.sourcePath) {
225
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] ").concat(relative, " not found; @we-debug/miniprogram must declare componentGenerics.").concat(constants_1.GENERIC_NAME));
226
+ }
227
+ return this.subpackageNpmFiles.map(function (file) {
228
+ if (file.relative !== relative)
229
+ return file;
230
+ var json;
231
+ try {
232
+ json = JSON.parse(fs_1.default.readFileSync(source.sourcePath, 'utf-8'));
233
+ }
234
+ catch (e) {
235
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] parse ").concat(source.sourcePath, " failed: ").concat(e));
236
+ }
237
+ if (!json.componentGenerics || !json.componentGenerics[constants_1.GENERIC_NAME]) {
238
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] ").concat(source.sourcePath, " lacks componentGenerics.").concat(constants_1.GENERIC_NAME));
239
+ }
240
+ json.componentGenerics[constants_1.GENERIC_NAME].default = "/".concat(_this.hostDir, "/index");
241
+ return {
242
+ relative: file.relative,
243
+ contents: Buffer.from(JSON.stringify(json, null, 2))
244
+ };
245
+ });
246
+ };
247
+ Injector.prototype.resolveOutputPath = function (absPath) {
248
+ return this.relocation ? (0, entry_1.relocatePath)(this.relocation, absPath) : absPath;
249
+ };
250
+ Injector.prototype.checkMainNpm = function (dir) {
251
+ if (!this.options.subpackage)
252
+ return;
253
+ var pkgDir = path_1.default.join(dir, this.options.npmDirname, '@we-debug', 'miniprogram');
254
+ if (fs_1.default.existsSync(pkgDir)) {
255
+ this.warn("".concat((0, utils_1.toPosix)(pkgDir), " exists in the main package, move @we-debug/* to devDependencies"));
256
+ }
257
+ };
258
+ Injector.prototype.warn = function (message) {
259
+ if (this.warnings.indexOf(message) === -1)
260
+ this.warnings.push(message);
261
+ };
262
+ Injector.prototype.getSubpackageEntry = function () {
263
+ var subpackage = this.options.subpackage;
264
+ return "./".concat(subpackage.root, "/").concat(this.getSubpackageEntryPath());
265
+ };
266
+ Injector.prototype.getSubpackageEntryPath = function () {
267
+ var entryFile = this.options.entryFile;
268
+ var withoutExt = normalizeEntry(entryFile).replace(/\.(js|ts)$/, '');
269
+ var relative = path_1.default.posix.relative((0, exports.getEntryDir)(entryFile), withoutExt);
270
+ return "".concat(constants_1.SUBPACKAGE_ENTRY_DIR, "/").concat(relative, ".js");
271
+ };
272
+ Injector.prototype.getSubpackageNpmNames = function () {
273
+ var names = ["".concat(constants_1.WE_DEBUG_SCOPE, "miniprogram")];
274
+ var pkgFile = path_1.default.join(this.options.projectDir, 'package.json');
275
+ if (fs_1.default.existsSync(pkgFile)) {
276
+ var pkg = JSON.parse(fs_1.default.readFileSync(pkgFile, 'utf-8'));
277
+ Object.keys(__assign(__assign({}, (pkg.dependencies || {})), (pkg.devDependencies || {}))).forEach(function (name) {
278
+ if (name.indexOf(constants_1.WE_DEBUG_SCOPE) === 0 && constants_1.COMPILER_PACKAGES.indexOf(name) === -1 && names.indexOf(name) === -1) {
279
+ names.push(name);
280
+ }
281
+ });
282
+ }
283
+ return names;
97
284
  };
98
285
  Injector.prototype.withGenericHost = function (wxml) {
99
- if (!this.uiPlugins.length)
286
+ if (!this.uiPlugins.length || this.options.subpackage)
100
287
  return wxml;
101
288
  var name = this.options.compName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
102
289
  return wxml.replace(new RegExp("<".concat(name, "(?=[\\s/>])")), "$& generic:".concat(constants_1.GENERIC_NAME, "=\"").concat(constants_1.HOST_COMPONENT_NAME, "\""));
@@ -117,8 +304,32 @@ var Injector = (function () {
117
304
  default:
118
305
  break;
119
306
  }
307
+ if (this.relocation)
308
+ this.relocateEntryFile(file);
120
309
  return file;
121
310
  };
311
+ Injector.prototype.relocateEntryFile = function (file) {
312
+ var r = this.relocation;
313
+ var isScript = file.extname === '.js' || file.extname === '.ts';
314
+ var logical = path_1.default.join(this.options.baseDir, file.relative);
315
+ if (!(0, utils_1.isInside)(logical, r.entryDir)) {
316
+ if (isScript)
317
+ this.checkMainPackageRequire(file, logical);
318
+ return;
319
+ }
320
+ if (isScript)
321
+ file.contents = Buffer.from((0, entry_1.rewriteRequires)(r, logical, String(file.contents)));
322
+ file.path = path_1.default.join(file.base, path_1.default.relative(this.options.baseDir, (0, entry_1.relocatePath)(r, logical)));
323
+ };
324
+ Injector.prototype.checkMainPackageRequire = function (file, logical) {
325
+ var r = this.relocation;
326
+ if ((0, utils_1.isInside)(logical, r.mainNpmDir) || (0, utils_1.isInside)(logical, path_1.default.dirname(r.targetDir)))
327
+ return;
328
+ if (/['"/]@we-debug\//.test(String(file.contents))) {
329
+ var relative = (0, utils_1.toPosix)(path_1.default.relative(this.options.baseDir, logical));
330
+ this.warn("".concat(relative, " requires @we-debug/*, which puts we-debug back into the main package"));
331
+ }
332
+ };
122
333
  Injector.prototype.parseWxml = function (file) {
123
334
  var _a = this.options, filter = _a.filter, wxml = _a.wxml, compName = _a.compName;
124
335
  this.plugin.execLifecycle('wxml', file);
@@ -141,7 +352,7 @@ var Injector = (function () {
141
352
  this.plugin.execLifecycle('afterInsertWxml', file);
142
353
  };
143
354
  Injector.prototype.parseJson = function (file) {
144
- var _a = this.options, baseDir = _a.baseDir, compName = _a.compName, compPath = _a.compPath;
355
+ var _a = this.options, baseDir = _a.baseDir, compName = _a.compName, compPath = _a.compPath, subpackage = _a.subpackage;
145
356
  this.plugin.execLifecycle('json', file);
146
357
  if (!(0, utils_1.belongsApp)(file.path, baseDir))
147
358
  return;
@@ -154,10 +365,17 @@ var Injector = (function () {
154
365
  }
155
366
  json.usingComponents = json.usingComponents || {};
156
367
  json.usingComponents[compName] = compPath;
157
- if (this.uiPlugins.length) {
158
- json.usingComponents[constants_1.HOST_COMPONENT_NAME] = "/".concat(constants_1.HOST_DIR, "/index");
368
+ if (this.uiPlugins.length && !subpackage) {
369
+ json.usingComponents[constants_1.HOST_COMPONENT_NAME] = "/".concat(this.hostDir, "/index");
370
+ }
371
+ if (subpackage) {
372
+ json.componentPlaceholder = json.componentPlaceholder || {};
373
+ json.componentPlaceholder[compName] = 'view';
374
+ this.addSubpackage(json, subpackage.root);
375
+ }
376
+ else if (this.uiPlugins.length) {
159
377
  json.pages = json.pages || [];
160
- (0, ui_1.getPluginPagePaths)(this.uiPlugins, this.options.npmDirname).forEach(function (p) {
378
+ (0, ui_1.getPluginPagePaths)(this.uiPlugins, this.uiNpmDirname).forEach(function (p) {
161
379
  if (json.pages.indexOf(p) === -1)
162
380
  json.pages.push(p);
163
381
  });
@@ -165,33 +383,65 @@ var Injector = (function () {
165
383
  file.contents = Buffer.from(JSON.stringify(json, null, 2));
166
384
  this.injectedAppJson = true;
167
385
  };
386
+ Injector.prototype.addSubpackage = function (json, root) {
387
+ var key = json.subPackages && !json.subpackages ? 'subPackages' : 'subpackages';
388
+ var list = (json[key] = json[key] || []);
389
+ var pages = [constants_1.PLACEHOLDER_PAGE].concat((0, ui_1.getPluginPagePaths)(this.uiPlugins, constants_1.SUBPACKAGE_NPM_DIRNAME));
390
+ var existing = list.filter(function (s) { return s.root.replace(/\/+$/, '') === root; })[0];
391
+ if (existing && (existing.pages || []).indexOf(constants_1.PLACEHOLDER_PAGE) === -1) {
392
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] subpackage root \"").concat(root, "\" already exists in app.json"));
393
+ }
394
+ if (existing)
395
+ existing.pages = pages;
396
+ else
397
+ list.push({ root: root, pages: pages });
398
+ };
168
399
  Injector.prototype.parseScript = function (file) {
169
- var _a = this.options, baseDir = _a.baseDir, entryFile = _a.entryFile;
400
+ var _a = this.options, baseDir = _a.baseDir, entryFile = _a.entryFile, subpackage = _a.subpackage;
170
401
  this.plugin.execLifecycle('script', file);
171
402
  if (!(0, utils_1.belongsApp)(file.path, baseDir) && file.relative !== 'app.js')
172
403
  return;
173
404
  this.plugin.execLifecycle('beforeInsertScript', file);
174
405
  var code = String(file.contents);
175
- var entryRequire = (0, exports.getEntryRequire)(entryFile);
406
+ this.checkInjectionMode(code);
176
407
  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);
408
+ if (subpackage) {
409
+ var stubRequire = (0, exports.getStubRequire)();
410
+ if (injectedCode.indexOf(stubRequire) === -1)
411
+ injectedCode = "".concat(stubRequire, "\n").concat(injectedCode);
412
+ }
413
+ else {
414
+ var entryRequire = (0, exports.getEntryRequire)(entryFile);
415
+ if (this.uiPlugins.length) {
416
+ var manifestRequire = "require('./".concat(constants_1.HOST_DIR, "/manifest.js')");
417
+ if (injectedCode.indexOf(manifestRequire) === -1) {
418
+ injectedCode = "".concat(manifestRequire, "\n").concat(injectedCode);
419
+ }
420
+ if (injectedCode.indexOf(entryRequire) === -1) {
421
+ injectedCode = injectedCode.replace(manifestRequire, "".concat(manifestRequire, "\n").concat(entryRequire));
422
+ }
181
423
  }
182
- if (injectedCode.indexOf(entryRequire) === -1) {
183
- injectedCode = injectedCode.replace(manifestRequire, "".concat(manifestRequire, "\n").concat(entryRequire));
424
+ else if (injectedCode.indexOf(entryRequire) === -1) {
425
+ injectedCode = "".concat(entryRequire, "\n").concat(injectedCode);
184
426
  }
185
427
  }
186
- else if (injectedCode.indexOf(entryRequire) === -1) {
187
- injectedCode = "".concat(entryRequire, "\n").concat(injectedCode);
188
- }
189
428
  if (injectedCode !== code) {
190
429
  file.contents = Buffer.from(injectedCode);
191
430
  this.injectedAppScript = true;
192
431
  }
193
432
  this.plugin.execLifecycle('afterInsertScript', file);
194
433
  };
434
+ Injector.prototype.checkInjectionMode = function (code) {
435
+ var _a = this.options, entryFile = _a.entryFile, subpackage = _a.subpackage;
436
+ if (subpackage &&
437
+ (code.indexOf((0, exports.getEntryRequire)(entryFile)) > -1 ||
438
+ code.indexOf("require('./".concat(constants_1.HOST_DIR, "/manifest.js')")) > -1)) {
439
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] app.js was injected without subpackage mode; inject from a clean build output instead"));
440
+ }
441
+ if (!subpackage && code.indexOf((0, exports.getStubRequire)()) > -1) {
442
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] app.js was injected in subpackage mode; inject from a clean build output instead"));
443
+ }
444
+ };
195
445
  return Injector;
196
446
  }());
197
447
  exports.Injector = Injector;
package/dist/npm.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { IUIFile } from './ui';
2
+ export interface ICollectedNpmFiles {
3
+ files: IUIFile[];
4
+ names: string[];
5
+ }
6
+ export declare function collectNpmFilesWithNames(names: string[], fromDir: string, npmDirname: string): ICollectedNpmFiles;
7
+ export declare function collectNpmFiles(names: string[], fromDir: string, npmDirname: string): IUIFile[];
package/dist/npm.js ADDED
@@ -0,0 +1,56 @@
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.collectNpmFiles = exports.collectNpmFilesWithNames = void 0;
7
+ var fs_1 = __importDefault(require("fs"));
8
+ var path_1 = __importDefault(require("path"));
9
+ var constants_1 = require("./constants");
10
+ var utils_1 = require("./utils");
11
+ var SKIP_FILE = /\.(d\.ts|map|less)$/;
12
+ function collectNpmFilesWithNames(names, fromDir, npmDirname) {
13
+ var files = [];
14
+ var visited = {};
15
+ var collectedNames = [];
16
+ var visit = function (name, from) {
17
+ if (visited[name])
18
+ return;
19
+ visited[name] = true;
20
+ collectedNames.push(name);
21
+ var dir = (0, utils_1.findPackageDir)(name, from);
22
+ if (!dir)
23
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] npm package ").concat(name, " not found in node_modules"));
24
+ var pkg = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, 'package.json'), 'utf-8'));
25
+ var main = pkg.main || 'index.js';
26
+ var srcDir = path_1.default.join(dir, pkg.miniprogram || path_1.default.dirname(main));
27
+ if (!fs_1.default.existsSync(srcDir)) {
28
+ throw new Error("[".concat(constants_1.PLUGIN_NAME, "] ").concat(name, ": ").concat((0, utils_1.toPosix)(path_1.default.relative(dir, srcDir)), " not found, build the package first"));
29
+ }
30
+ var destDir = "".concat(npmDirname, "/").concat(name);
31
+ var mainRel = pkg.miniprogram
32
+ ? ''
33
+ : (0, utils_1.toPosix)(path_1.default.relative(srcDir, path_1.default.join(dir, main))).replace(/\.js$/, '');
34
+ var needsMainShim = !pkg.miniprogram && mainRel !== 'index';
35
+ (0, utils_1.walkFiles)(srcDir, SKIP_FILE).forEach(function (abs) {
36
+ var relative = (0, utils_1.toPosix)(path_1.default.relative(srcDir, abs));
37
+ if (needsMainShim && relative === 'index.js')
38
+ return;
39
+ files.push({ relative: "".concat(destDir, "/").concat(relative), sourcePath: abs });
40
+ });
41
+ if (needsMainShim) {
42
+ files.push({
43
+ relative: "".concat(destDir, "/index.js"),
44
+ contents: Buffer.from("module.exports = require('./".concat(mainRel, "');\n"))
45
+ });
46
+ }
47
+ Object.keys(pkg.dependencies || {}).forEach(function (dep) { return visit(dep, dir); });
48
+ };
49
+ names.forEach(function (name) { return visit(name, fromDir); });
50
+ return { files: files, names: collectedNames };
51
+ }
52
+ exports.collectNpmFilesWithNames = collectNpmFilesWithNames;
53
+ function collectNpmFiles(names, fromDir, npmDirname) {
54
+ return collectNpmFilesWithNames(names, fromDir, npmDirname).files;
55
+ }
56
+ exports.collectNpmFiles = collectNpmFiles;
package/dist/stub.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export interface IStubOption {
2
+ entry: string;
3
+ manifest?: string;
4
+ bufferSize: number;
5
+ }
6
+ export declare function generateStub(option: IStubOption): string;
package/dist/stub.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateStub = void 0;
4
+ var singleQuoted = function (value) {
5
+ return "'".concat(value
6
+ .replace(/\\/g, '\\\\')
7
+ .replace(/'/g, "\\'")
8
+ .replace(/\n/g, '\\n')
9
+ .replace(/\r/g, '\\r')
10
+ .replace(/\u2028/g, '\\u2028')
11
+ .replace(/\u2029/g, '\\u2029'), "'");
12
+ };
13
+ var load = function (option) {
14
+ return option.manifest
15
+ ? "require.async(".concat(singleQuoted(option.manifest), ").then(function () { return require.async(").concat(singleQuoted(option.entry), "); })")
16
+ : "require.async(".concat(singleQuoted(option.entry), ")");
17
+ };
18
+ function generateStub(option) {
19
+ return "(function () {\n if (typeof wx === 'undefined' || wx.__weDebugBoot__) return;\n var limit = ".concat(option.bufferSize, ";\n var boot = { events: [], dropped: 0, lastId: 0, originals: {}, emit: null, takeover: takeover };\n wx.__weDebugBoot__ = boot;\n\n function record(type, payload) {\n if (boot.emit) return boot.emit(type, payload);\n if (boot.events.length >= limit) {\n boot.events.shift();\n boot.dropped++;\n }\n boot.events.push({ type: type, payload: payload });\n }\n\n ['request', 'downloadFile', 'uploadFile'].forEach(function (method) {\n var original = wx[method];\n if (typeof original !== 'function') return;\n boot.originals[method] = original;\n var wrapped = function (opt) {\n opt = opt || {};\n var out = Object.assign({}, opt);\n var id = ++boot.lastId;\n var startTime = Date.now();\n out.header = out.header || {};\n out.data = out.data || {};\n record('network:request-start', { id: id, method: method, option: out, startTime: startTime });\n function finish(key, res) {\n var payload = { id: id, method: method, option: out, startTime: startTime, endTime: Date.now() };\n payload[key] = res;\n record('network:request-finished', payload);\n }\n out.success = function (res) {\n finish('response', res);\n if (typeof opt.success === 'function') opt.success.apply(this, arguments);\n };\n out.fail = function (err) {\n finish('error', err);\n if (typeof opt.fail === 'function') opt.fail.apply(this, arguments);\n };\n return original.call(wx, out);\n };\n Object.defineProperty(wx, method, { configurable: true, get: function () { return wrapped; } });\n });\n\n function onError(err) {\n record('error', err);\n }\n if (typeof wx.onError === 'function') wx.onError(onError);\n\n function takeover(emit) {\n var events = boot.events;\n boot.events = [];\n boot.emit = emit;\n if (typeof wx.offError === 'function') wx.offError(onError);\n return events;\n }\n\n function fail(e) {\n console.error('[we-debug] load subpackage failed', e);\n }\n if (typeof require.async !== 'function') return fail(new Error('require.async is not supported'));\n ").concat(load(option), ".catch(fail);\n})();\n");
20
+ }
21
+ exports.generateStub = generateStub;
package/dist/types.d.ts CHANGED
@@ -60,6 +60,10 @@ export interface ICompilerPluginOption<T extends IAnyObject = IAnyObject> {
60
60
  package: ICompilerPluginPackageOption<T>;
61
61
  options?: T;
62
62
  }
63
+ export interface ISubpackageOption {
64
+ root?: string;
65
+ bufferSize?: number;
66
+ }
63
67
  export interface ICompilerOption<T extends IAnyObject = IAnyObject> {
64
68
  baseDir?: string;
65
69
  wxml?: string | ((props: {
@@ -74,4 +78,5 @@ export interface ICompilerOption<T extends IAnyObject = IAnyObject> {
74
78
  autoDiscoverUIPlugins?: boolean;
75
79
  npmDirname?: string;
76
80
  projectDir?: string;
81
+ subpackage?: boolean | ISubpackageOption;
77
82
  }
package/dist/ui.d.ts CHANGED
@@ -24,4 +24,4 @@ export interface IUIDiscoverOption {
24
24
  }
25
25
  export declare function discoverUIPlugins(option: IUIDiscoverOption): IUIPlugin[];
26
26
  export declare function getPluginPagePaths(plugins: IUIPlugin[], npmDirname: string): string[];
27
- export declare function generateUIFiles(plugins: IUIPlugin[], npmDirname: string): IUIFile[];
27
+ export declare function generateUIFiles(plugins: IUIPlugin[], npmDirname: string, hostDir?: string): IUIFile[];
package/dist/ui.js CHANGED
@@ -33,18 +33,6 @@ function normalizeDeclared(value, packageName) {
33
33
  }
34
34
  return normalized;
35
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
36
  function getCandidateNames(option) {
49
37
  var names = [];
50
38
  if (option.uiPlugins) {
@@ -67,7 +55,7 @@ function discoverUIPlugins(option) {
67
55
  .slice()
68
56
  .sort()
69
57
  .forEach(function (name) {
70
- var dir = findPackageDir(name, option.projectDir);
58
+ var dir = (0, utils_1.findPackageDir)(name, option.projectDir);
71
59
  if (!dir) {
72
60
  if (explicit)
73
61
  throw new Error("[".concat(constants_1.PLUGIN_NAME, "] UI plugin ").concat(name, " not found in node_modules"));
@@ -113,18 +101,8 @@ function getPluginPagePaths(plugins, npmDirname) {
113
101
  return pages;
114
102
  }
115
103
  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) {
104
+ function generateUIFiles(plugins, npmDirname, hostDir) {
105
+ if (hostDir === void 0) { hostDir = constants_1.HOST_DIR; }
128
106
  if (!plugins.length)
129
107
  return [];
130
108
  npmDirname = normalizeRelative(npmDirname);
@@ -155,25 +133,25 @@ function generateUIFiles(plugins, npmDirname) {
155
133
  .join('\n');
156
134
  var files = [
157
135
  {
158
- relative: "".concat(constants_1.HOST_DIR, "/index.json"),
136
+ relative: "".concat(hostDir, "/index.json"),
159
137
  contents: Buffer.from(JSON.stringify({ component: true, usingComponents: usingComponents }, null, 2))
160
138
  },
161
- { relative: "".concat(constants_1.HOST_DIR, "/index.wxml"), contents: Buffer.from(wxml) },
139
+ { relative: "".concat(hostDir, "/index.wxml"), contents: Buffer.from(wxml) },
162
140
  {
163
- relative: "".concat(constants_1.HOST_DIR, "/index.wxss"),
141
+ relative: "".concat(hostDir, "/index.wxss"),
164
142
  contents: Buffer.from(".".concat(PANEL_CLASS, " { display: block; height: 100%; }\n"))
165
143
  },
166
144
  {
167
- relative: "".concat(constants_1.HOST_DIR, "/index.js"),
145
+ relative: "".concat(hostDir, "/index.js"),
168
146
  contents: Buffer.from("Component({ behaviors: [require('@we-debug/miniprogram/host-behavior')] });\n")
169
147
  },
170
148
  {
171
- relative: "".concat(constants_1.HOST_DIR, "/manifest.js"),
149
+ relative: "".concat(hostDir, "/manifest.js"),
172
150
  contents: Buffer.from("require('@we-debug/miniprogram').registerUIManifest(".concat(JSON.stringify(manifest, null, 2), ");\n"))
173
151
  }
174
152
  ];
175
153
  plugins.forEach(function (p) {
176
- walkFiles(p.miniprogramDir).forEach(function (abs) {
154
+ (0, utils_1.walkFiles)(p.miniprogramDir).forEach(function (abs) {
177
155
  files.push({
178
156
  relative: (0, utils_1.toPosix)(path_1.default.join(npmDirname, p.name, path_1.default.relative(p.miniprogramDir, abs))),
179
157
  sourcePath: abs
package/dist/utils.d.ts CHANGED
@@ -6,3 +6,7 @@ export declare function belongsPage(fullPath: string, pages?: string[]): boolean
6
6
  export declare function belongsApp(fullPath: string, projectDir: string): boolean;
7
7
  export declare function hitPageFilter(filter: FilterOption | FilterOption[], pathStr: string): boolean;
8
8
  export declare function hitExclude(exclude: FilterOption[], relativePosix: string): boolean;
9
+ export declare function findPackageDir(name: string, fromDir: string): string;
10
+ export declare function walkFiles(dir: string, skip?: RegExp, files?: string[]): string[];
11
+ export declare function isInside(target: string, dir: string): boolean;
12
+ export declare function toRequirePath(fromDir: string, target: string): string;
package/dist/utils.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.hitExclude = exports.hitPageFilter = exports.belongsApp = exports.belongsPage = exports.lookupPages = exports.toPosix = exports.getAbsolutePath = void 0;
6
+ exports.toRequirePath = exports.isInside = exports.walkFiles = exports.findPackageDir = exports.hitExclude = exports.hitPageFilter = exports.belongsApp = exports.belongsPage = exports.lookupPages = exports.toPosix = exports.getAbsolutePath = void 0;
7
7
  var fs_1 = __importDefault(require("fs"));
8
8
  var path_1 = __importDefault(require("path"));
9
9
  var getAbsolutePath = function (p, src) {
@@ -53,3 +53,39 @@ function hitExclude(exclude, relativePosix) {
53
53
  });
54
54
  }
55
55
  exports.hitExclude = hitExclude;
56
+ function findPackageDir(name, fromDir) {
57
+ var dir = fromDir;
58
+ for (;;) {
59
+ var candidate = path_1.default.join(dir, 'node_modules', name);
60
+ if (fs_1.default.existsSync(path_1.default.join(candidate, 'package.json')))
61
+ return candidate;
62
+ var parent = path_1.default.dirname(dir);
63
+ if (parent === dir)
64
+ return '';
65
+ dir = parent;
66
+ }
67
+ }
68
+ exports.findPackageDir = findPackageDir;
69
+ function walkFiles(dir, skip, files) {
70
+ if (skip === void 0) { skip = /\.d\.ts$/; }
71
+ if (files === void 0) { files = []; }
72
+ fs_1.default.readdirSync(dir, { withFileTypes: true }).forEach(function (entry) {
73
+ var abs = path_1.default.join(dir, entry.name);
74
+ if (entry.isDirectory() && entry.name !== 'node_modules' && entry.name !== '.git')
75
+ walkFiles(abs, skip, files);
76
+ else if (entry.isFile() && !skip.test(entry.name))
77
+ files.push(abs);
78
+ });
79
+ return files;
80
+ }
81
+ exports.walkFiles = walkFiles;
82
+ function isInside(target, dir) {
83
+ var rel = path_1.default.relative(path_1.default.resolve(dir), path_1.default.resolve(target));
84
+ return rel === '' || (rel !== '..' && !rel.startsWith("..".concat(path_1.default.sep)) && !path_1.default.isAbsolute(rel));
85
+ }
86
+ exports.isInside = isInside;
87
+ function toRequirePath(fromDir, target) {
88
+ var rel = (0, exports.toPosix)(path_1.default.relative(fromDir, target));
89
+ return /^\.\.?\//.test(rel) ? rel : "./".concat(rel);
90
+ }
91
+ exports.toRequirePath = toRequirePath;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@we-debug/compiler-core",
3
- "version": "0.51.0",
3
+ "version": "0.52.0",
4
4
  "description": "we-debug compiler core, shared by @we-debug/cli and @we-debug/gulp-tool",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -11,7 +11,7 @@
11
11
  "access": "public"
12
12
  },
13
13
  "scripts": {
14
- "test": "node test/injector.test.js && node test/ui.test.js"
14
+ "test": "node test/injector.test.js && node test/ui.test.js && node test/utils.test.js && node test/npm.test.js && node test/stub.test.js && node test/entry.test.js && node test/subpackage.test.js"
15
15
  },
16
16
  "keywords": [
17
17
  "we-debug",
@@ -25,5 +25,5 @@
25
25
  "engines": {
26
26
  "node": ">=14.14.0"
27
27
  },
28
- "gitHead": "22641ac4972a154619c6dc8f44b1bfdcbb92c8eb"
28
+ "gitHead": "bc98652915ac460bb4015b9918c32f899fe049a5"
29
29
  }