@athenna/http 5.14.0 → 5.16.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@athenna/http",
3
- "version": "5.14.0",
3
+ "version": "5.16.0",
4
4
  "description": "The Athenna Http server. Built on top of fastify.",
5
5
  "license": "MIT",
6
6
  "author": "João Lenon <lenon@athenna.io>",
@@ -82,13 +82,13 @@
82
82
  "@athenna/test": "^5.2.0",
83
83
  "@athenna/tsconfig": "^5.0.0",
84
84
  "@athenna/view": "^5.1.0",
85
+ "@athenna/vite": "^5.1.0",
85
86
  "@fastify/cors": "^10.0.1",
86
87
  "@fastify/helmet": "^13.0.0",
87
88
  "@fastify/rate-limit": "^10.2.1",
88
89
  "@fastify/static": "^8.0.3",
89
90
  "@fastify/swagger": "^9.4.0",
90
91
  "@fastify/swagger-ui": "^5.2.0",
91
- "@fastify/vite": "^7.0.1",
92
92
  "@typescript-eslint/eslint-plugin": "^7.18.0",
93
93
  "@typescript-eslint/parser": "^7.18.0",
94
94
  "autocannon": "^7.15.0",
@@ -100,7 +100,9 @@ export class Response {
100
100
  .createRenderer()
101
101
  .share({ request: this.request })
102
102
  .render(view, data);
103
- await this.safeHeader('Content-Type', 'text/html; charset=utf-8').send(content);
103
+ await this.header('Content-Security-Policy', "default-src 'self' 'unsafe-inline'")
104
+ .safeHeader('Content-Type', 'text/html; charset=utf-8')
105
+ .send(content);
104
106
  this.response.body = content;
105
107
  return this;
106
108
  }
