@konomi-app/k2 3.4.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,19 +1,12 @@
1
1
  #!/usr/bin/env node
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
- }) : x)(function(x) {
5
- if (typeof require !== "undefined") return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
2
 
9
3
  // src/index.ts
10
- import { program as program6 } from "commander";
4
+ import { program as program5 } from "commander";
11
5
 
12
6
  // src/commands/build.ts
13
7
  import { program } from "commander";
14
- import "fs-extra";
15
8
  import path6 from "path";
16
- import chalk2 from "chalk";
9
+ import chalk from "chalk";
17
10
 
18
11
  // src/lib/constants.ts
19
12
  import path from "path";
@@ -143,198 +136,131 @@ var getDefaultK2Config = () => {
143
136
  };
144
137
  };
145
138
 
146
- // src/lib/vite.ts
147
- import chalk from "chalk";
148
- import fs2 from "fs-extra";
149
- import os from "os";
139
+ // src/lib/rsbuild.ts
140
+ import { createRsbuild } from "@rsbuild/core";
150
141
  import path5 from "path";
151
- import { build as viteBuild } from "vite";
152
- var DEFAULT_CONCURRENCY = Math.max(1, os.cpus().length - 1);
153
- async function parallelLimit(items, concurrency, fn) {
154
- const results = [];
155
- const executing = [];
156
- for (const item of items) {
157
- const promise = fn(item).then((result) => {
158
- results.push(result);
159
- });
160
- const e = promise.then(() => {
161
- executing.splice(executing.indexOf(e), 1);
162
- });
163
- executing.push(e);
164
- if (executing.length >= concurrency) {
165
- await Promise.race(executing);
142
+ import fs2 from "fs-extra";
143
+ async function buildWithRsbuild(params) {
144
+ const { entries, outDir, minify = true, sourcemap = false, injectStyles = true } = params;
145
+ const sourceMapConfig = sourcemap === "inline" ? "cheap-module-source-map" : sourcemap ? "source-map" : false;
146
+ const rsbuild = await createRsbuild({
147
+ rsbuildConfig: {
148
+ source: { entry: entries },
149
+ output: {
150
+ target: "web",
151
+ distPath: { root: outDir, js: "" },
152
+ filename: { js: "[name].js" },
153
+ filenameHash: false,
154
+ cleanDistPath: true,
155
+ injectStyles,
156
+ sourceMap: { js: sourceMapConfig },
157
+ minify
158
+ },
159
+ performance: {
160
+ chunkSplit: { strategy: "all-in-one" }
161
+ },
162
+ tools: {
163
+ htmlPlugin: false
164
+ }
166
165
  }
167
- }
168
- await Promise.all(executing);
169
- return results;
166
+ });
167
+ await rsbuild.build();
170
168
  }
171
- var createViteConfig = (config = {}) => {
172
- const plugins = [...config.plugins ?? []];
173
- try {
174
- const tsconfigPaths = __require("vite-tsconfig-paths");
175
- plugins.push(tsconfigPaths.default ? tsconfigPaths.default() : tsconfigPaths());
176
- } catch {
177
- }
178
- const mode = config.mode ?? "production";
179
- return {
180
- ...config,
181
- configFile: false,
182
- // ソースマップ関連のエラーメッセージを抑制
183
- logLevel: config.logLevel ?? "warn",
184
- // ブラウザ向けにNode.js固有のオブジェクトをビルド時に解決
185
- define: {
186
- "process.env.NODE_ENV": JSON.stringify(mode),
187
- "process.env": JSON.stringify({}),
188
- ...config.define
169
+ async function startRsbuildDevServer(params) {
170
+ const { entries, outDir, port, https, publicDir, onFirstCompile, onRecompile } = params;
171
+ const rsbuildConfig = {
172
+ source: { entry: entries },
173
+ output: {
174
+ target: "web",
175
+ distPath: { root: outDir, js: "" },
176
+ filename: { js: "[name].js" },
177
+ filenameHash: false,
178
+ cleanDistPath: false,
179
+ injectStyles: true,
180
+ sourceMap: { js: "cheap-module-source-map" },
181
+ minify: false
189
182
  },
190
- build: {
191
- ...config.build,
192
- // ブラウザ向けターゲット
193
- target: config.build?.target ?? "es2020",
194
- cssCodeSplit: false,
195
- rollupOptions: {
196
- ...config.build?.rollupOptions,
197
- onwarn: (warning, warn) => {
198
- if (["MODULE_LEVEL_DIRECTIVE"].includes(warning.code ?? "")) {
199
- return;
200
- }
201
- if (warning.message?.includes("sourcemap") || warning.code === "SOURCEMAP_ERROR") {
202
- return;
203
- }
204
- warn(warning);
205
- }
206
- }
183
+ performance: {
184
+ chunkSplit: { strategy: "all-in-one" }
207
185
  },
208
- plugins,
209
- resolve: {
210
- ...config.resolve,
211
- alias: {
212
- "@": path5.resolve(process.cwd(), "src"),
213
- ...config.resolve?.alias
214
- }
186
+ tools: {
187
+ htmlPlugin: false
188
+ },
189
+ server: {
190
+ port,
191
+ host: "0.0.0.0",
192
+ ...https ? { https } : {},
193
+ ...publicDir && fs2.existsSync(publicDir) ? { publicDir: { name: publicDir } } : {}
194
+ },
195
+ dev: {
196
+ writeToDisk: true
215
197
  }
216
198
  };
217
- };
218
- async function buildEntriesWithVite(params) {
219
- const {
220
- entries,
221
- outDir,
222
- mode = "production",
223
- sourcemap = false,
224
- minify = true,
225
- viteConfig = {},
226
- concurrency = DEFAULT_CONCURRENCY
227
- } = params;
228
- const entryNames = Object.keys(entries);
229
- if (entryNames.length === 1) {
230
- const name = entryNames[0];
231
- await buildSingleEntry({
232
- name,
233
- entryPath: entries[name],
234
- outDir,
235
- mode,
236
- sourcemap,
237
- minify,
238
- viteConfig
239
- });
240
- return;
241
- }
242
- await parallelLimit(entryNames, concurrency, async (name) => {
243
- await buildSingleEntry({
244
- name,
245
- entryPath: entries[name],
246
- outDir,
247
- mode,
248
- sourcemap,
249
- minify,
250
- viteConfig
251
- });
252
- });
253
- }
254
- async function buildSingleEntry(params) {
255
- const { name, entryPath, outDir, mode, sourcemap, minify, viteConfig } = params;
256
- const config = createViteConfig({
257
- ...viteConfig,
258
- mode,
259
- build: {
260
- ...viteConfig.build,
261
- rollupOptions: {
262
- ...viteConfig.build?.rollupOptions,
263
- input: entryPath,
264
- output: {
265
- entryFileNames: `${name}.js`,
266
- assetFileNames: `${name}.[ext]`,
267
- format: "iife",
268
- // 外部ライブラリのソースマップを無視して警告を抑制
269
- sourcemapIgnoreList: (relativeSourcePath) => {
270
- return relativeSourcePath.includes("node_modules");
271
- },
272
- ...viteConfig.build?.rollupOptions?.output
199
+ const rsbuild = await createRsbuild({ rsbuildConfig });
200
+ if (onFirstCompile || onRecompile) {
201
+ rsbuild.addPlugins([
202
+ {
203
+ name: "k2-dev-hooks",
204
+ setup(api) {
205
+ api.onDevCompileDone(async ({ isFirstCompile }) => {
206
+ if (isFirstCompile && onFirstCompile) {
207
+ await onFirstCompile();
208
+ } else if (!isFirstCompile && onRecompile) {
209
+ await onRecompile();
210
+ }
211
+ });
273
212
  }
274
- },
275
- outDir,
276
- emptyOutDir: false,
277
- sourcemap,
278
- minify,
279
- cssCodeSplit: false
280
- }
281
- });
282
- await viteBuild(config);
283
- const outputPath = path5.join(outDir, `${name}.js`);
284
- if (fs2.existsSync(outputPath)) {
285
- const content = await fs2.readFile(outputPath, "utf-8");
286
- const wrapped = `(function(){
287
- ${content}
288
- })();`;
289
- await fs2.writeFile(outputPath, wrapped);
213
+ }
214
+ ]);
290
215
  }
216
+ const result = await rsbuild.startDevServer();
217
+ return {
218
+ port: result.port,
219
+ close: result.server.close
220
+ };
291
221
  }
292
- var ENTRY_FILE_NAMES = ["index.ts", "index.tsx", "index.js", "index.jsx", "index.mjs"];
293
- function getEntryPointsFromDir(inputDir) {
294
- const entries = {};
222
+ function getAppEntryPoints(inputDir) {
295
223
  if (!fs2.existsSync(inputDir)) {
296
- throw new Error(`Input directory not found: ${inputDir}`);
224
+ return {};
297
225
  }
298
- const dirs = fs2.readdirSync(inputDir, { withFileTypes: true });
299
- for (const dirent of dirs) {
300
- if (!dirent.isDirectory()) continue;
301
- const dirName = dirent.name;
302
- const dirPath = path5.join(inputDir, dirName);
303
- for (const filename of ENTRY_FILE_NAMES) {
304
- const entryPath = path5.join(dirPath, filename);
305
- if (fs2.existsSync(entryPath)) {
306
- entries[dirName] = entryPath;
307
- break;
226
+ const allProjects = fs2.readdirSync(inputDir);
227
+ return allProjects.reduce((acc, dir) => {
228
+ const dirPath = path5.join(inputDir, dir);
229
+ if (!fs2.statSync(dirPath).isDirectory()) return acc;
230
+ for (const filename of ["index.ts", "index.tsx", "index.js", "index.jsx", "index.mjs"]) {
231
+ const filePath = path5.join(inputDir, dir, filename);
232
+ if (fs2.existsSync(filePath)) {
233
+ return { ...acc, [dir]: filePath };
308
234
  }
309
235
  }
310
- }
311
- return entries;
236
+ return acc;
237
+ }, {});
312
238
  }
313
239
 
314
240
  // src/commands/build.ts
315
241
  function command() {
316
- program.command("build").option("-o, --outdir <outdir>", "Output directory.", path6.join(WORKSPACE_DIRECTORY, "prod")).option("-i, --input <input>", "Input directory.", path6.join("src", "apps")).option("--config <config>", "k2 config file path").description("Build the project for production with Vite.").action(action);
242
+ program.command("build").option("-o, --outdir <outdir>", "Output directory.", path6.join(WORKSPACE_DIRECTORY, "prod")).option("-i, --input <input>", "Input directory.", path6.join("src", "apps")).option("--config <config>", "k2 config file path").description("Build the project for production with rsbuild.").action(action);
317
243
  }
318
244
  async function action(options) {
319
245
  console.group("\u{1F373} Build the project for production");
320
246
  try {
321
247
  const { outdir, input, config } = options;
322
248
  const outDir = path6.resolve(outdir);
323
- const entries = getEntryPointsFromDir(path6.resolve(input));
249
+ const entries = getAppEntryPoints(path6.resolve(input));
324
250
  const entryNames = Object.keys(entries);
325
251
  if (entryNames.length === 0) {
326
252
  throw new Error(`No entry points found in ${input}`);
327
253
  }
328
- console.log(chalk2.gray(` Entry points: ${entryNames.join(", ")}`));
254
+ console.log(chalk.gray(` Entry points: ${entryNames.join(", ")}`));
329
255
  const k2Config = config ? await importK2Config(config) : getDefaultK2Config();
330
256
  const fullConfig = { ...k2Config, outDir };
331
257
  const results = await Promise.allSettled([
332
- buildEntriesWithVite({
258
+ buildWithRsbuild({
333
259
  entries,
334
260
  outDir,
335
- mode: "production",
261
+ minify: true,
336
262
  sourcemap: false,
337
- minify: true
263
+ injectStyles: true
338
264
  }),
339
265
  buildTailwind(fullConfig)
340
266
  ]);
@@ -353,15 +279,14 @@ async function action(options) {
353
279
 
354
280
  // src/commands/dev/index.ts
355
281
  import { program as program2 } from "commander";
356
- import { createServer } from "vite";
357
- import fs6 from "fs-extra";
358
- import path9 from "path";
359
- import chalk4 from "chalk";
282
+ import "fs-extra";
283
+ import path10 from "path";
284
+ import chalk3 from "chalk";
360
285
 
361
286
  // src/commands/dev/tailwind.ts
362
287
  import path7 from "path";
363
- import chalk3 from "chalk";
364
- import fs4 from "fs-extra";
288
+ import chalk2 from "chalk";
289
+ import fs3 from "fs-extra";
365
290
  var watchCss = async (params) => {
366
291
  const { k2Config, outdir } = params;
367
292
  if (!k2Config.tailwind?.css || !k2Config.tailwind?.config) {
@@ -371,8 +296,8 @@ var watchCss = async (params) => {
371
296
  const tailwindConfig = await getTailwindConfigFromK2Config(k2Config.tailwind);
372
297
  const input = path7.resolve(k2Config.tailwind.css);
373
298
  const output = path7.join(outdir, "tailwind.css");
374
- if (!await fs4.pathExists(output)) {
375
- await fs4.outputFile(output, "");
299
+ if (!await fs3.pathExists(output)) {
300
+ await fs3.outputFile(output, "");
376
301
  }
377
302
  return watchTailwindCSS({
378
303
  input,
@@ -381,50 +306,239 @@ var watchCss = async (params) => {
381
306
  onChanges: ({ output: output2, type }) => {
382
307
  const outputFileName = path7.basename(output2);
383
308
  console.log(
384
- chalk3.hex("#e5e7eb")(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} `) + chalk3.cyan(`[css] `) + outputFileName + (type === "init" ? " init" : ` rebuilt(${type})`)
309
+ chalk2.hex("#e5e7eb")(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} `) + chalk2.cyan(`[css] `) + outputFileName + (type === "init" ? " init" : ` rebuilt(${type})`)
385
310
  );
386
311
  }
387
312
  });
388
313
  };
389
314
 
390
- // src/lib/exec.ts
391
- import { exec as defaultExec } from "child_process";
392
- import { promisify } from "util";
393
- var exec = promisify(defaultExec);
315
+ // src/lib/cert/index.ts
316
+ import fs4 from "fs-extra";
317
+ import path9 from "path";
318
+
319
+ // src/lib/cert/cert.ts
320
+ import forge from "node-forge";
321
+ import net from "net";
322
+ var { md, pki } = forge;
323
+ function createCertificate(serial, publicKey, subject, issuer, extensions, validity, signWith) {
324
+ const cert = pki.createCertificate();
325
+ cert.serialNumber = Buffer.from(serial).toString("hex");
326
+ cert.publicKey = publicKey;
327
+ cert.setSubject(subject);
328
+ cert.setIssuer(issuer);
329
+ cert.setExtensions(extensions);
330
+ cert.validity.notBefore = /* @__PURE__ */ new Date();
331
+ cert.validity.notAfter = /* @__PURE__ */ new Date();
332
+ cert.validity.notAfter.setDate(cert.validity.notAfter.getDate() + validity);
333
+ cert.sign(signWith, md.sha256.create());
334
+ return cert;
335
+ }
336
+ function generateCertInternal(params) {
337
+ const { subject, issuer, extensions, validity, signWith } = params;
338
+ const serial = Math.floor(Math.random() * 95e3 + 5e4).toString();
339
+ const keyPair = pki.rsa.generateKeyPair(2048);
340
+ const privateKey = signWith ? pki.privateKeyFromPem(signWith) : keyPair.privateKey;
341
+ const cert = createCertificate(
342
+ serial,
343
+ keyPair.publicKey,
344
+ subject,
345
+ issuer,
346
+ extensions,
347
+ validity,
348
+ privateKey
349
+ );
350
+ return {
351
+ key: pki.privateKeyToPem(keyPair.privateKey),
352
+ cert: pki.certificateToPem(cert)
353
+ };
354
+ }
355
+ function createCA(params = {}) {
356
+ const {
357
+ organization = "K2 Development CA",
358
+ countryCode = "JP",
359
+ state = "Tokyo",
360
+ locality = "Tokyo",
361
+ validity = 7300
362
+ } = params;
363
+ const attributes = [
364
+ { name: "commonName", value: organization },
365
+ { name: "countryName", value: countryCode },
366
+ { name: "stateOrProvinceName", value: state },
367
+ { name: "localityName", value: locality },
368
+ { name: "organizationName", value: organization }
369
+ ];
370
+ const extensions = [
371
+ { name: "basicConstraints", cA: true, critical: true },
372
+ { name: "keyUsage", keyCertSign: true, critical: true }
373
+ ];
374
+ return generateCertInternal({
375
+ subject: attributes,
376
+ issuer: attributes,
377
+ extensions,
378
+ validity
379
+ });
380
+ }
381
+ function createCert(params) {
382
+ const { ca, domains, validity = 7300 } = params;
383
+ const attributes = [{ name: "commonName", value: domains[0] }];
384
+ const extensions = [
385
+ { name: "basicConstraints", cA: false, critical: true },
386
+ {
387
+ name: "keyUsage",
388
+ digitalSignature: true,
389
+ keyEncipherment: true,
390
+ critical: true
391
+ },
392
+ { name: "extKeyUsage", serverAuth: true, clientAuth: true },
393
+ {
394
+ name: "subjectAltName",
395
+ altNames: domains.map((domain) => {
396
+ const TYPE_DOMAIN = 2;
397
+ const TYPE_IP = 7;
398
+ return net.isIP(domain) ? { type: TYPE_IP, ip: domain } : { type: TYPE_DOMAIN, value: domain };
399
+ })
400
+ }
401
+ ];
402
+ const caCert = pki.certificateFromPem(ca.cert.toString());
403
+ return generateCertInternal({
404
+ subject: attributes,
405
+ issuer: caCert.subject.attributes,
406
+ extensions,
407
+ validity,
408
+ signWith: ca.key.toString()
409
+ });
410
+ }
394
411
 
395
- // src/lib/cert.ts
396
- import fs5 from "fs-extra";
412
+ // src/lib/cert/constants.ts
397
413
  import path8 from "path";
414
+ var PKG_NAME = "k2";
415
+ var isSupported = process.platform === "darwin" || process.platform === "linux" || process.platform === "win32";
416
+ function getApplicationConfigPath(name) {
417
+ if (process.platform === "darwin") {
418
+ return path8.join(process.env.HOME, "Library", "Application Support", name);
419
+ }
420
+ if (process.platform === "win32") {
421
+ return process.env.LOCALAPPDATA ? path8.join(process.env.LOCALAPPDATA, name) : path8.join(process.env.USERPROFILE, "Local Settings", "Application Data", name);
422
+ }
423
+ return process.env.XDG_CONFIG_HOME ? path8.join(process.env.XDG_CONFIG_HOME, name) : path8.join(process.env.HOME, ".config", name);
424
+ }
425
+ var pkgDir = getApplicationConfigPath(PKG_NAME);
426
+ var rootCAPath = path8.resolve(pkgDir, "rootCA.pem");
427
+ var rootCAKeyPath = path8.resolve(pkgDir, "rootCA-key.pem");
428
+
429
+ // src/lib/cert/platforms.ts
430
+ import { spawnSync } from "child_process";
431
+
432
+ // src/lib/logger.ts
433
+ var PKG_NAME2 = "@konomi-app/k2";
434
+ function createLogger(prefix = PKG_NAME2) {
435
+ return {
436
+ log: (...args) => console.log(`[${prefix}]`, ...args),
437
+ info: (...args) => console.info(`[${prefix}]`, ...args),
438
+ warn: (...args) => console.warn(`[${prefix}]`, ...args),
439
+ error: (...args) => console.error(`[${prefix}]`, ...args)
440
+ };
441
+ }
442
+ var logger_default = createLogger();
443
+
444
+ // src/lib/cert/platforms.ts
445
+ function addToTrustStoresDarwin(certPath) {
446
+ logger_default.log("Adding certificate to trusted store. Admin rights may be required.");
447
+ spawnSync(
448
+ "sudo",
449
+ [
450
+ "security",
451
+ "add-trusted-cert",
452
+ "-d",
453
+ "-r",
454
+ "trustRoot",
455
+ "-k",
456
+ "/Library/Keychains/System.keychain",
457
+ "-p",
458
+ "ssl",
459
+ "-p",
460
+ "basic",
461
+ certPath
462
+ ],
463
+ { stdio: "inherit" }
464
+ );
465
+ }
466
+ var targetCA = `/usr/local/share/ca-certificates/${PKG_NAME}.crt`;
467
+ function addToTrustStoresLinux(certPath) {
468
+ logger_default.log("Adding certificate to trusted store. Admin rights may be required.");
469
+ spawnSync("sudo", ["cp", certPath, targetCA]);
470
+ spawnSync("sudo", ["update-ca-certificates"]);
471
+ }
472
+ function addToTrustStoresWin32(certPath) {
473
+ spawnSync("certutil", ["-addstore", "-user", "root", certPath], {
474
+ stdio: "inherit"
475
+ });
476
+ }
477
+ function addToTrustStores(certPath) {
478
+ switch (process.platform) {
479
+ case "darwin":
480
+ return addToTrustStoresDarwin(certPath);
481
+ case "linux":
482
+ return addToTrustStoresLinux(certPath);
483
+ case "win32":
484
+ return addToTrustStoresWin32(certPath);
485
+ }
486
+ }
487
+
488
+ // src/lib/cert/index.ts
398
489
  var CERT_KEY_FILENAME = "localhost-key.pem";
399
490
  var CERT_FILENAME = "localhost-cert.pem";
400
- var generateCert = async (outDir) => {
401
- await fs5.ensureDir(outDir);
402
- const { stdout } = await exec(`mkcert localhost 127.0.0.1 ::1`);
403
- [
404
- { input: "localhost+2.pem", output: CERT_FILENAME },
405
- { input: "localhost+2-key.pem", output: CERT_KEY_FILENAME }
406
- ].forEach(({ input, output }) => {
407
- if (fs5.existsSync(input)) {
408
- fs5.moveSync(`./${input}`, path8.join(outDir, output), {
409
- overwrite: true
410
- });
491
+ function install(options = {}) {
492
+ const { validity = 7300 } = options;
493
+ if (!isSupported) {
494
+ throw new Error(`Platform not supported: "${process.platform}"`);
495
+ }
496
+ if (!fs4.existsSync(rootCAPath) && !fs4.existsSync(rootCAKeyPath)) {
497
+ const ca = createCA({ validity });
498
+ fs4.outputFileSync(rootCAPath, ca.cert);
499
+ fs4.outputFileSync(rootCAKeyPath, ca.key);
500
+ try {
501
+ addToTrustStores(rootCAPath);
502
+ } catch {
503
+ console.warn(
504
+ "\u26A0 Failed to add CA to system trust store. You may need to trust the certificate manually."
505
+ );
411
506
  }
412
- });
413
- return { stdout };
414
- };
507
+ }
508
+ }
509
+ function certificateFor(requestedDomains = []) {
510
+ const validity = 7300;
511
+ install({ validity });
512
+ const requests = Array.isArray(requestedDomains) ? requestedDomains : [requestedDomains];
513
+ const domains = [
514
+ .../* @__PURE__ */ new Set(["localhost", "localhost.localdomain", "127.0.0.1", "0.0.0.0", "::1", ...requests])
515
+ ];
516
+ const ca = {
517
+ cert: fs4.readFileSync(rootCAPath),
518
+ key: fs4.readFileSync(rootCAKeyPath)
519
+ };
520
+ return createCert({ ca, domains, validity });
521
+ }
522
+ function generateCert(outDir) {
523
+ fs4.ensureDirSync(outDir);
524
+ const result = certificateFor();
525
+ fs4.outputFileSync(path9.join(outDir, CERT_FILENAME), result.cert);
526
+ fs4.outputFileSync(path9.join(outDir, CERT_KEY_FILENAME), result.key);
527
+ return result;
528
+ }
415
529
  function hasCertificates(certDir) {
416
- return fs5.existsSync(path8.join(certDir, CERT_KEY_FILENAME)) && fs5.existsSync(path8.join(certDir, CERT_FILENAME));
530
+ return fs4.existsSync(path9.join(certDir, CERT_KEY_FILENAME)) && fs4.existsSync(path9.join(certDir, CERT_FILENAME));
417
531
  }
418
532
  function loadCertificates(certDir) {
419
533
  return {
420
- key: fs5.readFileSync(path8.join(certDir, CERT_KEY_FILENAME)),
421
- cert: fs5.readFileSync(path8.join(certDir, CERT_FILENAME))
534
+ key: fs4.readFileSync(path9.join(certDir, CERT_KEY_FILENAME)),
535
+ cert: fs4.readFileSync(path9.join(certDir, CERT_FILENAME))
422
536
  };
423
537
  }
424
538
 
425
539
  // src/commands/dev/index.ts
426
540
  function command2() {
427
- program2.command("dev").description("Start development server with Vite.").option("-i, --input <input>", "Input directory", "src/apps").option("-o, --outdir <outdir>", "Output directory.", DEVELOPMENT_DIRECTORY).option("-c, --certdir <certdir>", "Certificate directory", WORKSPACE_DIRECTORY).option("--config <config>", "k2 config file path").option("-p, --port <port>", "Port number").action(action2);
541
+ program2.command("dev").description("Start development server with rsbuild.").option("-i, --input <input>", "Input directory", "src/apps").option("-o, --outdir <outdir>", "Output directory.", DEVELOPMENT_DIRECTORY).option("-c, --certdir <certdir>", "Certificate directory", WORKSPACE_DIRECTORY).option("--config <config>", "k2 config file path").option("-p, --port <port>", "Port number").action(action2);
428
542
  }
429
543
  async function action2(options) {
430
544
  const { certdir, outdir, config, port: specifiedPort, input } = options;
@@ -439,100 +553,45 @@ async function action2(options) {
439
553
  console.log(`\u2699 ${CONFIG_FILE_NAME} not found. use default settings.`);
440
554
  }
441
555
  const port = Number(specifiedPort ?? k2Config?.server?.port ?? DEFAULT_PORT);
442
- const certDirPath = path9.resolve(certdir);
443
- const outputDir = path9.resolve(outdir);
444
- const inputDir = path9.resolve(input);
556
+ const certDirPath = path10.resolve(certdir);
557
+ const outputDir = path10.resolve(outdir);
558
+ const inputDir = path10.resolve(input);
445
559
  if (!hasCertificates(certDirPath)) {
446
- console.log(chalk4.yellow("\u{1F4DC} SSL certificates not found. Generating..."));
560
+ console.log(chalk3.yellow("\u{1F4DC} SSL certificates not found. Generating with node-forge..."));
447
561
  try {
448
- await generateCert(certDirPath);
449
- console.log(chalk4.green("\u2705 SSL certificates generated successfully"));
562
+ generateCert(certDirPath);
563
+ console.log(chalk3.green("\u2705 SSL certificates generated successfully"));
450
564
  } catch (error) {
451
- console.log(
452
- chalk4.red("\u274C Failed to generate SSL certificates. Make sure mkcert is installed.")
453
- );
454
- console.log(chalk4.gray(" Install mkcert: https://github.com/FiloSottile/mkcert"));
565
+ console.log(chalk3.red("\u274C Failed to generate SSL certificates."));
455
566
  throw error;
456
567
  }
457
568
  }
458
- const entries = getEntryPointsFromDir(inputDir);
569
+ const entries = getAppEntryPoints(inputDir);
459
570
  const entryNames = Object.keys(entries);
460
571
  if (entryNames.length === 0) {
461
572
  throw new Error(`No entry points found in ${input}`);
462
573
  }
463
- console.log(chalk4.gray(` Entry points: ${entryNames.join(", ")}`));
464
- await fs6.emptyDir(outputDir);
574
+ console.log(chalk3.gray(` Entry points: ${entryNames.join(", ")}`));
465
575
  const { key, cert } = loadCertificates(certDirPath);
466
- console.log(chalk4.gray(" Building..."));
467
- await buildEntriesWithVite({
576
+ const { port: actualPort } = await startRsbuildDevServer({
468
577
  entries,
469
578
  outDir: outputDir,
470
- mode: "development",
471
- sourcemap: "inline",
472
- minify: false
473
- });
474
- const serverConfig = createViteConfig({
475
- root: outputDir,
476
- server: {
477
- port,
478
- https: { key, cert }
479
- }
480
- });
481
- const server = await createServer(serverConfig);
482
- await server.listen();
483
- console.log(chalk4.green(`
579
+ port,
580
+ https: { key, cert },
581
+ publicDir: outputDir,
582
+ onFirstCompile: () => {
583
+ console.log(chalk3.green(`
484
584
  \u2728 Development server ready!`));
485
- console.log(chalk4.cyan(` Local: https://localhost:${port}`));
486
- console.log(chalk4.gray(` Output: ${outputDir}`));
487
- console.log(chalk4.gray("\n Watching for changes...\n"));
488
- const chokidar2 = await import("chokidar");
489
- const watchDirs = [inputDir, path9.resolve("src", "lib")].filter((dir) => fs6.existsSync(dir));
490
- console.log(chalk4.gray(` Watching directories: ${watchDirs.join(", ")}`));
491
- const watcher = chokidar2.watch(watchDirs, {
492
- ignored: /node_modules/,
493
- persistent: true,
494
- ignoreInitial: true
495
- });
496
- const watchExtensions = [".ts", ".tsx", ".js", ".jsx", ".css", ".scss"];
497
- const shouldRebuild = (filePath) => {
498
- const ext = path9.extname(filePath).toLowerCase();
499
- return watchExtensions.includes(ext);
500
- };
501
- const rebuild = async () => {
502
- console.log(chalk4.gray(` ${(/* @__PURE__ */ new Date()).toLocaleTimeString()} Rebuilding...`));
503
- await buildEntriesWithVite({
504
- entries,
505
- outDir: outputDir,
506
- mode: "development",
507
- sourcemap: "inline",
508
- minify: false
509
- });
510
- console.log(chalk4.gray(` ${(/* @__PURE__ */ new Date()).toLocaleTimeString()} Rebuild complete`));
511
- };
512
- watcher.on("ready", () => {
513
- console.log(chalk4.green(" \u2713 File watcher ready"));
514
- });
515
- watcher.on("change", (filePath) => {
516
- if (shouldRebuild(filePath)) {
517
- console.log(chalk4.cyan(` [change] ${filePath}`));
518
- rebuild();
519
- }
520
- });
521
- watcher.on("add", (filePath) => {
522
- if (shouldRebuild(filePath)) {
523
- console.log(chalk4.cyan(` [add] ${filePath}`));
524
- rebuild();
525
- }
526
- });
527
- watcher.on("unlink", (filePath) => {
528
- if (shouldRebuild(filePath)) {
529
- console.log(chalk4.cyan(` [unlink] ${filePath}`));
530
- rebuild();
585
+ console.log(chalk3.cyan(` Local: https://localhost:${actualPort}`));
586
+ console.log(chalk3.gray(` Output: ${outputDir}`));
587
+ console.log(chalk3.gray("\n Watching for changes...\n"));
588
+ },
589
+ onRecompile: () => {
590
+ console.log(
591
+ chalk3.hex("#e5e7eb")(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} `) + chalk3.cyan(`[rsbuild] `) + `rebuild complete`
592
+ );
531
593
  }
532
594
  });
533
- watcher.on("error", (error) => {
534
- console.error(chalk4.red(` Watcher error: ${error}`));
535
- });
536
595
  if (k2Config) {
537
596
  await watchCss({ k2Config, outdir });
538
597
  }
@@ -545,69 +604,15 @@ async function action2(options) {
545
604
 
546
605
  // src/commands/genkey.ts
547
606
  import { program as program3 } from "commander";
548
-
549
- // src/commands/genkey-base.ts
550
- async function action3(options) {
551
- const { output } = options;
552
- console.group("\u{1F373} Generate SSL key for localhost");
553
- try {
554
- const { stdout } = await generateCert(output);
555
- if (stdout) {
556
- console.log(stdout);
557
- }
558
- console.log(`\u{1F511} key generation success. Output to ./${output}`);
559
- } catch (error) {
560
- throw error;
561
- } finally {
562
- console.groupEnd();
563
- }
564
- }
565
-
566
- // src/commands/genkey.ts
567
607
  function command3() {
568
- program3.command("genkey").description("Generate SSL key for localhost. (Require mkcert)").option("-o, --output <output>", "Output directory.", WORKSPACE_DIRECTORY).action(action4);
569
- }
570
- async function action4(options) {
571
- await action3(options);
572
- }
573
-
574
- // src/commands/build-esbuild.ts
575
- import { program as program4 } from "commander";
576
- import "fs-extra";
577
- import path10 from "path";
578
- import chalk5 from "chalk";
579
- function command4() {
580
- program4.command("esbuild-build").option("-o, --outdir <outdir>", "Output directory.", path10.join(WORKSPACE_DIRECTORY, "prod")).option("-i, --input <input>", "Input directory.", path10.join("src", "apps")).option("--config <config>", "k2 config file path").description("Build the project for production with Vite. (Legacy command name, now uses Vite)").action(action5);
608
+ program3.command("genkey").description("Generate SSL certificate for localhost using node-forge.").option("-o, --output <output>", "Output directory.", WORKSPACE_DIRECTORY).action(action3);
581
609
  }
582
- async function action5(options) {
583
- console.group("\u{1F373} Build the project for production");
610
+ async function action3(options) {
611
+ const { output } = options;
612
+ console.group("\u{1F373} Generate SSL certificate for localhost");
584
613
  try {
585
- const { outdir, input, config } = options;
586
- const outDir = path10.resolve(outdir);
587
- const entries = getEntryPointsFromDir(path10.resolve(input));
588
- const entryNames = Object.keys(entries);
589
- if (entryNames.length === 0) {
590
- throw new Error(`No entry points found in ${input}`);
591
- }
592
- console.log(chalk5.gray(` Entry points: ${entryNames.join(", ")}`));
593
- const k2Config = config ? await importK2Config(config) : getDefaultK2Config();
594
- const fullConfig = { ...k2Config, outDir };
595
- const results = await Promise.allSettled([
596
- buildEntriesWithVite({
597
- entries,
598
- outDir,
599
- mode: "production",
600
- sourcemap: false,
601
- minify: true
602
- }),
603
- buildTailwind(fullConfig)
604
- ]);
605
- for (const result of results) {
606
- if (result.status === "rejected") {
607
- throw result.reason;
608
- }
609
- }
610
- console.log("\u2728 Build success.");
614
+ generateCert(output);
615
+ console.log(`\u{1F511} Certificate generated. Output to ./${output}`);
611
616
  } catch (error) {
612
617
  throw error;
613
618
  } finally {
@@ -616,7 +621,7 @@ async function action5(options) {
616
621
  }
617
622
 
618
623
  // src/commands/lint.ts
619
- import { program as program5 } from "commander";
624
+ import { program as program4 } from "commander";
620
625
 
621
626
  // src/lib/lint.ts
622
627
  import { ESLint } from "eslint";
@@ -648,10 +653,10 @@ async function lint() {
648
653
  }
649
654
 
650
655
  // src/commands/lint.ts
651
- function command5() {
652
- program5.command("lint").description("Lint source files").option("-c, --config <config>", "Config file path").action(action6);
656
+ function command4() {
657
+ program4.command("lint").description("Lint source files").option("-c, --config <config>", "Config file path").action(action4);
653
658
  }
654
- async function action6(options) {
659
+ async function action4(options) {
655
660
  try {
656
661
  lint();
657
662
  } catch (error) {
@@ -661,11 +666,10 @@ async function action6(options) {
661
666
  }
662
667
 
663
668
  // src/index.ts
664
- program6.name("k2").version("1.12.0").description("k2 - \u{1F373} kintone kitchen \u{1F373}");
669
+ program5.name("k2").version("4.0.0").description("k2 - \u{1F373} kintone kitchen \u{1F373}");
665
670
  command();
666
- command4();
667
671
  command2();
668
672
  command3();
669
- command5();
670
- program6.parse(process.argv);
673
+ command4();
674
+ program5.parse(process.argv);
671
675
  //# sourceMappingURL=index.js.map