@blinkk/root 1.0.0-alpha.10 → 1.0.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ // src/core/plugin.ts
2
+ async function configureServerPlugins(server, callback, plugins, options) {
3
+ const postHooks = [];
4
+ for (const plugin of plugins) {
5
+ if (plugin.configureServer) {
6
+ const postHook = await plugin.configureServer(server, options);
7
+ if (postHook) {
8
+ postHooks.push(postHook);
9
+ }
10
+ }
11
+ }
12
+ callback();
13
+ for (const postHook of postHooks) {
14
+ await postHook();
15
+ }
16
+ }
17
+ function getVitePlugins(plugins) {
18
+ const vitePlugins = [];
19
+ for (const plugin of plugins) {
20
+ if (plugin.vitePlugins) {
21
+ vitePlugins.push(...plugin.vitePlugins);
22
+ }
23
+ }
24
+ return vitePlugins;
25
+ }
26
+
27
+ export {
28
+ configureServerPlugins,
29
+ getVitePlugins
30
+ };
31
+ //# sourceMappingURL=chunk-ZB7R6ZOY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/plugin.ts"],"sourcesContent":["import {PluginOption as VitePlugin} from 'vite';\nimport {Server} from './types';\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type ConfigureServerHook = (\n server: Server,\n options: ConfigureServerOptions\n) => MaybePromise<void> | MaybePromise<() => void>;\n\nexport interface ConfigureServerOptions {\n type: 'dev' | 'preview' | 'prod';\n}\n\nexport interface Plugin {\n name?: string;\n\n /** Configures the root.js express server . */\n configureServer?: ConfigureServerHook;\n\n /** Adds vite plugins. */\n vitePlugins?: VitePlugin[];\n}\n\n/**\n * Runs the pre-hook configureServer method of every plugin, calls a callback\n * function, and then runs the configureServer's post-hook if provided. Plugins\n * provide a post-hook by returning a callback function from configureServer.\n */\nexport async function configureServerPlugins(\n server: Server,\n callback: () => Promise<void>,\n plugins: Plugin[],\n options: ConfigureServerOptions\n) {\n const postHooks: Array<() => void> = [];\n\n // Call the `configureServer()` method for each plugin.\n for (const plugin of plugins) {\n if (plugin.configureServer) {\n const postHook = await plugin.configureServer(server, options);\n if (postHook) {\n postHooks.push(postHook);\n }\n }\n }\n\n // Register any built-in middleware.\n callback();\n\n // Run any post hooks returned by `plugin.configureServer()`.\n for (const postHook of postHooks) {\n await postHook();\n }\n}\n\nexport function getVitePlugins(plugins: Plugin[]): VitePlugin[] {\n const vitePlugins: VitePlugin[] = [];\n for (const plugin of plugins) {\n if (plugin.vitePlugins) {\n vitePlugins.push(...plugin.vitePlugins);\n }\n }\n return vitePlugins;\n}\n"],"mappings":";AA6BA,eAAsB,uBACpB,QACA,UACA,SACA,SACA;AACA,QAAM,YAA+B,CAAC;AAGtC,aAAW,UAAU,SAAS;AAC5B,QAAI,OAAO,iBAAiB;AAC1B,YAAM,WAAW,MAAM,OAAO,gBAAgB,QAAQ,OAAO;AAC7D,UAAI,UAAU;AACZ,kBAAU,KAAK,QAAQ;AAAA,MACzB;AAAA,IACF;AAAA,EACF;AAGA,WAAS;AAGT,aAAW,YAAY,WAAW;AAChC,UAAM,SAAS;AAAA,EACjB;AACF;AAEO,SAAS,eAAe,SAAiC;AAC9D,QAAM,cAA4B,CAAC;AACnC,aAAW,UAAU,SAAS;AAC5B,QAAI,OAAO,aAAa;AACtB,kBAAY,KAAK,GAAG,OAAO,WAAW;AAAA,IACxC;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
package/dist/cli.js CHANGED
@@ -1,3 +1,8 @@
1
+ import {
2
+ configureServerPlugins,
3
+ getVitePlugins
4
+ } from "./chunk-ZB7R6ZOY.js";
5
+
1
6
  // src/cli/commands/dev.ts
2
7
  import path4 from "node:path";
3
8
  import { fileURLToPath } from "node:url";
