@walkeros/cli 0.3.1
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 +45 -0
- package/README.md +285 -0
- package/dist/__tests__/bundle/bundler-integration.test.d.ts +2 -0
- package/dist/__tests__/bundle/bundler-integration.test.d.ts.map +1 -0
- package/dist/__tests__/bundle/bundler-integration.test.js +106 -0
- package/dist/__tests__/bundle/bundler-integration.test.js.map +1 -0
- package/dist/__tests__/bundle/bundler.test.d.ts +2 -0
- package/dist/__tests__/bundle/bundler.test.d.ts.map +1 -0
- package/dist/__tests__/bundle/bundler.test.js +281 -0
- package/dist/__tests__/bundle/bundler.test.js.map +1 -0
- package/dist/__tests__/bundle/programmatic.test.d.ts +2 -0
- package/dist/__tests__/bundle/programmatic.test.d.ts.map +1 -0
- package/dist/__tests__/bundle/programmatic.test.js +118 -0
- package/dist/__tests__/bundle/programmatic.test.js.map +1 -0
- package/dist/__tests__/bundle/serializer.test.d.ts +2 -0
- package/dist/__tests__/bundle/serializer.test.d.ts.map +1 -0
- package/dist/__tests__/bundle/serializer.test.js +173 -0
- package/dist/__tests__/bundle/serializer.test.js.map +1 -0
- package/dist/__tests__/bundle/template-engine.test.d.ts +2 -0
- package/dist/__tests__/bundle/template-engine.test.d.ts.map +1 -0
- package/dist/__tests__/bundle/template-engine.test.js +107 -0
- package/dist/__tests__/bundle/template-engine.test.js.map +1 -0
- package/dist/__tests__/cli-e2e.test.d.ts +8 -0
- package/dist/__tests__/cli-e2e.test.d.ts.map +1 -0
- package/dist/__tests__/cli-e2e.test.js +144 -0
- package/dist/__tests__/cli-e2e.test.js.map +1 -0
- package/dist/__tests__/cli.test.d.ts +2 -0
- package/dist/__tests__/cli.test.d.ts.map +1 -0
- package/dist/__tests__/cli.test.js +255 -0
- package/dist/__tests__/cli.test.js.map +1 -0
- package/dist/__tests__/config-loader.test.d.ts +7 -0
- package/dist/__tests__/config-loader.test.d.ts.map +1 -0
- package/dist/__tests__/config-loader.test.js +393 -0
- package/dist/__tests__/config-loader.test.js.map +1 -0
- package/dist/__tests__/core/config.test.d.ts +2 -0
- package/dist/__tests__/core/config.test.d.ts.map +1 -0
- package/dist/__tests__/core/config.test.js +72 -0
- package/dist/__tests__/core/config.test.js.map +1 -0
- package/dist/__tests__/core/logger.test.d.ts +2 -0
- package/dist/__tests__/core/logger.test.d.ts.map +1 -0
- package/dist/__tests__/core/logger.test.js +53 -0
- package/dist/__tests__/core/logger.test.js.map +1 -0
- package/dist/__tests__/simulate/programmatic.test.d.ts +2 -0
- package/dist/__tests__/simulate/programmatic.test.d.ts.map +1 -0
- package/dist/__tests__/simulate/programmatic.test.js +51 -0
- package/dist/__tests__/simulate/programmatic.test.js.map +1 -0
- package/dist/__tests__/simulate/simulator.test.d.ts +2 -0
- package/dist/__tests__/simulate/simulator.test.d.ts.map +1 -0
- package/dist/__tests__/simulate/simulator.test.js +29 -0
- package/dist/__tests__/simulate/simulator.test.js.map +1 -0
- package/dist/commands/bundle/bundler.d.ts +14 -0
- package/dist/commands/bundle/bundler.d.ts.map +1 -0
- package/dist/commands/bundle/bundler.js +372 -0
- package/dist/commands/bundle/bundler.js.map +1 -0
- package/dist/commands/bundle/index.d.ts +51 -0
- package/dist/commands/bundle/index.d.ts.map +1 -0
- package/dist/commands/bundle/index.js +200 -0
- package/dist/commands/bundle/index.js.map +1 -0
- package/dist/commands/bundle/package-manager.d.ts +7 -0
- package/dist/commands/bundle/package-manager.d.ts.map +1 -0
- package/dist/commands/bundle/package-manager.js +170 -0
- package/dist/commands/bundle/package-manager.js.map +1 -0
- package/dist/commands/bundle/serializer.d.ts +23 -0
- package/dist/commands/bundle/serializer.d.ts.map +1 -0
- package/dist/commands/bundle/serializer.js +127 -0
- package/dist/commands/bundle/serializer.js.map +1 -0
- package/dist/commands/bundle/stats.d.ts +23 -0
- package/dist/commands/bundle/stats.d.ts.map +1 -0
- package/dist/commands/bundle/stats.js +52 -0
- package/dist/commands/bundle/stats.js.map +1 -0
- package/dist/commands/bundle/template-engine.d.ts +18 -0
- package/dist/commands/bundle/template-engine.d.ts.map +1 -0
- package/dist/commands/bundle/template-engine.js +49 -0
- package/dist/commands/bundle/template-engine.js.map +1 -0
- package/dist/commands/run/__tests__/run.integration.test.d.ts +8 -0
- package/dist/commands/run/__tests__/run.integration.test.d.ts.map +1 -0
- package/dist/commands/run/__tests__/run.integration.test.js +53 -0
- package/dist/commands/run/__tests__/run.integration.test.js.map +1 -0
- package/dist/commands/run/__tests__/validators.test.d.ts +2 -0
- package/dist/commands/run/__tests__/validators.test.d.ts.map +1 -0
- package/dist/commands/run/__tests__/validators.test.js +80 -0
- package/dist/commands/run/__tests__/validators.test.js.map +1 -0
- package/dist/commands/run/index.d.ts +39 -0
- package/dist/commands/run/index.d.ts.map +1 -0
- package/dist/commands/run/index.js +251 -0
- package/dist/commands/run/index.js.map +1 -0
- package/dist/commands/run/types.d.ts +56 -0
- package/dist/commands/run/types.d.ts.map +1 -0
- package/dist/commands/run/types.js +7 -0
- package/dist/commands/run/types.js.map +1 -0
- package/dist/commands/run/validators.d.ts +29 -0
- package/dist/commands/run/validators.d.ts.map +1 -0
- package/dist/commands/run/validators.js +54 -0
- package/dist/commands/run/validators.js.map +1 -0
- package/dist/commands/simulate/index.d.ts +47 -0
- package/dist/commands/simulate/index.d.ts.map +1 -0
- package/dist/commands/simulate/index.js +121 -0
- package/dist/commands/simulate/index.js.map +1 -0
- package/dist/commands/simulate/simulator.d.ts +18 -0
- package/dist/commands/simulate/simulator.d.ts.map +1 -0
- package/dist/commands/simulate/simulator.js +236 -0
- package/dist/commands/simulate/simulator.js.map +1 -0
- package/dist/commands/simulate/tracker.d.ts +30 -0
- package/dist/commands/simulate/tracker.d.ts.map +1 -0
- package/dist/commands/simulate/tracker.js +96 -0
- package/dist/commands/simulate/tracker.js.map +1 -0
- package/dist/commands/simulate/types.d.ts +18 -0
- package/dist/commands/simulate/types.d.ts.map +1 -0
- package/dist/commands/simulate/types.js +2 -0
- package/dist/commands/simulate/types.js.map +1 -0
- package/dist/config/defaults.d.ts +33 -0
- package/dist/config/defaults.d.ts.map +1 -0
- package/dist/config/defaults.js +73 -0
- package/dist/config/defaults.js.map +1 -0
- package/dist/config/index.d.ts +14 -0
- package/dist/config/index.d.ts.map +1 -0
- package/dist/config/index.js +16 -0
- package/dist/config/index.js.map +1 -0
- package/dist/config/loader.d.ts +74 -0
- package/dist/config/loader.d.ts.map +1 -0
- package/dist/config/loader.js +136 -0
- package/dist/config/loader.js.map +1 -0
- package/dist/config/parser.d.ts +64 -0
- package/dist/config/parser.d.ts.map +1 -0
- package/dist/config/parser.js +137 -0
- package/dist/config/parser.js.map +1 -0
- package/dist/config/utils.d.ts +38 -0
- package/dist/config/utils.d.ts.map +1 -0
- package/dist/config/utils.js +66 -0
- package/dist/config/utils.js.map +1 -0
- package/dist/config/validators.d.ts +23 -0
- package/dist/config/validators.d.ts.map +1 -0
- package/dist/config/validators.js +45 -0
- package/dist/config/validators.js.map +1 -0
- package/dist/core/docker.d.ts +42 -0
- package/dist/core/docker.d.ts.map +1 -0
- package/dist/core/docker.js +114 -0
- package/dist/core/docker.js.map +1 -0
- package/dist/core/execution.d.ts +33 -0
- package/dist/core/execution.d.ts.map +1 -0
- package/dist/core/execution.js +57 -0
- package/dist/core/execution.js.map +1 -0
- package/dist/core/index.d.ts +6 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +6 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/logger.d.ts +17 -0
- package/dist/core/logger.d.ts.map +1 -0
- package/dist/core/logger.js +74 -0
- package/dist/core/logger.js.map +1 -0
- package/dist/core/output.d.ts +30 -0
- package/dist/core/output.d.ts.map +1 -0
- package/dist/core/output.js +46 -0
- package/dist/core/output.js.map +1 -0
- package/dist/core/timer.d.ts +14 -0
- package/dist/core/timer.d.ts.map +1 -0
- package/dist/core/timer.js +29 -0
- package/dist/core/timer.js.map +1 -0
- package/dist/index.d.ts +614 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1940 -0
- package/dist/index.js.map +1 -0
- package/dist/types/bundle.d.ts +251 -0
- package/dist/types/bundle.d.ts.map +1 -0
- package/dist/types/bundle.js +10 -0
- package/dist/types/bundle.js.map +1 -0
- package/dist/types/global.d.ts +51 -0
- package/dist/types/global.d.ts.map +1 -0
- package/dist/types/global.js +30 -0
- package/dist/types/global.js.map +1 -0
- package/dist/types/index.d.ts +8 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +8 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/template.d.ts +108 -0
- package/dist/types/template.d.ts.map +1 -0
- package/dist/types/template.js +10 -0
- package/dist/types/template.js.map +1 -0
- package/package.json +59 -0
- package/templates/base.hbs +44 -0
- package/templates/server.hbs +29 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1940 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { Command } from "commander";
|
|
5
|
+
|
|
6
|
+
// src/commands/bundle/index.ts
|
|
7
|
+
import path6 from "path";
|
|
8
|
+
|
|
9
|
+
// src/core/logger.ts
|
|
10
|
+
import chalk from "chalk";
|
|
11
|
+
function createLogger(options = {}) {
|
|
12
|
+
const { verbose = false, silent = false, json = false } = options;
|
|
13
|
+
const shouldLog = !silent && !json;
|
|
14
|
+
const shouldDebug = verbose && !silent && !json;
|
|
15
|
+
return {
|
|
16
|
+
log: (color, ...args) => {
|
|
17
|
+
if (shouldLog) {
|
|
18
|
+
const message = args.map((arg) => String(arg)).join(" ");
|
|
19
|
+
const colorMap = {
|
|
20
|
+
red: chalk.red,
|
|
21
|
+
green: chalk.green,
|
|
22
|
+
blue: chalk.blue,
|
|
23
|
+
yellow: chalk.yellow,
|
|
24
|
+
gray: chalk.gray,
|
|
25
|
+
grey: chalk.gray,
|
|
26
|
+
cyan: chalk.cyan,
|
|
27
|
+
magenta: chalk.magenta,
|
|
28
|
+
white: chalk.white,
|
|
29
|
+
black: chalk.black
|
|
30
|
+
};
|
|
31
|
+
const colorFn = colorMap[color];
|
|
32
|
+
const coloredMessage = colorFn ? colorFn(message) : message;
|
|
33
|
+
console.log(coloredMessage);
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
info: (...args) => {
|
|
37
|
+
if (shouldLog) {
|
|
38
|
+
const message = args.map((arg) => String(arg)).join(" ");
|
|
39
|
+
console.log(chalk.blue(message));
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
success: (...args) => {
|
|
43
|
+
if (shouldLog) {
|
|
44
|
+
const message = args.map((arg) => String(arg)).join(" ");
|
|
45
|
+
console.log(chalk.green(message));
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
warning: (...args) => {
|
|
49
|
+
if (shouldLog) {
|
|
50
|
+
const message = args.map((arg) => String(arg)).join(" ");
|
|
51
|
+
console.log(chalk.yellow(message));
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
warn: (...args) => {
|
|
55
|
+
if (shouldLog) {
|
|
56
|
+
const message = args.map((arg) => String(arg)).join(" ");
|
|
57
|
+
console.log(chalk.yellow(message));
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
error: (...args) => {
|
|
61
|
+
if (!json) {
|
|
62
|
+
const message = args.map((arg) => String(arg)).join(" ");
|
|
63
|
+
console.error(chalk.red(message));
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
debug: (...args) => {
|
|
67
|
+
if (shouldDebug) {
|
|
68
|
+
const message = args.map((arg) => String(arg)).join(" ");
|
|
69
|
+
console.log(chalk.gray(message));
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
gray: (...args) => {
|
|
73
|
+
if (shouldLog) {
|
|
74
|
+
const message = args.map((arg) => String(arg)).join(" ");
|
|
75
|
+
console.log(chalk.gray(message));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/core/timer.ts
|
|
82
|
+
function createTimer() {
|
|
83
|
+
let startTime = 0;
|
|
84
|
+
let endTime = 0;
|
|
85
|
+
return {
|
|
86
|
+
start() {
|
|
87
|
+
startTime = Date.now();
|
|
88
|
+
endTime = 0;
|
|
89
|
+
},
|
|
90
|
+
end() {
|
|
91
|
+
endTime = Date.now();
|
|
92
|
+
return endTime - startTime;
|
|
93
|
+
},
|
|
94
|
+
getElapsed() {
|
|
95
|
+
const currentTime = endTime || Date.now();
|
|
96
|
+
return currentTime - startTime;
|
|
97
|
+
},
|
|
98
|
+
format() {
|
|
99
|
+
const elapsed = this.getElapsed();
|
|
100
|
+
return (elapsed / 1e3).toFixed(2) + "s";
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// src/core/output.ts
|
|
106
|
+
function createJsonOutput(success, data, error, duration) {
|
|
107
|
+
return {
|
|
108
|
+
success,
|
|
109
|
+
...data && { data },
|
|
110
|
+
...error && { error },
|
|
111
|
+
...duration && { duration }
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function createSuccessOutput(data, duration) {
|
|
115
|
+
return createJsonOutput(true, data, void 0, duration);
|
|
116
|
+
}
|
|
117
|
+
function createErrorOutput(error, duration) {
|
|
118
|
+
return createJsonOutput(false, void 0, error, duration);
|
|
119
|
+
}
|
|
120
|
+
function formatBytes(bytes) {
|
|
121
|
+
return (bytes / 1024).toFixed(2);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// src/core/docker.ts
|
|
125
|
+
import { spawn } from "child_process";
|
|
126
|
+
var DOCKER_IMAGE = process.env.WALKEROS_DOCKER_IMAGE || "walkeros/cli:latest";
|
|
127
|
+
function buildDockerCommand(command, args, options = {}) {
|
|
128
|
+
const cwd = process.cwd();
|
|
129
|
+
const cmd = [
|
|
130
|
+
"docker",
|
|
131
|
+
"run",
|
|
132
|
+
"--rm",
|
|
133
|
+
// Mount current directory
|
|
134
|
+
"-v",
|
|
135
|
+
`${cwd}:/workspace`,
|
|
136
|
+
"-w",
|
|
137
|
+
"/workspace"
|
|
138
|
+
];
|
|
139
|
+
if (process.platform !== "win32") {
|
|
140
|
+
try {
|
|
141
|
+
const uid = process.getuid?.();
|
|
142
|
+
const gid = process.getgid?.();
|
|
143
|
+
if (uid !== void 0 && gid !== void 0) {
|
|
144
|
+
cmd.push("--user", `${uid}:${gid}`);
|
|
145
|
+
}
|
|
146
|
+
} catch {
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (options.verbose) {
|
|
150
|
+
cmd.push("-e", "VERBOSE=true");
|
|
151
|
+
}
|
|
152
|
+
if (options.silent) {
|
|
153
|
+
cmd.push("-e", "SILENT=true");
|
|
154
|
+
}
|
|
155
|
+
cmd.push(DOCKER_IMAGE);
|
|
156
|
+
cmd.push(command, ...args);
|
|
157
|
+
return cmd;
|
|
158
|
+
}
|
|
159
|
+
async function executeInDocker(command, args, options = {}) {
|
|
160
|
+
const dockerCmd = buildDockerCommand(command, args, options);
|
|
161
|
+
return new Promise((resolve2, reject) => {
|
|
162
|
+
const proc = spawn(dockerCmd[0], dockerCmd.slice(1), {
|
|
163
|
+
stdio: options.silent ? "ignore" : "inherit",
|
|
164
|
+
shell: false
|
|
165
|
+
});
|
|
166
|
+
proc.on("error", (error) => {
|
|
167
|
+
reject(new Error(`Docker execution failed: ${error.message}`));
|
|
168
|
+
});
|
|
169
|
+
proc.on("exit", (code) => {
|
|
170
|
+
if (code === 0) {
|
|
171
|
+
resolve2();
|
|
172
|
+
} else {
|
|
173
|
+
reject(new Error(`Docker command exited with code ${code}`));
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
async function isDockerAvailable() {
|
|
179
|
+
return new Promise((resolve2) => {
|
|
180
|
+
const proc = spawn("docker", ["--version"], {
|
|
181
|
+
stdio: "ignore"
|
|
182
|
+
});
|
|
183
|
+
proc.on("error", () => resolve2(false));
|
|
184
|
+
proc.on("exit", (code) => resolve2(code === 0));
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// src/core/execution.ts
|
|
189
|
+
function getExecutionMode(options) {
|
|
190
|
+
return options.local ? "local" : "docker";
|
|
191
|
+
}
|
|
192
|
+
async function executeCommand(localHandler, dockerCommand, dockerArgs, options, logger) {
|
|
193
|
+
const mode = getExecutionMode(options);
|
|
194
|
+
if (options.dryRun) {
|
|
195
|
+
if (mode === "docker") {
|
|
196
|
+
const cmd = `docker run walkeros/cli:latest ${dockerCommand} ${dockerArgs.join(" ")}`;
|
|
197
|
+
logger?.info(`[DRY-RUN] Would execute: ${cmd}`);
|
|
198
|
+
} else {
|
|
199
|
+
logger?.info(
|
|
200
|
+
`[DRY-RUN] Would execute locally: ${dockerCommand} ${dockerArgs.join(" ")}`
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (mode === "local") {
|
|
206
|
+
if (logger && !options.silent) {
|
|
207
|
+
logger.info("\u{1F5A5}\uFE0F Executing locally...");
|
|
208
|
+
}
|
|
209
|
+
await localHandler();
|
|
210
|
+
} else {
|
|
211
|
+
const dockerAvailable = await isDockerAvailable();
|
|
212
|
+
if (!dockerAvailable) {
|
|
213
|
+
throw new Error(
|
|
214
|
+
"Docker is not available. Please install Docker or use --local flag to execute locally."
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
if (logger && !options.silent) {
|
|
218
|
+
logger.info("\u{1F433} Executing in Docker container...");
|
|
219
|
+
}
|
|
220
|
+
await executeInDocker(dockerCommand, dockerArgs, options);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// src/config/validators.ts
|
|
225
|
+
function isObject(value) {
|
|
226
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
|
|
227
|
+
}
|
|
228
|
+
function validatePlatform(platform) {
|
|
229
|
+
return platform === "web" || platform === "server";
|
|
230
|
+
}
|
|
231
|
+
function isMultiEnvConfig(data) {
|
|
232
|
+
return isObject(data) && "version" in data && data.version === 1 && "environments" in data && isObject(data.environments);
|
|
233
|
+
}
|
|
234
|
+
function isSingleEnvConfig(data) {
|
|
235
|
+
return isObject(data) && "flow" in data && "build" in data && isObject(data.flow) && isObject(data.build) && "platform" in data.flow && validatePlatform(data.flow.platform);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// src/config/utils.ts
|
|
239
|
+
import fs from "fs-extra";
|
|
240
|
+
import path from "path";
|
|
241
|
+
async function loadJsonConfig(configPath) {
|
|
242
|
+
const absolutePath = path.resolve(configPath);
|
|
243
|
+
if (!await fs.pathExists(absolutePath)) {
|
|
244
|
+
throw new Error(`Configuration file not found: ${absolutePath}`);
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
const rawConfig = await fs.readJson(absolutePath);
|
|
248
|
+
return rawConfig;
|
|
249
|
+
} catch (error) {
|
|
250
|
+
throw new Error(
|
|
251
|
+
`Invalid JSON in config file: ${configPath}. ${error instanceof Error ? error.message : error}`
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
function getTempDir(tempDir = ".tmp") {
|
|
256
|
+
const randomId = Math.random().toString(36).substring(2, 11);
|
|
257
|
+
const basePath = path.isAbsolute(tempDir) ? tempDir : path.join(process.cwd(), tempDir);
|
|
258
|
+
return path.join(basePath, `cli-${Date.now()}-${randomId}`);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// src/config/defaults.ts
|
|
262
|
+
function getDefaultBuildOptions(platform, code, output) {
|
|
263
|
+
const common = {
|
|
264
|
+
code,
|
|
265
|
+
packages: {},
|
|
266
|
+
minify: false,
|
|
267
|
+
sourcemap: false,
|
|
268
|
+
cache: true
|
|
269
|
+
};
|
|
270
|
+
if (platform === "web") {
|
|
271
|
+
return {
|
|
272
|
+
...common,
|
|
273
|
+
platform: "browser",
|
|
274
|
+
format: "iife",
|
|
275
|
+
target: "es2020",
|
|
276
|
+
output: output || "./dist/walker.js",
|
|
277
|
+
globalName: "walkerOS"
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
return {
|
|
281
|
+
...common,
|
|
282
|
+
platform: "node",
|
|
283
|
+
format: "esm",
|
|
284
|
+
target: "node18",
|
|
285
|
+
output: output || "./dist/bundle.js"
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function ensureBuildOptions(buildOptions, flowPlatform) {
|
|
289
|
+
const defaults = getDefaultBuildOptions(
|
|
290
|
+
flowPlatform,
|
|
291
|
+
buildOptions.code || "",
|
|
292
|
+
buildOptions.output
|
|
293
|
+
);
|
|
294
|
+
if (!buildOptions.code && !defaults.code) {
|
|
295
|
+
throw new Error("BuildOptions.code is required");
|
|
296
|
+
}
|
|
297
|
+
if (!buildOptions.output && !defaults.output) {
|
|
298
|
+
throw new Error("BuildOptions.output is required");
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
...defaults,
|
|
302
|
+
...buildOptions,
|
|
303
|
+
code: buildOptions.code || defaults.code,
|
|
304
|
+
output: buildOptions.output || defaults.output,
|
|
305
|
+
packages: buildOptions.packages || defaults.packages
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// src/config/parser.ts
|
|
310
|
+
import path2 from "path";
|
|
311
|
+
function parseBundleConfig(data) {
|
|
312
|
+
if (!isObject(data)) {
|
|
313
|
+
throw new Error(`Invalid config: expected object, got ${typeof data}`);
|
|
314
|
+
}
|
|
315
|
+
if (!("flow" in data) || !isObject(data.flow)) {
|
|
316
|
+
throw new Error(
|
|
317
|
+
`Invalid config: missing "flow" field. Expected format: { flow: { platform: "web" | "server", ... }, build: { ... } }`
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
if (!("build" in data) || !isObject(data.build)) {
|
|
321
|
+
throw new Error(
|
|
322
|
+
`Invalid config: missing "build" field. Expected format: { flow: { platform: "web" | "server", ... }, build: { ... } }`
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
const flowData = data.flow;
|
|
326
|
+
if (!("platform" in flowData) || flowData.platform !== "web" && flowData.platform !== "server") {
|
|
327
|
+
throw new Error(
|
|
328
|
+
`Invalid config: flow.platform must be "web" or "server", got "${flowData.platform}"`
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
const buildData = data.build;
|
|
332
|
+
if ("packages" in buildData && !isObject(buildData.packages)) {
|
|
333
|
+
throw new Error(
|
|
334
|
+
`Invalid config: build.packages must be an object, got ${typeof buildData.packages}`
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
const config = data;
|
|
338
|
+
return normalizeConfigs(config, "/unknown/path");
|
|
339
|
+
}
|
|
340
|
+
function normalizeConfigs(config, configPath) {
|
|
341
|
+
const flowConfig = config.flow;
|
|
342
|
+
const platform = flowConfig.platform;
|
|
343
|
+
if (!validatePlatform(platform)) {
|
|
344
|
+
throw new Error(
|
|
345
|
+
`Invalid platform "${platform}". Must be "web" or "server".`
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
const buildDefaults = platform === "web" ? {
|
|
349
|
+
platform: "browser",
|
|
350
|
+
format: "iife",
|
|
351
|
+
target: "es2020",
|
|
352
|
+
minify: false,
|
|
353
|
+
sourcemap: false,
|
|
354
|
+
tempDir: ".tmp",
|
|
355
|
+
cache: true
|
|
356
|
+
} : {
|
|
357
|
+
platform: "node",
|
|
358
|
+
format: "esm",
|
|
359
|
+
target: "node20",
|
|
360
|
+
minify: false,
|
|
361
|
+
sourcemap: false,
|
|
362
|
+
tempDir: ".tmp",
|
|
363
|
+
cache: true
|
|
364
|
+
};
|
|
365
|
+
const buildConfig = {
|
|
366
|
+
...buildDefaults,
|
|
367
|
+
...config.build
|
|
368
|
+
};
|
|
369
|
+
if (configPath && buildConfig.template && !path2.isAbsolute(buildConfig.template)) {
|
|
370
|
+
if (buildConfig.template.startsWith("./") || buildConfig.template.startsWith("../")) {
|
|
371
|
+
const configDir = path2.dirname(configPath);
|
|
372
|
+
buildConfig.template = path2.resolve(configDir, buildConfig.template);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
const buildOptions = ensureBuildOptions(buildConfig, platform);
|
|
376
|
+
return {
|
|
377
|
+
flowConfig,
|
|
378
|
+
buildOptions
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// src/config/loader.ts
|
|
383
|
+
function loadBundleConfig(rawConfig, options) {
|
|
384
|
+
if (isMultiEnvConfig(rawConfig)) {
|
|
385
|
+
return loadMultiEnvironmentConfig(rawConfig, options);
|
|
386
|
+
}
|
|
387
|
+
if (isSingleEnvConfig(rawConfig)) {
|
|
388
|
+
return loadSingleEnvironmentConfig(rawConfig, options);
|
|
389
|
+
}
|
|
390
|
+
const configType = isObject(rawConfig) ? "platform" in rawConfig ? `invalid platform value: "${rawConfig.platform}"` : 'missing "flow" and "build" fields' : `not an object (got ${typeof rawConfig})`;
|
|
391
|
+
throw new Error(
|
|
392
|
+
`Invalid configuration format at ${options.configPath}.
|
|
393
|
+
Configuration ${configType}.
|
|
394
|
+
|
|
395
|
+
Expected either:
|
|
396
|
+
1. Multi-environment: { version: 1, environments: { prod: { flow: {...}, build: {...} } } }
|
|
397
|
+
2. Single-environment: { flow: { platform: "web" | "server", ... }, build: { packages: {...}, ... } }`
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
function loadMultiEnvironmentConfig(setup, options) {
|
|
401
|
+
const availableEnvironments = Object.keys(setup.environments);
|
|
402
|
+
if (!options.environment) {
|
|
403
|
+
throw new Error(
|
|
404
|
+
`Multi-environment configuration detected. Please specify an environment using --env flag.
|
|
405
|
+
Available environments: ${availableEnvironments.join(", ")}`
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
const selectedEnv = options.environment;
|
|
409
|
+
if (!setup.environments[selectedEnv]) {
|
|
410
|
+
throw new Error(
|
|
411
|
+
`Environment "${selectedEnv}" not found in configuration.
|
|
412
|
+
Available environments: ${availableEnvironments.join(", ")}`
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
const envConfig = setup.environments[selectedEnv];
|
|
416
|
+
const { flowConfig, buildOptions } = normalizeConfigs(
|
|
417
|
+
envConfig,
|
|
418
|
+
options.configPath
|
|
419
|
+
);
|
|
420
|
+
if (options.logger) {
|
|
421
|
+
options.logger.info(
|
|
422
|
+
`\u{1F4E6} Using environment: ${selectedEnv} (${availableEnvironments.length} total)`
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
return {
|
|
426
|
+
flowConfig,
|
|
427
|
+
buildOptions,
|
|
428
|
+
environment: selectedEnv,
|
|
429
|
+
isMultiEnvironment: true,
|
|
430
|
+
availableEnvironments
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
function loadSingleEnvironmentConfig(config, options) {
|
|
434
|
+
const { flowConfig, buildOptions } = normalizeConfigs(
|
|
435
|
+
config,
|
|
436
|
+
options.configPath
|
|
437
|
+
);
|
|
438
|
+
if (options.logger && options.environment) {
|
|
439
|
+
options.logger.warn(
|
|
440
|
+
`--env flag specified but configuration is single-environment. Ignoring flag.`
|
|
441
|
+
);
|
|
442
|
+
}
|
|
443
|
+
return {
|
|
444
|
+
flowConfig,
|
|
445
|
+
buildOptions,
|
|
446
|
+
environment: "default",
|
|
447
|
+
isMultiEnvironment: false
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
function loadAllEnvironments(rawConfig, options) {
|
|
451
|
+
if (!isMultiEnvConfig(rawConfig)) {
|
|
452
|
+
throw new Error(
|
|
453
|
+
`--all flag requires a multi-environment configuration (Setup format).
|
|
454
|
+
Your configuration appears to be single-environment.`
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
const setup = rawConfig;
|
|
458
|
+
const environments = Object.keys(setup.environments);
|
|
459
|
+
if (options.logger) {
|
|
460
|
+
options.logger.info(
|
|
461
|
+
`\u{1F4E6} Loading all ${environments.length} environments: ${environments.join(", ")}`
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
return environments.map(
|
|
465
|
+
(envName) => loadMultiEnvironmentConfig(setup, {
|
|
466
|
+
...options,
|
|
467
|
+
environment: envName
|
|
468
|
+
})
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// src/commands/bundle/bundler.ts
|
|
473
|
+
import esbuild from "esbuild";
|
|
474
|
+
import path5 from "path";
|
|
475
|
+
import fs4 from "fs-extra";
|
|
476
|
+
|
|
477
|
+
// src/commands/bundle/package-manager.ts
|
|
478
|
+
import pacote from "pacote";
|
|
479
|
+
import path3 from "path";
|
|
480
|
+
import fs2 from "fs-extra";
|
|
481
|
+
function getPackageDirectory(baseDir, packageName, version) {
|
|
482
|
+
return path3.join(baseDir, "node_modules", packageName);
|
|
483
|
+
}
|
|
484
|
+
function getCachedPackagePath(pkg, tempDir) {
|
|
485
|
+
const cacheDir = path3.join(".tmp", "cache", "packages");
|
|
486
|
+
const safeName = pkg.name.replace(/\//g, "-").replace(/@/g, "");
|
|
487
|
+
return path3.join(cacheDir, `${safeName}-${pkg.version}`);
|
|
488
|
+
}
|
|
489
|
+
async function isPackageCached(pkg, tempDir) {
|
|
490
|
+
const cachedPath = getCachedPackagePath(pkg, tempDir);
|
|
491
|
+
return fs2.pathExists(cachedPath);
|
|
492
|
+
}
|
|
493
|
+
function validateNoDuplicatePackages(packages) {
|
|
494
|
+
const packageMap = /* @__PURE__ */ new Map();
|
|
495
|
+
for (const pkg of packages) {
|
|
496
|
+
if (!packageMap.has(pkg.name)) {
|
|
497
|
+
packageMap.set(pkg.name, []);
|
|
498
|
+
}
|
|
499
|
+
packageMap.get(pkg.name).push(pkg.version);
|
|
500
|
+
}
|
|
501
|
+
const conflicts = [];
|
|
502
|
+
for (const [name, versions] of packageMap.entries()) {
|
|
503
|
+
const uniqueVersions = [...new Set(versions)];
|
|
504
|
+
if (uniqueVersions.length > 1) {
|
|
505
|
+
conflicts.push(`${name}: [${uniqueVersions.join(", ")}]`);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
if (conflicts.length > 0) {
|
|
509
|
+
throw new Error(
|
|
510
|
+
`Version conflicts detected:
|
|
511
|
+
${conflicts.map((c) => ` - ${c}`).join("\n")}
|
|
512
|
+
|
|
513
|
+
Each package must use the same version across all declarations. Please update your configuration to use consistent versions.`
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
async function resolveDependencies(pkg, packageDir, logger, visited = /* @__PURE__ */ new Set()) {
|
|
518
|
+
const dependencies = [];
|
|
519
|
+
const pkgKey = `${pkg.name}@${pkg.version}`;
|
|
520
|
+
if (visited.has(pkgKey)) {
|
|
521
|
+
return dependencies;
|
|
522
|
+
}
|
|
523
|
+
visited.add(pkgKey);
|
|
524
|
+
try {
|
|
525
|
+
const packageJsonPath = path3.join(packageDir, "package.json");
|
|
526
|
+
if (await fs2.pathExists(packageJsonPath)) {
|
|
527
|
+
const packageJson = await fs2.readJson(packageJsonPath);
|
|
528
|
+
const deps = {
|
|
529
|
+
...packageJson.dependencies,
|
|
530
|
+
...packageJson.peerDependencies
|
|
531
|
+
};
|
|
532
|
+
for (const [name, versionSpec] of Object.entries(deps)) {
|
|
533
|
+
if (typeof versionSpec === "string") {
|
|
534
|
+
dependencies.push({ name, version: versionSpec });
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
} catch (error) {
|
|
539
|
+
logger.debug(`Failed to read dependencies for ${pkgKey}: ${error}`);
|
|
540
|
+
}
|
|
541
|
+
return dependencies;
|
|
542
|
+
}
|
|
543
|
+
async function downloadPackages(packages, targetDir, logger, useCache = true) {
|
|
544
|
+
const packagePaths = /* @__PURE__ */ new Map();
|
|
545
|
+
const downloadQueue = [...packages];
|
|
546
|
+
const processed = /* @__PURE__ */ new Set();
|
|
547
|
+
validateNoDuplicatePackages(packages);
|
|
548
|
+
await fs2.ensureDir(targetDir);
|
|
549
|
+
while (downloadQueue.length > 0) {
|
|
550
|
+
const pkg = downloadQueue.shift();
|
|
551
|
+
const pkgKey = `${pkg.name}@${pkg.version}`;
|
|
552
|
+
if (processed.has(pkgKey)) {
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
processed.add(pkgKey);
|
|
556
|
+
const packageSpec = `${pkg.name}@${pkg.version}`;
|
|
557
|
+
const packageDir = getPackageDirectory(targetDir, pkg.name, pkg.version);
|
|
558
|
+
const cachedPath = getCachedPackagePath(pkg, targetDir);
|
|
559
|
+
if (useCache && await isPackageCached(pkg, targetDir)) {
|
|
560
|
+
logger.debug(`Using cached ${packageSpec}...`);
|
|
561
|
+
try {
|
|
562
|
+
await fs2.ensureDir(path3.dirname(packageDir));
|
|
563
|
+
await fs2.copy(cachedPath, packageDir);
|
|
564
|
+
packagePaths.set(pkg.name, packageDir);
|
|
565
|
+
const deps = await resolveDependencies(pkg, packageDir, logger);
|
|
566
|
+
for (const dep of deps) {
|
|
567
|
+
const depKey = `${dep.name}@${dep.version}`;
|
|
568
|
+
if (!processed.has(depKey)) {
|
|
569
|
+
downloadQueue.push(dep);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
continue;
|
|
573
|
+
} catch (error) {
|
|
574
|
+
logger.debug(
|
|
575
|
+
`Failed to use cache for ${packageSpec}, downloading fresh: ${error}`
|
|
576
|
+
);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
logger.debug(`Downloading ${packageSpec}...`);
|
|
580
|
+
try {
|
|
581
|
+
await fs2.ensureDir(path3.dirname(packageDir));
|
|
582
|
+
const cacheDir = process.env.NPM_CACHE_DIR || path3.join(process.cwd(), ".npm-cache");
|
|
583
|
+
await pacote.extract(packageSpec, packageDir, {
|
|
584
|
+
// Force npm registry download, prevent workspace resolution
|
|
585
|
+
registry: "https://registry.npmjs.org",
|
|
586
|
+
// Force online fetching from registry (don't use cached workspace packages)
|
|
587
|
+
preferOnline: true,
|
|
588
|
+
// Cache for performance
|
|
589
|
+
cache: cacheDir,
|
|
590
|
+
// Don't resolve relative to workspace context
|
|
591
|
+
where: void 0
|
|
592
|
+
});
|
|
593
|
+
if (useCache) {
|
|
594
|
+
try {
|
|
595
|
+
await fs2.ensureDir(path3.dirname(cachedPath));
|
|
596
|
+
await fs2.copy(packageDir, cachedPath);
|
|
597
|
+
logger.debug(`Cached ${packageSpec} for future use`);
|
|
598
|
+
} catch (cacheError) {
|
|
599
|
+
logger.debug(`Failed to cache ${packageSpec}: ${cacheError}`);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
packagePaths.set(pkg.name, packageDir);
|
|
603
|
+
const deps = await resolveDependencies(pkg, packageDir, logger);
|
|
604
|
+
for (const dep of deps) {
|
|
605
|
+
const depKey = `${dep.name}@${dep.version}`;
|
|
606
|
+
if (!processed.has(depKey)) {
|
|
607
|
+
downloadQueue.push(dep);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
} catch (error) {
|
|
611
|
+
throw new Error(`Failed to download ${packageSpec}: ${error}`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
return packagePaths;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/commands/bundle/template-engine.ts
|
|
618
|
+
import fs3 from "fs-extra";
|
|
619
|
+
import path4 from "path";
|
|
620
|
+
import Handlebars from "handlebars";
|
|
621
|
+
|
|
622
|
+
// src/commands/bundle/serializer.ts
|
|
623
|
+
function serializeToJS(value, options = {}) {
|
|
624
|
+
const { indent = 2, singleQuotes = false } = options;
|
|
625
|
+
const quote = singleQuotes ? "'" : '"';
|
|
626
|
+
function serialize(val, currentIndent = 0) {
|
|
627
|
+
if (val === null) return "null";
|
|
628
|
+
if (val === void 0) return "undefined";
|
|
629
|
+
if (typeof val === "boolean" || typeof val === "number") {
|
|
630
|
+
return String(val);
|
|
631
|
+
}
|
|
632
|
+
if (typeof val === "string") {
|
|
633
|
+
if (val.includes("=>")) {
|
|
634
|
+
const arrowPatterns = [
|
|
635
|
+
/^\s*\([^)]*\)\s*=>/,
|
|
636
|
+
// (param) => or () =>
|
|
637
|
+
/^\s*\w+\s*=>/,
|
|
638
|
+
// param =>
|
|
639
|
+
/^\s*\([^)]*\)\s*=>\s*\{/,
|
|
640
|
+
// (param) => {
|
|
641
|
+
/^\s*\w+\s*=>\s*\{/
|
|
642
|
+
// param => {
|
|
643
|
+
];
|
|
644
|
+
if (arrowPatterns.some((pattern) => pattern.test(val))) {
|
|
645
|
+
return val;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return quote + val.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, '\\"') + quote;
|
|
649
|
+
}
|
|
650
|
+
if (Array.isArray(val)) {
|
|
651
|
+
if (val.length === 0) return "[]";
|
|
652
|
+
const nextIndent = currentIndent + indent;
|
|
653
|
+
const spacing = " ".repeat(nextIndent);
|
|
654
|
+
const items = val.map((item) => spacing + serialize(item, nextIndent)).join(",\n");
|
|
655
|
+
return `[
|
|
656
|
+
${items}
|
|
657
|
+
${" ".repeat(currentIndent)}]`;
|
|
658
|
+
}
|
|
659
|
+
if (isObject(val)) {
|
|
660
|
+
const entries = Object.entries(val);
|
|
661
|
+
if (entries.length === 0) return "{}";
|
|
662
|
+
const nextIndent = currentIndent + indent;
|
|
663
|
+
const spacing = " ".repeat(nextIndent);
|
|
664
|
+
const props = entries.map(([key, value2]) => {
|
|
665
|
+
const needsQuotes = /[^a-zA-Z0-9_$]/.test(key) || /^[0-9]/.test(key);
|
|
666
|
+
const keyStr = needsQuotes ? quote + key + quote : key;
|
|
667
|
+
return spacing + keyStr + ": " + serialize(value2, nextIndent);
|
|
668
|
+
}).join(",\n");
|
|
669
|
+
return `{
|
|
670
|
+
${props}
|
|
671
|
+
${" ".repeat(currentIndent)}}`;
|
|
672
|
+
}
|
|
673
|
+
return String(val);
|
|
674
|
+
}
|
|
675
|
+
return serialize(value);
|
|
676
|
+
}
|
|
677
|
+
function serializeConfig(config) {
|
|
678
|
+
if (!config || Object.keys(config).length === 0) {
|
|
679
|
+
return "{}";
|
|
680
|
+
}
|
|
681
|
+
return serializeToJS(config, { indent: 2, singleQuotes: true });
|
|
682
|
+
}
|
|
683
|
+
function processTemplateVariables(variables) {
|
|
684
|
+
const processed = { ...variables };
|
|
685
|
+
if (isObject(processed.sources)) {
|
|
686
|
+
const sourcesObj = processed.sources;
|
|
687
|
+
const processedSources = {};
|
|
688
|
+
for (const [name, source] of Object.entries(sourcesObj)) {
|
|
689
|
+
const typedSource = source;
|
|
690
|
+
const { env: _, ...sourceWithoutEnv } = typedSource;
|
|
691
|
+
processedSources[name] = {
|
|
692
|
+
...sourceWithoutEnv,
|
|
693
|
+
config: isObject(typedSource.config) ? serializeConfig(typedSource.config) : typedSource.config,
|
|
694
|
+
// Pass through string configs unchanged
|
|
695
|
+
...typedSource.env !== void 0 && { env: typedSource.env }
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
processed.sources = processedSources;
|
|
699
|
+
}
|
|
700
|
+
if (isObject(processed.destinations)) {
|
|
701
|
+
const destinationsObj = processed.destinations;
|
|
702
|
+
const processedDestinations = {};
|
|
703
|
+
for (const [name, dest] of Object.entries(destinationsObj)) {
|
|
704
|
+
const typedDest = dest;
|
|
705
|
+
const { env: _, ...destWithoutEnv } = typedDest;
|
|
706
|
+
processedDestinations[name] = {
|
|
707
|
+
...destWithoutEnv,
|
|
708
|
+
config: isObject(typedDest.config) ? serializeConfig(typedDest.config) : typedDest.config,
|
|
709
|
+
...typedDest.env !== void 0 && { env: typedDest.env }
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
processed.destinations = processedDestinations;
|
|
713
|
+
}
|
|
714
|
+
if (isObject(processed.collector)) {
|
|
715
|
+
processed.collector = serializeConfig(
|
|
716
|
+
processed.collector
|
|
717
|
+
);
|
|
718
|
+
}
|
|
719
|
+
return processed;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// src/commands/bundle/template-engine.ts
|
|
723
|
+
var TemplateEngine = class {
|
|
724
|
+
handlebars;
|
|
725
|
+
constructor() {
|
|
726
|
+
this.handlebars = Handlebars.create();
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Load template content from file path
|
|
730
|
+
*/
|
|
731
|
+
async loadTemplate(templatePath) {
|
|
732
|
+
const resolvedPath = path4.resolve(templatePath);
|
|
733
|
+
if (!await fs3.pathExists(resolvedPath)) {
|
|
734
|
+
throw new Error(`Template file not found: ${resolvedPath}`);
|
|
735
|
+
}
|
|
736
|
+
return await fs3.readFile(resolvedPath, "utf-8");
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Apply template with user code and variable substitution
|
|
740
|
+
*/
|
|
741
|
+
applyTemplate(template, userCode, sources, destinations, collector, build) {
|
|
742
|
+
const processedVariables = processTemplateVariables({
|
|
743
|
+
sources,
|
|
744
|
+
destinations,
|
|
745
|
+
collector
|
|
746
|
+
});
|
|
747
|
+
const templateData = {
|
|
748
|
+
CODE: userCode,
|
|
749
|
+
build: build || {},
|
|
750
|
+
...processedVariables
|
|
751
|
+
};
|
|
752
|
+
const compiledTemplate = this.handlebars.compile(template);
|
|
753
|
+
return compiledTemplate(templateData);
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* Process template with user code
|
|
757
|
+
*/
|
|
758
|
+
async process(templatePath, userCode, sources, destinations, collector, build) {
|
|
759
|
+
const template = await this.loadTemplate(templatePath);
|
|
760
|
+
return this.applyTemplate(
|
|
761
|
+
template,
|
|
762
|
+
userCode,
|
|
763
|
+
sources,
|
|
764
|
+
destinations,
|
|
765
|
+
collector,
|
|
766
|
+
build
|
|
767
|
+
);
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
// src/commands/bundle/bundler.ts
|
|
772
|
+
async function bundleCore(flowConfig, buildOptions, logger, showStats = false) {
|
|
773
|
+
const bundleStartTime = Date.now();
|
|
774
|
+
const TEMP_DIR = buildOptions.tempDir ? path5.isAbsolute(buildOptions.tempDir) ? buildOptions.tempDir : path5.resolve(buildOptions.tempDir) : getTempDir();
|
|
775
|
+
try {
|
|
776
|
+
if (!buildOptions.tempDir) {
|
|
777
|
+
await fs4.emptyDir(TEMP_DIR);
|
|
778
|
+
}
|
|
779
|
+
logger.debug("Cleaned temporary directory");
|
|
780
|
+
logger.info("\u{1F4E5} Downloading packages...");
|
|
781
|
+
const packagesArray = Object.entries(buildOptions.packages).map(
|
|
782
|
+
([name, packageConfig]) => ({
|
|
783
|
+
name,
|
|
784
|
+
version: packageConfig.version || "latest"
|
|
785
|
+
})
|
|
786
|
+
);
|
|
787
|
+
const packagePaths = await downloadPackages(
|
|
788
|
+
packagesArray,
|
|
789
|
+
TEMP_DIR,
|
|
790
|
+
logger,
|
|
791
|
+
buildOptions.cache
|
|
792
|
+
);
|
|
793
|
+
for (const [pkgName, pkgPath] of packagePaths.entries()) {
|
|
794
|
+
if (pkgName.startsWith("@walkeros/")) {
|
|
795
|
+
const pkgJsonPath = path5.join(pkgPath, "package.json");
|
|
796
|
+
const pkgJson = await fs4.readJSON(pkgJsonPath);
|
|
797
|
+
if (!pkgJson.exports && pkgJson.module) {
|
|
798
|
+
pkgJson.exports = {
|
|
799
|
+
".": {
|
|
800
|
+
import: pkgJson.module,
|
|
801
|
+
require: pkgJson.main
|
|
802
|
+
}
|
|
803
|
+
};
|
|
804
|
+
await fs4.writeJSON(pkgJsonPath, pkgJson, { spaces: 2 });
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
const packageJsonPath = path5.join(TEMP_DIR, "package.json");
|
|
809
|
+
await fs4.writeFile(
|
|
810
|
+
packageJsonPath,
|
|
811
|
+
JSON.stringify({ type: "module" }, null, 2)
|
|
812
|
+
);
|
|
813
|
+
logger.info("\u{1F4DD} Creating entry point...");
|
|
814
|
+
const entryContent = await createEntryPoint(
|
|
815
|
+
flowConfig,
|
|
816
|
+
buildOptions,
|
|
817
|
+
packagePaths
|
|
818
|
+
);
|
|
819
|
+
const entryPath = path5.join(TEMP_DIR, "entry.js");
|
|
820
|
+
await fs4.writeFile(entryPath, entryContent);
|
|
821
|
+
logger.info("\u26A1 Bundling with esbuild...");
|
|
822
|
+
const outputPath = path5.resolve(buildOptions.output);
|
|
823
|
+
await fs4.ensureDir(path5.dirname(outputPath));
|
|
824
|
+
const esbuildOptions = createEsbuildOptions(
|
|
825
|
+
buildOptions,
|
|
826
|
+
entryPath,
|
|
827
|
+
outputPath,
|
|
828
|
+
TEMP_DIR,
|
|
829
|
+
packagePaths,
|
|
830
|
+
logger
|
|
831
|
+
);
|
|
832
|
+
try {
|
|
833
|
+
await esbuild.build(esbuildOptions);
|
|
834
|
+
} catch (buildError) {
|
|
835
|
+
throw createBuildError(buildError, buildOptions.code);
|
|
836
|
+
}
|
|
837
|
+
logger.gray(`Output: ${outputPath}`);
|
|
838
|
+
let stats;
|
|
839
|
+
if (showStats) {
|
|
840
|
+
stats = await collectBundleStats(
|
|
841
|
+
outputPath,
|
|
842
|
+
buildOptions.packages,
|
|
843
|
+
bundleStartTime,
|
|
844
|
+
entryContent
|
|
845
|
+
);
|
|
846
|
+
}
|
|
847
|
+
if (!buildOptions.tempDir) {
|
|
848
|
+
await fs4.remove(TEMP_DIR);
|
|
849
|
+
logger.debug("Cleaned up temporary files");
|
|
850
|
+
}
|
|
851
|
+
return stats;
|
|
852
|
+
} catch (error) {
|
|
853
|
+
if (!buildOptions.tempDir) {
|
|
854
|
+
await fs4.remove(TEMP_DIR).catch(() => {
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
throw error;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
async function collectBundleStats(outputPath, packages, startTime, entryContent) {
|
|
861
|
+
const stats = await fs4.stat(outputPath);
|
|
862
|
+
const totalSize = stats.size;
|
|
863
|
+
const buildTime = Date.now() - startTime;
|
|
864
|
+
const packageStats = Object.entries(packages).map(([name, pkg]) => {
|
|
865
|
+
const importPattern = new RegExp(`from\\s+['"]${name}['"]`, "g");
|
|
866
|
+
const namedImportPattern = new RegExp(
|
|
867
|
+
`import\\s+\\{[^}]*\\}\\s+from\\s+['"]${name}['"]`,
|
|
868
|
+
"g"
|
|
869
|
+
);
|
|
870
|
+
const hasImports = importPattern.test(entryContent) || namedImportPattern.test(entryContent);
|
|
871
|
+
const packagesCount = Object.keys(packages).length;
|
|
872
|
+
const estimatedSize = hasImports ? Math.floor(totalSize / packagesCount) : 0;
|
|
873
|
+
return {
|
|
874
|
+
name: `${name}@${pkg.version || "latest"}`,
|
|
875
|
+
size: estimatedSize
|
|
876
|
+
};
|
|
877
|
+
});
|
|
878
|
+
const hasWildcardImports = /import\s+\*\s+as\s+\w+\s+from/.test(entryContent);
|
|
879
|
+
const treeshakingEffective = !hasWildcardImports;
|
|
880
|
+
return {
|
|
881
|
+
totalSize,
|
|
882
|
+
packages: packageStats,
|
|
883
|
+
buildTime,
|
|
884
|
+
treeshakingEffective
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
function createEsbuildOptions(buildOptions, entryPath, outputPath, tempDir, packagePaths, logger) {
|
|
888
|
+
const alias = {};
|
|
889
|
+
const baseOptions = {
|
|
890
|
+
entryPoints: [entryPath],
|
|
891
|
+
bundle: true,
|
|
892
|
+
format: buildOptions.format,
|
|
893
|
+
platform: buildOptions.platform,
|
|
894
|
+
outfile: outputPath,
|
|
895
|
+
absWorkingDir: tempDir,
|
|
896
|
+
// Resolve modules from temp directory
|
|
897
|
+
// alias removed - not needed with absWorkingDir
|
|
898
|
+
mainFields: ["module", "main"],
|
|
899
|
+
// Prefer ESM over CJS
|
|
900
|
+
treeShaking: true,
|
|
901
|
+
logLevel: "error",
|
|
902
|
+
minify: buildOptions.minify,
|
|
903
|
+
sourcemap: buildOptions.sourcemap,
|
|
904
|
+
resolveExtensions: [".mjs", ".js", ".ts", ".json"],
|
|
905
|
+
// Prefer .mjs
|
|
906
|
+
// Enhanced minification options when minify is enabled
|
|
907
|
+
...buildOptions.minify && {
|
|
908
|
+
minifyWhitespace: buildOptions.minifyOptions?.whitespace ?? true,
|
|
909
|
+
minifyIdentifiers: buildOptions.minifyOptions?.identifiers ?? true,
|
|
910
|
+
minifySyntax: buildOptions.minifyOptions?.syntax ?? true,
|
|
911
|
+
legalComments: buildOptions.minifyOptions?.legalComments ?? "none",
|
|
912
|
+
keepNames: buildOptions.minifyOptions?.keepNames ?? false,
|
|
913
|
+
charset: "utf8"
|
|
914
|
+
}
|
|
915
|
+
};
|
|
916
|
+
if (buildOptions.platform === "browser") {
|
|
917
|
+
baseOptions.define = {
|
|
918
|
+
"process.env.NODE_ENV": '"production"',
|
|
919
|
+
global: "globalThis"
|
|
920
|
+
};
|
|
921
|
+
baseOptions.external = buildOptions.external || [];
|
|
922
|
+
} else if (buildOptions.platform === "node") {
|
|
923
|
+
const nodeBuiltins = [
|
|
924
|
+
"crypto",
|
|
925
|
+
"fs",
|
|
926
|
+
"path",
|
|
927
|
+
"os",
|
|
928
|
+
"util",
|
|
929
|
+
"stream",
|
|
930
|
+
"buffer",
|
|
931
|
+
"events",
|
|
932
|
+
"http",
|
|
933
|
+
"https",
|
|
934
|
+
"url",
|
|
935
|
+
"querystring",
|
|
936
|
+
"zlib"
|
|
937
|
+
];
|
|
938
|
+
const npmPackages = [
|
|
939
|
+
"zod",
|
|
940
|
+
"zod/*",
|
|
941
|
+
"express",
|
|
942
|
+
"express/*",
|
|
943
|
+
"cors",
|
|
944
|
+
"cors/*"
|
|
945
|
+
];
|
|
946
|
+
baseOptions.external = buildOptions.external ? [...nodeBuiltins, ...npmPackages, ...buildOptions.external] : [...nodeBuiltins, ...npmPackages];
|
|
947
|
+
}
|
|
948
|
+
if (buildOptions.target) {
|
|
949
|
+
baseOptions.target = buildOptions.target;
|
|
950
|
+
} else if (buildOptions.platform === "node") {
|
|
951
|
+
baseOptions.target = "node18";
|
|
952
|
+
} else {
|
|
953
|
+
baseOptions.target = "es2018";
|
|
954
|
+
}
|
|
955
|
+
if (buildOptions.globalName && buildOptions.format === "iife") {
|
|
956
|
+
baseOptions.globalName = buildOptions.globalName;
|
|
957
|
+
}
|
|
958
|
+
return baseOptions;
|
|
959
|
+
}
|
|
960
|
+
function packageNameToVariable(packageName) {
|
|
961
|
+
return packageName.replace("@", "_").replace(/[/-]/g, "_").split("_").map(
|
|
962
|
+
(part, i) => i === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1)
|
|
963
|
+
).join("");
|
|
964
|
+
}
|
|
965
|
+
async function createEntryPoint(flowConfig, buildOptions, packagePaths) {
|
|
966
|
+
const importStatements = [];
|
|
967
|
+
const examplesMappings = [];
|
|
968
|
+
const destinationPackages = /* @__PURE__ */ new Set();
|
|
969
|
+
const destinations = flowConfig.destinations;
|
|
970
|
+
if (destinations) {
|
|
971
|
+
for (const [destKey, destConfig] of Object.entries(destinations)) {
|
|
972
|
+
if (typeof destConfig === "object" && destConfig !== null && "package" in destConfig && typeof destConfig.package === "string") {
|
|
973
|
+
destinationPackages.add(destConfig.package);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
for (const [packageName, packageConfig] of Object.entries(
|
|
978
|
+
buildOptions.packages
|
|
979
|
+
)) {
|
|
980
|
+
if (packageConfig.imports && packageConfig.imports.length > 0) {
|
|
981
|
+
const uniqueImports = [...new Set(packageConfig.imports)];
|
|
982
|
+
const defaultImports = [];
|
|
983
|
+
const namedImports = [];
|
|
984
|
+
for (const imp of uniqueImports) {
|
|
985
|
+
if (imp.startsWith("default as ")) {
|
|
986
|
+
defaultImports.push(imp.replace("default as ", ""));
|
|
987
|
+
} else {
|
|
988
|
+
namedImports.push(imp);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
if (defaultImports.length > 0) {
|
|
992
|
+
for (const defaultImport of defaultImports) {
|
|
993
|
+
importStatements.push(
|
|
994
|
+
`import ${defaultImport} from '${packageName}';`
|
|
995
|
+
);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
if (namedImports.length > 0) {
|
|
999
|
+
const importList = namedImports.join(", ");
|
|
1000
|
+
importStatements.push(
|
|
1001
|
+
`import { ${importList} } from '${packageName}';`
|
|
1002
|
+
);
|
|
1003
|
+
}
|
|
1004
|
+
const examplesImport = uniqueImports.find(
|
|
1005
|
+
(imp) => imp.includes("examples as ")
|
|
1006
|
+
);
|
|
1007
|
+
if (examplesImport) {
|
|
1008
|
+
const examplesVarName = examplesImport.split(" as ")[1];
|
|
1009
|
+
const destinationMatch = packageName.match(
|
|
1010
|
+
/@walkeros\/web-destination-(.+)$/
|
|
1011
|
+
);
|
|
1012
|
+
if (destinationMatch) {
|
|
1013
|
+
const destinationName = destinationMatch[1];
|
|
1014
|
+
examplesMappings.push(
|
|
1015
|
+
` ${destinationName}: typeof ${examplesVarName} !== 'undefined' ? ${examplesVarName} : undefined`
|
|
1016
|
+
);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
} else {
|
|
1020
|
+
const varName = packageNameToVariable(packageName);
|
|
1021
|
+
importStatements.push(
|
|
1022
|
+
`import * as ${varName} from '${packageName}'; // Consider specifying explicit imports`
|
|
1023
|
+
);
|
|
1024
|
+
}
|
|
1025
|
+
if (destinationPackages.has(packageName)) {
|
|
1026
|
+
const destinationMatch = packageName.match(
|
|
1027
|
+
/@walkeros\/(?:(?:web|server)-)?destination-(.+)$/
|
|
1028
|
+
);
|
|
1029
|
+
if (destinationMatch) {
|
|
1030
|
+
const destinationName = destinationMatch[1];
|
|
1031
|
+
const examplesVarName = `${destinationName.replace(/-/g, "_")}_examples`;
|
|
1032
|
+
const isDemoPackage = packageName.includes("-demo");
|
|
1033
|
+
if (isDemoPackage) {
|
|
1034
|
+
importStatements.push(
|
|
1035
|
+
`import { examples as ${examplesVarName} } from '${packageName}';`
|
|
1036
|
+
);
|
|
1037
|
+
} else {
|
|
1038
|
+
importStatements.push(
|
|
1039
|
+
`import * as ${examplesVarName} from '${packageName}/examples';`
|
|
1040
|
+
);
|
|
1041
|
+
}
|
|
1042
|
+
examplesMappings.push(` ${destinationName}: ${examplesVarName}`);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
const examplesObject = examplesMappings.length > 0 ? `const examples = {
|
|
1047
|
+
${examplesMappings.join(",\n")}
|
|
1048
|
+
};
|
|
1049
|
+
|
|
1050
|
+
` : "";
|
|
1051
|
+
const importsCode = importStatements.join("\n");
|
|
1052
|
+
let templatedCode;
|
|
1053
|
+
if (buildOptions.template) {
|
|
1054
|
+
const templateEngine = new TemplateEngine();
|
|
1055
|
+
const flowWithProps = flowConfig;
|
|
1056
|
+
templatedCode = await templateEngine.process(
|
|
1057
|
+
buildOptions.template,
|
|
1058
|
+
buildOptions.code,
|
|
1059
|
+
// Pass user code as parameter
|
|
1060
|
+
flowWithProps.sources || {},
|
|
1061
|
+
flowWithProps.destinations || {},
|
|
1062
|
+
flowWithProps.collector || {},
|
|
1063
|
+
buildOptions
|
|
1064
|
+
// Pass build config to template
|
|
1065
|
+
);
|
|
1066
|
+
} else {
|
|
1067
|
+
templatedCode = buildOptions.code;
|
|
1068
|
+
}
|
|
1069
|
+
let wrappedCode = templatedCode;
|
|
1070
|
+
const hasExport = /^\s*export\s/m.test(templatedCode);
|
|
1071
|
+
if (!hasExport) {
|
|
1072
|
+
if (buildOptions.format === "esm") {
|
|
1073
|
+
wrappedCode = `export default ${templatedCode}`;
|
|
1074
|
+
} else if (buildOptions.platform === "browser" && buildOptions.globalName) {
|
|
1075
|
+
wrappedCode = `window['${buildOptions.globalName}'] = ${templatedCode}`;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
let finalCode = importsCode ? `${importsCode}
|
|
1079
|
+
|
|
1080
|
+
${examplesObject}${wrappedCode}` : `${examplesObject}${wrappedCode}`;
|
|
1081
|
+
if (examplesObject && buildOptions.format === "esm") {
|
|
1082
|
+
finalCode += `
|
|
1083
|
+
|
|
1084
|
+
export { examples };`;
|
|
1085
|
+
}
|
|
1086
|
+
return finalCode;
|
|
1087
|
+
}
|
|
1088
|
+
function createBuildError(buildError, code) {
|
|
1089
|
+
if (!buildError.errors || buildError.errors.length === 0) {
|
|
1090
|
+
return new Error(`Build failed: ${buildError.message || buildError}`);
|
|
1091
|
+
}
|
|
1092
|
+
const firstError = buildError.errors[0];
|
|
1093
|
+
const location = firstError.location;
|
|
1094
|
+
if (location && location.file && location.file.includes("entry.js")) {
|
|
1095
|
+
const line = location.line;
|
|
1096
|
+
const column = location.column;
|
|
1097
|
+
const codeLines = code.split("\n");
|
|
1098
|
+
const errorLine = codeLines[line - 1] || "";
|
|
1099
|
+
return new Error(
|
|
1100
|
+
`Code syntax error at line ${line}, column ${column}:
|
|
1101
|
+
${errorLine}
|
|
1102
|
+
${" ".repeat(column - 1)}^
|
|
1103
|
+
${firstError.text}`
|
|
1104
|
+
);
|
|
1105
|
+
}
|
|
1106
|
+
return new Error(
|
|
1107
|
+
`Build error: ${firstError.text}
|
|
1108
|
+
` + (location ? ` at ${location.file}:${location.line}:${location.column}` : "")
|
|
1109
|
+
);
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// src/commands/bundle/stats.ts
|
|
1113
|
+
function displayStats(stats, logger) {
|
|
1114
|
+
logger.info("\n\u{1F4CA} Bundle Statistics");
|
|
1115
|
+
logger.info("\u2500".repeat(50));
|
|
1116
|
+
const sizeKB = formatBytes(stats.totalSize);
|
|
1117
|
+
logger.info(`Total Size: ${sizeKB} KB`);
|
|
1118
|
+
const timeSeconds = (stats.buildTime / 1e3).toFixed(2);
|
|
1119
|
+
logger.info(`Build Time: ${timeSeconds}s`);
|
|
1120
|
+
const treeshakingStatus = stats.treeshakingEffective ? "\u2705 Effective" : "\u26A0\uFE0F Not optimal (consider using named imports)";
|
|
1121
|
+
logger.info(`Tree-shaking: ${treeshakingStatus}`);
|
|
1122
|
+
if (stats.packages.length > 0) {
|
|
1123
|
+
logger.info(`
|
|
1124
|
+
Package Breakdown:`);
|
|
1125
|
+
stats.packages.forEach((pkg) => {
|
|
1126
|
+
if (pkg.size > 0) {
|
|
1127
|
+
const pkgSizeKB = formatBytes(pkg.size);
|
|
1128
|
+
logger.info(` \u2022 ${pkg.name}: ${pkgSizeKB} KB`);
|
|
1129
|
+
}
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
1132
|
+
logger.info("\u2500".repeat(50));
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
// src/commands/bundle/index.ts
|
|
1136
|
+
async function bundleCommand(options) {
|
|
1137
|
+
const timer = createTimer();
|
|
1138
|
+
timer.start();
|
|
1139
|
+
const logger = createLogger({
|
|
1140
|
+
verbose: options.verbose,
|
|
1141
|
+
silent: options.silent ?? false,
|
|
1142
|
+
json: options.json
|
|
1143
|
+
});
|
|
1144
|
+
const dockerArgs = [options.config];
|
|
1145
|
+
if (options.env) dockerArgs.push("--env", options.env);
|
|
1146
|
+
if (options.all) dockerArgs.push("--all");
|
|
1147
|
+
if (options.stats) dockerArgs.push("--stats");
|
|
1148
|
+
if (options.json) dockerArgs.push("--json");
|
|
1149
|
+
if (options.cache === false) dockerArgs.push("--no-cache");
|
|
1150
|
+
if (options.verbose) dockerArgs.push("--verbose");
|
|
1151
|
+
if (options.silent) dockerArgs.push("--silent");
|
|
1152
|
+
await executeCommand(
|
|
1153
|
+
async () => {
|
|
1154
|
+
try {
|
|
1155
|
+
if (options.env && options.all) {
|
|
1156
|
+
throw new Error("Cannot use both --env and --all flags together");
|
|
1157
|
+
}
|
|
1158
|
+
logger.info("\u{1F4E6} Reading configuration...");
|
|
1159
|
+
const configPath = path6.resolve(options.config);
|
|
1160
|
+
const rawConfig = await loadJsonConfig(configPath);
|
|
1161
|
+
const configsToBundle = options.all ? loadAllEnvironments(rawConfig, { configPath, logger }) : [
|
|
1162
|
+
loadBundleConfig(rawConfig, {
|
|
1163
|
+
configPath,
|
|
1164
|
+
environment: options.env,
|
|
1165
|
+
logger
|
|
1166
|
+
})
|
|
1167
|
+
];
|
|
1168
|
+
const results = [];
|
|
1169
|
+
for (const {
|
|
1170
|
+
flowConfig,
|
|
1171
|
+
buildOptions,
|
|
1172
|
+
environment,
|
|
1173
|
+
isMultiEnvironment
|
|
1174
|
+
} of configsToBundle) {
|
|
1175
|
+
try {
|
|
1176
|
+
if (options.cache !== void 0) {
|
|
1177
|
+
buildOptions.cache = options.cache;
|
|
1178
|
+
}
|
|
1179
|
+
if (isMultiEnvironment || options.all) {
|
|
1180
|
+
logger.info(`
|
|
1181
|
+
\u{1F527} Building environment: ${environment}`);
|
|
1182
|
+
} else {
|
|
1183
|
+
logger.info("\u{1F527} Starting bundle process...");
|
|
1184
|
+
}
|
|
1185
|
+
const shouldCollectStats = options.stats || options.json;
|
|
1186
|
+
const stats = await bundleCore(
|
|
1187
|
+
flowConfig,
|
|
1188
|
+
buildOptions,
|
|
1189
|
+
logger,
|
|
1190
|
+
shouldCollectStats
|
|
1191
|
+
);
|
|
1192
|
+
results.push({
|
|
1193
|
+
environment,
|
|
1194
|
+
success: true,
|
|
1195
|
+
stats
|
|
1196
|
+
});
|
|
1197
|
+
if (!options.json && !options.all && options.stats && stats) {
|
|
1198
|
+
displayStats(stats, logger);
|
|
1199
|
+
}
|
|
1200
|
+
} catch (error) {
|
|
1201
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1202
|
+
results.push({
|
|
1203
|
+
environment,
|
|
1204
|
+
success: false,
|
|
1205
|
+
error: errorMessage
|
|
1206
|
+
});
|
|
1207
|
+
if (!options.all) {
|
|
1208
|
+
throw error;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
const duration = timer.end() / 1e3;
|
|
1213
|
+
const successCount = results.filter((r) => r.success).length;
|
|
1214
|
+
const failureCount = results.filter((r) => !r.success).length;
|
|
1215
|
+
if (options.json) {
|
|
1216
|
+
const outputLogger = createLogger({ silent: false, json: false });
|
|
1217
|
+
const output = failureCount === 0 ? createSuccessOutput(
|
|
1218
|
+
{
|
|
1219
|
+
environments: results,
|
|
1220
|
+
summary: {
|
|
1221
|
+
total: results.length,
|
|
1222
|
+
success: successCount,
|
|
1223
|
+
failed: failureCount
|
|
1224
|
+
}
|
|
1225
|
+
},
|
|
1226
|
+
duration
|
|
1227
|
+
) : createErrorOutput(
|
|
1228
|
+
`${failureCount} environment(s) failed to build`,
|
|
1229
|
+
duration
|
|
1230
|
+
);
|
|
1231
|
+
outputLogger.log("white", JSON.stringify(output, null, 2));
|
|
1232
|
+
} else {
|
|
1233
|
+
if (options.all) {
|
|
1234
|
+
logger.info(`
|
|
1235
|
+
\u{1F4CA} Build Summary:`);
|
|
1236
|
+
logger.info(` Total: ${results.length}`);
|
|
1237
|
+
logger.success(` \u2705 Success: ${successCount}`);
|
|
1238
|
+
if (failureCount > 0) {
|
|
1239
|
+
logger.error(` \u274C Failed: ${failureCount}`);
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
if (failureCount === 0) {
|
|
1243
|
+
logger.success(
|
|
1244
|
+
`
|
|
1245
|
+
\u2705 Bundle created successfully in ${timer.format()}`
|
|
1246
|
+
);
|
|
1247
|
+
} else {
|
|
1248
|
+
throw new Error(`${failureCount} environment(s) failed to build`);
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
} catch (error) {
|
|
1252
|
+
const duration = timer.getElapsed() / 1e3;
|
|
1253
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1254
|
+
if (options.json) {
|
|
1255
|
+
const outputLogger = createLogger({ silent: false, json: false });
|
|
1256
|
+
const output = createErrorOutput(errorMessage, duration);
|
|
1257
|
+
outputLogger.log("white", JSON.stringify(output, null, 2));
|
|
1258
|
+
} else {
|
|
1259
|
+
logger.error("\u274C Bundle failed:");
|
|
1260
|
+
logger.error(errorMessage);
|
|
1261
|
+
}
|
|
1262
|
+
process.exit(1);
|
|
1263
|
+
}
|
|
1264
|
+
},
|
|
1265
|
+
"bundle",
|
|
1266
|
+
dockerArgs,
|
|
1267
|
+
options,
|
|
1268
|
+
logger
|
|
1269
|
+
);
|
|
1270
|
+
}
|
|
1271
|
+
async function bundle(configOrPath, options = {}) {
|
|
1272
|
+
let rawConfig;
|
|
1273
|
+
if (typeof configOrPath === "string") {
|
|
1274
|
+
rawConfig = await loadJsonConfig(configOrPath);
|
|
1275
|
+
} else {
|
|
1276
|
+
rawConfig = configOrPath;
|
|
1277
|
+
}
|
|
1278
|
+
const { flowConfig, buildOptions } = parseBundleConfig(rawConfig);
|
|
1279
|
+
if (options.cache !== void 0) {
|
|
1280
|
+
buildOptions.cache = options.cache;
|
|
1281
|
+
}
|
|
1282
|
+
const logger = createLogger({
|
|
1283
|
+
silent: options.silent ?? false,
|
|
1284
|
+
verbose: options.verbose ?? false
|
|
1285
|
+
});
|
|
1286
|
+
return await bundleCore(
|
|
1287
|
+
flowConfig,
|
|
1288
|
+
buildOptions,
|
|
1289
|
+
logger,
|
|
1290
|
+
options.stats ?? false
|
|
1291
|
+
);
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
// src/commands/simulate/simulator.ts
|
|
1295
|
+
import path7 from "path";
|
|
1296
|
+
import fs5 from "fs-extra";
|
|
1297
|
+
|
|
1298
|
+
// src/commands/simulate/tracker.ts
|
|
1299
|
+
var CallTracker = class {
|
|
1300
|
+
calls = /* @__PURE__ */ new Map();
|
|
1301
|
+
/**
|
|
1302
|
+
* Wrap a function to track its calls
|
|
1303
|
+
*/
|
|
1304
|
+
wrapFunction(name, fn) {
|
|
1305
|
+
const self = this;
|
|
1306
|
+
const targetFn = fn || (() => {
|
|
1307
|
+
});
|
|
1308
|
+
return new Proxy(targetFn, {
|
|
1309
|
+
apply(_target, thisArg, args) {
|
|
1310
|
+
self.logCall(name, args);
|
|
1311
|
+
return targetFn.apply(thisArg, args);
|
|
1312
|
+
}
|
|
1313
|
+
});
|
|
1314
|
+
}
|
|
1315
|
+
/**
|
|
1316
|
+
* Wrap an environment object, tracking specified paths
|
|
1317
|
+
*
|
|
1318
|
+
* @param env - Environment object (from destination's examples/env.ts)
|
|
1319
|
+
* @param paths - Paths to track (e.g., ['gtag:window.gtag', 'gtag:window.dataLayer.push'])
|
|
1320
|
+
*/
|
|
1321
|
+
wrapEnv(env, paths) {
|
|
1322
|
+
const wrapped = {};
|
|
1323
|
+
for (const [key, value] of Object.entries(env)) {
|
|
1324
|
+
if (typeof value === "object" && value !== null) {
|
|
1325
|
+
wrapped[key] = Array.isArray(value) ? [...value] : { ...value };
|
|
1326
|
+
} else {
|
|
1327
|
+
wrapped[key] = value;
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
for (const fullPath of paths) {
|
|
1331
|
+
const [destKey, ...pathParts] = fullPath.split(":");
|
|
1332
|
+
const path9 = pathParts.join(":");
|
|
1333
|
+
if (!path9) continue;
|
|
1334
|
+
const cleanPath = path9.replace(/^call:/, "");
|
|
1335
|
+
const parts = cleanPath.split(".");
|
|
1336
|
+
let current = wrapped;
|
|
1337
|
+
let source = env;
|
|
1338
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
1339
|
+
const part = parts[i];
|
|
1340
|
+
if (!current[part]) {
|
|
1341
|
+
current[part] = {};
|
|
1342
|
+
}
|
|
1343
|
+
current = current[part];
|
|
1344
|
+
source = source && typeof source[part] === "object" && source[part] !== null ? source[part] : void 0;
|
|
1345
|
+
}
|
|
1346
|
+
const finalKey = parts[parts.length - 1];
|
|
1347
|
+
const originalFn = source?.[finalKey];
|
|
1348
|
+
current[finalKey] = this.wrapFunction(
|
|
1349
|
+
`${destKey}:${cleanPath}`,
|
|
1350
|
+
typeof originalFn === "function" ? originalFn : void 0
|
|
1351
|
+
);
|
|
1352
|
+
}
|
|
1353
|
+
return wrapped;
|
|
1354
|
+
}
|
|
1355
|
+
logCall(fullPath, args) {
|
|
1356
|
+
const [destKey, ...pathParts] = fullPath.split(":");
|
|
1357
|
+
const apiPath = pathParts.join(":");
|
|
1358
|
+
if (!this.calls.has(destKey)) {
|
|
1359
|
+
this.calls.set(destKey, []);
|
|
1360
|
+
}
|
|
1361
|
+
this.calls.get(destKey).push({
|
|
1362
|
+
type: "call",
|
|
1363
|
+
path: apiPath,
|
|
1364
|
+
args,
|
|
1365
|
+
timestamp: Date.now()
|
|
1366
|
+
});
|
|
1367
|
+
}
|
|
1368
|
+
getCalls() {
|
|
1369
|
+
return Object.fromEntries(this.calls);
|
|
1370
|
+
}
|
|
1371
|
+
reset() {
|
|
1372
|
+
this.calls.clear();
|
|
1373
|
+
}
|
|
1374
|
+
};
|
|
1375
|
+
|
|
1376
|
+
// src/commands/simulate/simulator.ts
|
|
1377
|
+
function generateId() {
|
|
1378
|
+
return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
|
|
1379
|
+
}
|
|
1380
|
+
async function simulateCore(configPath, event, options = {}) {
|
|
1381
|
+
const logger = createLogger({
|
|
1382
|
+
verbose: options.verbose || false,
|
|
1383
|
+
silent: options.silent || false,
|
|
1384
|
+
json: options.json || false
|
|
1385
|
+
});
|
|
1386
|
+
try {
|
|
1387
|
+
logger.info("\u{1F3AF} Starting walkerOS simulation...");
|
|
1388
|
+
logger.info("\u{1F4E6} Loading bundle configuration...");
|
|
1389
|
+
const fullConfigPath = path7.resolve(configPath);
|
|
1390
|
+
const rawConfig = await loadJsonConfig(fullConfigPath);
|
|
1391
|
+
parseBundleConfig(rawConfig);
|
|
1392
|
+
logger.info(`\u{1F680} Executing simulation with event: ${JSON.stringify(event)}`);
|
|
1393
|
+
const result = await executeSimulation(event, fullConfigPath);
|
|
1394
|
+
if (result.success) {
|
|
1395
|
+
logger.info(`\u2705 Simulation completed successfully`);
|
|
1396
|
+
} else {
|
|
1397
|
+
logger.error(`\u274C Simulation failed: ${result.error}`);
|
|
1398
|
+
}
|
|
1399
|
+
return result;
|
|
1400
|
+
} catch (error) {
|
|
1401
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1402
|
+
logger.error(`\u{1F4A5} Simulation error: ${errorMessage}`);
|
|
1403
|
+
return {
|
|
1404
|
+
success: false,
|
|
1405
|
+
error: errorMessage
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
function parseEventInput(eventString = "") {
|
|
1410
|
+
if (!eventString) {
|
|
1411
|
+
return {};
|
|
1412
|
+
}
|
|
1413
|
+
try {
|
|
1414
|
+
const parsed = JSON.parse(eventString);
|
|
1415
|
+
return isObject(parsed) ? parsed : {};
|
|
1416
|
+
} catch {
|
|
1417
|
+
return { name: eventString };
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
function formatSimulationResult(result, options = {}) {
|
|
1421
|
+
if (options.json) {
|
|
1422
|
+
const output = {
|
|
1423
|
+
result: result.elbResult,
|
|
1424
|
+
usage: result.usage,
|
|
1425
|
+
duration: result.duration
|
|
1426
|
+
};
|
|
1427
|
+
return JSON.stringify(output, null, 2);
|
|
1428
|
+
}
|
|
1429
|
+
if (result.success) {
|
|
1430
|
+
return "\u2705 Simulation completed successfully";
|
|
1431
|
+
} else {
|
|
1432
|
+
return `\u274C Simulation failed: ${result.error}`;
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
async function executeSimulation(event, configPath) {
|
|
1436
|
+
const startTime = Date.now();
|
|
1437
|
+
let bundlePath;
|
|
1438
|
+
const tempDir = getTempDir();
|
|
1439
|
+
try {
|
|
1440
|
+
await fs5.ensureDir(tempDir);
|
|
1441
|
+
const rawConfig = await loadJsonConfig(configPath);
|
|
1442
|
+
const { flowConfig, buildOptions } = parseBundleConfig(rawConfig);
|
|
1443
|
+
const packagesArray = Object.entries(buildOptions.packages).map(
|
|
1444
|
+
([name, packageConfig]) => ({
|
|
1445
|
+
name,
|
|
1446
|
+
version: (typeof packageConfig === "object" && packageConfig !== null && "version" in packageConfig && typeof packageConfig.version === "string" ? packageConfig.version : void 0) || "latest"
|
|
1447
|
+
})
|
|
1448
|
+
);
|
|
1449
|
+
const packagePaths = await downloadPackages(
|
|
1450
|
+
packagesArray,
|
|
1451
|
+
tempDir,
|
|
1452
|
+
// downloadPackages will add 'node_modules' subdirectory itself
|
|
1453
|
+
createLogger({ silent: true }),
|
|
1454
|
+
buildOptions.cache
|
|
1455
|
+
);
|
|
1456
|
+
const tracker = new CallTracker();
|
|
1457
|
+
const envSetupCode = [];
|
|
1458
|
+
const destinations = flowConfig.destinations;
|
|
1459
|
+
if (destinations) {
|
|
1460
|
+
for (const [key, dest] of Object.entries(destinations)) {
|
|
1461
|
+
const destName = key.replace(/-/g, "_");
|
|
1462
|
+
envSetupCode.push(`
|
|
1463
|
+
// Inject tracked env for destination '${key}' using examples from bundle
|
|
1464
|
+
if (examples && examples['${key}'] && examples['${key}'].env) {
|
|
1465
|
+
const mockEnv = examples['${key}'].env.push;
|
|
1466
|
+
const trackPaths = examples['${key}'].env.simulation || [];
|
|
1467
|
+
if (mockEnv) {
|
|
1468
|
+
const wrappedPaths = trackPaths.map((p) => '${key}:' + p);
|
|
1469
|
+
const trackedEnv = __simulationTracker.wrapEnv(mockEnv, wrappedPaths);
|
|
1470
|
+
if (config.destinations && config.destinations['${key}']) {
|
|
1471
|
+
config.destinations['${key}'].env = trackedEnv;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
`);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
const modifiedCode = `
|
|
1479
|
+
// Inject tracked envs into destination configs
|
|
1480
|
+
${envSetupCode.join("\n")}
|
|
1481
|
+
|
|
1482
|
+
${buildOptions.code || ""}
|
|
1483
|
+
`;
|
|
1484
|
+
const tempOutput = path7.join(
|
|
1485
|
+
tempDir,
|
|
1486
|
+
`simulation-bundle-${generateId()}.mjs`
|
|
1487
|
+
);
|
|
1488
|
+
const simulationBuildOptions = {
|
|
1489
|
+
...buildOptions,
|
|
1490
|
+
code: modifiedCode,
|
|
1491
|
+
output: tempOutput,
|
|
1492
|
+
tempDir,
|
|
1493
|
+
// Use same temp dir for bundle
|
|
1494
|
+
format: "esm",
|
|
1495
|
+
// Force node platform for simulation since we're running in Node.js
|
|
1496
|
+
platform: "node"
|
|
1497
|
+
};
|
|
1498
|
+
await bundleCore(
|
|
1499
|
+
flowConfig,
|
|
1500
|
+
simulationBuildOptions,
|
|
1501
|
+
createLogger({ silent: true }),
|
|
1502
|
+
false
|
|
1503
|
+
);
|
|
1504
|
+
bundlePath = tempOutput;
|
|
1505
|
+
const globalWithSim = globalThis;
|
|
1506
|
+
if (!globalWithSim.window) {
|
|
1507
|
+
globalWithSim.window = {};
|
|
1508
|
+
}
|
|
1509
|
+
if (!globalWithSim.document) {
|
|
1510
|
+
globalWithSim.document = {};
|
|
1511
|
+
}
|
|
1512
|
+
const timestamp = Date.now();
|
|
1513
|
+
const moduleUrl = `file://${bundlePath}?t=${timestamp}`;
|
|
1514
|
+
const module = await import(moduleUrl);
|
|
1515
|
+
const importedExamples = module.examples;
|
|
1516
|
+
const destinations2 = flowConfig.destinations;
|
|
1517
|
+
if (importedExamples && destinations2) {
|
|
1518
|
+
for (const [key, dest] of Object.entries(destinations2)) {
|
|
1519
|
+
const destEnv = importedExamples[key]?.env?.push;
|
|
1520
|
+
if (destEnv) {
|
|
1521
|
+
if (destEnv.window && typeof globalWithSim.window === "object" && globalWithSim.window !== null) {
|
|
1522
|
+
Object.assign(globalWithSim.window, destEnv.window);
|
|
1523
|
+
}
|
|
1524
|
+
if (destEnv.document && typeof globalWithSim.document === "object" && globalWithSim.document !== null) {
|
|
1525
|
+
Object.assign(globalWithSim.document, destEnv.document);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
const flowResult = await module.default({ tracker });
|
|
1531
|
+
if (!flowResult || typeof flowResult.elb !== "function") {
|
|
1532
|
+
throw new Error(
|
|
1533
|
+
"Bundle did not export valid flow object with elb function"
|
|
1534
|
+
);
|
|
1535
|
+
}
|
|
1536
|
+
const { elb } = flowResult;
|
|
1537
|
+
const elbResult = await elb(event);
|
|
1538
|
+
const usage = tracker.getCalls();
|
|
1539
|
+
const duration = Date.now() - startTime;
|
|
1540
|
+
return {
|
|
1541
|
+
success: true,
|
|
1542
|
+
elbResult,
|
|
1543
|
+
usage,
|
|
1544
|
+
duration,
|
|
1545
|
+
logs: []
|
|
1546
|
+
};
|
|
1547
|
+
} catch (error) {
|
|
1548
|
+
const duration = Date.now() - startTime;
|
|
1549
|
+
return {
|
|
1550
|
+
success: false,
|
|
1551
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1552
|
+
duration
|
|
1553
|
+
};
|
|
1554
|
+
} finally {
|
|
1555
|
+
if (tempDir) {
|
|
1556
|
+
await fs5.remove(tempDir).catch(() => {
|
|
1557
|
+
});
|
|
1558
|
+
}
|
|
1559
|
+
const globalWithSim = globalThis;
|
|
1560
|
+
delete globalWithSim.window;
|
|
1561
|
+
delete globalWithSim.document;
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
// src/commands/simulate/index.ts
|
|
1566
|
+
async function simulateCommand(options) {
|
|
1567
|
+
const logger = createLogger({
|
|
1568
|
+
verbose: options.verbose,
|
|
1569
|
+
silent: options.silent ?? false,
|
|
1570
|
+
json: options.json
|
|
1571
|
+
});
|
|
1572
|
+
const dockerArgs = [options.config];
|
|
1573
|
+
if (options.event) dockerArgs.push("--event", options.event);
|
|
1574
|
+
if (options.json) dockerArgs.push("--json");
|
|
1575
|
+
if (options.verbose) dockerArgs.push("--verbose");
|
|
1576
|
+
if (options.silent) dockerArgs.push("--silent");
|
|
1577
|
+
await executeCommand(
|
|
1578
|
+
async () => {
|
|
1579
|
+
const startTime = Date.now();
|
|
1580
|
+
try {
|
|
1581
|
+
const event = parseEventInput(options.event);
|
|
1582
|
+
const result = await simulateCore(options.config, event, {
|
|
1583
|
+
json: options.json,
|
|
1584
|
+
verbose: options.verbose,
|
|
1585
|
+
silent: options.silent
|
|
1586
|
+
});
|
|
1587
|
+
const resultWithDuration = {
|
|
1588
|
+
...result,
|
|
1589
|
+
duration: (Date.now() - startTime) / 1e3
|
|
1590
|
+
};
|
|
1591
|
+
const outputLogger = createLogger({ silent: false, json: false });
|
|
1592
|
+
const output = formatSimulationResult(resultWithDuration, {
|
|
1593
|
+
json: options.json
|
|
1594
|
+
});
|
|
1595
|
+
outputLogger.log("white", output);
|
|
1596
|
+
if (!result.success) {
|
|
1597
|
+
process.exit(1);
|
|
1598
|
+
}
|
|
1599
|
+
} catch (error) {
|
|
1600
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1601
|
+
if (options.json) {
|
|
1602
|
+
const outputLogger = createLogger({ silent: false, json: false });
|
|
1603
|
+
const errorOutput = JSON.stringify(
|
|
1604
|
+
{
|
|
1605
|
+
success: false,
|
|
1606
|
+
error: errorMessage,
|
|
1607
|
+
duration: (Date.now() - startTime) / 1e3
|
|
1608
|
+
},
|
|
1609
|
+
null,
|
|
1610
|
+
2
|
|
1611
|
+
);
|
|
1612
|
+
outputLogger.log("white", errorOutput);
|
|
1613
|
+
} else {
|
|
1614
|
+
const errorLogger = createLogger({ silent: false, json: false });
|
|
1615
|
+
errorLogger.error(`\u274C Simulate command failed: ${errorMessage}`);
|
|
1616
|
+
}
|
|
1617
|
+
process.exit(1);
|
|
1618
|
+
}
|
|
1619
|
+
},
|
|
1620
|
+
"simulate",
|
|
1621
|
+
dockerArgs,
|
|
1622
|
+
options,
|
|
1623
|
+
logger
|
|
1624
|
+
);
|
|
1625
|
+
}
|
|
1626
|
+
async function simulate(configOrPath, event, options = {}) {
|
|
1627
|
+
if (typeof configOrPath !== "string") {
|
|
1628
|
+
throw new Error(
|
|
1629
|
+
"simulate() currently only supports config file paths. Config object support will be added in a future version. Please provide a path to a configuration file."
|
|
1630
|
+
);
|
|
1631
|
+
}
|
|
1632
|
+
return await simulateCore(configOrPath, event, {
|
|
1633
|
+
json: options.json ?? false,
|
|
1634
|
+
verbose: options.verbose ?? false
|
|
1635
|
+
});
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
// src/commands/run/index.ts
|
|
1639
|
+
import path8 from "path";
|
|
1640
|
+
import os from "os";
|
|
1641
|
+
import {
|
|
1642
|
+
runFlow,
|
|
1643
|
+
runServeMode
|
|
1644
|
+
} from "@walkeros/docker";
|
|
1645
|
+
|
|
1646
|
+
// src/commands/run/validators.ts
|
|
1647
|
+
import { existsSync } from "fs";
|
|
1648
|
+
import { resolve } from "path";
|
|
1649
|
+
var VALID_MODES = ["collect", "serve"];
|
|
1650
|
+
function validateMode(mode) {
|
|
1651
|
+
if (!VALID_MODES.includes(mode)) {
|
|
1652
|
+
throw new Error(
|
|
1653
|
+
`Invalid mode: "${mode}"
|
|
1654
|
+
Valid modes: ${VALID_MODES.join(", ")}
|
|
1655
|
+
Example: walkeros run collect ./flow.json`
|
|
1656
|
+
);
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
function validateFlowFile(filePath) {
|
|
1660
|
+
const absolutePath = resolve(filePath);
|
|
1661
|
+
if (!existsSync(absolutePath)) {
|
|
1662
|
+
throw new Error(
|
|
1663
|
+
`Flow file not found: ${filePath}
|
|
1664
|
+
Resolved path: ${absolutePath}
|
|
1665
|
+
Make sure the file exists and the path is correct`
|
|
1666
|
+
);
|
|
1667
|
+
}
|
|
1668
|
+
return absolutePath;
|
|
1669
|
+
}
|
|
1670
|
+
function validatePort(port) {
|
|
1671
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
1672
|
+
throw new Error(
|
|
1673
|
+
`Invalid port: ${port}
|
|
1674
|
+
Port must be an integer between 1 and 65535
|
|
1675
|
+
Example: --port 8080`
|
|
1676
|
+
);
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
// src/commands/run/index.ts
|
|
1681
|
+
async function runCommand(mode, options) {
|
|
1682
|
+
const timer = createTimer();
|
|
1683
|
+
timer.start();
|
|
1684
|
+
const logger = createLogger({
|
|
1685
|
+
verbose: options.verbose,
|
|
1686
|
+
silent: options.silent ?? false,
|
|
1687
|
+
json: options.json
|
|
1688
|
+
});
|
|
1689
|
+
const dockerArgs = [mode, options.config];
|
|
1690
|
+
if (options.port !== void 0)
|
|
1691
|
+
dockerArgs.push("--port", String(options.port));
|
|
1692
|
+
if (options.host) dockerArgs.push("--host", options.host);
|
|
1693
|
+
if (options.staticDir) dockerArgs.push("--static-dir", options.staticDir);
|
|
1694
|
+
if (options.json) dockerArgs.push("--json");
|
|
1695
|
+
if (options.verbose) dockerArgs.push("--verbose");
|
|
1696
|
+
if (options.silent) dockerArgs.push("--silent");
|
|
1697
|
+
await executeCommand(
|
|
1698
|
+
async () => {
|
|
1699
|
+
try {
|
|
1700
|
+
validateMode(mode);
|
|
1701
|
+
const configPath = validateFlowFile(options.config);
|
|
1702
|
+
if (options.port !== void 0) {
|
|
1703
|
+
validatePort(options.port);
|
|
1704
|
+
}
|
|
1705
|
+
const isPreBuilt = configPath.endsWith(".mjs") || configPath.endsWith(".js") || configPath.endsWith(".cjs");
|
|
1706
|
+
let flowPath;
|
|
1707
|
+
if (isPreBuilt) {
|
|
1708
|
+
flowPath = path8.resolve(configPath);
|
|
1709
|
+
if (!options.json) {
|
|
1710
|
+
logger.info(`\u{1F4E6} Using pre-built flow: ${path8.basename(flowPath)}`);
|
|
1711
|
+
}
|
|
1712
|
+
} else {
|
|
1713
|
+
if (!options.json) {
|
|
1714
|
+
logger.info("\u{1F528} Building flow bundle...");
|
|
1715
|
+
}
|
|
1716
|
+
const rawConfig = await loadJsonConfig(configPath);
|
|
1717
|
+
const tempPath = path8.join(
|
|
1718
|
+
os.tmpdir(),
|
|
1719
|
+
`walkeros-${Date.now()}-${Math.random().toString(36).slice(2, 9)}.mjs`
|
|
1720
|
+
);
|
|
1721
|
+
const existingBuild = typeof rawConfig === "object" && rawConfig !== null && "build" in rawConfig && typeof rawConfig.build === "object" ? rawConfig.build : {};
|
|
1722
|
+
const configWithOutput = {
|
|
1723
|
+
...rawConfig,
|
|
1724
|
+
build: {
|
|
1725
|
+
...existingBuild,
|
|
1726
|
+
output: tempPath
|
|
1727
|
+
}
|
|
1728
|
+
};
|
|
1729
|
+
await bundle(configWithOutput, {
|
|
1730
|
+
cache: true,
|
|
1731
|
+
verbose: options.verbose,
|
|
1732
|
+
silent: options.json
|
|
1733
|
+
});
|
|
1734
|
+
flowPath = tempPath;
|
|
1735
|
+
if (!options.json) {
|
|
1736
|
+
logger.success("\u2705 Bundle ready");
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
if (!options.json) {
|
|
1740
|
+
const modeLabel = mode === "collect" ? "Collector" : "Server";
|
|
1741
|
+
logger.info(`\u{1F680} Starting ${modeLabel}...`);
|
|
1742
|
+
}
|
|
1743
|
+
switch (mode) {
|
|
1744
|
+
case "collect": {
|
|
1745
|
+
const config = {
|
|
1746
|
+
port: options.port,
|
|
1747
|
+
host: options.host
|
|
1748
|
+
};
|
|
1749
|
+
await runFlow(flowPath, config);
|
|
1750
|
+
break;
|
|
1751
|
+
}
|
|
1752
|
+
case "serve": {
|
|
1753
|
+
const config = {
|
|
1754
|
+
port: options.port,
|
|
1755
|
+
host: options.host,
|
|
1756
|
+
staticDir: options.staticDir
|
|
1757
|
+
};
|
|
1758
|
+
await runServeMode(config);
|
|
1759
|
+
break;
|
|
1760
|
+
}
|
|
1761
|
+
default:
|
|
1762
|
+
throw new Error(`Unknown mode: ${mode}`);
|
|
1763
|
+
}
|
|
1764
|
+
} catch (error) {
|
|
1765
|
+
const duration = timer.getElapsed() / 1e3;
|
|
1766
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1767
|
+
if (options.json) {
|
|
1768
|
+
const output = {
|
|
1769
|
+
success: false,
|
|
1770
|
+
mode,
|
|
1771
|
+
error: errorMessage,
|
|
1772
|
+
duration
|
|
1773
|
+
};
|
|
1774
|
+
console.log(JSON.stringify(output, null, 2));
|
|
1775
|
+
} else {
|
|
1776
|
+
logger.error("\u274C Run failed:");
|
|
1777
|
+
logger.error(errorMessage);
|
|
1778
|
+
}
|
|
1779
|
+
process.exit(1);
|
|
1780
|
+
}
|
|
1781
|
+
},
|
|
1782
|
+
"run",
|
|
1783
|
+
dockerArgs,
|
|
1784
|
+
options,
|
|
1785
|
+
logger
|
|
1786
|
+
);
|
|
1787
|
+
}
|
|
1788
|
+
async function run(mode, options) {
|
|
1789
|
+
const startTime = Date.now();
|
|
1790
|
+
try {
|
|
1791
|
+
validateMode(mode);
|
|
1792
|
+
let flowFile;
|
|
1793
|
+
if (typeof options.config === "string") {
|
|
1794
|
+
flowFile = validateFlowFile(options.config);
|
|
1795
|
+
} else {
|
|
1796
|
+
throw new Error("Programmatic run() requires config file path");
|
|
1797
|
+
}
|
|
1798
|
+
if (options.port !== void 0) {
|
|
1799
|
+
validatePort(options.port);
|
|
1800
|
+
}
|
|
1801
|
+
const isPreBuilt = flowFile.endsWith(".mjs") || flowFile.endsWith(".js") || flowFile.endsWith(".cjs");
|
|
1802
|
+
let flowPath;
|
|
1803
|
+
if (isPreBuilt) {
|
|
1804
|
+
flowPath = path8.resolve(flowFile);
|
|
1805
|
+
} else {
|
|
1806
|
+
const rawConfig = await loadJsonConfig(flowFile);
|
|
1807
|
+
const tempPath = path8.join(
|
|
1808
|
+
os.tmpdir(),
|
|
1809
|
+
`walkeros-${Date.now()}-${Math.random().toString(36).slice(2, 9)}.mjs`
|
|
1810
|
+
);
|
|
1811
|
+
const existingBuild = typeof rawConfig === "object" && rawConfig !== null && "build" in rawConfig && typeof rawConfig.build === "object" ? rawConfig.build : {};
|
|
1812
|
+
const configWithOutput = {
|
|
1813
|
+
...rawConfig,
|
|
1814
|
+
build: {
|
|
1815
|
+
...existingBuild,
|
|
1816
|
+
output: tempPath
|
|
1817
|
+
}
|
|
1818
|
+
};
|
|
1819
|
+
await bundle(configWithOutput, {
|
|
1820
|
+
cache: true,
|
|
1821
|
+
verbose: options.verbose,
|
|
1822
|
+
silent: true
|
|
1823
|
+
});
|
|
1824
|
+
flowPath = tempPath;
|
|
1825
|
+
}
|
|
1826
|
+
switch (mode) {
|
|
1827
|
+
case "collect": {
|
|
1828
|
+
const config = {
|
|
1829
|
+
port: options.port,
|
|
1830
|
+
host: options.host
|
|
1831
|
+
};
|
|
1832
|
+
await runFlow(flowPath, config);
|
|
1833
|
+
break;
|
|
1834
|
+
}
|
|
1835
|
+
case "serve": {
|
|
1836
|
+
const config = {
|
|
1837
|
+
port: options.port,
|
|
1838
|
+
host: options.host,
|
|
1839
|
+
staticDir: options.staticDir
|
|
1840
|
+
};
|
|
1841
|
+
await runServeMode(config);
|
|
1842
|
+
break;
|
|
1843
|
+
}
|
|
1844
|
+
default:
|
|
1845
|
+
throw new Error(`Unknown mode: ${mode}`);
|
|
1846
|
+
}
|
|
1847
|
+
return {
|
|
1848
|
+
success: true,
|
|
1849
|
+
exitCode: 0,
|
|
1850
|
+
duration: Date.now() - startTime
|
|
1851
|
+
};
|
|
1852
|
+
} catch (error) {
|
|
1853
|
+
return {
|
|
1854
|
+
success: false,
|
|
1855
|
+
exitCode: 1,
|
|
1856
|
+
duration: Date.now() - startTime,
|
|
1857
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1858
|
+
};
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
// src/index.ts
|
|
1863
|
+
import { fileURLToPath } from "url";
|
|
1864
|
+
var program = new Command();
|
|
1865
|
+
program.name("walkeros").description("walkerOS CLI - Bundle and deploy walkerOS components").version("0.1.0");
|
|
1866
|
+
program.command("bundle").description("Bundle NPM packages with custom code").option(
|
|
1867
|
+
"-c, --config <path>",
|
|
1868
|
+
"configuration file path",
|
|
1869
|
+
"bundle.config.json"
|
|
1870
|
+
).option(
|
|
1871
|
+
"-e, --env <name>",
|
|
1872
|
+
"environment to build (for multi-environment configs)"
|
|
1873
|
+
).option("--all", "build all environments (for multi-environment configs)").option("-s, --stats", "show bundle statistics").option("--json", "output statistics in JSON format (implies --stats)").option("--no-cache", "disable package caching and download fresh packages").option("-v, --verbose", "verbose output").option("--local", "execute in local Node.js instead of Docker").option("--dry-run", "preview command without executing").option("--silent", "suppress output").action(async (options) => {
|
|
1874
|
+
await bundleCommand({
|
|
1875
|
+
config: options.config,
|
|
1876
|
+
env: options.env,
|
|
1877
|
+
all: options.all,
|
|
1878
|
+
stats: options.stats,
|
|
1879
|
+
json: options.json,
|
|
1880
|
+
cache: options.cache,
|
|
1881
|
+
verbose: options.verbose,
|
|
1882
|
+
local: options.local,
|
|
1883
|
+
dryRun: options.dryRun,
|
|
1884
|
+
silent: options.silent
|
|
1885
|
+
});
|
|
1886
|
+
});
|
|
1887
|
+
program.command("simulate").description("Simulate event processing and capture API calls").option(
|
|
1888
|
+
"-c, --config <path>",
|
|
1889
|
+
"Bundle configuration file",
|
|
1890
|
+
"bundle.config.json"
|
|
1891
|
+
).option("-e, --event <json>", "Event to simulate (JSON string)").option("--json", "Output results as JSON").option("-v, --verbose", "Verbose output").option("--local", "execute in local Node.js instead of Docker").option("--dry-run", "preview command without executing").option("--silent", "suppress output").action(async (options) => {
|
|
1892
|
+
await simulateCommand({
|
|
1893
|
+
config: options.config,
|
|
1894
|
+
event: options.event,
|
|
1895
|
+
json: options.json,
|
|
1896
|
+
verbose: options.verbose,
|
|
1897
|
+
local: options.local,
|
|
1898
|
+
dryRun: options.dryRun,
|
|
1899
|
+
silent: options.silent
|
|
1900
|
+
});
|
|
1901
|
+
});
|
|
1902
|
+
var runCmd = program.command("run").description("Run walkerOS flows in collect or serve mode");
|
|
1903
|
+
runCmd.command("collect <file>").description("Run collector mode (event collection endpoint)").option("-p, --port <number>", "Port to listen on (default: 8080)", parseInt).option("-h, --host <address>", "Host address (default: 0.0.0.0)").option("--json", "Output results as JSON").option("-v, --verbose", "Verbose output").option("--local", "execute in local Node.js instead of Docker").option("--dry-run", "preview command without executing").option("--silent", "suppress output").action(async (file, options) => {
|
|
1904
|
+
await runCommand("collect", {
|
|
1905
|
+
config: file,
|
|
1906
|
+
port: options.port,
|
|
1907
|
+
host: options.host,
|
|
1908
|
+
json: options.json,
|
|
1909
|
+
verbose: options.verbose,
|
|
1910
|
+
local: options.local,
|
|
1911
|
+
dryRun: options.dryRun,
|
|
1912
|
+
silent: options.silent
|
|
1913
|
+
});
|
|
1914
|
+
});
|
|
1915
|
+
runCmd.command("serve <file>").description("Run serve mode (static file server for browser bundles)").option("-p, --port <number>", "Port to listen on (default: 8080)", parseInt).option("-h, --host <address>", "Host address (default: 0.0.0.0)").option("--static-dir <dir>", "Static directory for serve mode").option("--json", "Output results as JSON").option("-v, --verbose", "Verbose output").option("--local", "execute in local Node.js instead of Docker").option("--dry-run", "preview command without executing").option("--silent", "suppress output").action(async (file, options) => {
|
|
1916
|
+
await runCommand("serve", {
|
|
1917
|
+
config: file,
|
|
1918
|
+
port: options.port,
|
|
1919
|
+
host: options.host,
|
|
1920
|
+
staticDir: options.staticDir,
|
|
1921
|
+
json: options.json,
|
|
1922
|
+
verbose: options.verbose,
|
|
1923
|
+
local: options.local,
|
|
1924
|
+
dryRun: options.dryRun,
|
|
1925
|
+
silent: options.silent
|
|
1926
|
+
});
|
|
1927
|
+
});
|
|
1928
|
+
var isMainModule = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
|
|
1929
|
+
if (isMainModule) {
|
|
1930
|
+
program.parse();
|
|
1931
|
+
}
|
|
1932
|
+
export {
|
|
1933
|
+
bundle,
|
|
1934
|
+
bundleCommand,
|
|
1935
|
+
run,
|
|
1936
|
+
runCommand,
|
|
1937
|
+
simulate,
|
|
1938
|
+
simulateCommand
|
|
1939
|
+
};
|
|
1940
|
+
//# sourceMappingURL=index.js.map
|