monitai 0.0.0-stage → 0.4.4
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/LICENSE +21 -0
- package/README.md +75 -2
- package/dist/actions-registry-B5JBDO5F.js +43 -0
- package/dist/chunk-63FHD5ZT.js +169 -0
- package/dist/chunk-JU76LRZA.js +623 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +984 -0
- package/dist/client-Dq7v7zCx.d.ts +91 -0
- package/dist/client.d.ts +2 -0
- package/dist/client.js +26 -0
- package/dist/index.d.ts +163 -0
- package/dist/index.js +98 -0
- package/dist/internal/island-runtime.d.ts +3 -0
- package/dist/internal/island-runtime.js +19 -0
- package/package.json +61 -4
- package/template/.env.example +16 -0
- package/template/_gitignore +8 -0
- package/template/islands/counter/counter.view.tsx +18 -0
- package/template/islands/incident-simulator/incident-simulator.actions.ts +36 -0
- package/template/islands/incident-simulator/incident-simulator.view.tsx +50 -0
- package/template/islands/service-monitor/service-monitor.server.ts +24 -0
- package/template/islands/service-monitor/service-monitor.types.ts +20 -0
- package/template/islands/service-monitor/service-monitor.view.tsx +38 -0
- package/template/islands/summary-banner/summary-banner.view.tsx +51 -0
- package/template/islands/weather/weather.server.ts +66 -0
- package/template/islands/weather/weather.types.ts +14 -0
- package/template/islands/weather/weather.view.tsx +35 -0
- package/template/main.tsx +45 -0
- package/template/package.json +16 -0
- package/template/styles.css +1 -0
- package/template/tsconfig.json +17 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,984 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
clearRegisteredIslandNames,
|
|
4
|
+
getRegisteredIslandNames,
|
|
5
|
+
resetIslandInstanceCounter
|
|
6
|
+
} from "./chunk-JU76LRZA.js";
|
|
7
|
+
|
|
8
|
+
// src/cli.ts
|
|
9
|
+
import * as p from "@clack/prompts";
|
|
10
|
+
import fs5 from "fs";
|
|
11
|
+
import path5 from "path";
|
|
12
|
+
import { fileURLToPath, pathToFileURL as pathToFileURL2 } from "url";
|
|
13
|
+
|
|
14
|
+
// src/internal/env-loader.ts
|
|
15
|
+
import fs from "fs";
|
|
16
|
+
import path from "path";
|
|
17
|
+
function parseEnvContent(content) {
|
|
18
|
+
const result = {};
|
|
19
|
+
const lines = content.split(/\r?\n/);
|
|
20
|
+
for (const rawLine of lines) {
|
|
21
|
+
const line = rawLine.trim();
|
|
22
|
+
if (!line || line.startsWith("#")) continue;
|
|
23
|
+
const eqIndex = line.indexOf("=");
|
|
24
|
+
if (eqIndex === -1) continue;
|
|
25
|
+
const key = line.slice(0, eqIndex).trim();
|
|
26
|
+
if (!key) continue;
|
|
27
|
+
let value = line.slice(eqIndex + 1).trim();
|
|
28
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
29
|
+
value = value.slice(1, -1);
|
|
30
|
+
} else {
|
|
31
|
+
const commentIdx = value.indexOf(" #");
|
|
32
|
+
if (commentIdx !== -1) {
|
|
33
|
+
value = value.slice(0, commentIdx).trim();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
result[key] = value;
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
function loadProjectEnv(userRoot) {
|
|
41
|
+
const envFiles = [".env", ".env.local"];
|
|
42
|
+
const merged = {};
|
|
43
|
+
for (const file of envFiles) {
|
|
44
|
+
const filePath = path.join(userRoot, file);
|
|
45
|
+
if (fs.existsSync(filePath)) {
|
|
46
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
47
|
+
Object.assign(merged, parseEnvContent(content));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
51
|
+
if (process.env[key] === void 0) {
|
|
52
|
+
process.env[key] = value;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return merged;
|
|
56
|
+
}
|
|
57
|
+
function getClientEnvDefines() {
|
|
58
|
+
const defines = {
|
|
59
|
+
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "development")
|
|
60
|
+
};
|
|
61
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
62
|
+
if (key.startsWith("MONITAI_PUBLIC_") && value !== void 0) {
|
|
63
|
+
defines[`process.env.${key}`] = JSON.stringify(value);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return defines;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// src/internal/bundler.ts
|
|
70
|
+
import * as esbuild from "esbuild";
|
|
71
|
+
import fs3 from "fs";
|
|
72
|
+
import path3 from "path";
|
|
73
|
+
import { createRequire } from "module";
|
|
74
|
+
import { pathToFileURL } from "url";
|
|
75
|
+
import { spawn } from "child_process";
|
|
76
|
+
|
|
77
|
+
// src/internal/forbid-server-imports.ts
|
|
78
|
+
function createForbidServerImportsPlugin() {
|
|
79
|
+
return {
|
|
80
|
+
name: "forbid-server-imports",
|
|
81
|
+
setup(build2) {
|
|
82
|
+
build2.onResolve(
|
|
83
|
+
{ filter: /\.(server|actions)(\.(ts|js|tsx|jsx))?$/ },
|
|
84
|
+
(args) => ({
|
|
85
|
+
errors: [
|
|
86
|
+
{
|
|
87
|
+
text: `Forbidden import of server file "${args.path}" into client component "${args.importer}". Use *.types.ts for shared contracts.`
|
|
88
|
+
}
|
|
89
|
+
]
|
|
90
|
+
})
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// src/internal/island-name.ts
|
|
97
|
+
import path2 from "path";
|
|
98
|
+
import fs2 from "fs";
|
|
99
|
+
var toPosix = (p2) => p2.replace(/\\/g, "/");
|
|
100
|
+
function getCanonicalIslandName(islandsDir, filePath) {
|
|
101
|
+
const base = toPosix(path2.resolve(islandsDir)).replace(/\/$/, "") + "/";
|
|
102
|
+
const normalized = toPosix(path2.resolve(filePath));
|
|
103
|
+
if (!normalized.startsWith(base)) {
|
|
104
|
+
throw new Error(`File is not under islands/: ${filePath}`);
|
|
105
|
+
}
|
|
106
|
+
let rel = normalized.slice(base.length).replace(/\.view\.(tsx|jsx|ts|js)$/, "");
|
|
107
|
+
rel = rel.replace(/\.(tsx|jsx|ts|js)$/, "");
|
|
108
|
+
const parts = rel.split("/");
|
|
109
|
+
if (parts.length >= 2 && parts[parts.length - 1] === parts[parts.length - 2]) {
|
|
110
|
+
return parts.slice(0, -1).join("/");
|
|
111
|
+
}
|
|
112
|
+
return rel;
|
|
113
|
+
}
|
|
114
|
+
function scanIslandFiles(userRoot) {
|
|
115
|
+
const islandsDir = path2.resolve(userRoot, "islands");
|
|
116
|
+
const out = [];
|
|
117
|
+
function walk(dir) {
|
|
118
|
+
if (!fs2.existsSync(dir)) return;
|
|
119
|
+
for (const entry of fs2.readdirSync(dir, { withFileTypes: true })) {
|
|
120
|
+
const full = path2.join(dir, entry.name);
|
|
121
|
+
if (entry.isDirectory()) walk(full);
|
|
122
|
+
else if (/\.view\.(tsx|jsx)$/.test(entry.name)) out.push(full);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
walk(islandsDir);
|
|
126
|
+
return out.sort();
|
|
127
|
+
}
|
|
128
|
+
function validateIslandNames(userRoot, registeredNames) {
|
|
129
|
+
const islandsDir = path2.resolve(userRoot, "islands");
|
|
130
|
+
const files = scanIslandFiles(userRoot);
|
|
131
|
+
const fromDisk = new Set(
|
|
132
|
+
files.map((f) => getCanonicalIslandName(islandsDir, f))
|
|
133
|
+
);
|
|
134
|
+
const warnings = [];
|
|
135
|
+
for (const name of registeredNames) {
|
|
136
|
+
if (!fromDisk.has(name)) {
|
|
137
|
+
warnings.push(
|
|
138
|
+
`island('${name}') not found among *.view.tsx (expected islands/${name}/\u2026 or islands/${name}.view.tsx)`
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
for (const name of fromDisk) {
|
|
143
|
+
if (!registeredNames.includes(name)) {
|
|
144
|
+
warnings.push(
|
|
145
|
+
`Found ${name}.view.tsx, but island('${name}', \u2026) was not called in main.tsx`
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return warnings;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/internal/bundler.ts
|
|
153
|
+
import { renderToString } from "preact-render-to-string";
|
|
154
|
+
function getBundlerPaths(userRoot, mode) {
|
|
155
|
+
const outDir = mode === "dev" ? path3.resolve(userRoot, ".monitai") : path3.resolve(userRoot, "dist");
|
|
156
|
+
return {
|
|
157
|
+
outDir,
|
|
158
|
+
serverBundle: path3.join(outDir, "server.mjs"),
|
|
159
|
+
clientBundle: path3.join(outDir, "client.js"),
|
|
160
|
+
cssBundle: path3.join(outDir, "styles.css")
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function resolveFromRoots(spec, userRoot, packageRoot2) {
|
|
164
|
+
for (const root of [userRoot, packageRoot2]) {
|
|
165
|
+
try {
|
|
166
|
+
const req = createRequire(path3.join(root, "package.json"));
|
|
167
|
+
return req.resolve(spec);
|
|
168
|
+
} catch {
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
throw new Error(`Cannot resolve ${spec} from user or monitai node_modules`);
|
|
172
|
+
}
|
|
173
|
+
function resolveMonitaiClient(packageRoot2) {
|
|
174
|
+
return path3.resolve(packageRoot2, "dist/client.js");
|
|
175
|
+
}
|
|
176
|
+
function createPreactAliasPlugin(userRoot, packageRoot2) {
|
|
177
|
+
const cache = /* @__PURE__ */ new Map();
|
|
178
|
+
return {
|
|
179
|
+
name: "monitai-preact-alias",
|
|
180
|
+
setup(build2) {
|
|
181
|
+
build2.onResolve({ filter: /^(preact)(\/.*)?$/ }, (args) => {
|
|
182
|
+
let resolved = cache.get(args.path);
|
|
183
|
+
if (!resolved) {
|
|
184
|
+
resolved = resolveFromRoots(args.path, userRoot, packageRoot2);
|
|
185
|
+
cache.set(args.path, resolved);
|
|
186
|
+
}
|
|
187
|
+
return { path: resolved };
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function createMonitaiClientAliasPlugin(clientEntry) {
|
|
193
|
+
return {
|
|
194
|
+
name: "monitai-client-alias",
|
|
195
|
+
setup(build2) {
|
|
196
|
+
build2.onResolve({ filter: /^monitai$/ }, () => ({
|
|
197
|
+
path: clientEntry
|
|
198
|
+
}));
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function buildClientEntrypointSource(userRoot, entryDir) {
|
|
203
|
+
const files = scanIslandFiles(userRoot);
|
|
204
|
+
const islandsDir = path3.resolve(userRoot, "islands");
|
|
205
|
+
const imports = [];
|
|
206
|
+
const registry = [];
|
|
207
|
+
files.forEach((file, i) => {
|
|
208
|
+
const name = getCanonicalIslandName(islandsDir, file);
|
|
209
|
+
let rel = toPosix(path3.relative(entryDir, file));
|
|
210
|
+
if (!rel.startsWith(".")) rel = "./" + rel;
|
|
211
|
+
imports.push(`import * as Island${i} from ${JSON.stringify(rel)}`);
|
|
212
|
+
registry.push(` ${JSON.stringify(name)}: Island${i}.default`);
|
|
213
|
+
});
|
|
214
|
+
return `
|
|
215
|
+
import { hydrateIslands } from 'monitai/internal/island-runtime'
|
|
216
|
+
${imports.join("\n")}
|
|
217
|
+
|
|
218
|
+
hydrateIslands({
|
|
219
|
+
${registry.join(",\n")}
|
|
220
|
+
})
|
|
221
|
+
`;
|
|
222
|
+
}
|
|
223
|
+
async function writeClientVirtualEntry(userRoot, outDir) {
|
|
224
|
+
const entryPath = path3.join(outDir, "_client_entry.mjs");
|
|
225
|
+
fs3.mkdirSync(outDir, { recursive: true });
|
|
226
|
+
fs3.writeFileSync(
|
|
227
|
+
entryPath,
|
|
228
|
+
buildClientEntrypointSource(userRoot, outDir),
|
|
229
|
+
"utf-8"
|
|
230
|
+
);
|
|
231
|
+
return entryPath;
|
|
232
|
+
}
|
|
233
|
+
function resolveTailwindCliEntry(packageRoot2) {
|
|
234
|
+
const req = createRequire(path3.join(packageRoot2, "package.json"));
|
|
235
|
+
const cliPkgJson = req.resolve("@tailwindcss/cli/package.json");
|
|
236
|
+
return path3.join(path3.dirname(cliPkgJson), "dist", "index.mjs");
|
|
237
|
+
}
|
|
238
|
+
function tailwindEnv(packageRoot2) {
|
|
239
|
+
return {
|
|
240
|
+
...process.env,
|
|
241
|
+
NODE_PATH: [
|
|
242
|
+
path3.join(packageRoot2, "node_modules"),
|
|
243
|
+
process.env.NODE_PATH
|
|
244
|
+
].filter(Boolean).join(path3.delimiter)
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
function runTailwindOnce(options) {
|
|
248
|
+
const entry = resolveTailwindCliEntry(options.packageRoot);
|
|
249
|
+
const args = [entry, "-i", options.inputCss, "-o", options.outputCss];
|
|
250
|
+
if (options.minify) args.push("--minify");
|
|
251
|
+
return new Promise((resolve, reject) => {
|
|
252
|
+
const child = spawn(process.execPath, args, {
|
|
253
|
+
cwd: options.userRoot,
|
|
254
|
+
stdio: "inherit",
|
|
255
|
+
env: tailwindEnv(options.packageRoot)
|
|
256
|
+
});
|
|
257
|
+
child.on("error", reject);
|
|
258
|
+
child.on(
|
|
259
|
+
"exit",
|
|
260
|
+
(code) => code === 0 ? resolve() : reject(new Error(`tailwindcss exited with code ${code}`))
|
|
261
|
+
);
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
function startTailwindWatch(options) {
|
|
265
|
+
const entry = resolveTailwindCliEntry(options.packageRoot);
|
|
266
|
+
const args = [
|
|
267
|
+
entry,
|
|
268
|
+
"-i",
|
|
269
|
+
options.inputCss,
|
|
270
|
+
"-o",
|
|
271
|
+
options.outputCss,
|
|
272
|
+
"--watch"
|
|
273
|
+
];
|
|
274
|
+
return spawn(process.execPath, args, {
|
|
275
|
+
cwd: options.userRoot,
|
|
276
|
+
stdio: "inherit",
|
|
277
|
+
env: tailwindEnv(options.packageRoot)
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
function waitForFile(filePath, timeoutMs) {
|
|
281
|
+
const started = Date.now();
|
|
282
|
+
return new Promise((resolve, reject) => {
|
|
283
|
+
const tick = () => {
|
|
284
|
+
if (fs3.existsSync(filePath) && fs3.statSync(filePath).size > 0) {
|
|
285
|
+
resolve();
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (Date.now() - started > timeoutMs) {
|
|
289
|
+
reject(new Error(`Timed out waiting for ${filePath}`));
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
setTimeout(tick, 50);
|
|
293
|
+
};
|
|
294
|
+
tick();
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
async function warmUpPage(page, options) {
|
|
298
|
+
if (!page?.getRuntime) return;
|
|
299
|
+
const { clearActions, registerActions } = await import("./actions-registry-B5JBDO5F.js");
|
|
300
|
+
clearActions();
|
|
301
|
+
registerActions(page.actions);
|
|
302
|
+
if (!page.render) return;
|
|
303
|
+
try {
|
|
304
|
+
resetIslandInstanceCounter();
|
|
305
|
+
const runtime = page.getRuntime();
|
|
306
|
+
const snapshot = runtime.store.getSnapshot();
|
|
307
|
+
const vnode = await page.render({ snapshot });
|
|
308
|
+
renderToString(vnode);
|
|
309
|
+
} catch (err) {
|
|
310
|
+
console.warn(
|
|
311
|
+
"[monitai] warm-up render failed:",
|
|
312
|
+
err instanceof Error ? err.message : err
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
if (options?.userRoot) {
|
|
316
|
+
const warnings = validateIslandNames(
|
|
317
|
+
options.userRoot,
|
|
318
|
+
getRegisteredIslandNames()
|
|
319
|
+
);
|
|
320
|
+
for (const w of warnings) {
|
|
321
|
+
console.warn(`[monitai] ${w}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
async function startDevBundler(options) {
|
|
326
|
+
const { userRoot, packageRoot: packageRoot2 } = options;
|
|
327
|
+
const paths = getBundlerPaths(userRoot, "dev");
|
|
328
|
+
fs3.mkdirSync(paths.outDir, { recursive: true });
|
|
329
|
+
const monitaiClient = resolveMonitaiClient(packageRoot2);
|
|
330
|
+
const mainFile = path3.resolve(userRoot, "main.tsx");
|
|
331
|
+
const stylesIn = path3.resolve(userRoot, "styles.css");
|
|
332
|
+
let pageModule = null;
|
|
333
|
+
let httpServer = null;
|
|
334
|
+
let reloadQueue = Promise.resolve();
|
|
335
|
+
let children = [];
|
|
336
|
+
let suppressWatchReload = false;
|
|
337
|
+
const enqueueReload = (task) => {
|
|
338
|
+
reloadQueue = reloadQueue.then(task).catch((err) => {
|
|
339
|
+
console.error("[monitai] reload failed:", err);
|
|
340
|
+
});
|
|
341
|
+
return reloadQueue;
|
|
342
|
+
};
|
|
343
|
+
const loadServerModule = async () => {
|
|
344
|
+
let oldRuntime = null;
|
|
345
|
+
if (pageModule?.default?.getRuntime) {
|
|
346
|
+
try {
|
|
347
|
+
oldRuntime = pageModule.default.getRuntime();
|
|
348
|
+
oldRuntime.store.markAllStale();
|
|
349
|
+
oldRuntime.store.resetAllPaused();
|
|
350
|
+
oldRuntime.agent.stop();
|
|
351
|
+
oldRuntime.poller.reset();
|
|
352
|
+
} catch {
|
|
353
|
+
oldRuntime = null;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
clearRegisteredIslandNames();
|
|
357
|
+
const url = pathToFileURL(paths.serverBundle).href + `?t=${Date.now()}`;
|
|
358
|
+
pageModule = await import(url);
|
|
359
|
+
await warmUpPage(pageModule.default, { userRoot });
|
|
360
|
+
if (oldRuntime) {
|
|
361
|
+
const removed = oldRuntime.store.removeStaleSources();
|
|
362
|
+
for (const id of removed) {
|
|
363
|
+
try {
|
|
364
|
+
pageModule.default.getRuntime().poller.unregister(id);
|
|
365
|
+
} catch {
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
if (!suppressWatchReload) httpServer?.broadcastReload();
|
|
370
|
+
};
|
|
371
|
+
const clientEntry = await writeClientVirtualEntry(userRoot, paths.outDir);
|
|
372
|
+
const sharedJsx = {
|
|
373
|
+
jsx: "automatic",
|
|
374
|
+
jsxImportSource: "preact"
|
|
375
|
+
};
|
|
376
|
+
const serverCtx = await esbuild.context({
|
|
377
|
+
absWorkingDir: userRoot,
|
|
378
|
+
entryPoints: [mainFile],
|
|
379
|
+
outfile: paths.serverBundle,
|
|
380
|
+
bundle: true,
|
|
381
|
+
platform: "node",
|
|
382
|
+
format: "esm",
|
|
383
|
+
...sharedJsx,
|
|
384
|
+
packages: "bundle",
|
|
385
|
+
plugins: [createPreactAliasPlugin(userRoot, packageRoot2)],
|
|
386
|
+
external: [
|
|
387
|
+
"monitai",
|
|
388
|
+
"monitai/internal/island-runtime",
|
|
389
|
+
"monitai/client"
|
|
390
|
+
]
|
|
391
|
+
});
|
|
392
|
+
const clientCtx = await esbuild.context({
|
|
393
|
+
absWorkingDir: userRoot,
|
|
394
|
+
entryPoints: [clientEntry],
|
|
395
|
+
outfile: paths.clientBundle,
|
|
396
|
+
bundle: true,
|
|
397
|
+
platform: "browser",
|
|
398
|
+
format: "esm",
|
|
399
|
+
...sharedJsx,
|
|
400
|
+
define: getClientEnvDefines(),
|
|
401
|
+
plugins: [
|
|
402
|
+
createForbidServerImportsPlugin(),
|
|
403
|
+
createMonitaiClientAliasPlugin(monitaiClient),
|
|
404
|
+
createPreactAliasPlugin(userRoot, packageRoot2)
|
|
405
|
+
]
|
|
406
|
+
});
|
|
407
|
+
suppressWatchReload = true;
|
|
408
|
+
const serverResult = await serverCtx.rebuild();
|
|
409
|
+
if (serverResult.errors.length) {
|
|
410
|
+
throw new Error(
|
|
411
|
+
"Server bundle failed: " + serverResult.errors.map((e) => e.text).join("; ")
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
await clientCtx.rebuild();
|
|
415
|
+
await loadServerModule();
|
|
416
|
+
suppressWatchReload = false;
|
|
417
|
+
await serverCtx.watch();
|
|
418
|
+
await clientCtx.watch();
|
|
419
|
+
const serverWatcher = fs3.watch(paths.outDir, (event, filename) => {
|
|
420
|
+
if (filename === "server.mjs" && (event === "change" || event === "rename")) {
|
|
421
|
+
void enqueueReload(loadServerModule);
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
if (fs3.existsSync(stylesIn)) {
|
|
425
|
+
const tw = startTailwindWatch({
|
|
426
|
+
userRoot,
|
|
427
|
+
packageRoot: packageRoot2,
|
|
428
|
+
inputCss: stylesIn,
|
|
429
|
+
outputCss: paths.cssBundle
|
|
430
|
+
});
|
|
431
|
+
children.push(tw);
|
|
432
|
+
await waitForFile(paths.cssBundle, 15e3);
|
|
433
|
+
}
|
|
434
|
+
const islandsDir = path3.resolve(userRoot, "islands");
|
|
435
|
+
let islandsWatcher = null;
|
|
436
|
+
if (fs3.existsSync(islandsDir)) {
|
|
437
|
+
islandsWatcher = fs3.watch(islandsDir, { recursive: true }, () => {
|
|
438
|
+
void (async () => {
|
|
439
|
+
await writeClientVirtualEntry(userRoot, paths.outDir);
|
|
440
|
+
await clientCtx.rebuild();
|
|
441
|
+
})();
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
return {
|
|
445
|
+
paths,
|
|
446
|
+
getPageModule: () => {
|
|
447
|
+
if (!pageModule) throw new Error("Server module not loaded");
|
|
448
|
+
return pageModule;
|
|
449
|
+
},
|
|
450
|
+
setHttpServer: (h) => {
|
|
451
|
+
httpServer = h;
|
|
452
|
+
},
|
|
453
|
+
stop: async () => {
|
|
454
|
+
serverWatcher.close();
|
|
455
|
+
islandsWatcher?.close();
|
|
456
|
+
await serverCtx.dispose();
|
|
457
|
+
await clientCtx.dispose();
|
|
458
|
+
for (const child of children) {
|
|
459
|
+
try {
|
|
460
|
+
child.kill();
|
|
461
|
+
} catch {
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
children = [];
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
async function buildProduction(options) {
|
|
469
|
+
const { userRoot, packageRoot: packageRoot2 } = options;
|
|
470
|
+
const paths = getBundlerPaths(userRoot, "build");
|
|
471
|
+
fs3.mkdirSync(paths.outDir, { recursive: true });
|
|
472
|
+
const monitaiClient = resolveMonitaiClient(packageRoot2);
|
|
473
|
+
const mainFile = path3.resolve(userRoot, "main.tsx");
|
|
474
|
+
const stylesIn = path3.resolve(userRoot, "styles.css");
|
|
475
|
+
const clientEntry = await writeClientVirtualEntry(userRoot, paths.outDir);
|
|
476
|
+
const sharedJsx = {
|
|
477
|
+
jsx: "automatic",
|
|
478
|
+
jsxImportSource: "preact"
|
|
479
|
+
};
|
|
480
|
+
await esbuild.build({
|
|
481
|
+
absWorkingDir: userRoot,
|
|
482
|
+
entryPoints: [mainFile],
|
|
483
|
+
outfile: paths.serverBundle,
|
|
484
|
+
bundle: true,
|
|
485
|
+
platform: "node",
|
|
486
|
+
format: "esm",
|
|
487
|
+
minify: true,
|
|
488
|
+
...sharedJsx,
|
|
489
|
+
plugins: [createPreactAliasPlugin(userRoot, packageRoot2)],
|
|
490
|
+
external: [
|
|
491
|
+
"monitai",
|
|
492
|
+
"monitai/internal/island-runtime",
|
|
493
|
+
"monitai/client"
|
|
494
|
+
]
|
|
495
|
+
});
|
|
496
|
+
await esbuild.build({
|
|
497
|
+
absWorkingDir: userRoot,
|
|
498
|
+
entryPoints: [clientEntry],
|
|
499
|
+
outfile: paths.clientBundle,
|
|
500
|
+
bundle: true,
|
|
501
|
+
platform: "browser",
|
|
502
|
+
format: "esm",
|
|
503
|
+
minify: true,
|
|
504
|
+
...sharedJsx,
|
|
505
|
+
define: {
|
|
506
|
+
...getClientEnvDefines(),
|
|
507
|
+
"process.env.NODE_ENV": JSON.stringify("production")
|
|
508
|
+
},
|
|
509
|
+
plugins: [
|
|
510
|
+
createForbidServerImportsPlugin(),
|
|
511
|
+
createMonitaiClientAliasPlugin(monitaiClient),
|
|
512
|
+
createPreactAliasPlugin(userRoot, packageRoot2)
|
|
513
|
+
]
|
|
514
|
+
});
|
|
515
|
+
if (fs3.existsSync(stylesIn)) {
|
|
516
|
+
await runTailwindOnce({
|
|
517
|
+
userRoot,
|
|
518
|
+
packageRoot: packageRoot2,
|
|
519
|
+
inputCss: stylesIn,
|
|
520
|
+
outputCss: paths.cssBundle,
|
|
521
|
+
minify: true
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
return paths;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// src/internal/http-server.ts
|
|
528
|
+
import http from "http";
|
|
529
|
+
import fs4 from "fs";
|
|
530
|
+
import path4 from "path";
|
|
531
|
+
import { renderToString as renderToString2 } from "preact-render-to-string";
|
|
532
|
+
var MIME = {
|
|
533
|
+
".html": "text/html; charset=utf-8",
|
|
534
|
+
".js": "application/javascript; charset=utf-8",
|
|
535
|
+
".css": "text/css; charset=utf-8",
|
|
536
|
+
".json": "application/json; charset=utf-8",
|
|
537
|
+
".svg": "image/svg+xml",
|
|
538
|
+
".png": "image/png",
|
|
539
|
+
".jpg": "image/jpeg",
|
|
540
|
+
".jpeg": "image/jpeg",
|
|
541
|
+
".gif": "image/gif",
|
|
542
|
+
".ico": "image/x-icon",
|
|
543
|
+
".woff": "font/woff",
|
|
544
|
+
".woff2": "font/woff2"
|
|
545
|
+
};
|
|
546
|
+
var lastRefreshAt = 0;
|
|
547
|
+
var REFRESH_COOLDOWN_MS = 5e3;
|
|
548
|
+
function startHttpServer(options) {
|
|
549
|
+
const sseClients = /* @__PURE__ */ new Set();
|
|
550
|
+
const broadcastReload = () => {
|
|
551
|
+
for (const res of sseClients) {
|
|
552
|
+
try {
|
|
553
|
+
res.write(`event: reload
|
|
554
|
+
data: {}
|
|
555
|
+
|
|
556
|
+
`);
|
|
557
|
+
} catch {
|
|
558
|
+
sseClients.delete(res);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
const server = http.createServer(async (req, res) => {
|
|
563
|
+
try {
|
|
564
|
+
await handleRequest(req, res, options, sseClients);
|
|
565
|
+
} catch (err) {
|
|
566
|
+
if (!res.headersSent) {
|
|
567
|
+
res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
|
|
568
|
+
}
|
|
569
|
+
res.end(`Error: ${err instanceof Error ? err.stack : String(err)}`);
|
|
570
|
+
}
|
|
571
|
+
});
|
|
572
|
+
server.listen(options.port, options.host, () => {
|
|
573
|
+
console.log(
|
|
574
|
+
`
|
|
575
|
+
\u26A1 Monitai server: http://${options.host === "0.0.0.0" ? "localhost" : options.host}:${options.port}/`
|
|
576
|
+
);
|
|
577
|
+
});
|
|
578
|
+
return {
|
|
579
|
+
server,
|
|
580
|
+
broadcastReload,
|
|
581
|
+
close: () => new Promise((resolve, reject) => {
|
|
582
|
+
for (const res of sseClients) {
|
|
583
|
+
try {
|
|
584
|
+
res.end();
|
|
585
|
+
} catch {
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
sseClients.clear();
|
|
589
|
+
server.close((err) => err ? reject(err) : resolve());
|
|
590
|
+
})
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
async function handleRequest(req, res, options, sseClients) {
|
|
594
|
+
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
|
|
595
|
+
const pathname = url.pathname;
|
|
596
|
+
const method = req.method || "GET";
|
|
597
|
+
if (method === "GET" && pathname === "/_monitai/client.js") {
|
|
598
|
+
return pipeFile(res, options.clientBundlePath, "application/javascript; charset=utf-8");
|
|
599
|
+
}
|
|
600
|
+
if (method === "GET" && pathname === "/styles.css") {
|
|
601
|
+
if (fs4.existsSync(options.cssBundlePath)) {
|
|
602
|
+
return pipeFile(res, options.cssBundlePath, "text/css; charset=utf-8");
|
|
603
|
+
}
|
|
604
|
+
res.writeHead(200, { "Content-Type": "text/css; charset=utf-8" });
|
|
605
|
+
res.end("");
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
let page = null;
|
|
609
|
+
let runtime = null;
|
|
610
|
+
try {
|
|
611
|
+
page = options.getPageModule().default;
|
|
612
|
+
if (page?.getRuntime) runtime = page.getRuntime();
|
|
613
|
+
} catch {
|
|
614
|
+
runtime = null;
|
|
615
|
+
}
|
|
616
|
+
if (method === "GET" && pathname === "/_monitai/snapshot") {
|
|
617
|
+
if (!runtime) return json(res, 503, { error: "runtime_unavailable" });
|
|
618
|
+
return json(res, 200, runtime.store.getSnapshot());
|
|
619
|
+
}
|
|
620
|
+
if (method === "GET" && pathname.startsWith("/_monitai/sources/")) {
|
|
621
|
+
if (!runtime) return json(res, 503, { error: "runtime_unavailable" });
|
|
622
|
+
const id = decodeURIComponent(pathname.slice("/_monitai/sources/".length));
|
|
623
|
+
const source = runtime.store.getSource(id);
|
|
624
|
+
return json(res, source ? 200 : 404, source ?? { error: "not_found" });
|
|
625
|
+
}
|
|
626
|
+
if (method === "GET" && pathname === "/_monitai/summary") {
|
|
627
|
+
if (!runtime) return json(res, 503, { error: "runtime_unavailable" });
|
|
628
|
+
return json(res, 200, { summary: runtime.store.getSnapshot().summary });
|
|
629
|
+
}
|
|
630
|
+
if (method === "POST" && pathname === "/_monitai/summary/refresh") {
|
|
631
|
+
if (!runtime) return json(res, 503, { error: "runtime_unavailable" });
|
|
632
|
+
const now = Date.now();
|
|
633
|
+
if (now - lastRefreshAt < REFRESH_COOLDOWN_MS) {
|
|
634
|
+
return json(res, 429, {
|
|
635
|
+
error: "rate_limited",
|
|
636
|
+
summary: runtime.store.getSnapshot().summary
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
lastRefreshAt = now;
|
|
640
|
+
const summary = await runtime.agent.triggerSummary(true);
|
|
641
|
+
return json(res, 200, { summary });
|
|
642
|
+
}
|
|
643
|
+
if (method === "POST" && pathname.startsWith("/_monitai/actions/")) {
|
|
644
|
+
if (!runtime) return json(res, 503, { error: "runtime_unavailable" });
|
|
645
|
+
const actionId = decodeURIComponent(
|
|
646
|
+
pathname.slice("/_monitai/actions/".length)
|
|
647
|
+
);
|
|
648
|
+
const { getAction, touchActionCalled } = await import("./actions-registry-B5JBDO5F.js");
|
|
649
|
+
const action = getAction(actionId);
|
|
650
|
+
if (!action) return json(res, 404, { error: "action_not_found" });
|
|
651
|
+
const contentType = req.headers["content-type"];
|
|
652
|
+
if (!contentType?.startsWith("application/json")) {
|
|
653
|
+
return json(res, 415, { error: "unsupported_media_type" });
|
|
654
|
+
}
|
|
655
|
+
const rateMs = action.rateLimitMs ?? 0;
|
|
656
|
+
if (rateMs > 0 && Date.now() - action.lastCalledAt < rateMs) {
|
|
657
|
+
return json(res, 429, { error: "rate_limited" });
|
|
658
|
+
}
|
|
659
|
+
const maxBytes = action.maxBodyBytes ?? 65536;
|
|
660
|
+
let body;
|
|
661
|
+
try {
|
|
662
|
+
const raw = await readBodyLimited(req, maxBytes);
|
|
663
|
+
body = raw.length ? JSON.parse(raw) : null;
|
|
664
|
+
} catch (err) {
|
|
665
|
+
if (err.code === "PAYLOAD_TOO_LARGE") {
|
|
666
|
+
return json(res, 413, { error: "payload_too_large" });
|
|
667
|
+
}
|
|
668
|
+
return json(res, 400, { error: "invalid_json" });
|
|
669
|
+
}
|
|
670
|
+
touchActionCalled(actionId);
|
|
671
|
+
try {
|
|
672
|
+
const result = await action.handler(body, {
|
|
673
|
+
store: runtime.store,
|
|
674
|
+
poller: runtime.poller,
|
|
675
|
+
agent: runtime.agent
|
|
676
|
+
});
|
|
677
|
+
return json(res, 200, { data: result });
|
|
678
|
+
} catch (err) {
|
|
679
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
680
|
+
return json(res, 500, { error: message });
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
if (method === "GET" && pathname === "/_monitai/stream") {
|
|
684
|
+
if (!runtime) {
|
|
685
|
+
res.writeHead(503, { "Content-Type": "text/plain; charset=utf-8" });
|
|
686
|
+
res.end("runtime_unavailable");
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
res.writeHead(200, {
|
|
690
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
691
|
+
"Cache-Control": "no-cache, no-transform",
|
|
692
|
+
Connection: "keep-alive"
|
|
693
|
+
});
|
|
694
|
+
res.write(": connected\n\n");
|
|
695
|
+
const snap = runtime.store.getSnapshot();
|
|
696
|
+
for (const source of Object.values(snap.sources)) {
|
|
697
|
+
res.write(
|
|
698
|
+
`event: source:updated
|
|
699
|
+
data: ${JSON.stringify({ type: "source:updated", source })}
|
|
700
|
+
|
|
701
|
+
`
|
|
702
|
+
);
|
|
703
|
+
}
|
|
704
|
+
if (snap.summary) {
|
|
705
|
+
res.write(
|
|
706
|
+
`event: summary:updated
|
|
707
|
+
data: ${JSON.stringify({ type: "summary:updated", summary: snap.summary })}
|
|
708
|
+
|
|
709
|
+
`
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
sseClients.add(res);
|
|
713
|
+
const unsub = runtime.store.subscribe((event) => {
|
|
714
|
+
try {
|
|
715
|
+
res.write(`event: ${event.type}
|
|
716
|
+
data: ${JSON.stringify(event)}
|
|
717
|
+
|
|
718
|
+
`);
|
|
719
|
+
} catch {
|
|
720
|
+
unsub();
|
|
721
|
+
sseClients.delete(res);
|
|
722
|
+
}
|
|
723
|
+
});
|
|
724
|
+
const heartbeat = setInterval(() => {
|
|
725
|
+
try {
|
|
726
|
+
res.write(`: ping
|
|
727
|
+
|
|
728
|
+
`);
|
|
729
|
+
} catch {
|
|
730
|
+
clearInterval(heartbeat);
|
|
731
|
+
unsub();
|
|
732
|
+
sseClients.delete(res);
|
|
733
|
+
}
|
|
734
|
+
}, 15e3);
|
|
735
|
+
req.on("close", () => {
|
|
736
|
+
clearInterval(heartbeat);
|
|
737
|
+
unsub();
|
|
738
|
+
sseClients.delete(res);
|
|
739
|
+
});
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
if (method === "GET" && pathname === "/") {
|
|
743
|
+
if (!page || !runtime) {
|
|
744
|
+
res.writeHead(503, { "Content-Type": "text/plain; charset=utf-8" });
|
|
745
|
+
res.end("Page module or runtime unavailable");
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
resetIslandInstanceCounter();
|
|
749
|
+
const snapshot = runtime.store.getSnapshot();
|
|
750
|
+
const vnode = await page.render({ snapshot });
|
|
751
|
+
const bodyHtml = renderToString2(vnode);
|
|
752
|
+
const title = page.title ?? "Monitai App";
|
|
753
|
+
const html = `<!DOCTYPE html>
|
|
754
|
+
<html lang="ru">
|
|
755
|
+
<head>
|
|
756
|
+
<meta charset="utf-8" />
|
|
757
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
758
|
+
<title>${escapeHtml(title)}</title>
|
|
759
|
+
<link rel="stylesheet" href="/styles.css" />
|
|
760
|
+
<script type="module" src="/_monitai/client.js"></script>
|
|
761
|
+
</head>
|
|
762
|
+
<body>
|
|
763
|
+
${bodyHtml}
|
|
764
|
+
</body>
|
|
765
|
+
</html>`;
|
|
766
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
767
|
+
res.end(html);
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
if (method === "GET" && pathname !== "/") {
|
|
771
|
+
const safe = safePublicPath(options.publicDir, pathname);
|
|
772
|
+
if (safe && fs4.existsSync(safe) && fs4.statSync(safe).isFile()) {
|
|
773
|
+
const ext = path4.extname(safe).toLowerCase();
|
|
774
|
+
return pipeFile(res, safe, MIME[ext] || "application/octet-stream");
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
|
778
|
+
res.end("Not Found");
|
|
779
|
+
}
|
|
780
|
+
function json(res, status, body) {
|
|
781
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
782
|
+
res.end(JSON.stringify(body));
|
|
783
|
+
}
|
|
784
|
+
async function readBodyLimited(req, maxBytes) {
|
|
785
|
+
const chunks = [];
|
|
786
|
+
let total = 0;
|
|
787
|
+
for await (const chunk of req) {
|
|
788
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
789
|
+
total += buf.length;
|
|
790
|
+
if (total > maxBytes) {
|
|
791
|
+
req.resume();
|
|
792
|
+
const err = new Error("payload_too_large");
|
|
793
|
+
err.code = "PAYLOAD_TOO_LARGE";
|
|
794
|
+
throw err;
|
|
795
|
+
}
|
|
796
|
+
chunks.push(buf);
|
|
797
|
+
}
|
|
798
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
799
|
+
}
|
|
800
|
+
function pipeFile(res, filePath, contentType) {
|
|
801
|
+
res.writeHead(200, { "Content-Type": contentType });
|
|
802
|
+
fs4.createReadStream(filePath).pipe(res);
|
|
803
|
+
}
|
|
804
|
+
function safePublicPath(publicDir, pathname) {
|
|
805
|
+
if (pathname.includes("\0")) return null;
|
|
806
|
+
const decoded = decodeURIComponent(pathname);
|
|
807
|
+
const root = path4.resolve(publicDir);
|
|
808
|
+
const candidate = path4.resolve(root, "." + decoded);
|
|
809
|
+
if (!candidate.startsWith(root + path4.sep) && candidate !== root) return null;
|
|
810
|
+
return candidate;
|
|
811
|
+
}
|
|
812
|
+
function escapeHtml(s) {
|
|
813
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// src/cli.ts
|
|
817
|
+
var __dirname = path5.dirname(fileURLToPath(import.meta.url));
|
|
818
|
+
var packageRoot = path5.resolve(__dirname, "..");
|
|
819
|
+
var command = process.argv[2];
|
|
820
|
+
async function runInit(options = {}) {
|
|
821
|
+
const local = options.local === true;
|
|
822
|
+
p.intro(
|
|
823
|
+
local ? "\u{1F680} Initializing Monitai project (local package)" : "\u{1F680} Initializing Monitai project"
|
|
824
|
+
);
|
|
825
|
+
const targetDir = process.cwd();
|
|
826
|
+
const templateDir = path5.resolve(__dirname, "../template");
|
|
827
|
+
if (!fs5.existsSync(templateDir)) {
|
|
828
|
+
p.cancel(`Template folder not found: ${templateDir}`);
|
|
829
|
+
process.exit(1);
|
|
830
|
+
}
|
|
831
|
+
const spinner2 = p.spinner();
|
|
832
|
+
spinner2.start("Creating project structure...");
|
|
833
|
+
fs5.cpSync(templateDir, targetDir, { recursive: true });
|
|
834
|
+
const gitignorePath = path5.join(targetDir, "_gitignore");
|
|
835
|
+
if (fs5.existsSync(gitignorePath)) {
|
|
836
|
+
fs5.renameSync(gitignorePath, path5.join(targetDir, ".gitignore"));
|
|
837
|
+
}
|
|
838
|
+
const pkgPath = path5.join(targetDir, "package.json");
|
|
839
|
+
if (fs5.existsSync(pkgPath)) {
|
|
840
|
+
const pkg = JSON.parse(fs5.readFileSync(pkgPath, "utf-8"));
|
|
841
|
+
pkg.name = path5.basename(targetDir);
|
|
842
|
+
pkg.dependencies = pkg.dependencies ?? {};
|
|
843
|
+
pkg.dependencies.preact = "^10.24.0";
|
|
844
|
+
pkg.devDependencies = pkg.devDependencies ?? {};
|
|
845
|
+
pkg.devDependencies["@types/node"] = "^22.0.0";
|
|
846
|
+
if (local) {
|
|
847
|
+
pkg.dependencies.monitai = `file:${packageRoot}`;
|
|
848
|
+
} else {
|
|
849
|
+
delete pkg.dependencies.monitai;
|
|
850
|
+
}
|
|
851
|
+
fs5.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
|
|
852
|
+
}
|
|
853
|
+
fs5.writeFileSync(
|
|
854
|
+
path5.join(targetDir, "tsconfig.json"),
|
|
855
|
+
`${JSON.stringify(
|
|
856
|
+
{
|
|
857
|
+
compilerOptions: {
|
|
858
|
+
target: "ESNext",
|
|
859
|
+
module: "ESNext",
|
|
860
|
+
moduleResolution: "Bundler",
|
|
861
|
+
skipLibCheck: true,
|
|
862
|
+
strict: true,
|
|
863
|
+
jsx: "react-jsx",
|
|
864
|
+
jsxImportSource: "preact",
|
|
865
|
+
types: ["node"]
|
|
866
|
+
}
|
|
867
|
+
},
|
|
868
|
+
null,
|
|
869
|
+
2
|
|
870
|
+
)}
|
|
871
|
+
`
|
|
872
|
+
);
|
|
873
|
+
spinner2.stop("Files created successfully!");
|
|
874
|
+
p.outro(
|
|
875
|
+
local ? "Done! npm install && npx monitai dev" : "Done! For local package development use monitai init-dev, then npm install && npx monitai dev"
|
|
876
|
+
);
|
|
877
|
+
}
|
|
878
|
+
async function runDev() {
|
|
879
|
+
const userRoot = process.cwd();
|
|
880
|
+
const mainFile = path5.resolve(userRoot, "main.tsx");
|
|
881
|
+
if (!fs5.existsSync(mainFile)) {
|
|
882
|
+
console.error("\u274C main.tsx not found. Run: monitai init-dev");
|
|
883
|
+
process.exit(1);
|
|
884
|
+
}
|
|
885
|
+
loadProjectEnv(userRoot);
|
|
886
|
+
const bundler = await startDevBundler({ userRoot, packageRoot });
|
|
887
|
+
const port = Number(process.env.PORT) || 3e3;
|
|
888
|
+
const host = process.env.HOST || "0.0.0.0";
|
|
889
|
+
const http2 = startHttpServer({
|
|
890
|
+
port,
|
|
891
|
+
host,
|
|
892
|
+
clientBundlePath: bundler.paths.clientBundle,
|
|
893
|
+
cssBundlePath: bundler.paths.cssBundle,
|
|
894
|
+
publicDir: path5.resolve(userRoot, "public"),
|
|
895
|
+
getPageModule: bundler.getPageModule,
|
|
896
|
+
isDev: true
|
|
897
|
+
});
|
|
898
|
+
bundler.setHttpServer(http2);
|
|
899
|
+
const shutdown = async () => {
|
|
900
|
+
try {
|
|
901
|
+
const rt = bundler.getPageModule().default.getRuntime();
|
|
902
|
+
rt.agent.stop();
|
|
903
|
+
rt.poller.reset();
|
|
904
|
+
} catch {
|
|
905
|
+
}
|
|
906
|
+
await http2.close();
|
|
907
|
+
await bundler.stop();
|
|
908
|
+
process.exit(0);
|
|
909
|
+
};
|
|
910
|
+
process.on("SIGINT", () => void shutdown());
|
|
911
|
+
process.on("SIGTERM", () => void shutdown());
|
|
912
|
+
}
|
|
913
|
+
async function runBuild() {
|
|
914
|
+
const userRoot = process.cwd();
|
|
915
|
+
if (!fs5.existsSync(path5.resolve(userRoot, "main.tsx"))) {
|
|
916
|
+
console.error("\u274C main.tsx not found");
|
|
917
|
+
process.exit(1);
|
|
918
|
+
}
|
|
919
|
+
loadProjectEnv(userRoot);
|
|
920
|
+
const spinner2 = p.spinner();
|
|
921
|
+
spinner2.start("Building production bundles...");
|
|
922
|
+
const paths = await buildProduction({ userRoot, packageRoot });
|
|
923
|
+
spinner2.stop(`Done: ${paths.outDir}`);
|
|
924
|
+
}
|
|
925
|
+
async function runStart() {
|
|
926
|
+
const userRoot = process.cwd();
|
|
927
|
+
const serverBundle = path5.resolve(userRoot, "dist/server.mjs");
|
|
928
|
+
if (!fs5.existsSync(serverBundle)) {
|
|
929
|
+
console.error("\u274C dist/server.mjs not found. Run: monitai build");
|
|
930
|
+
process.exit(1);
|
|
931
|
+
}
|
|
932
|
+
loadProjectEnv(userRoot);
|
|
933
|
+
clearRegisteredIslandNames();
|
|
934
|
+
const mod = await import(pathToFileURL2(serverBundle).href);
|
|
935
|
+
const page = mod.default;
|
|
936
|
+
if (!page?.getRuntime || !page?.render) {
|
|
937
|
+
console.error("\u274C dist/server.mjs does not export a Monitai page (createPage)");
|
|
938
|
+
process.exit(1);
|
|
939
|
+
}
|
|
940
|
+
await warmUpPage(page, { userRoot });
|
|
941
|
+
const port = Number(process.env.PORT) || 3e3;
|
|
942
|
+
const host = process.env.HOST || "0.0.0.0";
|
|
943
|
+
const http2 = startHttpServer({
|
|
944
|
+
port,
|
|
945
|
+
host,
|
|
946
|
+
clientBundlePath: path5.resolve(userRoot, "dist/client.js"),
|
|
947
|
+
cssBundlePath: path5.resolve(userRoot, "dist/styles.css"),
|
|
948
|
+
publicDir: path5.resolve(userRoot, "public"),
|
|
949
|
+
getPageModule: () => mod,
|
|
950
|
+
isDev: false
|
|
951
|
+
});
|
|
952
|
+
const shutdown = async () => {
|
|
953
|
+
try {
|
|
954
|
+
const rt = page.getRuntime();
|
|
955
|
+
rt.agent.stop();
|
|
956
|
+
rt.poller.reset();
|
|
957
|
+
} catch {
|
|
958
|
+
}
|
|
959
|
+
await http2.close();
|
|
960
|
+
process.exit(0);
|
|
961
|
+
};
|
|
962
|
+
process.on("SIGINT", () => void shutdown());
|
|
963
|
+
process.on("SIGTERM", () => void shutdown());
|
|
964
|
+
void http2;
|
|
965
|
+
}
|
|
966
|
+
async function main() {
|
|
967
|
+
if (command === "init") await runInit();
|
|
968
|
+
else if (command === "init-dev") await runInit({ local: true });
|
|
969
|
+
else if (command === "dev") await runDev();
|
|
970
|
+
else if (command === "build") await runBuild();
|
|
971
|
+
else if (command === "start") await runStart();
|
|
972
|
+
else {
|
|
973
|
+
console.log("Usage:");
|
|
974
|
+
console.log(" monitai init \u2014 scaffold a project");
|
|
975
|
+
console.log(" monitai init-dev \u2014 scaffold + file:monitai");
|
|
976
|
+
console.log(" monitai dev \u2014 dev server (esbuild watch)");
|
|
977
|
+
console.log(" monitai build \u2014 production build to dist/");
|
|
978
|
+
console.log(" monitai start \u2014 run dist/server.mjs");
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
main().catch((err) => {
|
|
982
|
+
console.error(err);
|
|
983
|
+
process.exit(1);
|
|
984
|
+
});
|