@adonisjs/assembler 6.1.3-3 → 6.1.3-30

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.
@@ -1,152 +0,0 @@
1
- import slash from 'slash';
2
- import copyfiles from 'cpy';
3
- import fs from 'node:fs/promises';
4
- import { fileURLToPath } from 'node:url';
5
- import { join, relative } from 'node:path';
6
- import { cliui } from '@poppinss/cliui';
7
- import { run } from './run.js';
8
- import { parseConfig } from './parse_config.js';
9
- const ui = cliui();
10
- export class Bundler {
11
- #cwd;
12
- #cwdPath;
13
- #ts;
14
- #logger = ui.logger;
15
- #options;
16
- get #colors() {
17
- return this.#logger.getColors();
18
- }
19
- constructor(cwd, ts, options) {
20
- this.#cwd = cwd;
21
- this.#cwdPath = fileURLToPath(this.#cwd);
22
- this.#ts = ts;
23
- this.#options = options;
24
- }
25
- #getRelativeName(filePath) {
26
- return slash(relative(this.#cwdPath, filePath));
27
- }
28
- async #cleanupBuildDirectory(outDir) {
29
- await fs.rm(outDir, { recursive: true, force: true, maxRetries: 5 });
30
- }
31
- async #buildAssets() {
32
- const assetsBundler = this.#options.assets;
33
- if (!assetsBundler?.serve) {
34
- return true;
35
- }
36
- try {
37
- this.#logger.info('compiling frontend assets', { suffix: assetsBundler.cmd });
38
- await run(this.#cwd, {
39
- stdio: 'inherit',
40
- script: assetsBundler.cmd,
41
- scriptArgs: [],
42
- });
43
- return true;
44
- }
45
- catch {
46
- return false;
47
- }
48
- }
49
- async #runTsc(outDir) {
50
- try {
51
- await run(this.#cwd, {
52
- stdio: 'inherit',
53
- script: 'tsc',
54
- scriptArgs: ['--outDir', outDir],
55
- });
56
- return true;
57
- }
58
- catch {
59
- return false;
60
- }
61
- }
62
- async #copyFiles(files, outDir) {
63
- try {
64
- await copyfiles(files, outDir, { cwd: this.#cwdPath });
65
- }
66
- catch (error) {
67
- if (!error.message.includes("the file doesn't exist")) {
68
- throw error;
69
- }
70
- }
71
- }
72
- async #copyMetaFiles(outDir, additionalFilesToCopy) {
73
- const metaFiles = (this.#options.metaFiles || [])
74
- .map((file) => file.pattern)
75
- .concat(additionalFilesToCopy);
76
- await this.#copyFiles(metaFiles, outDir);
77
- }
78
- async #copyAdonisRcFile(outDir) {
79
- const existingContents = JSON.parse(await fs.readFile(join(this.#cwdPath, '.adonisrc.json'), 'utf-8'));
80
- const compiledContents = Object.assign({}, existingContents, {
81
- typescript: false,
82
- lastCompiledAt: new Date().toISOString(),
83
- });
84
- await fs.mkdir(outDir, { recursive: true });
85
- await fs.writeFile(join(outDir, '.adonisrc.json'), JSON.stringify(compiledContents, null, 2) + '\n');
86
- }
87
- #getClientLockFile(client) {
88
- switch (client) {
89
- case 'npm':
90
- return 'package-lock.json';
91
- case 'yarn':
92
- return 'yarn.lock';
93
- case 'pnpm':
94
- return 'pnpm-lock.yaml';
95
- }
96
- }
97
- #getClientInstallCommand(client) {
98
- switch (client) {
99
- case 'npm':
100
- return 'npm ci --omit="dev"';
101
- case 'yarn':
102
- return 'yarn install --production';
103
- case 'pnpm':
104
- return 'pnpm i --prod';
105
- }
106
- }
107
- setLogger(logger) {
108
- this.#logger = logger;
109
- return this;
110
- }
111
- async bundle(stopOnError = true, client = 'npm') {
112
- const config = parseConfig(this.#cwd, this.#ts);
113
- if (!config) {
114
- return false;
115
- }
116
- const outDir = config.options.outDir || fileURLToPath(new URL('build/', this.#cwd));
117
- this.#logger.info('cleaning up output directory', { suffix: this.#getRelativeName(outDir) });
118
- await this.#cleanupBuildDirectory(outDir);
119
- if (!(await this.#buildAssets())) {
120
- return false;
121
- }
122
- this.#logger.info('compiling typescript source', { suffix: 'tsc' });
123
- const buildCompleted = await this.#runTsc(outDir);
124
- await this.#copyFiles(['ace.js'], outDir);
125
- if (!buildCompleted && stopOnError) {
126
- await this.#cleanupBuildDirectory(outDir);
127
- const instructions = ui
128
- .sticker()
129
- .fullScreen()
130
- .drawBorder((borderChar, colors) => colors.red(borderChar));
131
- instructions.add(this.#colors.red('Cannot complete the build process as there are TypeScript errors.'));
132
- instructions.add(this.#colors.red('Use "--ignore-ts-errors" flag to ignore TypeScript errors and continue the build.'));
133
- this.#logger.logError(instructions.prepare());
134
- return false;
135
- }
136
- const pkgFiles = ['package.json', this.#getClientLockFile(client)];
137
- this.#logger.info('copying meta files to the output directory');
138
- await this.#copyMetaFiles(outDir, pkgFiles);
139
- this.#logger.info('copying .adonisrc.json file to the output directory');
140
- await this.#copyAdonisRcFile(outDir);
141
- this.#logger.success('build completed');
142
- this.#logger.log('');
143
- ui.instructions()
144
- .useRenderer(this.#logger.getRenderer())
145
- .heading('Run the following commands to start the server in production')
146
- .add(this.#colors.cyan(`cd ${this.#getRelativeName(outDir)}`))
147
- .add(this.#colors.cyan(this.#getClientInstallCommand(client)))
148
- .add(this.#colors.cyan('node bin/server.js'))
149
- .render();
150
- return true;
151
- }
152
- }
@@ -1,286 +0,0 @@
1
- import getPort from 'get-port';
2
- import picomatch from 'picomatch';
3
- import { cliui } from '@poppinss/cliui';
4
- import { EnvLoader, EnvParser } from '@adonisjs/env';
5
- import { watch } from './watch.js';
6
- import { run, runNode } from './run.js';
7
- const ui = cliui();
8
- export class DevServer {
9
- #cwd;
10
- #logger = ui.logger;
11
- #options;
12
- #isWatching = false;
13
- #scriptFile = 'bin/server.js';
14
- #httpServerProcess;
15
- #isMetaFileWithReloadsEnabled;
16
- #isMetaFileWithReloadsDisabled;
17
- #watcher;
18
- #assetsServerProcess;
19
- #onError;
20
- #onClose;
21
- get #colors() {
22
- return this.#logger.getColors();
23
- }
24
- constructor(cwd, options) {
25
- this.#cwd = cwd;
26
- this.#options = options;
27
- this.#isMetaFileWithReloadsEnabled = picomatch((this.#options.metaFiles || [])
28
- .filter(({ reloadServer }) => reloadServer === true)
29
- .map(({ pattern }) => pattern));
30
- this.#isMetaFileWithReloadsDisabled = picomatch((this.#options.metaFiles || [])
31
- .filter(({ reloadServer }) => reloadServer !== true)
32
- .map(({ pattern }) => pattern));
33
- }
34
- #isDotEnvFile(filePath) {
35
- if (filePath === '.env') {
36
- return true;
37
- }
38
- return filePath.includes('.env.');
39
- }
40
- #isRcFile(filePath) {
41
- return filePath === '.adonisrc.json';
42
- }
43
- #isAdonisJSReadyMessage(message) {
44
- return (message !== null &&
45
- typeof message === 'object' &&
46
- 'isAdonisJS' in message &&
47
- 'environment' in message &&
48
- message.environment === 'web');
49
- }
50
- #clearScreen() {
51
- if (this.#options.clearScreen) {
52
- process.stdout.write('\u001Bc');
53
- }
54
- }
55
- #logViteDevServerMessage(data) {
56
- const dataString = data.toString();
57
- const lines = dataString.split('\n');
58
- if (dataString.includes('ready in')) {
59
- console.log('');
60
- console.log(dataString.trim());
61
- return;
62
- }
63
- if (dataString.includes('Local') && dataString.includes('Network')) {
64
- const sticker = ui.sticker().useColors(this.#colors).useRenderer(this.#logger.getRenderer());
65
- lines.forEach((line) => {
66
- if (line.trim()) {
67
- sticker.add(line);
68
- }
69
- });
70
- sticker.render();
71
- return;
72
- }
73
- lines.forEach((line) => {
74
- if (line.trim()) {
75
- console.log(line);
76
- }
77
- });
78
- }
79
- #logAssetsDevServerMessage(data) {
80
- const dataString = data.toString();
81
- const lines = dataString.split('\n');
82
- lines.forEach((line) => {
83
- if (line.trim()) {
84
- console.log(line);
85
- }
86
- });
87
- }
88
- async #getPort() {
89
- if (process.env.PORT) {
90
- return getPort({ port: Number(process.env.PORT) });
91
- }
92
- const files = await new EnvLoader(this.#cwd).load();
93
- for (let file of files) {
94
- const envVariables = new EnvParser(file.contents).parse();
95
- if (envVariables.PORT) {
96
- return getPort({ port: Number(envVariables.PORT) });
97
- }
98
- }
99
- return getPort({ port: 3333 });
100
- }
101
- #startHTTPServer(port, mode) {
102
- this.#httpServerProcess = runNode(this.#cwd, {
103
- script: this.#scriptFile,
104
- env: { PORT: port, ...this.#options.env },
105
- nodeArgs: this.#options.nodeArgs,
106
- scriptArgs: this.#options.scriptArgs,
107
- });
108
- this.#httpServerProcess.on('message', (message) => {
109
- if (this.#isAdonisJSReadyMessage(message)) {
110
- ui.sticker()
111
- .useColors(this.#colors)
112
- .useRenderer(this.#logger.getRenderer())
113
- .add(`Server address: ${this.#colors.cyan(`http://${message.host}:${message.port}`)}`)
114
- .add(`File system watcher: ${this.#colors.cyan(`${this.#isWatching ? 'enabled' : 'disabled'}`)}`)
115
- .render();
116
- }
117
- });
118
- this.#httpServerProcess
119
- .then((result) => {
120
- this.#logger.warning(`underlying HTTP server closed with status code "${result.exitCode}"`);
121
- if (mode === 'nonblocking') {
122
- this.#onClose?.(result.exitCode);
123
- this.#watcher?.close();
124
- }
125
- })
126
- .catch((error) => {
127
- this.#logger.warning('unable to connect to underlying HTTP server process');
128
- this.#logger.fatal(error);
129
- this.#onError?.(error);
130
- this.#watcher?.close();
131
- });
132
- }
133
- #startAssetsServer() {
134
- const assetsBundler = this.#options.assets;
135
- if (!assetsBundler?.serve) {
136
- return;
137
- }
138
- this.#logger.info(`starting "${assetsBundler.driver}" dev server...`);
139
- this.#assetsServerProcess = run(this.#cwd, {
140
- script: assetsBundler.cmd,
141
- stdio: 'pipe',
142
- scriptArgs: this.#options.scriptArgs,
143
- });
144
- this.#assetsServerProcess.stdout?.on('data', (data) => {
145
- if (assetsBundler.driver === 'vite') {
146
- this.#logViteDevServerMessage(data);
147
- }
148
- else {
149
- this.#logAssetsDevServerMessage(data);
150
- }
151
- });
152
- this.#assetsServerProcess.stderr?.on('data', (data) => {
153
- if (assetsBundler.driver === 'vite') {
154
- this.#logViteDevServerMessage(data);
155
- }
156
- else {
157
- this.#logAssetsDevServerMessage(data);
158
- }
159
- });
160
- this.#assetsServerProcess
161
- .then((result) => {
162
- this.#logger.warning(`"${assetsBundler.driver}" dev server closed with status code "${result.exitCode}"`);
163
- })
164
- .catch((error) => {
165
- this.#logger.warning(`unable to connect to "${assetsBundler.driver}" dev server`);
166
- this.#logger.fatal(error);
167
- });
168
- }
169
- #restart(port) {
170
- if (this.#httpServerProcess) {
171
- this.#httpServerProcess.removeAllListeners();
172
- this.#httpServerProcess.kill('SIGKILL');
173
- }
174
- this.#startHTTPServer(port, 'blocking');
175
- }
176
- setLogger(logger) {
177
- this.#logger = logger;
178
- return this;
179
- }
180
- onClose(callback) {
181
- this.#onClose = callback;
182
- return this;
183
- }
184
- onError(callback) {
185
- this.#onError = callback;
186
- return this;
187
- }
188
- async start() {
189
- this.#clearScreen();
190
- this.#logger.info('starting HTTP server...');
191
- this.#startHTTPServer(String(await this.#getPort()), 'nonblocking');
192
- this.#startAssetsServer();
193
- }
194
- async startAndWatch(ts, options) {
195
- const port = String(await this.#getPort());
196
- this.#isWatching = true;
197
- this.#clearScreen();
198
- this.#logger.info('starting HTTP server...');
199
- this.#startHTTPServer(port, 'blocking');
200
- this.#startAssetsServer();
201
- const output = watch(this.#cwd, ts, options || {});
202
- if (!output) {
203
- this.#onClose?.(1);
204
- return;
205
- }
206
- this.#watcher = output.chokidar;
207
- output.watcher.on('watcher:ready', () => {
208
- this.#logger.info('watching file system for changes...');
209
- });
210
- output.chokidar.on('error', (error) => {
211
- this.#logger.warning('file system watcher failure');
212
- this.#logger.fatal(error);
213
- this.#onError?.(error);
214
- output.chokidar.close();
215
- });
216
- output.watcher.on('source:add', ({ relativePath }) => {
217
- this.#clearScreen();
218
- this.#logger.log(`${this.#colors.green('add')} ${relativePath}`);
219
- this.#restart(port);
220
- });
221
- output.watcher.on('source:change', ({ relativePath }) => {
222
- this.#clearScreen();
223
- this.#logger.log(`${this.#colors.green('update')} ${relativePath}`);
224
- this.#restart(port);
225
- });
226
- output.watcher.on('source:unlink', ({ relativePath }) => {
227
- this.#clearScreen();
228
- this.#logger.log(`${this.#colors.green('delete')} ${relativePath}`);
229
- this.#restart(port);
230
- });
231
- output.watcher.on('add', ({ relativePath }) => {
232
- if (this.#isDotEnvFile(relativePath) || this.#isRcFile(relativePath)) {
233
- this.#clearScreen();
234
- this.#logger.log(`${this.#colors.green('add')} ${relativePath}`);
235
- this.#restart(port);
236
- return;
237
- }
238
- if (this.#isMetaFileWithReloadsEnabled(relativePath)) {
239
- this.#clearScreen();
240
- this.#logger.log(`${this.#colors.green('add')} ${relativePath}`);
241
- this.#restart(port);
242
- return;
243
- }
244
- if (this.#isMetaFileWithReloadsDisabled(relativePath)) {
245
- this.#clearScreen();
246
- this.#logger.log(`${this.#colors.green('add')} ${relativePath}`);
247
- }
248
- });
249
- output.watcher.on('change', ({ relativePath }) => {
250
- if (this.#isDotEnvFile(relativePath) || this.#isRcFile(relativePath)) {
251
- this.#clearScreen();
252
- this.#logger.log(`${this.#colors.green('update')} ${relativePath}`);
253
- this.#restart(port);
254
- return;
255
- }
256
- if (this.#isMetaFileWithReloadsEnabled(relativePath)) {
257
- this.#clearScreen();
258
- this.#logger.log(`${this.#colors.green('update')} ${relativePath}`);
259
- this.#restart(port);
260
- return;
261
- }
262
- if (this.#isMetaFileWithReloadsDisabled(relativePath)) {
263
- this.#clearScreen();
264
- this.#logger.log(`${this.#colors.green('update')} ${relativePath}`);
265
- }
266
- });
267
- output.watcher.on('unlink', ({ relativePath }) => {
268
- if (this.#isDotEnvFile(relativePath) || this.#isRcFile(relativePath)) {
269
- this.#clearScreen();
270
- this.#logger.log(`${this.#colors.green('delete')} ${relativePath}`);
271
- this.#restart(port);
272
- return;
273
- }
274
- if (this.#isMetaFileWithReloadsEnabled(relativePath)) {
275
- this.#clearScreen();
276
- this.#logger.log(`${this.#colors.green('delete')} ${relativePath}`);
277
- this.#restart(port);
278
- return;
279
- }
280
- if (this.#isMetaFileWithReloadsDisabled(relativePath)) {
281
- this.#clearScreen();
282
- this.#logger.log(`${this.#colors.green('delete')} ${relativePath}`);
283
- }
284
- });
285
- }
286
- }
@@ -1,3 +0,0 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- import type tsStatic from 'typescript';
3
- export declare function parseConfig(cwd: string | URL, ts: typeof tsStatic): tsStatic.ParsedCommandLine | undefined;
@@ -1,15 +0,0 @@
1
- import { ConfigParser } from '@poppinss/chokidar-ts';
2
- export function parseConfig(cwd, ts) {
3
- const { config, error } = new ConfigParser(cwd, 'tsconfig.json', ts).parse();
4
- if (error) {
5
- const compilerHost = ts.createCompilerHost({});
6
- console.log(ts.formatDiagnosticsWithColorAndContext([error], compilerHost));
7
- return;
8
- }
9
- if (config.errors.length) {
10
- const compilerHost = ts.createCompilerHost({});
11
- console.log(ts.formatDiagnosticsWithColorAndContext(config.errors, compilerHost));
12
- return;
13
- }
14
- return config;
15
- }
@@ -1,4 +0,0 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- import type { RunOptions } from './types.js';
3
- export declare function runNode(cwd: string | URL, options: RunOptions): import("execa").ExecaChildProcess<string>;
4
- export declare function run(cwd: string | URL, options: Omit<RunOptions, 'nodeArgs'>): import("execa").ExecaChildProcess<string>;
package/build/src/run.js DELETED
@@ -1,37 +0,0 @@
1
- import { execaNode, execa } from 'execa';
2
- const DEFAULT_NODE_ARGS = [
3
- '--loader=ts-node/esm',
4
- '--no-warnings',
5
- '--experimental-import-meta-resolve',
6
- ];
7
- export function runNode(cwd, options) {
8
- const childProcess = execaNode(options.script, options.scriptArgs, {
9
- nodeOptions: DEFAULT_NODE_ARGS.concat(options.nodeArgs),
10
- preferLocal: true,
11
- windowsHide: false,
12
- localDir: cwd,
13
- cwd,
14
- buffer: false,
15
- stdio: options.stdio || 'inherit',
16
- env: {
17
- ...(options.stdio === 'pipe' ? { FORCE_COLOR: 'true' } : {}),
18
- ...options.env,
19
- },
20
- });
21
- return childProcess;
22
- }
23
- export function run(cwd, options) {
24
- const childProcess = execa(options.script, options.scriptArgs, {
25
- preferLocal: true,
26
- windowsHide: false,
27
- localDir: cwd,
28
- cwd,
29
- buffer: false,
30
- stdio: options.stdio || 'inherit',
31
- env: {
32
- ...(options.stdio === 'pipe' ? { FORCE_COLOR: 'true' } : {}),
33
- ...options.env,
34
- },
35
- });
36
- return childProcess;
37
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,8 +0,0 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- import type tsStatic from 'typescript';
3
- import { Watcher } from '@poppinss/chokidar-ts';
4
- import type { WatchOptions } from './types.js';
5
- export declare function watch(cwd: string | URL, ts: typeof tsStatic, options: WatchOptions): {
6
- watcher: Watcher;
7
- chokidar: import("chokidar").FSWatcher;
8
- } | undefined;
@@ -1,12 +0,0 @@
1
- import { fileURLToPath } from 'node:url';
2
- import { Watcher } from '@poppinss/chokidar-ts';
3
- import { parseConfig } from './parse_config.js';
4
- export function watch(cwd, ts, options) {
5
- const config = parseConfig(cwd, ts);
6
- if (!config) {
7
- return;
8
- }
9
- const watcher = new Watcher(typeof cwd === 'string' ? cwd : fileURLToPath(cwd), config);
10
- const chokidar = watcher.watch(['.'], { usePolling: options.poll });
11
- return { watcher, chokidar };
12
- }