zero-com 0.0.4 → 0.0.5

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/lib/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.execServerFn = exports.serverFn = void 0;
4
+ const serverFn = (sfn) => {
5
+ const clonedSfn = (...rest) => sfn(null, ...rest);
6
+ clonedSfn.serverFn = sfn;
7
+ return clonedSfn;
8
+ };
9
+ exports.serverFn = serverFn;
10
+ const execServerFn = (sfn, ctx, args) => {
11
+ if (sfn.serverFn) {
12
+ return sfn.serverFn.call(null, ctx, ...args);
13
+ }
14
+ else {
15
+ return sfn.call(null, ...args);
16
+ }
17
+ };
18
+ exports.execServerFn = execServerFn;
package/lib/index.ts ADDED
@@ -0,0 +1,19 @@
1
+
2
+ declare global {
3
+ var ZERO_COM_SERVER_REGISTRY: { [funcId: string]: (...args: any[]) => any }
4
+ var ZERO_COM_CLIENT_SEND: (...args: any[]) => Promise<any>
5
+ }
6
+
7
+ export const serverFn = <Ctx, Rest extends any[], R>(sfn: (ctx: Ctx, ...rest: Rest) => R) => {
8
+ const clonedSfn = (...rest: Rest): R => sfn(null as Ctx, ...rest)
9
+ clonedSfn.serverFn = sfn
10
+ return clonedSfn
11
+ }
12
+
13
+ export const execServerFn = (sfn: ReturnType<typeof serverFn>, ctx: any, args: any[]): ReturnType<typeof sfn> => {
14
+ if (sfn.serverFn) {
15
+ return sfn.serverFn.call(null, ctx, ...args)
16
+ } else {
17
+ return sfn.call(null, ...args)
18
+ }
19
+ }
package/lib/rollup.js ADDED
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.zeroComRollupPlugin = zeroComRollupPlugin;
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const minimatch_1 = require("minimatch");
18
+ const path_1 = __importDefault(require("path"));
19
+ const ts_morph_1 = require("ts-morph");
20
+ const typescript_1 = __importDefault(require("typescript"));
21
+ const common_1 = require("./common");
22
+ function zeroComRollupPlugin(options) {
23
+ const { development = true, patterns } = options;
24
+ const compilationId = String(Math.floor(Math.random() * 1000000));
25
+ const clientPattern = patterns.client;
26
+ const serverPattern = patterns.server;
27
+ const replacements = [
28
+ { target: common_1.ZERO_COM_CLIENT_SEND, replacement: `__ZERO_COM_CLIENT_SEND_${compilationId}` },
29
+ { target: common_1.ZERO_COM_SERVER_REGISTRY, replacement: `__ZERO_COM_SERVER_REGISTRY_${compilationId}` }
30
+ ];
31
+ return {
32
+ name: 'zero-com-rollup-plugin',
33
+ resolveId(source, importer, options) {
34
+ return __awaiter(this, void 0, void 0, function* () {
35
+ if (!importer)
36
+ return null;
37
+ const resolveResult = yield this.resolve(source, importer, Object.assign(Object.assign({}, options), { skipSelf: true }));
38
+ if (!resolveResult)
39
+ return null;
40
+ const absolutePath = resolveResult.id;
41
+ const isServerFile = (0, minimatch_1.minimatch)(absolutePath, path_1.default.join(process.cwd(), serverPattern));
42
+ if (!isServerFile)
43
+ return null;
44
+ const requestedFromClient = (0, minimatch_1.minimatch)(importer, path_1.default.join(process.cwd(), clientPattern));
45
+ const tsPath = absolutePath + '.ts';
46
+ const jsPath = absolutePath + '.js';
47
+ const mjsPath = absolutePath + '.mjs';
48
+ let resolvedPath = '';
49
+ if (fs_1.default.existsSync(tsPath)) {
50
+ resolvedPath = tsPath;
51
+ }
52
+ else if (fs_1.default.existsSync(jsPath)) {
53
+ resolvedPath = jsPath;
54
+ }
55
+ else if (fs_1.default.existsSync(mjsPath)) {
56
+ resolvedPath = mjsPath;
57
+ }
58
+ else {
59
+ return null;
60
+ }
61
+ return {
62
+ id: resolvedPath,
63
+ meta: {
64
+ isClient: requestedFromClient,
65
+ }
66
+ };
67
+ });
68
+ },
69
+ load(id) {
70
+ var _a;
71
+ const meta = (_a = this.getModuleInfo(id)) === null || _a === void 0 ? void 0 : _a.meta;
72
+ if (meta === undefined || meta.isClient === undefined)
73
+ return null;
74
+ const originalContent = fs_1.default.readFileSync(id, 'utf8');
75
+ const project = new ts_morph_1.Project({
76
+ compilerOptions: {
77
+ target: typescript_1.default.ScriptTarget.ES2017,
78
+ module: typescript_1.default.ModuleKind.ESNext,
79
+ },
80
+ });
81
+ const sourceFile = project.createSourceFile(id, originalContent, { overwrite: true });
82
+ if (meta.isClient) {
83
+ sourceFile.getFunctions().forEach(func => {
84
+ if (func.isExported() && func.isAsync()) {
85
+ const funcName = String(func.getName());
86
+ const lineNumber = func.getStartLineNumber();
87
+ const funcParams = func.getParameters().map(p => p.getName()).join(', ');
88
+ const funcId = (0, common_1.formatFuncIdName)(funcName, path_1.default.relative(process.cwd(), id), lineNumber);
89
+ const newFunctionBody = `return window.${common_1.ZERO_COM_CLIENT_SEND}({funcId: '${funcId}', params: [${funcParams}]})`;
90
+ func.setBodyText(newFunctionBody);
91
+ }
92
+ });
93
+ sourceFile.getVariableDeclarations().forEach(decl => {
94
+ const initializer = decl.getInitializer();
95
+ if (initializer && initializer instanceof ts_morph_1.ArrowFunction) {
96
+ if (decl.isExported() && initializer.isAsync()) {
97
+ const funcName = decl.getName();
98
+ const lineNumber = decl.getStartLineNumber();
99
+ const funcParams = initializer.getParameters().map(p => p.getName()).join(', ');
100
+ const funcId = (0, common_1.formatFuncIdName)(funcName, path_1.default.relative(process.cwd(), id), lineNumber);
101
+ const newFunctionBody = `return window.${common_1.ZERO_COM_CLIENT_SEND}({funcId: '${funcId}', params: [${funcParams}]})`;
102
+ initializer.setBodyText(newFunctionBody);
103
+ }
104
+ }
105
+ });
106
+ }
107
+ else {
108
+ const chunks = [];
109
+ sourceFile.getFunctions().forEach(func => {
110
+ if (func.isExported() && func.isAsync()) {
111
+ const funcName = String(func.getName());
112
+ const lineNumber = func.getStartLineNumber();
113
+ const funcId = (0, common_1.formatFuncIdName)(funcName, path_1.default.relative(process.cwd(), id), lineNumber);
114
+ chunks.push(`global.${common_1.ZERO_COM_SERVER_REGISTRY}['${funcId}'] = ${funcName}`);
115
+ }
116
+ });
117
+ sourceFile.getVariableDeclarations().forEach(decl => {
118
+ const initializer = decl.getInitializer();
119
+ if (initializer && initializer instanceof ts_morph_1.ArrowFunction) {
120
+ if (decl.isExported() && initializer.isAsync()) {
121
+ const funcName = decl.getName();
122
+ const lineNumber = decl.getStartLineNumber();
123
+ const funcId = (0, common_1.formatFuncIdName)(funcName, path_1.default.relative(process.cwd(), id), lineNumber);
124
+ chunks.push(`global.${common_1.ZERO_COM_SERVER_REGISTRY}['${funcId}'] = ${funcName}`);
125
+ }
126
+ }
127
+ });
128
+ if (chunks.length > 0) {
129
+ const textToAdd = `\nif (!global.${common_1.ZERO_COM_SERVER_REGISTRY}) global.${common_1.ZERO_COM_SERVER_REGISTRY} = Object.create(null); ${chunks.join(',')}`;
130
+ sourceFile.insertText(sourceFile.getEnd(), textToAdd);
131
+ }
132
+ }
133
+ const result = project.emitToMemory();
134
+ const newContent = result.getFiles()[0].text;
135
+ return newContent;
136
+ },
137
+ renderChunk(code, chunk, options) {
138
+ if (development)
139
+ return null;
140
+ let modified = false;
141
+ let newCode = code;
142
+ replacements.forEach(({ target, replacement }) => {
143
+ if (newCode.includes(target)) {
144
+ newCode = newCode.replaceAll(target, replacement);
145
+ modified = true;
146
+ }
147
+ });
148
+ if (modified) {
149
+ return { code: newCode, map: null };
150
+ }
151
+ return null;
152
+ }
153
+ };
154
+ }
package/lib/rollup.ts ADDED
@@ -0,0 +1,155 @@
1
+ import fs from 'fs'
2
+ import { minimatch } from 'minimatch'
3
+ import path from 'path'
4
+ import { ArrowFunction, Project } from 'ts-morph'
5
+ import ts from 'typescript'
6
+ import {
7
+ Plugin,
8
+ PluginContext,
9
+ ResolveIdResult,
10
+ LoadResult,
11
+ NormalizedOutputOptions,
12
+ RenderedChunk
13
+ } from 'rollup'
14
+ import { Options, ZERO_COM_CLIENT_SEND, ZERO_COM_SERVER_REGISTRY, formatFuncIdName } from './common'
15
+
16
+ export function zeroComRollupPlugin(options: Options): Plugin {
17
+ const { development = true, patterns } = options
18
+ const compilationId = String(Math.floor(Math.random() * 1000000))
19
+ const clientPattern = patterns.client
20
+ const serverPattern = patterns.server
21
+
22
+ const replacements = [
23
+ { target: ZERO_COM_CLIENT_SEND, replacement: `__ZERO_COM_CLIENT_SEND_${compilationId}` },
24
+ { target: ZERO_COM_SERVER_REGISTRY, replacement: `__ZERO_COM_SERVER_REGISTRY_${compilationId}` }
25
+ ]
26
+
27
+ return {
28
+ name: 'zero-com-rollup-plugin',
29
+
30
+ async resolveId(this: PluginContext, source: string, importer: string | undefined, options: { isEntry: boolean }): Promise<ResolveIdResult> {
31
+ if (!importer) return null
32
+
33
+ const resolveResult = await this.resolve(source, importer, { ...options, skipSelf: true })
34
+ if (!resolveResult) return null
35
+
36
+ const absolutePath = resolveResult.id
37
+ const isServerFile = minimatch(absolutePath, path.join(process.cwd(), serverPattern))
38
+ if (!isServerFile) return null
39
+
40
+ const requestedFromClient = minimatch(importer, path.join(process.cwd(), clientPattern))
41
+
42
+ const tsPath = absolutePath + '.ts'
43
+ const jsPath = absolutePath + '.js'
44
+ const mjsPath = absolutePath + '.mjs'
45
+ let resolvedPath = ''
46
+
47
+ if (fs.existsSync(tsPath)) {
48
+ resolvedPath = tsPath
49
+ } else if (fs.existsSync(jsPath)) {
50
+ resolvedPath = jsPath
51
+ } else if (fs.existsSync(mjsPath)) {
52
+ resolvedPath = mjsPath
53
+ } else {
54
+ return null
55
+ }
56
+
57
+ return {
58
+ id: resolvedPath,
59
+ meta: {
60
+ isClient: requestedFromClient,
61
+ }
62
+ }
63
+ },
64
+
65
+ load(this: PluginContext, id: string): LoadResult {
66
+ const meta = this.getModuleInfo(id)?.meta
67
+ if (meta === undefined || meta.isClient === undefined) return null
68
+
69
+ const originalContent = fs.readFileSync(id, 'utf8')
70
+ const project = new Project({
71
+ compilerOptions: {
72
+ target: ts.ScriptTarget.ES2017,
73
+ module: ts.ModuleKind.ESNext,
74
+ },
75
+ })
76
+
77
+ const sourceFile = project.createSourceFile(id, originalContent, { overwrite: true })
78
+
79
+ if (meta.isClient) {
80
+ sourceFile.getFunctions().forEach(func => {
81
+ if (func.isExported() && func.isAsync()) {
82
+ const funcName = String(func.getName())
83
+ const lineNumber = func.getStartLineNumber()
84
+ const funcParams = func.getParameters().map(p => p.getName()).join(', ')
85
+ const funcId = formatFuncIdName(funcName, path.relative(process.cwd(), id), lineNumber)
86
+ const newFunctionBody = `return window.${ZERO_COM_CLIENT_SEND}({funcId: '${funcId}', params: [${funcParams}]})`
87
+ func.setBodyText(newFunctionBody)
88
+ }
89
+ })
90
+ sourceFile.getVariableDeclarations().forEach(decl => {
91
+ const initializer = decl.getInitializer()
92
+ if (initializer && initializer instanceof ArrowFunction) {
93
+ if (decl.isExported() && initializer.isAsync()) {
94
+ const funcName = decl.getName()
95
+ const lineNumber = decl.getStartLineNumber()
96
+ const funcParams = initializer.getParameters().map(p => p.getName()).join(', ')
97
+ const funcId = formatFuncIdName(funcName, path.relative(process.cwd(), id), lineNumber)
98
+ const newFunctionBody = `return window.${ZERO_COM_CLIENT_SEND}({funcId: '${funcId}', params: [${funcParams}]})`
99
+ initializer.setBodyText(newFunctionBody)
100
+ }
101
+ }
102
+ })
103
+ } else {
104
+ const chunks: string[] = []
105
+ sourceFile.getFunctions().forEach(func => {
106
+ if (func.isExported() && func.isAsync()) {
107
+ const funcName = String(func.getName())
108
+ const lineNumber = func.getStartLineNumber()
109
+ const funcId = formatFuncIdName(funcName, path.relative(process.cwd(), id), lineNumber)
110
+ chunks.push(`global.${ZERO_COM_SERVER_REGISTRY}['${funcId}'] = ${funcName}`)
111
+ }
112
+ })
113
+ sourceFile.getVariableDeclarations().forEach(decl => {
114
+ const initializer = decl.getInitializer()
115
+ if (initializer && initializer instanceof ArrowFunction) {
116
+ if (decl.isExported() && initializer.isAsync()) {
117
+ const funcName = decl.getName()
118
+ const lineNumber = decl.getStartLineNumber()
119
+ const funcId = formatFuncIdName(funcName, path.relative(process.cwd(), id), lineNumber)
120
+ chunks.push(`global.${ZERO_COM_SERVER_REGISTRY}['${funcId}'] = ${funcName}`)
121
+ }
122
+ }
123
+ })
124
+
125
+ if (chunks.length > 0) {
126
+ const textToAdd = `\nif (!global.${ZERO_COM_SERVER_REGISTRY}) global.${ZERO_COM_SERVER_REGISTRY} = Object.create(null); ${chunks.join(',')}`
127
+ sourceFile.insertText(sourceFile.getEnd(), textToAdd);
128
+ }
129
+ }
130
+
131
+ const result = project.emitToMemory()
132
+ const newContent = result.getFiles()[0].text
133
+ return newContent
134
+ },
135
+
136
+ renderChunk(this: PluginContext, code: string, chunk: RenderedChunk, options: NormalizedOutputOptions) {
137
+ if (development) return null
138
+
139
+ let modified = false
140
+ let newCode = code
141
+ replacements.forEach(({ target, replacement }) => {
142
+ if (newCode.includes(target)) {
143
+ newCode = newCode.replaceAll(target, replacement)
144
+ modified = true
145
+ }
146
+ })
147
+
148
+ if (modified) {
149
+ return { code: newCode, map: null }
150
+ }
151
+
152
+ return null
153
+ }
154
+ }
155
+ }
package/lib/webpack.js ADDED
@@ -0,0 +1,146 @@
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.ZeroComWebpackPlugin = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const minimatch_1 = require("minimatch");
9
+ const path_1 = __importDefault(require("path"));
10
+ const ts_morph_1 = require("ts-morph");
11
+ const typescript_1 = __importDefault(require("typescript"));
12
+ const common_1 = require("./common");
13
+ class ZeroComWebpackPlugin {
14
+ constructor(options) {
15
+ this.options = Object.assign(Object.assign({ development: true }, options), { patterns: Object.assign({}, options.patterns) });
16
+ this.compilationId = String(Math.floor(Math.random() * 1000000));
17
+ this.clientPattern = this.options.patterns.client;
18
+ this.serverPattern = this.options.patterns.server;
19
+ }
20
+ apply(compiler) {
21
+ const pluginName = ZeroComWebpackPlugin.name;
22
+ const { webpack } = compiler;
23
+ const { RawSource } = webpack.sources;
24
+ compiler.hooks.normalModuleFactory.tap(pluginName, (nmf) => {
25
+ nmf.hooks.beforeResolve.tap(pluginName, (resolveData) => {
26
+ const absolutePath = path_1.default.resolve(resolveData.context, resolveData.request);
27
+ const isServerFile = (0, minimatch_1.minimatch)(absolutePath, path_1.default.join(compiler.context, this.serverPattern));
28
+ if (!isServerFile)
29
+ return;
30
+ const requestedFromClient = (0, minimatch_1.minimatch)(resolveData.contextInfo.issuer, path_1.default.join(compiler.context, this.clientPattern));
31
+ const tsPath = absolutePath + '.ts';
32
+ const jsPath = absolutePath + '.js';
33
+ const mjsPath = absolutePath + '.mjs';
34
+ let resolvedPath = '';
35
+ if (fs_1.default.existsSync(tsPath)) {
36
+ resolvedPath = tsPath;
37
+ }
38
+ else if (fs_1.default.existsSync(jsPath)) {
39
+ resolvedPath = jsPath;
40
+ }
41
+ else if (fs_1.default.existsSync(mjsPath)) {
42
+ resolvedPath = mjsPath;
43
+ }
44
+ else {
45
+ throw new Error('Unable to resolve: ' + absolutePath);
46
+ }
47
+ const originalContent = fs_1.default.readFileSync(resolvedPath, 'utf8');
48
+ const project = new ts_morph_1.Project({
49
+ compilerOptions: {
50
+ target: typescript_1.default.ScriptTarget.ES2017,
51
+ module: typescript_1.default.ModuleKind.ESNext,
52
+ },
53
+ });
54
+ const sourceFile = project.createSourceFile(absolutePath, originalContent, { overwrite: true });
55
+ let newModuleContent = '';
56
+ if (requestedFromClient) {
57
+ const generatedFunctions = [];
58
+ sourceFile.getFunctions().forEach(func => {
59
+ if (func.isExported() && func.isAsync()) {
60
+ const funcName = String(func.getName());
61
+ const lineNumber = func.getStartLineNumber();
62
+ const funcParams = func.getParameters().map(p => p.getName()).join(', ');
63
+ const funcId = (0, common_1.formatFuncIdName)(funcName, path_1.default.relative(compiler.context, absolutePath), lineNumber);
64
+ const newFunctionBody = `return window.${common_1.ZERO_COM_CLIENT_SEND}({funcId: '${funcId}', params: [${funcParams}]})`;
65
+ func.setBodyText(newFunctionBody);
66
+ generatedFunctions.push(func.getText());
67
+ console.log('client:', funcId);
68
+ }
69
+ });
70
+ sourceFile.getVariableDeclarations().forEach(decl => {
71
+ const initializer = decl.getInitializer();
72
+ if (initializer && initializer instanceof ts_morph_1.ArrowFunction) {
73
+ if (decl.isExported() && initializer.isAsync()) {
74
+ const funcName = decl.getName();
75
+ const lineNumber = decl.getStartLineNumber();
76
+ const funcParams = initializer.getParameters().map(p => p.getName()).join(', ');
77
+ const funcId = (0, common_1.formatFuncIdName)(funcName, path_1.default.relative(compiler.context, absolutePath), lineNumber);
78
+ const newFunctionBody = `return window.${common_1.ZERO_COM_CLIENT_SEND}({funcId: '${funcId}', params: [${funcParams}]})`;
79
+ initializer.setBodyText(newFunctionBody);
80
+ generatedFunctions.push(decl.getVariableStatementOrThrow().getText());
81
+ console.log('client:', funcId);
82
+ }
83
+ }
84
+ });
85
+ newModuleContent = generatedFunctions.join('\n\n');
86
+ }
87
+ else {
88
+ const chunks = [];
89
+ sourceFile.getFunctions().forEach(func => {
90
+ if (func.isExported() && func.isAsync()) {
91
+ const funcName = String(func.getName());
92
+ const lineNumber = func.getStartLineNumber();
93
+ const funcId = (0, common_1.formatFuncIdName)(funcName, path_1.default.relative(compiler.context, absolutePath), lineNumber);
94
+ chunks.push(`global.${common_1.ZERO_COM_SERVER_REGISTRY}['${funcId}'] = ${funcName}`);
95
+ console.log('server:', funcId);
96
+ }
97
+ });
98
+ sourceFile.getVariableDeclarations().forEach(decl => {
99
+ const initializer = decl.getInitializer();
100
+ if (initializer && initializer instanceof ts_morph_1.ArrowFunction) {
101
+ if (decl.isExported() && initializer.isAsync()) {
102
+ const funcName = decl.getName();
103
+ const lineNumber = decl.getStartLineNumber();
104
+ const funcId = (0, common_1.formatFuncIdName)(funcName, path_1.default.relative(compiler.context, absolutePath), lineNumber);
105
+ chunks.push(`global.${common_1.ZERO_COM_SERVER_REGISTRY}['${funcId}'] = ${funcName}`);
106
+ console.log('server:', funcId);
107
+ }
108
+ }
109
+ });
110
+ newModuleContent = `${originalContent} if (!global.${common_1.ZERO_COM_SERVER_REGISTRY}) global.${common_1.ZERO_COM_SERVER_REGISTRY} = Object.create(null); ${chunks.join(',')}`;
111
+ }
112
+ project.createSourceFile(absolutePath + '.ts', newModuleContent, { overwrite: true });
113
+ const result = project.emitToMemory();
114
+ const newContent = result.getFiles()[0].text;
115
+ const inlineLoader = `data:text/javascript,${encodeURIComponent(newContent)}`;
116
+ resolveData.request = inlineLoader;
117
+ });
118
+ });
119
+ if (this.options.development)
120
+ return;
121
+ const replacements = [
122
+ { target: common_1.ZERO_COM_CLIENT_SEND, replacement: `__ZERO_COM_CLIENT_SEND_${this.compilationId}` },
123
+ { target: common_1.ZERO_COM_SERVER_REGISTRY, replacement: `__ZERO_COM_SERVER_REGISTRY_${this.compilationId}` }
124
+ ];
125
+ compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
126
+ compilation.hooks.processAssets.tap({ name: pluginName, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE }, (assets) => {
127
+ for (const assetName in assets) {
128
+ if (assetName.endsWith('.js')) {
129
+ let assetSource = String(assets[assetName].source());
130
+ let modified = false;
131
+ replacements.forEach(({ target, replacement }) => {
132
+ if (assetSource.includes(target)) {
133
+ assetSource = assetSource.replaceAll(target, replacement);
134
+ modified = true;
135
+ }
136
+ });
137
+ if (modified) {
138
+ compilation.updateAsset(assetName, new RawSource(assetSource));
139
+ }
140
+ }
141
+ }
142
+ });
143
+ });
144
+ }
145
+ }
146
+ exports.ZeroComWebpackPlugin = ZeroComWebpackPlugin;
package/lib/webpack.ts ADDED
@@ -0,0 +1,167 @@
1
+ import fs from 'fs'
2
+ import { minimatch } from 'minimatch'
3
+ import path from 'path'
4
+ import { ArrowFunction, Project } from 'ts-morph'
5
+ import ts from 'typescript'
6
+ import { Compiler } from 'webpack'
7
+ import { Options, ZERO_COM_CLIENT_SEND, ZERO_COM_SERVER_REGISTRY, formatFuncIdName } from './common'
8
+
9
+ export type Message = {
10
+ funcId: string,
11
+ params: any[],
12
+ [key: string]: any
13
+ }
14
+
15
+ export class ZeroComWebpackPlugin {
16
+ private options: Options
17
+ private compilationId: string
18
+ private clientPattern: string
19
+ private serverPattern: string
20
+
21
+ constructor(options: Options) {
22
+ this.options = {
23
+ development: true,
24
+ ...options,
25
+ patterns: {
26
+ ...options.patterns
27
+ }
28
+ }
29
+ this.compilationId = String(Math.floor(Math.random() * 1000000))
30
+ this.clientPattern = this.options.patterns.client
31
+ this.serverPattern = this.options.patterns.server
32
+ }
33
+
34
+ apply(compiler: Compiler) {
35
+ const pluginName = ZeroComWebpackPlugin.name
36
+ const { webpack } = compiler
37
+ const { RawSource } = webpack.sources
38
+
39
+ compiler.hooks.normalModuleFactory.tap(pluginName, (nmf) => {
40
+ nmf.hooks.beforeResolve.tap(pluginName, (resolveData) => {
41
+ const absolutePath = path.resolve(resolveData.context, resolveData.request)
42
+ const isServerFile = minimatch(absolutePath, path.join(compiler.context, this.serverPattern))
43
+ if (!isServerFile) return
44
+
45
+ const requestedFromClient = minimatch(resolveData.contextInfo.issuer, path.join(compiler.context, this.clientPattern))
46
+
47
+ const tsPath = absolutePath + '.ts'
48
+ const jsPath = absolutePath + '.js'
49
+ const mjsPath = absolutePath + '.mjs'
50
+ let resolvedPath = ''
51
+
52
+ if (fs.existsSync(tsPath)) {
53
+ resolvedPath = tsPath
54
+ } else if (fs.existsSync(jsPath)) {
55
+ resolvedPath = jsPath
56
+ } else if (fs.existsSync(mjsPath)) {
57
+ resolvedPath = mjsPath
58
+ } else {
59
+ throw new Error('Unable to resolve: ' + absolutePath)
60
+ }
61
+
62
+ const originalContent = fs.readFileSync(resolvedPath, 'utf8')
63
+
64
+ const project = new Project({
65
+ compilerOptions: {
66
+ target: ts.ScriptTarget.ES2017,
67
+ module: ts.ModuleKind.ESNext,
68
+ },
69
+ })
70
+
71
+ const sourceFile = project.createSourceFile(absolutePath, originalContent, { overwrite: true })
72
+ let newModuleContent = ''
73
+
74
+ if (requestedFromClient) {
75
+ const generatedFunctions: string[] = []
76
+ sourceFile.getFunctions().forEach(func => {
77
+ if (func.isExported() && func.isAsync()) {
78
+ const funcName = String(func.getName())
79
+ const lineNumber = func.getStartLineNumber()
80
+ const funcParams = func.getParameters().map(p => p.getName()).join(', ')
81
+ const funcId = formatFuncIdName(funcName, path.relative(compiler.context, absolutePath), lineNumber)
82
+ const newFunctionBody = `return window.${ZERO_COM_CLIENT_SEND}({funcId: '${funcId}', params: [${funcParams}]})`
83
+ func.setBodyText(newFunctionBody)
84
+ generatedFunctions.push(func.getText())
85
+ console.log('client:', funcId)
86
+ }
87
+ })
88
+ sourceFile.getVariableDeclarations().forEach(decl => {
89
+ const initializer = decl.getInitializer()
90
+ if (initializer && initializer instanceof ArrowFunction) {
91
+ if (decl.isExported() && initializer.isAsync()) {
92
+ const funcName = decl.getName()
93
+ const lineNumber = decl.getStartLineNumber()
94
+ const funcParams = initializer.getParameters().map(p => p.getName()).join(', ')
95
+ const funcId = formatFuncIdName(funcName, path.relative(compiler.context, absolutePath), lineNumber)
96
+ const newFunctionBody = `return window.${ZERO_COM_CLIENT_SEND}({funcId: '${funcId}', params: [${funcParams}]})`
97
+ initializer.setBodyText(newFunctionBody)
98
+ generatedFunctions.push(decl.getVariableStatementOrThrow().getText())
99
+ console.log('client:', funcId)
100
+ }
101
+ }
102
+ })
103
+ newModuleContent = generatedFunctions.join('\n\n')
104
+ } else {
105
+ const chunks: string[] = []
106
+ sourceFile.getFunctions().forEach(func => {
107
+ if (func.isExported() && func.isAsync()) {
108
+ const funcName = String(func.getName())
109
+ const lineNumber = func.getStartLineNumber()
110
+ const funcId = formatFuncIdName(funcName, path.relative(compiler.context, absolutePath), lineNumber)
111
+ chunks.push(`global.${ZERO_COM_SERVER_REGISTRY}['${funcId}'] = ${funcName}`)
112
+ console.log('server:', funcId)
113
+ }
114
+ })
115
+ sourceFile.getVariableDeclarations().forEach(decl => {
116
+ const initializer = decl.getInitializer()
117
+ if (initializer && initializer instanceof ArrowFunction) {
118
+ if (decl.isExported() && initializer.isAsync()) {
119
+ const funcName = decl.getName()
120
+ const lineNumber = decl.getStartLineNumber()
121
+ const funcId = formatFuncIdName(funcName, path.relative(compiler.context, absolutePath), lineNumber)
122
+ chunks.push(`global.${ZERO_COM_SERVER_REGISTRY}['${funcId}'] = ${funcName}`)
123
+ console.log('server:', funcId)
124
+ }
125
+ }
126
+ })
127
+ newModuleContent = `${originalContent} if (!global.${ZERO_COM_SERVER_REGISTRY}) global.${ZERO_COM_SERVER_REGISTRY} = Object.create(null); ${chunks.join(',')}`
128
+ }
129
+
130
+ project.createSourceFile(absolutePath + '.ts', newModuleContent, { overwrite: true })
131
+ const result = project.emitToMemory()
132
+ const newContent = result.getFiles()[0].text
133
+ const inlineLoader = `data:text/javascript,${encodeURIComponent(newContent)}`
134
+ resolveData.request = inlineLoader
135
+ })
136
+ })
137
+
138
+ if (this.options.development) return
139
+
140
+ const replacements = [
141
+ { target: ZERO_COM_CLIENT_SEND, replacement: `__ZERO_COM_CLIENT_SEND_${this.compilationId}` },
142
+ { target: ZERO_COM_SERVER_REGISTRY, replacement: `__ZERO_COM_SERVER_REGISTRY_${this.compilationId}` }
143
+ ]
144
+
145
+ compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
146
+ compilation.hooks.processAssets.tap({ name: pluginName, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE }, (assets) => {
147
+ for (const assetName in assets) {
148
+ if (assetName.endsWith('.js')) {
149
+ let assetSource = String(assets[assetName].source())
150
+ let modified = false
151
+ replacements.forEach(({ target, replacement }) => {
152
+ if (assetSource.includes(target)) {
153
+ assetSource = assetSource.replaceAll(target, replacement)
154
+ modified = true
155
+ }
156
+ })
157
+ if (modified) {
158
+ compilation.updateAsset(assetName, new RawSource(assetSource))
159
+ }
160
+ }
161
+ }
162
+
163
+ })
164
+ })
165
+
166
+ }
167
+ }