@@ -33,7 +33,7 @@ export declare class HttpKernel {
33
33
  */
34
34
  registerRTracer(trace?: boolean): Promise<void>;
35
35
  /**
36
- * Register the @fastify/vite plugin in the Http server.
36
+ * Register the @athenna/vite plugin in the Http server.
37
37
  */
38
38
  registerVite(trace?: boolean): Promise<void>;
39
39
  /**
@@ -22,7 +22,7 @@ const swaggerUiPlugin = await Module.safeImport('@fastify/swagger-ui');
22
22
  const rateLimitPlugin = await Module.safeImport('@fastify/rate-limit');
23
23
  const staticPlugin = await Module.safeImport('@fastify/static');
24
24
  const rTracerPlugin = await Module.safeImport('cls-rtracer');
25
- const vitePlugin = await Module.safeImport('@fastify/vite');
25
+ const vitePlugin = await Module.safeImport('@athenna/vite/plugins/fastify');
26
26
  export class HttpKernel {
27
27
  /**
28
28
  * Register the @fastify/cors plugin in the Http server.
@@ -130,7 +130,7 @@ export class HttpKernel {
130
130
  await Server.plugin(rTracerPlugin.fastifyPlugin, this.getConfig('http.rTracer'));
131
131
  }
132
132
  /**
133
- * Register the @fastify/vite plugin in the Http server.
133
+ * Register the @athenna/vite plugin in the Http server.
134
134
  */
135
135
  async registerVite(trace) {
136
136
  if (trace === false) {
@@ -142,7 +142,7 @@ export class HttpKernel {
142
142
  return;
143
143
  }
144
144
  if (!vitePlugin) {
145
- debug('Not able to register vite plugin. Install @fastify/vite package.');
145
+ debug('Not able to register vite plugin. Install @athenna/vite package.');
146
146
  return;
147
147
  }
148
148
  await Server.plugin(vitePlugin, this.getConfig('http.vite'));
@@ -9,6 +9,5 @@
9
9
  import { ServiceProvider } from '@athenna/ioc';
10
10
  export declare class HttpServerProvider extends ServiceProvider {
11
11
  register(): void;
12
- boot(): void;
13
12
  shutdown(): Promise<void>;
14
13
  }
@@ -6,41 +6,12 @@
6
6
  * For the full copyright and license information, please view the LICENSE
7
7
  * file that was distributed with this source code.
8
8
  */
9
- import { View } from '@athenna/view';
10
- import { Vite } from '#src/vite/index';
11
- import { EdgeError } from 'edge-error';
12
9
  import { ServiceProvider } from '@athenna/ioc';
13
10
  import { ServerImpl } from '#src/server/ServerImpl';
14
11
  export class HttpServerProvider extends ServiceProvider {
15
12
  register() {
16
13
  this.container.instance('Athenna/Core/HttpServer', new ServerImpl(Config.get('http.fastify')));
17
14
  }
18
- boot() {
19
- View.edge.global('vite', new Vite());
20
- View.edge.registerTag({
21
- tagName: 'vite',
22
- seekable: true,
23
- block: false,
24
- compile(parser, buffer, token) {
25
- /**
26
- * Ensure an argument is defined
27
- */
28
- if (!token.properties.jsArg.trim()) {
29
- throw new EdgeError('Missing entrypoint name', 'E_RUNTIME_EXCEPTION', {
30
- filename: token.filename,
31
- line: token.loc.start.line,
32
- col: token.loc.start.col
33
- });
34
- }
35
- const parsed = parser.utils.transformAst(parser.utils.generateAST(token.properties.jsArg, token.loc, token.filename), token.filename, parser);
36
- const entrypoints = parser.utils.stringify(parsed);
37
- const methodCall = parsed.type === 'SequenceExpression'
38
- ? `generateEntryPointsTags${entrypoints}`
39
- : `generateEntryPointsTags(${entrypoints})`;
40
- buffer.outputExpression(`(await state.vite.${methodCall}).join('\\n')`, token.filename, token.loc.start.line, false);
41
- }
42
- });
43
- }
44
15
  async shutdown() {
45
16
  const Server = this.container.use('Athenna/Core/HttpServer');
46
17
  if (!Server) {
@@ -1,22 +0,0 @@
1
- /**
2
- * @athenna/http
3
- *
4
- * (c) João Lenon <lenon@athenna.io>
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- import type { ConfigEnv, Plugin, UserConfig } from 'vite';
10
- import type { PluginOptions } from '#src/types/vite/PluginOptions';
11
- /**
12
- * Resolve the `config.base` value
13
- */
14
- export declare function resolveBase(config: UserConfig, options: Required<PluginOptions>, command: 'build' | 'serve'): string;
15
- /**
16
- * Vite config hook
17
- */
18
- export declare function configHook(options: Required<PluginOptions>, userConfig: UserConfig, { command }: ConfigEnv): UserConfig;
19
- /**
20
- * Update the user vite config to match Athenna requirements.
21
- */
22
- export declare const config: (options: Required<PluginOptions>) => Plugin;
@@ -1,57 +0,0 @@
1
- /**
2
- * @athenna/http
3
- *
4
- * (c) João Lenon <lenon@athenna.io>
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- import { join } from 'node:path';
10
- /**
11
- * Resolve the `config.base` value
12
- */
13
- export function resolveBase(config, options, command) {
14
- if (config.base)
15
- return config.base;
16
- if (command === 'build') {
17
- return options.assetsUrl.endsWith('/')
18
- ? options.assetsUrl
19
- : options.assetsUrl + '/';
20
- }
21
- return '/';
22
- }
23
- /**
24
- * Vite config hook
25
- */
26
- export function configHook(options, userConfig, { command }) {
27
- const config = {
28
- publicDir: userConfig.publicDir ?? false,
29
- base: resolveBase(userConfig, options, command),
30
- /**
31
- * Disable the vite dev server cors handling. Otherwise, it will
32
- * override the cors settings defined by @fastify/cors.
33
- */
34
- server: { cors: userConfig.server?.cors ?? false },
35
- build: {
36
- assetsDir: '',
37
- emptyOutDir: true,
38
- manifest: userConfig.build?.manifest ?? true,
39
- outDir: userConfig.build?.outDir ?? options.buildDirectory,
40
- assetsInlineLimit: userConfig.build?.assetsInlineLimit ?? 0,
41
- rollupOptions: {
42
- input: options.entrypoints.map(entrypoint => join(userConfig.root || '', entrypoint))
43
- }
44
- }
45
- };
46
- return config;
47
- }
48
- /**
49
- * Update the user vite config to match Athenna requirements.
50
- */
51
- export const config = (options) => {
52
- return {
53
- name: 'vite-plugin-athenna:config',
54
- enforce: 'post',
55
- config: configHook.bind(null, options)
56
- };
57
- };
@@ -1,92 +0,0 @@
1
- /**
2
- * @athenna/http
3
- *
4
- * (c) João Lenon <lenon@athenna.io>
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- import type { Manifest, ModuleNode } from 'vite';
10
- export declare class Vite {
11
- /**
12
- * We cache the manifest file content in production
13
- * to avoid reading the file multiple times.
14
- */
15
- manifestCache?: Manifest;
16
- /**
17
- * Verify if vite is running in development mode.
18
- */
19
- get isViteRunning(): boolean;
20
- /**
21
- * Reads the file contents as JSON.
22
- */
23
- readFileAsJSON(filePath: string): any;
24
- /**
25
- * Returns a new array with unique items by the given key
26
- */
27
- uniqueBy<T>(array: T[], key: keyof T): T[];
28
- /**
29
- * Convert Record of attributes to a valid HTML string.
30
- */
31
- makeAttributes(attributes: Record<string, string | boolean>): string;
32
- /**
33
- * Generates a JSON element with a custom toString implementation.
34
- */
35
- generateElement(element: any): any;
36
- /**
37
- * Returns the script needed for the HMR working with Vite.
38
- */
39
- getViteHmrScript(): any;
40
- /**
41
- * Check if the given path is a CSS path.
42
- */
43
- isCssPath(path: string): boolean;
44
- /**
45
- * If the module is a style module.
46
- */
47
- isStyleModule(mod: ModuleNode): boolean;
48
- /**
49
- * Create a style tag for the given path
50
- */
51
- makeStyleTag(url: string, attributes?: any): any;
52
- /**
53
- * Create a script tag for the given path
54
- */
55
- makeScriptTag(url: string, attributes?: any): any;
56
- /**
57
- * Generate a HTML tag for the given asset
58
- */
59
- generateTag(asset: string, attributes?: any): any;
60
- /**
61
- * Get a chunk from the manifest file for a given file name
62
- */
63
- chunk(manifest: Manifest, entrypoint: string): import("vite").ManifestChunk;
64
- /**
65
- * Get a list of chunks for a given filename
66
- */
67
- chunksByFile(manifest: Manifest, file: string): import("vite").ManifestChunk[];
68
- /**
69
- * Generate preload tag for a given url
70
- */
71
- makePreloadTagForUrl(url: string): any;
72
- /**
73
- * Generate style and script tags for the given entrypoints
74
- * Also adds the @vite/client script
75
- */
76
- generateEntryPointsTagsForDevMode(entryPoints: string[], attributes?: any): Promise<any[]>;
77
- /**
78
- * Generate style and script tags for the given entrypoints
79
- * using the manifest file
80
- */
81
- generateEntryPointsTagsWithManifest(entryPoints: string[], attributes?: any): any[];
82
- /**
83
- * Generate tags for the entry points
84
- */
85
- generateEntryPointsTags(entryPoints: string[] | string, attributes?: any): Promise<any[]>;
86
- /**
87
- * Returns the manifest file contents
88
- *
89
- * @throws Will throw an exception when running in dev
90
- */
91
- manifest(): Manifest;
92
- }
package/src/vite/index.js DELETED
@@ -1,238 +0,0 @@
1
- /**
2
- * @athenna/http
3
- *
4
- * (c) João Lenon <lenon@athenna.io>
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- import { File, Path } from '@athenna/common';
10
- const styleFileRegex = /\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\?)/;
11
- export class Vite {
12
- /**
13
- * Verify if vite is running in development mode.
14
- */
15
- get isViteRunning() {
16
- return process.argv.includes('--vite');
17
- }
18
- /**
19
- * Reads the file contents as JSON.
20
- */
21
- readFileAsJSON(filePath) {
22
- return new File(filePath).getContentAsJsonSync();
23
- }
24
- /**
25
- * Returns a new array with unique items by the given key
26
- */
27
- uniqueBy(array, key) {
28
- const seen = new Set();
29
- return array.filter(item => {
30
- const k = item[key];
31
- return seen.has(k) ? false : seen.add(k);
32
- });
33
- }
34
- /**
35
- * Convert Record of attributes to a valid HTML string.
36
- */
37
- makeAttributes(attributes) {
38
- return Object.keys(attributes)
39
- .map(key => {
40
- const value = attributes[key];
41
- if (value === true) {
42
- return key;
43
- }
44
- if (!value) {
45
- return null;
46
- }
47
- return `${key}="${value}"`;
48
- })
49
- .filter(attr => attr !== null)
50
- .join(' ');
51
- }
52
- /**
53
- * Generates a JSON element with a custom toString implementation.
54
- */
55
- generateElement(element) {
56
- const makeAttributes = this.makeAttributes;
57
- return {
58
- ...element,
59
- toString() {
60
- const attributes = `${makeAttributes(element.attributes)}`;
61
- if (element.tag === 'link') {
62
- return `<${element.tag} ${attributes}/>`;
63
- }
64
- return `<${element.tag} ${attributes}>${element.children.join('\n')}</${element.tag}>`;
65
- }
66
- };
67
- }
68
- /**
69
- * Returns the script needed for the HMR working with Vite.
70
- */
71
- getViteHmrScript() {
72
- return this.generateElement({
73
- tag: 'script',
74
- attributes: {
75
- type: 'module',
76
- src: '/@vite/client'
77
- },
78
- children: []
79
- });
80
- }
81
- /**
82
- * Check if the given path is a CSS path.
83
- */
84
- isCssPath(path) {
85
- return path.match(styleFileRegex) !== null;
86
- }
87
- /**
88
- * If the module is a style module.
89
- */
90
- isStyleModule(mod) {
91
- if (this.isCssPath(mod.url) ||
92
- (mod.id && /\?vue&type=style/.test(mod.id))) {
93
- return true;
94
- }
95
- return false;
96
- }
97
- /**
98
- * Create a style tag for the given path
99
- */
100
- makeStyleTag(url, attributes) {
101
- return this.generateElement({
102
- tag: 'link',
103
- attributes: { rel: 'stylesheet', href: url, ...attributes }
104
- });
105
- }
106
- /**
107
- * Create a script tag for the given path
108
- */
109
- makeScriptTag(url, attributes) {
110
- return this.generateElement({
111
- tag: 'script',
112
- attributes: { type: 'module', src: url, ...attributes },
113
- children: []
114
- });
115
- }
116
- /**
117
- * Generate a HTML tag for the given asset
118
- */
119
- generateTag(asset, attributes) {
120
- let url = '';
121
- if (this.isViteRunning) {
122
- url = `/${asset}`;
123
- }
124
- else {
125
- url = asset;
126
- }
127
- if (this.isCssPath(asset)) {
128
- return this.makeStyleTag(url, attributes);
129
- }
130
- return this.makeScriptTag(url, attributes);
131
- }
132
- /**
133
- * Get a chunk from the manifest file for a given file name
134
- */
135
- chunk(manifest, entrypoint) {
136
- const chunk = manifest[entrypoint];
137
- if (!chunk) {
138
- throw new Error(`Cannot find "${entrypoint}" chunk in the manifest file`);
139
- }
140
- return chunk;
141
- }
142
- /**
143
- * Get a list of chunks for a given filename
144
- */
145
- chunksByFile(manifest, file) {
146
- return Object.entries(manifest)
147
- .filter(([, chunk]) => chunk.file === file)
148
- .map(([_, chunk]) => chunk);
149
- }
150
- /**
151
- * Generate preload tag for a given url
152
- */
153
- makePreloadTagForUrl(url) {
154
- const attributes = this.isCssPath(url)
155
- ? { rel: 'preload', as: 'style', href: url }
156
- : { rel: 'modulepreload', href: url };
157
- return this.generateElement({ tag: 'link', attributes });
158
- }
159
- /**
160
- * Generate style and script tags for the given entrypoints
161
- * Also adds the @vite/client script
162
- */
163
- async generateEntryPointsTagsForDevMode(entryPoints, attributes) {
164
- const tags = entryPoints.map(entrypoint => this.generateTag(entrypoint, attributes));
165
- const viteHmr = this.getViteHmrScript();
166
- const result = [viteHmr, tags];
167
- return result.sort(tag => (tag.tag === 'link' ? -1 : 1));
168
- }
169
- /**
170
- * Generate style and script tags for the given entrypoints
171
- * using the manifest file
172
- */
173
- generateEntryPointsTagsWithManifest(entryPoints, attributes) {
174
- const manifest = this.manifest();
175
- const tags = [];
176
- const preloads = [];
177
- for (const entryPoint of entryPoints) {
178
- const chunk = this.chunk(manifest, entryPoint);
179
- preloads.push({ path: chunk.file });
180
- tags.push({
181
- path: chunk.file,
182
- tag: this.generateTag(chunk.file, {
183
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
184
- // @ts-ignore
185
- integrity: chunk.integrity
186
- })
187
- });
188
- for (const css of chunk.css || []) {
189
- preloads.push({ path: css });
190
- tags.push({ path: css, tag: this.generateTag(css) });
191
- }
192
- for (const importNode of chunk.imports || []) {
193
- preloads.push({ path: manifest[importNode].file });
194
- for (const css of manifest[importNode].css || []) {
195
- const subChunk = this.chunksByFile(manifest, css);
196
- preloads.push({ path: css });
197
- tags.push({
198
- path: css,
199
- tag: this.generateTag(css, {
200
- ...attributes,
201
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
202
- // @ts-ignore
203
- integrity: subChunk[0]?.integrity
204
- })
205
- });
206
- }
207
- }
208
- }
209
- const preloadsElements = this.uniqueBy(preloads, 'path')
210
- .sort(preload => (this.isCssPath(preload.path) ? -1 : 1))
211
- .map(preload => this.makePreloadTagForUrl(preload.path));
212
- return preloadsElements.concat(tags.map(({ tag }) => tag));
213
- }
214
- /**
215
- * Generate tags for the entry points
216
- */
217
- async generateEntryPointsTags(entryPoints, attributes) {
218
- entryPoints = Array.isArray(entryPoints) ? entryPoints : [entryPoints];
219
- if (this.isViteRunning) {
220
- return this.generateEntryPointsTagsForDevMode(entryPoints, attributes);
221
- }
222
- return this.generateEntryPointsTagsWithManifest(entryPoints, attributes);
223
- }
224
- /**
225
- * Returns the manifest file contents
226
- *
227
- * @throws Will throw an exception when running in dev
228
- */
229
- manifest() {
230
- if (this.isViteRunning) {
231
- throw new Error('Cannot read the manifest file when running in dev mode');
232
- }
233
- if (!this.manifestCache) {
234
- this.manifestCache = this.readFileAsJSON(Path.public('assets/.vite/manifest.json'));
235
- }
236
- return this.manifestCache;
237
- }
238
- }
@@ -1,11 +0,0 @@
1
- /**
2
- * @athenna/http
3
- *
4
- * (c) João Lenon <lenon@athenna.io>
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- import type { PluginOption } from 'vite';
10
- import type { PluginOptions } from '#src/types/vite/PluginOptions';
11
- export declare function athenna(options: PluginOptions): PluginOption[];
@@ -1,18 +0,0 @@
1
- /**
2
- * @athenna/http
3
- *
4
- * (c) João Lenon <lenon@athenna.io>
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- import PluginRestart from 'vite-plugin-restart';
10
- import { config } from '#src/vite/config';
11
- export function athenna(options) {
12
- const fullOptions = Object.assign({
13
- assetsUrl: '/assets',
14
- buildDirectory: 'public/assets',
15
- reload: ['./src/resources/views/**/*.edge']
16
- }, options);
17
- return [PluginRestart({ reload: fullOptions.reload }), config(fullOptions)];
18
- }