@simplysm/sd-cli 12.5.10 → 12.5.12

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.
@@ -1,325 +0,0 @@
1
- import path from "path";
2
- import { FsUtil, Logger, PathUtil } from "@simplysm/sd-core-node";
3
- import { fileURLToPath } from "url";
4
- import nodeStdLibBrowser from "node-stdlib-browser";
5
- import nodeStdLibBrowserPlugin from "node-stdlib-browser/helpers/esbuild/plugin";
6
- import { INpmConfig, ISdCliClientBuilderCordovaConfig, ISdCliPackageBuildResult } from "../commons";
7
- import ts from "typescript";
8
- import { SdReactBundlerContext } from "./SdReactBundlerContext";
9
- import { IReactPluginResultCache, sdReactPlugin } from "../bundle-plugins/sdReactPlugin";
10
- import { transformSupportedBrowsersToTargets } from "@angular/build/src/tools/esbuild/utils";
11
- import browserslist from "browserslist";
12
- import { glob } from "glob";
13
-
14
- export class SdReactBundler {
15
- readonly #logger = Logger.get(["simplysm", "sd-cli", "SdNgBundler"]);
16
-
17
- readonly #modifiedFileSet = new Set<string>();
18
- readonly #compileResultCache: IReactPluginResultCache = {
19
- affectedFileSet: new Set<string>(),
20
- watchFileSet: new Set<string>(),
21
- };
22
- #contexts: SdReactBundlerContext[] | undefined;
23
-
24
- readonly #outputCache = new Map<string, string | number>();
25
-
26
- readonly #opt: IOptions;
27
-
28
- readonly #pkgNpmConf: INpmConfig;
29
- readonly #indexFilePath: string;
30
- readonly #tsConfigFilePath: string;
31
- readonly #browserTarget: string[];
32
-
33
- public constructor(opt: IOptions) {
34
- this.#opt = opt;
35
- this.#pkgNpmConf = FsUtil.readJson(path.resolve(opt.pkgPath, "package.json"));
36
- this.#indexFilePath = path.resolve(opt.pkgPath, "src/index.tsx");
37
- this.#tsConfigFilePath = path.resolve(opt.pkgPath, "tsconfig.json");
38
- this.#browserTarget = transformSupportedBrowsersToTargets(browserslist(["Chrome > 78"]));
39
- }
40
-
41
- public markForChanges(filePaths: string[]): void {
42
- for (const filePath of filePaths) {
43
- this.#modifiedFileSet.add(path.normalize(filePath));
44
- }
45
- }
46
-
47
- public async bundleAsync(): Promise<{
48
- program?: ts.Program;
49
- watchFileSet: Set<string>;
50
- affectedFileSet: Set<string>;
51
- results: ISdCliPackageBuildResult[];
52
- }> {
53
- this.#debug(`get contexts...`);
54
-
55
- if (!this.#contexts) {
56
- this.#contexts = [
57
- this._getAppContext(),
58
- ...(this.#opt.builderType === "electron" ? [this._getElectronMainContext()] : []),
59
- ];
60
- }
61
-
62
- this.#debug(`build...`);
63
-
64
- const bundlingResults = await this.#contexts.mapAsync(async (ctx, i) => await ctx.bundleAsync());
65
-
66
- //-- results
67
- const results = bundlingResults.mapMany((bundlingResult) => bundlingResult.results);
68
-
69
- this.#debug(`convert result...`);
70
-
71
- const outputFiles: IReactOutputFile[] = bundlingResults
72
- .mapMany((item) => item.outputFiles ?? [])
73
- .map((item) => ({
74
- relPath: path.relative(this.#opt.pkgPath, item.path),
75
- contents: item.contents,
76
- }));
77
-
78
- // cordova empty
79
- if (this.#opt.builderType === "cordova" && this.#opt.cordovaConfig?.plugins) {
80
- outputFiles.push({ relPath: "cordova-empty.js", contents: "export default {};" });
81
- }
82
-
83
- // index.html
84
- let indexHtml = await FsUtil.readFileAsync(path.resolve(this.#opt.pkgPath, "src/index.html"));
85
- indexHtml = indexHtml.replace(/<\/head>/, '<script type="module" src="index.js"></script></head>');
86
- if (this.#opt.builderType === "cordova") {
87
- indexHtml = indexHtml.replace(
88
- /(.*)<\/head>/,
89
- '<script type="module" src="cordova-entry.js"></script>\n$1</head>',
90
- );
91
- }
92
- if (outputFiles.some(item => item.relPath === "index.css")) {
93
- indexHtml = indexHtml.replace(
94
- /(.*)<\/head>/,
95
- '<link rel="stylesheet" href="index.css">\n$1</head>',
96
- );
97
- }
98
-
99
- outputFiles.push({
100
- relPath: "index.html",
101
- contents: indexHtml,
102
- });
103
-
104
- // copy assets
105
- outputFiles.push(
106
- ...this.#copyAssets("src", "favicon.ico"),
107
- ...this.#copyAssets("src", "manifest.webmanifest"),
108
- ...this.#copyAssets("src/assets", "**/*", "assets"),
109
- ...(this.#opt.dev && this.#opt.builderType === "cordova"
110
- ? Object.keys(this.#opt.cordovaConfig?.platform ?? { browser: {} }).mapMany((platform) => [
111
- ...this.#copyAssets(
112
- `.cordova/platforms/${platform}/platform_www/plugins`,
113
- "**/*",
114
- `cordova-${platform}/plugins`,
115
- ),
116
- ...this.#copyAssets(`.cordova/platforms/${platform}/platform_www`, "cordova.js", `cordova-${platform}`),
117
- ...this.#copyAssets(
118
- `.cordova/platforms/${platform}/platform_www`,
119
- "cordova_plugins.js",
120
- `cordova-${platform}`,
121
- ),
122
- ...this.#copyAssets(`.cordova/platforms/${platform}/www`, "config.xml", `cordova-${platform}`),
123
- ])
124
- : []),
125
- );
126
-
127
- // TODO: extract 3rdpartylicenses
128
- // TODO: service worker
129
-
130
- //-- write
131
- this.#debug(`write output files...(${outputFiles.length})`);
132
-
133
- for (const outputFile of outputFiles) {
134
- const distFilePath = path.resolve(this.#opt.outputPath, outputFile.relPath);
135
- const prev = this.#outputCache.get(distFilePath);
136
- if (prev !== Buffer.from(outputFile.contents).toString("base64")) {
137
- await FsUtil.writeFileAsync(distFilePath, outputFile.contents);
138
- this.#outputCache.set(distFilePath, Buffer.from(outputFile.contents).toString("base64"));
139
- }
140
- }
141
-
142
- this.#debug(`번들링중 영향받은 파일`, Array.from(this.#compileResultCache.affectedFileSet!));
143
-
144
- return {
145
- program: this.#compileResultCache.program,
146
- watchFileSet: new Set(this.#compileResultCache.watchFileSet),
147
- affectedFileSet: this.#compileResultCache.affectedFileSet!,
148
- results,
149
- };
150
- }
151
-
152
- #copyAssets(srcDir: string, globPath: string, distDir?: string): IReactOutputFile[] {
153
- const result: IReactOutputFile[] = [];
154
- const srcGlobPath = path.resolve(this.#opt.pkgPath, srcDir, globPath);
155
- const srcPaths = glob.sync(srcGlobPath);
156
- for (const srcPath of srcPaths) {
157
- if (!FsUtil.exists(srcPath)) continue;
158
- result.push({
159
- relPath: path.join(
160
- ...[distDir, path.relative(path.resolve(this.#opt.pkgPath, srcDir), srcPath)].filterExists(),
161
- ),
162
- contents: FsUtil.readFile(srcPath),
163
- });
164
- }
165
-
166
- return result;
167
- }
168
-
169
- private _getAppContext() {
170
- return new SdReactBundlerContext(this.#opt.pkgPath, {
171
- absWorkingDir: this.#opt.pkgPath,
172
- bundle: true,
173
- keepNames: true,
174
- format: "esm",
175
- assetNames: "media/[name]",
176
- conditions: ["es2020", "es2015", "module"],
177
- resolveExtensions: [".js", ".mjs", ".cjs", ".ts", ".tsx"],
178
- metafile: true,
179
- legalComments: this.#opt.dev ? "eof" : "none",
180
- logLevel: "silent",
181
- minifyIdentifiers: !this.#opt.dev,
182
- minifySyntax: !this.#opt.dev,
183
- minifyWhitespace: !this.#opt.dev,
184
- pure: ["forwardRef"],
185
- outdir: this.#opt.pkgPath,
186
- outExtension: undefined,
187
- sourcemap: true, //this.#opt.dev,
188
- splitting: true,
189
- chunkNames: "[name]-[hash]",
190
- tsconfig: this.#tsConfigFilePath,
191
- write: false,
192
- preserveSymlinks: false,
193
- define: {
194
- ...(!this.#opt.dev ? { ngDevMode: "false" } : {}),
195
- "ngJitMode": "false",
196
- "global": "global",
197
- "process": "process",
198
- "Buffer": "Buffer",
199
- "process.env.SD_VERSION": JSON.stringify(this.#pkgNpmConf.version),
200
- "process.env.NODE_ENV": JSON.stringify(this.#opt.dev ? "development" : "production"),
201
- ...(this.#opt.env
202
- ? Object.keys(this.#opt.env).toObject(
203
- (key) => `process.env.${key}`,
204
- (key) => JSON.stringify(this.#opt.env![key]),
205
- )
206
- : {}),
207
- },
208
- platform: "browser",
209
- mainFields: ["es2020", "es2015", "browser", "module", "main"],
210
- entryNames: "[name]",
211
- entryPoints: {
212
- index: this.#indexFilePath,
213
- },
214
- external: ["electron"],
215
- target: this.#browserTarget,
216
- supported: { "async-await": false, "object-rest-spread": false },
217
- loader: {
218
- ".png": "file",
219
- ".jpeg": "file",
220
- ".jpg": "file",
221
- ".jfif": "file",
222
- ".gif": "file",
223
- ".svg": "file",
224
- ".woff": "file",
225
- ".woff2": "file",
226
- ".ttf": "file",
227
- ".ttc": "file",
228
- ".eot": "file",
229
- ".ico": "file",
230
- ".otf": "file",
231
- ".csv": "file",
232
- ".xlsx": "file",
233
- ".xls": "file",
234
- ".pptx": "file",
235
- ".ppt": "file",
236
- ".docx": "file",
237
- ".doc": "file",
238
- ".zip": "file",
239
- ".pfx": "file",
240
- ".pkl": "file",
241
- ".mp3": "file",
242
- ".ogg": "file",
243
- },
244
- inject: [PathUtil.posix(fileURLToPath(import.meta.resolve("node-stdlib-browser/helpers/esbuild/shim")))],
245
- plugins: [
246
- ...(this.#opt.builderType === "cordova" && this.#opt.cordovaConfig?.plugins
247
- ? [
248
- {
249
- name: "cordova:plugin-empty",
250
- setup: ({ onResolve }) => {
251
- onResolve({ filter: new RegExp("(" + this.#opt.cordovaConfig!.plugins!.join("|") + ")") }, () => {
252
- return {
253
- path: `./cordova-empty.js`,
254
- external: true,
255
- };
256
- });
257
- },
258
- },
259
- ]
260
- : []),
261
- sdReactPlugin({
262
- modifiedFileSet: this.#modifiedFileSet,
263
- dev: this.#opt.dev,
264
- pkgPath: this.#opt.pkgPath,
265
- result: this.#compileResultCache,
266
- }),
267
- nodeStdLibBrowserPlugin(nodeStdLibBrowser),
268
- ],
269
- });
270
- }
271
-
272
- private _getElectronMainContext() {
273
- return new SdReactBundlerContext(this.#opt.pkgPath, {
274
- absWorkingDir: this.#opt.pkgPath,
275
- bundle: true,
276
- entryNames: "[name]",
277
- assetNames: "media/[name]",
278
- conditions: ["es2020", "es2015", "module"],
279
- resolveExtensions: [".js", ".mjs", ".cjs", ".ts"],
280
- metafile: true,
281
- legalComments: this.#opt.dev ? "eof" : "none",
282
- logLevel: "silent",
283
- minify: !this.#opt.dev,
284
- outdir: this.#opt.pkgPath,
285
- sourcemap: true, //this.#opt.dev,
286
- tsconfig: this.#tsConfigFilePath,
287
- write: false,
288
- preserveSymlinks: false,
289
- external: ["electron"],
290
- define: {
291
- ...(!this.#opt.dev ? { ngDevMode: "false" } : {}),
292
- "process.env.SD_VERSION": JSON.stringify(this.#pkgNpmConf.version),
293
- "process.env.NODE_ENV": JSON.stringify(this.#opt.dev ? "development" : "production"),
294
- ...(this.#opt.env
295
- ? Object.keys(this.#opt.env).toObject(
296
- (key) => `process.env.${key}`,
297
- (key) => JSON.stringify(this.#opt.env![key]),
298
- )
299
- : {}),
300
- },
301
- platform: "node",
302
- entryPoints: {
303
- "electron-main": path.resolve(this.#opt.pkgPath, "src/electron-main.ts"),
304
- },
305
- });
306
- }
307
-
308
- #debug(...msg: any[]): void {
309
- this.#logger.debug(`[${path.basename(this.#opt.pkgPath)}]`, ...msg);
310
- }
311
- }
312
-
313
- interface IOptions {
314
- dev: boolean;
315
- outputPath: string;
316
- pkgPath: string;
317
- builderType: string;
318
- env: Record<string, string> | undefined;
319
- cordovaConfig: ISdCliClientBuilderCordovaConfig | undefined;
320
- }
321
-
322
- interface IReactOutputFile {
323
- relPath: string;
324
- contents: Uint8Array | string;
325
- }
@@ -1,71 +0,0 @@
1
- import esbuild from "esbuild";
2
- import path from "path";
3
- import { ISdCliPackageBuildResult } from "../commons";
4
- import { Logger } from "@simplysm/sd-core-node";
5
-
6
- export class SdReactBundlerContext {
7
- readonly #logger = Logger.get(["simplysm", "sd-cli", "SdReactBundlerContext"]);
8
-
9
- private _context?: esbuild.BuildContext;
10
-
11
- public constructor(
12
- private readonly _pkgPath: string,
13
- private readonly _esbuildOptions: esbuild.BuildOptions,
14
- ) {}
15
-
16
- public async bundleAsync() {
17
- if (this._context == null) {
18
- this._context = await esbuild.context(this._esbuildOptions);
19
- }
20
-
21
- let buildResult: esbuild.BuildResult;
22
-
23
- try {
24
- this.#debug(`rebuild...`);
25
- buildResult = await this._context.rebuild();
26
- this.#debug(`rebuild completed`);
27
- } catch (err) {
28
- if ("warnings" in err || "errors" in err) {
29
- buildResult = err;
30
- } else {
31
- throw err;
32
- }
33
- }
34
-
35
- this.#debug(`convert results...`);
36
-
37
- const results = [
38
- ...buildResult.warnings.map((warn) => ({
39
- filePath: warn.location?.file !== undefined ? path.resolve(this._pkgPath, warn.location.file) : undefined,
40
- line: warn.location?.line,
41
- char: warn.location?.column,
42
- code: warn.text.slice(0, warn.text.indexOf(":")),
43
- severity: "warning",
44
- message: `${warn.pluginName ? `(${warn.pluginName}) ` : ""} ${warn.text.slice(warn.text.indexOf(":") + 1)}`,
45
- type: "build",
46
- })),
47
- ...buildResult.errors.map((err) => ({
48
- filePath: err.location?.file !== undefined ? path.resolve(this._pkgPath, err.location.file) : undefined,
49
- line: err.location?.line,
50
- char: err.location?.column !== undefined ? err.location.column + 1 : undefined,
51
- code: err.text.slice(0, err.text.indexOf(":")),
52
- severity: "error",
53
- message: `${err.pluginName ? `(${err.pluginName}) ` : ""} ${err.text.slice(err.text.indexOf(":") + 1)}`,
54
- type: "build",
55
- })),
56
- ] as ISdCliPackageBuildResult[];
57
-
58
- return {
59
- results,
60
- outputFiles: buildResult.outputFiles,
61
- metafile: buildResult.metafile,
62
- };
63
- }
64
-
65
- #debug(...msg: any[]): void {
66
- this.#logger.debug(
67
- `[${path.basename(this._pkgPath)}] (${Object.keys(this._esbuildOptions.entryPoints as Record<string, any>).join(", ")})`,
68
- ...msg,
69
- );
70
- }
71
- }
@@ -1,157 +0,0 @@
1
- import esbuild from "esbuild";
2
- import ts from "typescript";
3
- import path from "path";
4
- import { ISdTsCompilerResult, SdTsCompiler } from "../build-tools/SdTsCompiler";
5
- import { convertTypeScriptDiagnostic } from "@angular/build/src/tools/esbuild/angular/diagnostics";
6
- import postcss from "postcss";
7
- import { FsUtil } from "@simplysm/sd-core-node";
8
- import postcssUrl from "postcss-url";
9
- import postcssHas from "css-has-pseudo";
10
- import autoprefixer from "autoprefixer";
11
-
12
- export function sdReactPlugin(conf: {
13
- pkgPath: string;
14
- dev: boolean;
15
- modifiedFileSet: Set<string>;
16
- result: IReactPluginResultCache;
17
- }): esbuild.Plugin {
18
- return {
19
- name: "sd-ng-compiler",
20
- setup: (build: esbuild.PluginBuild) => {
21
- const compiler = new SdTsCompiler(conf.pkgPath, { declaration: false }, conf.dev);
22
-
23
- let buildResult: ISdTsCompilerResult;
24
- const outputContentsCacheMap = new Map<string, string | Uint8Array | undefined>();
25
-
26
- //---------------------------
27
-
28
- build.onStart(async () => {
29
- compiler.invalidate(conf.modifiedFileSet);
30
- for (const modifiedFile of conf.modifiedFileSet) {
31
- outputContentsCacheMap.delete(modifiedFile);
32
- }
33
-
34
- buildResult = await compiler.buildAsync();
35
-
36
- conf.result.watchFileSet = buildResult.watchFileSet;
37
- conf.result.affectedFileSet = buildResult.affectedFileSet;
38
- conf.result.program = buildResult.program;
39
-
40
- //-- return err/warn
41
- return {
42
- errors: [
43
- ...buildResult.typescriptDiagnostics
44
- .filter((item) => item.category === ts.DiagnosticCategory.Error)
45
- .map((item) => convertTypeScriptDiagnostic(ts, item)),
46
- ...Array.from(buildResult.stylesheetBundlingResultMap.values()).flatMap((item) => item.errors),
47
- ].filterExists(),
48
- warnings: [
49
- ...buildResult.typescriptDiagnostics
50
- .filter((item) => item.category !== ts.DiagnosticCategory.Error)
51
- .map((item) => convertTypeScriptDiagnostic(ts, item)),
52
- // ...Array.from(buildResult.stylesheetResultMap.values()).flatMap(item => item.warnings)
53
- ],
54
- };
55
- });
56
-
57
- build.onLoad({ filter: /\.tsx?$/ }, (args) => {
58
- const output = outputContentsCacheMap.get(path.normalize(args.path));
59
- if (output != null) {
60
- return { contents: output, loader: "js" };
61
- }
62
-
63
- const emittedJsFile = buildResult.emittedFilesCacheMap.get(path.normalize(args.path))?.last();
64
- if (!emittedJsFile) {
65
- throw new Error(`ts 빌더 결과 emit 파일이 존재하지 않습니다. ${args.path}`);
66
- }
67
-
68
- const contents = emittedJsFile.text;
69
-
70
- outputContentsCacheMap.set(path.normalize(args.path), contents);
71
-
72
- return { contents, loader: "js" };
73
- });
74
-
75
- build.onLoad({ filter: /\.[cm]?jsx?$/ }, (args) => {
76
- conf.result.watchFileSet!.add(path.normalize(args.path));
77
- return null;
78
- });
79
-
80
- build.onLoad({ filter: /\.css$/ }, async (args) => {
81
- conf.result.watchFileSet!.add(path.normalize(args.path));
82
- const output = outputContentsCacheMap.get(path.normalize(args.path));
83
- if (output != null) {
84
- return {
85
- contents: output,
86
- loader: "file",
87
- };
88
- }
89
-
90
- const css = await FsUtil.readFileAsync(path.normalize(args.path));
91
- const result = await postcss()
92
- .use(
93
- autoprefixer({
94
- overrideBrowserslist: ["Chrome > 78"]
95
- })
96
- )
97
- .use(
98
- postcssUrl({
99
- url: "copy",
100
- }),
101
- )
102
- .use(
103
- postcssHas()
104
- )
105
- .process(css, {
106
- from: path.normalize(args.path),
107
- to: path.resolve(conf.pkgPath, "dist", "media", path.basename(args.path)),
108
- });
109
-
110
- outputContentsCacheMap.set(path.normalize(args.path), result.css);
111
-
112
- return { contents: result.css, loader: "file" };
113
- });
114
-
115
- build.onLoad(
116
- {
117
- filter: new RegExp(
118
- "(" +
119
- Object.keys(build.initialOptions.loader!)
120
- .map((item) => "\\" + item)
121
- .join("|") +
122
- ")$",
123
- ),
124
- },
125
- (args) => {
126
- conf.result.watchFileSet!.add(path.normalize(args.path));
127
- return null;
128
- },
129
- );
130
-
131
- build.onEnd((result) => {
132
- for (const { outputFiles, metafile } of buildResult.stylesheetBundlingResultMap.values()) {
133
- result.outputFiles = result.outputFiles ?? [];
134
- result.outputFiles.push(...outputFiles);
135
-
136
- if (result.metafile && metafile) {
137
- result.metafile.inputs = { ...result.metafile.inputs, ...metafile.inputs };
138
- result.metafile.outputs = { ...result.metafile.outputs, ...metafile.outputs };
139
- }
140
- }
141
-
142
- conf.result.outputFiles = result.outputFiles;
143
- conf.result.metafile = result.metafile;
144
-
145
- conf.modifiedFileSet.clear();
146
- });
147
- },
148
- };
149
- }
150
-
151
- export interface IReactPluginResultCache {
152
- watchFileSet?: Set<string>;
153
- affectedFileSet?: Set<string>;
154
- program?: ts.Program;
155
- outputFiles?: esbuild.OutputFile[];
156
- metafile?: esbuild.Metafile;
157
- }