@@ -302,34 +307,68 @@ async function htmlMinify(html) {
302
307
  // src/cli/commands/dev.ts
303
308
  import glob2 from "tiny-glob";
304
309
  import { dim } from "kleur/colors";
310
+
311
+ // src/core/middleware.ts
312
+ function rootProjectMiddleware(options) {
313
+ return (req, _, next) => {
314
+ req.rootConfig = Object.assign({}, options.rootConfig, {
315
+ rootDir: options.rootDir
316
+ });
317
+ next();
318
+ };
319
+ }
320
+
321
+ // src/cli/commands/dev.ts
305
322
  var __dirname = path4.dirname(fileURLToPath(import.meta.url));
306
- async function createServer(options) {
307
- const rootDir = (options == null ? void 0 : options.rootDir) || process.cwd();
308
- const app = express();
309
- app.disable("x-powered-by");
310
- app.use(express.static("public"));
311
- const middlewares = await getMiddlewares({ rootDir });
312
- middlewares.forEach((middleware) => app.use(middleware));
323
+ async function dev(rootProjectDir) {
324
+ process.env.NODE_ENV = "development";
325
+ const rootDir = path4.resolve(rootProjectDir || process.cwd());
326
+ const server = await createServer({ rootDir });
313
327
  const port = parseInt(process.env.PORT || "4007");
314
328
  console.log();
315
329
  console.log(`${dim("\u2503")} project: ${rootDir}`);
316
330
  console.log(`${dim("\u2503")} server: http://localhost:${port}`);
331
+ console.log(`${dim("\u2503")} mode: development`);
317
332
  console.log();
318
- app.listen(port);
333
+ server.listen(port);
319
334
  }
320
- async function getMiddlewares(options) {
321
- var _a, _b, _c;
335
+ async function createServer(options) {
322
336
  const rootDir = path4.resolve((options == null ? void 0 : options.rootDir) || process.cwd());
323
337
  const rootConfig = await loadRootConfig(rootDir);
338
+ const server = express();
339
+ server.disable("x-powered-by");
340
+ server.use(rootProjectMiddleware({ rootDir, rootConfig }));
341
+ server.use(await viteServerMiddleware({ rootDir, rootConfig }));
342
+ server.use(rootDevRendererMiddleware());
343
+ const plugins = rootConfig.plugins || [];
344
+ await configureServerPlugins(
345
+ server,
346
+ async () => {
347
+ var _a;
348
+ const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
349
+ for (const middleware of userMiddlewares) {
350
+ server.use(middleware);
351
+ }
352
+ server.use(rootDevServerMiddleware());
353
+ server.use(rootDevServer404Middleware());
354
+ },
355
+ plugins,
356
+ { type: "dev" }
357
+ );
358
+ return server;
359
+ }
360
+ async function viteServerMiddleware(options) {
361
+ var _a, _b, _c;
362
+ const rootDir = options.rootDir;
363
+ const rootConfig = options.rootConfig;
324
364
  const viteConfig = rootConfig.vite || {};
325
- const renderModulePath = path4.resolve(__dirname, "./render.js");
326
- const pages = [];
365
+ const routeFiles = [];
327
366
  if (await isDirectory(path4.join(rootDir, "routes"))) {
328
367
  const pageFiles = await glob2("routes/**/*", { cwd: rootDir });
329
368
  pageFiles.forEach((file) => {
330
369
  const parts = path4.parse(file);
331
370
  if (!parts.name.startsWith("_") && isJsFile(parts.base)) {
332
- pages.push(file);
371
+ routeFiles.push(file);
333
372
  }
334
373
  });
335
374
  }
@@ -374,14 +413,25 @@ async function getMiddlewares(options) {
374
413
  }
375
414
  });
376
415
  }
416
+ const vitePlugins = [
417
+ pluginRoot({ rootDir, rootConfig }),
418
+ ...viteConfig.plugins || [],
419
+ ...getVitePlugins(rootConfig.plugins || [])
420
+ ];
377
421
  const viteServer = await createViteServer({
378
422
  ...viteConfig,
379
423
  mode: "development",
380
424
  root: rootDir,
425
+ publicDir: path4.join(rootDir, "public"),
381
426
  server: { middlewareMode: true },
382
427
  appType: "custom",
383
428
  optimizeDeps: {
384
- include: [...pages, ...elements, ...bundleScripts]
429
+ include: [
430
+ ...routeFiles,
431
+ ...elements,
432
+ ...bundleScripts,
433
+ ...((_c = viteConfig.optimizeDeps) == null ? void 0 : _c.include) || []
434
+ ]
385
435
  },
386
436
  ssr: {
387
437
  noExternal: ["@blinkk/root"]
@@ -390,18 +440,32 @@ async function getMiddlewares(options) {
390
440
  jsx: "automatic",
391
441
  jsxImportSource: "preact"
392
442
  },
393
- plugins: [...viteConfig.plugins || [], pluginRoot({ rootDir, rootConfig })]
443
+ plugins: vitePlugins
394
444
  });
395
- const rootMiddleware = async (req, res, next) => {
445
+ return async (req, _, next) => {
446
+ req.viteServer = viteServer;
447
+ next();
448
+ };
449
+ }
450
+ function rootDevRendererMiddleware() {
451
+ const renderModulePath = path4.resolve(__dirname, "./render.js");
452
+ return async (req, _, next) => {
453
+ const rootConfig = req.rootConfig;
454
+ const viteServer = req.viteServer;
455
+ const render = await viteServer.ssrLoadModule(renderModulePath);
456
+ const assetMap = new DevServerAssetMap(viteServer.moduleGraph);
457
+ req.renderer = new render.Renderer(rootConfig, { assetMap });
458
+ next();
459
+ };
460
+ }
461
+ function rootDevServerMiddleware() {
462
+ return async (req, res, next) => {
396
463
  const url = req.originalUrl;
397
- let renderer = null;
464
+ const renderer = req.renderer;
465
+ const viteServer = req.viteServer;
466
+ const rootConfig = req.rootConfig;
398
467
  try {
399
- const render = await viteServer.ssrLoadModule(renderModulePath);
400
- renderer = new render.Renderer(rootConfig);
401
- const assetMap = new DevServerAssetMap(viteServer.moduleGraph);
402
- const data = await renderer.render(url, {
403
- assetMap
404
- });
468
+ const data = await renderer.render(url);
405
469
  if (data.notFound || !data.html) {
406
470
  next();
407
471
  return;
@@ -428,35 +492,20 @@ async function getMiddlewares(options) {
428
492
  }
429
493
  }
430
494
  };
431
- const notFoundMiddleware = async (req, res) => {
495
+ }
496
+ function rootDevServer404Middleware() {
497
+ return async (req, res) => {
432
498
  const url = req.originalUrl;
433
499
  const ext = path4.extname(url);
500
+ const renderer = req.renderer;
434
501
  if (!ext) {
435
- const render = await viteServer.ssrLoadModule(renderModulePath);
436
- const renderer = new render.Renderer(rootConfig);
437
- const data = await renderer.renderDevNotFound();
502
+ const data = await renderer.renderDevServer404();
438
503
  const html = data.html || "";
439
504
  res.status(404).set({ "Content-Type": "text/html" }).end(html);
440
505
  return;
441
506
  }
442
507
  res.status(404).set({ "Content-Type": "text/plain" }).end("404");
443
508
  };
444
- const userMiddlewares = ((_c = rootConfig.server) == null ? void 0 : _c.middlewares) || [];
445
- return [
446
- ...userMiddlewares,
447
- viteServer.middlewares,
448
- rootMiddleware,
449
- notFoundMiddleware
450
- ];
451
- }
452
- async function dev(rootProjectDir) {
453
- process.env.NODE_ENV = "development";
454
- const rootDir = path4.resolve(rootProjectDir || process.cwd());
455
- try {
456
- await createServer({ rootDir });
457
- } catch (err) {
458
- console.error("an error occurred");
459
- }
460
509
  }
461
510
 
462
511
  // src/cli/commands/build.ts
@@ -661,6 +710,11 @@ async function build(rootProjectDir, options) {
661
710
  });
662
711
  }
663
712
  const viteConfig = rootConfig.vite || {};
713
+ const vitePlugins = [
714
+ pluginRoot({ rootDir, rootConfig }),
715
+ ...viteConfig.plugins || [],
716
+ ...getVitePlugins(rootConfig.plugins || [])
717
+ ];
664
718
  const baseConfig = {
665
719
  ...viteConfig,
666
720
  root: rootDir,
@@ -670,7 +724,7 @@ async function build(rootProjectDir, options) {
670
724
  jsxImportSource: "preact",
671
725
  treeShaking: true
672
726
  },
673
- plugins: [...viteConfig.plugins || [], pluginRoot({ rootDir, rootConfig })]
727
+ plugins: vitePlugins
674
728
  };
675
729
  await viteBuild({
676
730
  ...baseConfig,
@@ -739,13 +793,12 @@ async function build(rootProjectDir, options) {
739
793
  copyDir(path5.join(distDir, "client/chunks"), path5.join(buildDir, "chunks"));
740
794
  if (!ssrOnly) {
741
795
  const render = await import(path5.join(distDir, "server/render.js"));
742
- const renderer = new render.Renderer(rootConfig);
796
+ const renderer = new render.Renderer(rootConfig, { assetMap });
743
797
  const sitemap = await renderer.getSitemap();
744
798
  await Promise.all(
745
799
  Object.keys(sitemap).map(async (urlPath) => {
746
800
  const { route, params } = sitemap[urlPath];
747
801
  const data = await renderer.renderRoute(route, {
748
- assetMap,
749
802
  routeParams: params
750
803
  });
751
804
  let outPath = path5.join(distDir, `html${urlPath}`, "index.html");
@@ -765,14 +818,50 @@ async function build(rootProjectDir, options) {
765
818
  import path6 from "node:path";
766
819
  import { default as express2 } from "express";
767
820
  import { dim as dim3 } from "kleur/colors";
821
+ import sirv from "sirv";
822
+ import compression from "compression";
768
823
  async function preview(rootProjectDir) {
769
- var _a;
770
824
  process.env.NODE_ENV = "development";
771
825
  const rootDir = path6.resolve(rootProjectDir || process.cwd());
826
+ const server = await createServer2({ rootDir });
827
+ const port = parseInt(process.env.PORT || "4007");
828
+ console.log();
829
+ console.log(`${dim3("\u2503")} project: ${rootDir}`);
830
+ console.log(`${dim3("\u2503")} server: http://localhost:${port}`);
831
+ console.log(`${dim3("\u2503")} mode: staging`);
832
+ console.log();
833
+ server.listen(port);
834
+ }
835
+ async function createServer2(options) {
836
+ const rootDir = options.rootDir;
772
837
  const rootConfig = await loadRootConfig(rootDir);
773
838
  const distDir = path6.join(rootDir, "dist");
839
+ const server = express2();
840
+ server.disable("x-powered-by");
841
+ server.use(compression());
842
+ server.use(rootProjectMiddleware({ rootDir, rootConfig }));
843
+ server.use(await rootPreviewRendererMiddleware({ rootConfig, distDir }));
844
+ const plugins = rootConfig.plugins || [];
845
+ configureServerPlugins(
846
+ server,
847
+ async () => {
848
+ var _a;
849
+ const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
850
+ userMiddlewares.forEach((middleware) => {
851
+ server.use(middleware);
852
+ });
853
+ const publicDir = path6.join(distDir, "html");
854
+ server.use(sirv(publicDir, { dev: false }));
855
+ server.use(rootPreviewServerMiddleware());
856
+ },
857
+ plugins,
858
+ { type: "preview" }
859
+ );
860
+ return server;
861
+ }
862
+ async function rootPreviewRendererMiddleware(options) {
863
+ const { distDir, rootConfig } = options;
774
864
  const render = await import(path6.join(distDir, "server/render.js"));
775
- const renderer = new render.Renderer(rootConfig);
776
865
  const manifestPath = path6.join(distDir, "client/root-manifest.json");
777
866
  if (!await fileExists(manifestPath)) {
778
867
  throw new Error(
@@ -781,20 +870,19 @@ async function preview(rootProjectDir) {
781
870
  }
782
871
  const rootManifest = await loadJson(manifestPath);
783
872
  const assetMap = BuildAssetMap.fromRootManifest(rootManifest);
784
- const app = express2();
785
- app.disable("x-powered-by");
786
- const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
787
- userMiddlewares.forEach((middleware) => {
788
- app.use(middleware);
789
- });
790
- const publicDir = path6.join(distDir, "html");
791
- app.use(express2.static(publicDir));
792
- app.use(async (req, res, next) => {
873
+ const renderer = new render.Renderer(rootConfig, { assetMap });
874
+ return async (req, _, next) => {
875
+ req.renderer = renderer;
876
+ next();
877
+ };
878
+ }
879
+ function rootPreviewServerMiddleware() {
880
+ return async (req, res, next) => {
881
+ const rootConfig = req.rootConfig;
882
+ const renderer = req.renderer;
793
883
  try {
794
884
  const url = req.originalUrl;
795
- const data = await renderer.render(url, {
796
- assetMap
797
- });
885
+ const data = await renderer.render(url);
798
886
  if (data.notFound || !data.html) {
799
887
  next();
800
888
  return;
@@ -814,49 +902,78 @@ async function preview(rootProjectDir) {
814
902
  next(e);
815
903
  }
816
904
  }
817
- });
818
- const port = parseInt(process.env.PORT || "4007");
819
- console.log();
820
- console.log(`${dim3("\u2503")} project: ${rootDir}`);
821
- console.log(`${dim3("\u2503")} server: http://localhost:${port}`);
822
- console.log();
823
- app.listen(port);
905
+ };
824
906
  }
825
907
 
826
908
  // src/cli/commands/start.ts
827
909
  import path7 from "node:path";
828
910
  import { default as express3 } from "express";
829
911
  import { dim as dim4 } from "kleur/colors";
912
+ import sirv2 from "sirv";
913
+ import compression2 from "compression";
830
914
  async function start(rootProjectDir) {
831
- var _a;
832
915
  process.env.NODE_ENV = "production";
833
916
  const rootDir = path7.resolve(rootProjectDir || process.cwd());
917
+ const server = await createServer3({ rootDir });
918
+ const port = parseInt(process.env.PORT || "4007");
919
+ console.log();
920
+ console.log(`${dim4("\u2503")} project: ${rootDir}`);
921
+ console.log(`${dim4("\u2503")} server: http://localhost:${port}`);
922
+ console.log(`${dim4("\u2503")} mode: production`);
923
+ console.log();
924
+ server.listen(port);
925
+ }
926
+ async function createServer3(options) {
927
+ const rootDir = options.rootDir;
834
928
  const rootConfig = await loadRootConfig(rootDir);
835
929
  const distDir = path7.join(rootDir, "dist");
930
+ const server = express3();
931
+ server.disable("x-powered-by");
932
+ server.use(compression2());
933
+ server.use(rootProjectMiddleware({ rootDir, rootConfig }));
934
+ server.use(await rootProdRendererMiddleware({ rootConfig, distDir }));
935
+ const plugins = rootConfig.plugins || [];
936
+ configureServerPlugins(
937
+ server,
938
+ async () => {
939
+ var _a;
940
+ const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
941
+ userMiddlewares.forEach((middleware) => {
942
+ server.use(middleware);
943
+ });
944
+ const publicDir = path7.join(distDir, "html");
945
+ server.use(sirv2(publicDir, { dev: false }));
946
+ server.use(rootProdServerMiddleware());
947
+ },
948
+ plugins,
949
+ { type: "prod" }
950
+ );
951
+ return server;
952
+ }
953
+ async function rootProdRendererMiddleware(options) {
954
+ const { distDir, rootConfig } = options;
836
955
  const render = await import(path7.join(distDir, "server/render.js"));
837
- const renderer = new render.Renderer(rootConfig);
838
956
  const manifestPath = path7.join(distDir, "client/root-manifest.json");
839
957
  if (!await fileExists(manifestPath)) {
840
958
  throw new Error(
841
- `could not find ${manifestPath}. run \`root build\` before \`root start\`.`
959
+ `could not find ${manifestPath}. run \`root build\` before \`root preview\`.`
842
960
  );
843
961
  }
844
962
  const rootManifest = await loadJson(manifestPath);
845
963
  const assetMap = BuildAssetMap.fromRootManifest(rootManifest);
846
- const app = express3();
847
- app.disable("x-powered-by");
848
- const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
849
- userMiddlewares.forEach((middleware) => {
850
- app.use(middleware);
851
- });
852
- const publicDir = path7.join(distDir, "html");
853
- app.use(express3.static(publicDir));
854
- app.use(async (req, res, next) => {
964
+ const renderer = new render.Renderer(rootConfig, { assetMap });
965
+ return async (req, _, next) => {
966
+ req.renderer = renderer;
967
+ next();
968
+ };
969
+ }
970
+ function rootProdServerMiddleware() {
971
+ return async (req, res, next) => {
972
+ const rootConfig = req.rootConfig;
973
+ const renderer = req.renderer;
855
974
  try {
856
975
  const url = req.originalUrl;
857
- const data = await renderer.render(url, {
858
- assetMap
859
- });
976
+ const data = await renderer.render(url);
860
977
  if (data.notFound || !data.html) {
861
978
  next();
862
979
  return;
@@ -876,13 +993,7 @@ async function start(rootProjectDir) {
876
993
  next(e);
877
994
  }
878
995
  }
879
- });
880
- const port = parseInt(process.env.PORT || "4007");
881
- console.log();
882
- console.log(`${dim4("\u2503")} project: ${rootDir}`);
883
- console.log(`${dim4("\u2503")} server: http://localhost:${port}`);
884
- console.log();
885
- app.listen(port);
996
+ };
886
997
  }
887
998
  export {
888
999
  build,