zuby 1.0.30 → 1.0.32

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/README.md CHANGED
@@ -32,6 +32,12 @@ Following integrations are available:
32
32
  - [@zubyjs/preact](https://www.npmjs.com/package/@zubyjs/preact) - Preact integration for Zuby.js
33
33
  - [@zubyjs/react](https://www.npmjs.com/package/@zubyjs/react) - React integration for Zuby.js
34
34
 
35
+ ## Acknowledgements
36
+
37
+ Zuby.js is inspired by [Astro](https://astro.build/), [Next.js](https://nextjs.org/) and [iles](https://iles.pages.dev/)
38
+ to offer familiarity and a quick learning curve for developers but still do things differently.
39
+ You should definitely explore these frameworks too, they are awesome! Maybe you'll find one of them more suitable for your needs.
40
+
35
41
  ## Recommended versions
36
42
 
37
43
  - Node.js: 18
@@ -1,3 +1,3 @@
1
- import { BuildCommandOptions, ZubyConfig } from '../types.js';
1
+ import { BuildCommandOptions, ZubyInternalConfig } from '../types.js';
2
2
  export default function build(options: BuildCommandOptions): Promise<void>;
3
- export declare function getEntryFile(zubyConfig: ZubyConfig): Promise<string>;
3
+ export declare function getEntryFile(zubyInternalConfig: ZubyInternalConfig): Promise<string>;
package/commands/build.js CHANGED
@@ -1,12 +1,11 @@
1
1
  import { MODES } from '../types.js';
2
- import { getZubyConfig } from '../config.js';
2
+ import { getZubyInternalConfig } from '../config.js';
3
3
  import chalk from 'chalk';
4
4
  import { getTitle } from '../branding.js';
5
5
  import { build as viteBuild } from 'vite';
6
6
  import { dirname, join } from 'path';
7
7
  import { normalizePath } from '../utils/pathUtils.js';
8
8
  import { existsSync, rmSync, writeFileSync, copyFileSync, mkdirSync } from 'fs';
9
- import { ZUBY_CONFIG_FILE } from '../constants.js';
10
9
  import { TEMPLATES } from '../templates/types.js';
11
10
  import { glob } from 'glob';
12
11
  import { fileURLToPath } from 'url';
@@ -16,8 +15,8 @@ import { copyFile } from 'fs/promises';
16
15
  const __filename = fileURLToPath(import.meta.url);
17
16
  const __dirname = dirname(__filename);
18
17
  export default async function build(options) {
19
- const zubyConfig = await getZubyConfig(options.configFile);
20
- const { vite: viteConfig, customLogger: logger, outDir = '' } = zubyConfig;
18
+ const zubyInternalConfig = await getZubyInternalConfig(options.configFile);
19
+ const { vite: viteConfig, customLogger: logger, outDir, srcDir, publicDir, configFilePath, } = zubyInternalConfig;
21
20
  process.env.NODE_ENV = MODES.production;
22
21
  logger?.info(getTitle(chalk.gray(`building for production...`)));
23
22
  // Clean build directory
@@ -26,8 +25,9 @@ export default async function build(options) {
26
25
  recursive: true,
27
26
  });
28
27
  }
29
- // Load the entry file
30
- const entryFile = await getEntryFile(zubyConfig);
28
+ // Load the entry file from the project directory
29
+ // or jsxProvider
30
+ const entryFile = await getEntryFile(zubyInternalConfig);
31
31
  // Client build
32
32
  logger?.info(`${chalk.bgYellow.bold.whiteBright(` Step 1/4 `)} ${chalk.gray(`building client...`)}`);
33
33
  await viteBuild({
@@ -48,13 +48,15 @@ export default async function build(options) {
48
48
  // Server build
49
49
  logger?.info(`${chalk.bgYellow.bold.whiteBright(` Step 2/4 `)} ${chalk.gray(`building server...`)}`);
50
50
  await viteBuild({
51
- configFile: false,
52
51
  ...viteConfig,
52
+ configFile: false,
53
+ publicDir: false,
53
54
  build: {
54
55
  ...viteConfig?.build,
55
56
  outDir: normalizePath(join(outDir, 'server')),
56
57
  ssr: normalizePath(entryFile),
57
- ssrManifest: true,
58
+ ssrManifest: 'ssr-manifest.json',
59
+ target: 'node18',
58
60
  },
59
61
  optimizeDeps: {
60
62
  ...viteConfig?.optimizeDeps,
@@ -66,10 +68,9 @@ export default async function build(options) {
66
68
  mode: MODES.production,
67
69
  });
68
70
  // Add serialized zuby config to build directory
69
- writeFileSync(normalizePath(join(outDir, ZUBY_CONFIG_FILE.replace(/\.mjs$/, '.json'))), JSON.stringify(zubyConfig, null, 2));
71
+ writeFileSync(normalizePath(join(outDir, 'zuby.config.json')), JSON.stringify(zubyInternalConfig, null, 2));
70
72
  // Add standalone server assets
71
73
  copyFileSync(normalizePath(join(__dirname, '..', 'server', 'index.js')), normalizePath(join(outDir, 'server.mjs')));
72
- copyFileSync(normalizePath(join(__dirname, '..', 'server', 'expressApp.cjs')), normalizePath(join(outDir, 'expressApp.cjs')));
73
74
  const { name, version } = getZubyPackageConfig();
74
75
  // Write package.json
75
76
  writeFileSync(normalizePath(join(outDir, 'package.json')), JSON.stringify({
@@ -102,14 +103,10 @@ export default async function build(options) {
102
103
  await Promise.all(copyFilePromises);
103
104
  logger?.info(`Done! 🎉`);
104
105
  }
105
- export async function getEntryFile(zubyConfig) {
106
- const { srcDir = '', pageExtensions = [], jsx, customLogger: logger } = zubyConfig;
107
- const userEntryFile = (await glob(`${normalizePath(srcDir)}${TEMPLATES.entry}.{${pageExtensions.join(',')}}`)).pop();
108
- const entryFile = userEntryFile || jsx?.entryTemplateFile;
109
- if (!entryFile) {
110
- logger?.error(`No entry template is available. Please create a file named '${TEMPLATES.entry}' in your project directory or use different jsx.`);
111
- process.exit(1);
112
- }
106
+ export async function getEntryFile(zubyInternalConfig) {
107
+ const { srcDir, templateExtensions, jsx, customLogger: logger } = zubyInternalConfig;
108
+ const userEntryFile = (await glob(`${normalizePath(srcDir)}${TEMPLATES.entry}.{${templateExtensions.join(',')}}`)).pop();
109
+ const entryFile = userEntryFile || jsx.entryTemplateFile;
113
110
  if (userEntryFile) {
114
111
  logger?.info(chalk.gray(`Using custom entry template: '${userEntryFile}'`));
115
112
  }
package/commands/dev.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { MODES } from '../types.js';
2
- import { getZubyConfig } from '../config.js';
2
+ import { getZubyInternalConfig } from '../config.js';
3
3
  import { createServer } from 'vite';
4
4
  import { normalizePath } from '../utils/pathUtils.js';
5
5
  import { join } from 'path';
@@ -7,7 +7,7 @@ import { performance } from 'node:perf_hooks';
7
7
  import { getTitle } from '../branding.js';
8
8
  import chalk from 'chalk';
9
9
  export default async function dev(options) {
10
- const { vite: viteConfig, customLogger: logger, outDir = '', } = await getZubyConfig(options.configFile);
10
+ const { vite: viteConfig, customLogger: logger, outDir = '', } = await getZubyInternalConfig(options.configFile);
11
11
  const port = options.port ? Number(options.port) : viteConfig?.server?.port;
12
12
  const host = options.host || viteConfig?.server?.host;
13
13
  const mode = MODES.development;
package/commands/index.js CHANGED
@@ -11,21 +11,21 @@ program
11
11
  .command('dev')
12
12
  .description('Starts the development server')
13
13
  .option('-p, --port <port>', 'Port to use for the dev server', '3000')
14
- .option('-h, --host <host>', 'Host to use for the dev server', 'localhost')
15
- .option('-c, --config-file <file>', 'The relative path to file with Zuby config', 'zuby.config.mjs')
14
+ .option('-h, --host <host>', 'Host to use for the dev server', '127.0.0.1')
15
+ .option('-c, --config-file <file>', 'The relative path to file with Zuby config')
16
16
  .action(async (options) => dev(options));
17
17
  program
18
18
  .command('preview')
19
19
  .alias('start')
20
20
  .description('Starts the preview server for the production build')
21
21
  .option('-p, --port <port>', 'Port to use for the dev server', '3000')
22
- .option('-h, --host <host>', 'Host to use for the dev server', 'localhost')
23
- .option('-c, --config-file <file>', 'The relative path to file with Zuby config', 'zuby.config.mjs')
22
+ .option('-h, --host <host>', 'Host to use for the dev server', '127.0.0.1')
23
+ .option('-c, --config-file <file>', 'The relative path to file with Zuby config')
24
24
  .action(async (options) => preview(options));
25
25
  program
26
26
  .command('build')
27
27
  .description('Builds the app for production')
28
- .option('-c, --config-file <file>', 'The relative path to file with Zuby config', 'zuby.config.mjs')
28
+ .option('-c, --config-file <file>', 'The relative path to file with Zuby config')
29
29
  .action(async (options) => build(options));
30
30
  program
31
31
  .command('init')
@@ -1,9 +1,9 @@
1
- import { getZubyConfig } from '../config.js';
1
+ import { getZubyInternalConfig } from '../config.js';
2
2
  import { existsSync } from 'fs';
3
3
  import { normalizePath } from '../utils/pathUtils.js';
4
4
  import { resolve } from 'path';
5
5
  export default async function preview(options) {
6
- const { outDir = '' } = await getZubyConfig(options.configFile);
6
+ const { outDir } = await getZubyInternalConfig(options.configFile);
7
7
  if (outDir && !existsSync(outDir)) {
8
8
  throw new Error(`The outDir '${outDir}' does not exist. Did you forget to run 'zuby build' first?`);
9
9
  }
package/config.d.ts CHANGED
@@ -1,16 +1,30 @@
1
- import { ZubyConfig } from './types.js';
1
+ import { ZubyConfig, ZubyInternalConfig } from './types.js';
2
2
  /**
3
- * This function loads the config file and returns the config object with default values.
4
- * It also caches the config object for future use.
5
- * @param configFile
3
+ * Returns the path to the ZubyConfig file.
4
+ */
5
+ export declare const getDefaultConfigPath: () => string | undefined;
6
+ /**
7
+ * This function loads the config file and returns the config object.
8
+ */
9
+ export declare const getZubyConfig: (configFilePath?: string) => Promise<ZubyConfig>;
10
+ /**
11
+ * This function loads the ZubyConfig file and returns the ZubyInternalConfig object
12
+ * with default values added.
13
+ * @param configFilePath
6
14
  * @param cache
7
15
  */
8
- export declare const getZubyConfig: (configFile?: string, cache?: boolean) => Promise<ZubyConfig>;
16
+ export declare const getZubyInternalConfig: (configFilePath?: string, cache?: boolean) => Promise<ZubyInternalConfig>;
9
17
  /**
10
18
  * Adds default values to the config object.
11
19
  * @param config
12
20
  */
13
- export declare const mergeDefaultConfig: (config?: ZubyConfig) => Promise<ZubyConfig>;
21
+ export declare const validateConfig: (config: ZubyConfig) => void;
22
+ /**
23
+ * Adds default values to the ZubyConfig object
24
+ * and returns the ZubyInternalConfig object.
25
+ * @param config
26
+ */
27
+ export declare const mergeDefaultConfig: (config: ZubyConfig) => Promise<ZubyInternalConfig>;
14
28
  /**
15
29
  * This function returns the array of built-in Zuby plugins.
16
30
  * Check which framework components are relying on each plugin
package/config.js CHANGED
@@ -1,55 +1,75 @@
1
1
  import { ZUBY_CONFIG_FILE } from './constants.js';
2
2
  import { existsSync } from 'fs';
3
3
  import { bundleRequire } from 'bundle-require';
4
- import { getApps, getErrors, getInnerLayouts, getLayouts, getPages, getTemplates, } from './templates/index.js';
5
4
  import { createLogger } from './logger/index.js';
6
5
  // Plugins
7
6
  import contextPlugin from './plugins/contextPlugin/index.js';
8
7
  import compileTimePlugin from './plugins/compileTimePlugin/index.js';
9
8
  import chunkNamingPlugin from './plugins/chunkNamingPlugin/index.js';
10
9
  import prerenderPlugin from './plugins/prerenderPlugin/index.js';
11
- let zubyConfig;
10
+ let zubyInternalConfig;
12
11
  /**
13
- * This function loads the config file and returns the config object with default values.
14
- * It also caches the config object for future use.
15
- * @param configFile
16
- * @param cache
12
+ * Returns the path to the ZubyConfig file.
17
13
  */
18
- export const getZubyConfig = async (configFile = ZUBY_CONFIG_FILE, cache = true) => {
19
- // Return the cached config if it exists
20
- if (cache && zubyConfig)
21
- return zubyConfig;
14
+ export const getDefaultConfigPath = () => {
22
15
  // Find the config file with various extensions
23
- const foundConfigFile = [
24
- configFile,
25
- configFile.replace(/\.mjs$/, '.js'),
26
- configFile.replace(/\.mjs$/, '.ts'),
27
- configFile.replace(/\.mjs$/, '.json'),
16
+ return [
17
+ ZUBY_CONFIG_FILE,
18
+ ZUBY_CONFIG_FILE.replace(/\.mjs$/, '.js'),
19
+ ZUBY_CONFIG_FILE.replace(/\.mjs$/, '.ts'),
28
20
  ].find(file => existsSync(file));
29
- if (!foundConfigFile) {
30
- throw new Error(`Config file does not exist: ${configFile}`);
21
+ };
22
+ /**
23
+ * This function loads the config file and returns the config object.
24
+ */
25
+ export const getZubyConfig = async (configFilePath) => {
26
+ configFilePath = configFilePath || getDefaultConfigPath();
27
+ if (!configFilePath || !existsSync(configFilePath)) {
28
+ throw new Error(`ZubyConfig file was not found. Please create a zuby.config.js file in the root of your project.`);
31
29
  }
32
30
  // Loads the module regardless of the module format
33
31
  // and transpiles typescript if needed
34
32
  const { mod } = await bundleRequire({
35
- filepath: foundConfigFile,
33
+ filepath: configFilePath,
36
34
  });
37
35
  // Find the default export and cache the config
38
- zubyConfig = mod.default || mod;
36
+ const zubyConfig = mod.default || mod;
39
37
  if (!zubyConfig) {
40
- throw new Error(`No valid default export found in config file: ${foundConfigFile}`);
38
+ throw new Error(`No valid default export found in ZubyConfig file: ${configFilePath}`);
41
39
  }
42
- zubyConfig = await mergeDefaultConfig(zubyConfig);
43
- // Check if the user has provided the Jsx Provider
44
- if (!zubyConfig.jsx)
45
- throw new Error('You must provide the JSX provider.');
46
40
  return zubyConfig;
47
41
  };
42
+ /**
43
+ * This function loads the ZubyConfig file and returns the ZubyInternalConfig object
44
+ * with default values added.
45
+ * @param configFilePath
46
+ * @param cache
47
+ */
48
+ export const getZubyInternalConfig = async (configFilePath, cache = true) => {
49
+ // Return the cached config if it exists
50
+ if (cache && zubyInternalConfig)
51
+ return zubyInternalConfig;
52
+ const zubyConfig = await getZubyConfig(configFilePath);
53
+ zubyConfig.configFilePath = configFilePath;
54
+ validateConfig(zubyConfig);
55
+ zubyInternalConfig = await mergeDefaultConfig(zubyConfig);
56
+ return zubyInternalConfig;
57
+ };
48
58
  /**
49
59
  * Adds default values to the config object.
50
60
  * @param config
51
61
  */
52
- export const mergeDefaultConfig = async (config = {}) => {
62
+ export const validateConfig = (config) => {
63
+ if (!config.jsx) {
64
+ throw new Error(`No jsxProvider found in ZubyInternalConfig. The 'jsx' property must be a JsxProvider instance.`);
65
+ }
66
+ };
67
+ /**
68
+ * Adds default values to the ZubyConfig object
69
+ * and returns the ZubyInternalConfig object.
70
+ * @param config
71
+ */
72
+ export const mergeDefaultConfig = async (config) => {
53
73
  // Call the jsx function if user forgot to call it
54
74
  if (typeof config.jsx === 'function') {
55
75
  config.jsx = config.jsx();
@@ -60,10 +80,9 @@ export const mergeDefaultConfig = async (config = {}) => {
60
80
  config.outDir = config.outDir ?? 'build';
61
81
  config.output = config.output ?? 'static';
62
82
  config.prerenderPaths = config.prerenderPaths ?? [];
63
- config.pageExtensions = config.pageExtensions ?? ['tsx', 'jsx', 'ts', 'js', 'mjs'];
64
83
  // Default server config
65
84
  config.server = config.server ?? {};
66
- config.server.host = config.server.host ?? 'localhost';
85
+ config.server.host = config.server.host ?? '127.0.0.1';
67
86
  config.server.port = config.server.port ?? 3000;
68
87
  // Add minification
69
88
  config.minifyCSS = config.minifyCSS ?? true;
@@ -94,16 +113,10 @@ export const mergeDefaultConfig = async (config = {}) => {
94
113
  ...(config.jsx?.getPlugins() ?? []),
95
114
  ...(config.vite?.plugins ?? []),
96
115
  ];
97
- // Load templates
98
- const templates = await getTemplates();
99
- config.templates = config.templates ?? {};
100
- config.templates.pages = config.templates.pages ?? (await getPages(templates));
101
- config.templates.apps = config.templates.apps ?? (await getApps(templates));
102
- config.templates.layouts = config.templates.layouts ?? (await getLayouts(templates));
103
- config.templates.innerLayouts =
104
- config.templates.innerLayouts ?? (await getInnerLayouts(templates));
105
- config.templates.errors = config.templates.errors ?? (await getErrors(templates));
106
- return config;
116
+ return {
117
+ ...config,
118
+ templateExtensions: ['js', 'jsx', 'ts', 'tsx'],
119
+ };
107
120
  };
108
121
  /**
109
122
  * This function returns the array of built-in Zuby plugins.
@@ -1,18 +1,19 @@
1
1
  import { ZubyRawContext } from './types.js';
2
- declare class ZubyContext {
2
+ export declare class ZubyContext {
3
3
  readonly rawContext: ZubyRawContext;
4
4
  constructor(rawContext: ZubyRawContext);
5
- get title(): string | undefined;
6
- set title(title: string | undefined);
7
- get currentPath(): string | undefined;
8
5
  get templates(): {
9
6
  pages?: import("../templates/types.js").LazyTemplate[] | undefined;
10
7
  apps?: import("../templates/types.js").LazyTemplate[] | undefined;
11
8
  errors?: import("../templates/types.js").LazyTemplate[] | undefined;
12
9
  layouts?: import("../templates/types.js").LazyTemplate[] | undefined;
13
10
  innerLayouts?: import("../templates/types.js").LazyTemplate[] | undefined;
11
+ apis?: import("../templates/types.js").LazyTemplate[] | undefined;
14
12
  } | undefined;
15
- update: (newContext: ZubyRawContext) => this;
13
+ get site(): string | undefined;
14
+ get generator(): string | undefined;
15
+ get version(): string | undefined;
16
+ get renderToStream(): import("../types.js").RenderToStream | undefined;
17
+ get renderToString(): import("../types.js").RenderToString | undefined;
16
18
  }
17
19
  export declare const getContext: () => ZubyContext;
18
- export {};
package/context/index.js CHANGED
@@ -1,29 +1,24 @@
1
- class ZubyContext {
1
+ export class ZubyContext {
2
2
  constructor(rawContext) {
3
- this.update = (newContext) => {
4
- Object.assign(this.rawContext, newContext);
5
- return this;
6
- };
7
3
  this.rawContext = rawContext;
8
4
  }
9
- get title() {
10
- if (typeof document !== 'undefined' && document.title) {
11
- this.rawContext.title = document.title;
12
- return document.title;
13
- }
14
- return this.rawContext.title;
5
+ get templates() {
6
+ return this.rawContext.templates;
15
7
  }
16
- set title(title) {
17
- if (typeof document !== 'undefined' && document.title) {
18
- this.rawContext.title = document.title = title || '';
19
- }
20
- this.rawContext.title = title;
8
+ get site() {
9
+ return this.rawContext.site;
21
10
  }
22
- get currentPath() {
23
- return this.rawContext.currentPath;
11
+ get generator() {
12
+ return this.rawContext.generator;
24
13
  }
25
- get templates() {
26
- return this.rawContext.templates;
14
+ get version() {
15
+ return this.rawContext.version;
16
+ }
17
+ get renderToStream() {
18
+ return this.rawContext.render?.renderToStream;
19
+ }
20
+ get renderToString() {
21
+ return this.rawContext.render?.renderToString;
27
22
  }
28
23
  }
29
24
  const getRawContext = () => {
@@ -1,4 +1,5 @@
1
1
  import { LazyTemplate } from '../templates/types.js';
2
+ import { RenderToStream, RenderToString } from '../types.js';
2
3
  export interface ZubyRawContext {
3
4
  /**
4
5
  * The array with templates.
@@ -9,13 +10,28 @@ export interface ZubyRawContext {
9
10
  errors?: LazyTemplate[];
10
11
  layouts?: LazyTemplate[];
11
12
  innerLayouts?: LazyTemplate[];
13
+ apis?: LazyTemplate[];
12
14
  };
13
15
  /**
14
- * The current path of the page in both client and server env.
16
+ * The render module from JsxProvider.
15
17
  */
16
- currentPath?: string;
18
+ render?: {
19
+ renderToString?: RenderToString;
20
+ renderToStream?: RenderToStream;
21
+ };
22
+ /**
23
+ * The URL of the site
24
+ * @example https://example.com
25
+ */
26
+ site?: string;
27
+ /**
28
+ * The name of the generator together with its version number
29
+ * @example Zuby.js 1.0.0
30
+ */
31
+ generator?: string;
17
32
  /**
18
- * The current title of the page in both client and server env.
33
+ * The version of used Zuby.js
34
+ * @example 1.0.0
19
35
  */
20
- title?: string;
36
+ version?: string;
21
37
  }
package/package.json CHANGED
@@ -1,16 +1,15 @@
1
1
  {
2
2
  "name": "zuby",
3
- "version": "1.0.30",
3
+ "version": "1.0.32",
4
4
  "description": "Zuby.js is framework for building SPA apps using Vite",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "scripts": {
8
8
  "release": "cd ./dist && npm publish --access public && cd ..",
9
- "build": "rm -rf dist/ && tsc && cp -rf package.json README.md src/examples dist/ && npm run bundle-server && npm run bundle-express",
9
+ "build": "rm -rf dist/ && tsc && cp -rf package.json README.md src/examples dist/ && npm run bundle-server",
10
10
  "bundle-server": "esbuild src/server/index.ts --bundle --platform=node --format=esm --outfile=dist/server/index.js",
11
- "bundle-express": "esbuild src/server/expressApp.ts --bundle --platform=node --format=cjs --minify --outfile=dist/server/expressApp.cjs",
12
11
  "watch-build": "npm run build && tsc --watch",
13
- "push-build": "npm run build && cd dist && npm link && cd ..",
12
+ "push-build": "npm run build && cd dist && yalc push --force && cd ..",
14
13
  "test": "exit 0"
15
14
  },
16
15
  "publishConfig": {
@@ -32,9 +31,7 @@
32
31
  "vite": "^4.4.11"
33
32
  },
34
33
  "devDependencies": {
35
- "@types/express": "^4.17.20",
36
- "@types/inquirer": "^9.0.6",
37
- "express": "^4.18.2"
34
+ "@types/inquirer": "^9.0.6"
38
35
  },
39
36
  "bin": {
40
37
  "zuby": "./commands/index.js"
@@ -0,0 +1,35 @@
1
+ import { ZubyContext } from '../context/index.js';
2
+ export declare class ZubyPageContext {
3
+ protected _url: URL;
4
+ protected _title: string;
5
+ protected _request?: Request;
6
+ protected _params: Record<string, string>;
7
+ protected _clientAddress?: string;
8
+ protected _zubyContext: ZubyContext;
9
+ constructor(options: {
10
+ url?: URL;
11
+ title?: string;
12
+ request?: Request;
13
+ response?: Response;
14
+ clientAddress?: string;
15
+ });
16
+ get url(): URL;
17
+ get title(): string;
18
+ set title(title: string);
19
+ get request(): Request | undefined;
20
+ get params(): Record<string, string>;
21
+ set params(params: Record<string, string>);
22
+ get clientAddress(): string | undefined;
23
+ get isBrowserEnv(): boolean;
24
+ get site(): string | undefined;
25
+ get generator(): string | undefined;
26
+ get version(): string | undefined;
27
+ get templates(): {
28
+ pages?: import("../templates/types.js").LazyTemplate[] | undefined;
29
+ apps?: import("../templates/types.js").LazyTemplate[] | undefined;
30
+ errors?: import("../templates/types.js").LazyTemplate[] | undefined;
31
+ layouts?: import("../templates/types.js").LazyTemplate[] | undefined;
32
+ innerLayouts?: import("../templates/types.js").LazyTemplate[] | undefined;
33
+ apis?: import("../templates/types.js").LazyTemplate[] | undefined;
34
+ } | undefined;
35
+ }
@@ -0,0 +1,56 @@
1
+ import { getContext } from '../context/index.js';
2
+ export class ZubyPageContext {
3
+ constructor(options) {
4
+ this._url = options?.url || new URL('http://localhost/');
5
+ this._title = options?.title || '';
6
+ this._request = options?.request;
7
+ this._params = {};
8
+ this._clientAddress = options?.clientAddress;
9
+ this._zubyContext = getContext();
10
+ }
11
+ get url() {
12
+ if (this.isBrowserEnv) {
13
+ return new URL(window.location.href);
14
+ }
15
+ return this._url;
16
+ }
17
+ get title() {
18
+ if (this.isBrowserEnv) {
19
+ this._title = document.title;
20
+ }
21
+ return this._title;
22
+ }
23
+ set title(title) {
24
+ if (this.isBrowserEnv) {
25
+ document.title = title;
26
+ }
27
+ this._title = title;
28
+ }
29
+ get request() {
30
+ return this._request;
31
+ }
32
+ get params() {
33
+ return this._params;
34
+ }
35
+ set params(params) {
36
+ this._params = params;
37
+ }
38
+ get clientAddress() {
39
+ return this._clientAddress;
40
+ }
41
+ get isBrowserEnv() {
42
+ return typeof window !== 'undefined';
43
+ }
44
+ get site() {
45
+ return this._zubyContext.site;
46
+ }
47
+ get generator() {
48
+ return this._zubyContext.generator;
49
+ }
50
+ get version() {
51
+ return this._zubyContext.version;
52
+ }
53
+ get templates() {
54
+ return this._zubyContext.templates;
55
+ }
56
+ }
@@ -4,3 +4,4 @@ export default function index(): PluginOption;
4
4
  export declare function generateCompileTimeContextCode(): Promise<string>;
5
5
  export declare function generateTemplatesCode(): Promise<string>;
6
6
  export declare function generateTemplateCode(template: Template): Promise<string>;
7
+ export declare function generateRenderCode(): Promise<string>;
@@ -1,6 +1,8 @@
1
- import { getZubyConfig } from '../../config.js';
1
+ import { getZubyInternalConfig } from '../../config.js';
2
2
  import { relative } from 'path';
3
3
  import { normalizePath } from '../../utils/pathUtils.js';
4
+ import { getZubyPackageConfig } from '../../packageConfig.js';
5
+ import { getApis, getApps, getErrors, getInnerLayouts, getLayouts, getPages, getTemplates, } from '../../templates/index.js';
4
6
  let viteConfig;
5
7
  export default function index() {
6
8
  return {
@@ -19,21 +21,36 @@ export default function index() {
19
21
  };
20
22
  }
21
23
  export async function generateCompileTimeContextCode() {
24
+ const { site } = await getZubyInternalConfig();
25
+ const { version } = await getZubyPackageConfig();
22
26
  return `globalThis.ZubyRawContext = {
23
27
  ...(globalThis.ZubyRawContext || {}),
24
28
  templates: ${await generateTemplatesCode()},
29
+ render: ${await generateRenderCode()},
30
+ site: '${site || ''}',
31
+ generator: 'Zuby.js ${version}',
32
+ version: '${version}',
25
33
  };`;
26
34
  }
27
35
  export async function generateTemplatesCode() {
28
- const { templates } = await getZubyConfig();
29
- const pagesCode = await Promise.all(templates?.pages?.map(generateTemplateCode) || []);
30
- const appsCode = await Promise.all(templates?.apps?.map(generateTemplateCode) || []);
31
- const errorsCode = await Promise.all(templates?.errors?.map(generateTemplateCode) || []);
36
+ const templates = await getTemplates();
37
+ const pages = await getPages(templates);
38
+ const apps = await getApps(templates);
39
+ const layouts = await getLayouts(templates);
40
+ const innerLayouts = await getInnerLayouts(templates);
41
+ const errors = await getErrors(templates);
42
+ const apis = await getApis(templates);
43
+ const pagesCode = await Promise.all(pages.map(generateTemplateCode) || []);
44
+ const appsCode = await Promise.all(apps.map(generateTemplateCode) || []);
45
+ const errorsCode = await Promise.all(errors.map(generateTemplateCode) || []);
32
46
  const layoutsCode = viteConfig?.build.ssr
33
- ? await Promise.all(templates?.layouts?.map(generateTemplateCode) || [])
47
+ ? await Promise.all(layouts.map(generateTemplateCode) || [])
34
48
  : [];
35
49
  const innerLayoutsCode = viteConfig?.build.ssr
36
- ? await Promise.all(templates?.innerLayouts?.map(generateTemplateCode) || [])
50
+ ? await Promise.all(innerLayouts.map(generateTemplateCode) || [])
51
+ : [];
52
+ const apisCode = viteConfig?.build.ssr
53
+ ? await Promise.all(apis.map(generateTemplateCode) || [])
37
54
  : [];
38
55
  return `{
39
56
  pages: [${pagesCode.join(',')}],
@@ -41,6 +58,7 @@ export async function generateTemplatesCode() {
41
58
  errors: [${errorsCode.join(',')}],
42
59
  layouts: [${layoutsCode.join(',')}],
43
60
  innerLayouts: [${innerLayoutsCode.join(',')}],
61
+ apis: [${apisCode.join(',')}],
44
62
  }`;
45
63
  }
46
64
  export async function generateTemplateCode(template) {
@@ -49,7 +67,14 @@ export async function generateTemplateCode(template) {
49
67
  path: "${template.path}",
50
68
  pathRegex: ${template.pathRegex},
51
69
  pathParams: ${JSON.stringify(template.pathParams)},
70
+ pathType: "${template.pathType}",
52
71
  templateType: "${template.templateType}",
53
72
  component: () => import("${template.filename}"),
54
73
  }`;
55
74
  }
75
+ export async function generateRenderCode() {
76
+ const { jsx } = await getZubyInternalConfig();
77
+ if (!viteConfig?.build.ssr)
78
+ return '{}';
79
+ return `await import("${jsx.renderFile}")`;
80
+ }