@adonisjs/assembler 6.1.3-3 → 6.1.3-5

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/src/helpers.ts ADDED
@@ -0,0 +1,162 @@
1
+ /*
2
+ * @adonisjs/assembler
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+
10
+ import getRandomPort from 'get-port'
11
+ import type tsStatic from 'typescript'
12
+ import { fileURLToPath } from 'node:url'
13
+ import { execaNode, execa } from 'execa'
14
+ import { EnvLoader, EnvParser } from '@adonisjs/env'
15
+ import { ConfigParser, Watcher } from '@poppinss/chokidar-ts'
16
+
17
+ import type { RunOptions, WatchOptions } from './types.js'
18
+
19
+ /**
20
+ * Default set of args to pass in order to run TypeScript
21
+ * source. Used by "run" and "runNode" scripts
22
+ */
23
+ const DEFAULT_NODE_ARGS = [
24
+ // Use ts-node/esm loader. The project must install it
25
+ '--loader=ts-node/esm',
26
+ // Disable annonying warnings
27
+ '--no-warnings',
28
+ // Enable expiremental meta resolve for cases where someone uses magic import string
29
+ '--experimental-import-meta-resolve',
30
+ ]
31
+
32
+ /**
33
+ * Parses tsconfig.json and prints errors using typescript compiler
34
+ * host
35
+ */
36
+ export function parseConfig(cwd: string | URL, ts: typeof tsStatic) {
37
+ const { config, error } = new ConfigParser(cwd, 'tsconfig.json', ts).parse()
38
+ if (error) {
39
+ const compilerHost = ts.createCompilerHost({})
40
+ console.log(ts.formatDiagnosticsWithColorAndContext([error], compilerHost))
41
+ return
42
+ }
43
+
44
+ if (config!.errors.length) {
45
+ const compilerHost = ts.createCompilerHost({})
46
+ console.log(ts.formatDiagnosticsWithColorAndContext(config!.errors, compilerHost))
47
+ return
48
+ }
49
+
50
+ return config
51
+ }
52
+
53
+ /**
54
+ * Runs a Node.js script as a child process and inherits the stdio streams
55
+ */
56
+ export function runNode(cwd: string | URL, options: RunOptions) {
57
+ const childProcess = execaNode(options.script, options.scriptArgs, {
58
+ nodeOptions: DEFAULT_NODE_ARGS.concat(options.nodeArgs),
59
+ preferLocal: true,
60
+ windowsHide: false,
61
+ localDir: cwd,
62
+ cwd,
63
+ buffer: false,
64
+ stdio: options.stdio || 'inherit',
65
+ env: {
66
+ ...(options.stdio === 'pipe' ? { FORCE_COLOR: 'true' } : {}),
67
+ ...options.env,
68
+ },
69
+ })
70
+
71
+ return childProcess
72
+ }
73
+
74
+ /**
75
+ * Runs a script as a child process and inherits the stdio streams
76
+ */
77
+ export function run(cwd: string | URL, options: Omit<RunOptions, 'nodeArgs'>) {
78
+ const childProcess = execa(options.script, options.scriptArgs, {
79
+ preferLocal: true,
80
+ windowsHide: false,
81
+ localDir: cwd,
82
+ cwd,
83
+ buffer: false,
84
+ stdio: options.stdio || 'inherit',
85
+ env: {
86
+ ...(options.stdio === 'pipe' ? { FORCE_COLOR: 'true' } : {}),
87
+ ...options.env,
88
+ },
89
+ })
90
+
91
+ return childProcess
92
+ }
93
+
94
+ /**
95
+ * Watches the file system using tsconfig file
96
+ */
97
+ export function watch(cwd: string | URL, ts: typeof tsStatic, options: WatchOptions) {
98
+ const config = parseConfig(cwd, ts)
99
+ if (!config) {
100
+ return
101
+ }
102
+
103
+ const watcher = new Watcher(typeof cwd === 'string' ? cwd : fileURLToPath(cwd), config!)
104
+ const chokidar = watcher.watch(['.'], { usePolling: options.poll })
105
+ return { watcher, chokidar }
106
+ }
107
+
108
+ /**
109
+ * Check if file is an .env file
110
+ */
111
+ export function isDotEnvFile(filePath: string) {
112
+ if (filePath === '.env') {
113
+ return true
114
+ }
115
+
116
+ return filePath.includes('.env.')
117
+ }
118
+
119
+ /**
120
+ * Check if file is .adonisrc.json file
121
+ */
122
+ export function isRcFile(filePath: string) {
123
+ return filePath === '.adonisrc.json'
124
+ }
125
+
126
+ /**
127
+ * Returns the port to use after inspect the dot-env files inside
128
+ * a given directory.
129
+ *
130
+ * A random port is used when the specified port is in use. Following
131
+ * is the logic for finding a specified port.
132
+ *
133
+ * - The "process.env.PORT" value is used if exists.
134
+ * - The dot-env files are loaded using the "EnvLoader" and the PORT
135
+ * value is by iterating over all the loaded files. The iteration
136
+ * stops after first find.
137
+ */
138
+ export async function getPort(cwd: URL): Promise<number> {
139
+ /**
140
+ * Use existing port if exists
141
+ */
142
+ if (process.env.PORT) {
143
+ return getRandomPort({ port: Number(process.env.PORT) })
144
+ }
145
+
146
+ /**
147
+ * Loop over files and use the port from their contents. Stops
148
+ * after first match
149
+ */
150
+ const files = await new EnvLoader(cwd).load()
151
+ for (let file of files) {
152
+ const envVariables = new EnvParser(file.contents).parse()
153
+ if (envVariables.PORT) {
154
+ return getRandomPort({ port: Number(envVariables.PORT) })
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Use 3333 as the port
160
+ */
161
+ return getRandomPort({ port: 3333 })
162
+ }
@@ -0,0 +1,338 @@
1
+ /*
2
+ * @adonisjs/assembler
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+
10
+ import picomatch from 'picomatch'
11
+ import type tsStatic from 'typescript'
12
+ import { type ExecaChildProcess } from 'execa'
13
+ import { cliui, type Logger } from '@poppinss/cliui'
14
+ import type { Watcher } from '@poppinss/chokidar-ts'
15
+
16
+ import type { TestRunnerOptions } from './types.js'
17
+ import { AssetsDevServer } from './assets_dev_server.js'
18
+ import { getPort, isDotEnvFile, runNode, watch } from './helpers.js'
19
+
20
+ /**
21
+ * Instance of CLIUI
22
+ */
23
+ const ui = cliui()
24
+
25
+ /**
26
+ * Exposes the API to start the development. Optionally, the watch API can be
27
+ * used to watch for file changes and restart the development server.
28
+ *
29
+ * The Dev server performs the following actions
30
+ *
31
+ * - Assigns a random PORT, when PORT inside .env file is in use
32
+ * - Uses tsconfig.json file to collect a list of files to watch.
33
+ * - Uses metaFiles from .adonisrc.json file to collect a list of files to watch.
34
+ * - Restart HTTP server on every file change.
35
+ */
36
+ export class TestRunner {
37
+ #cwd: URL
38
+ #logger = ui.logger
39
+ #options: TestRunnerOptions
40
+ #scriptFile: string = 'bin/test.js'
41
+ #isMetaFile: picomatch.Matcher
42
+ #isTestFile: picomatch.Matcher
43
+
44
+ /**
45
+ * In watch mode, after a file is changed, we wait for the current
46
+ * set of tests to finish before triggering a re-run. Therefore,
47
+ * we use this flag to know if we are already busy in running
48
+ * tests and ignore file-changes.
49
+ */
50
+ #isBusy: boolean = false
51
+
52
+ #onError?: (error: any) => any
53
+ #onClose?: (exitCode: number) => any
54
+
55
+ #testScript?: ExecaChildProcess<string>
56
+ #watcher?: ReturnType<Watcher['watch']>
57
+ #assetsServer?: AssetsDevServer
58
+
59
+ /**
60
+ * Getting reference to colors library from logger
61
+ */
62
+ get #colors() {
63
+ return this.#logger.getColors()
64
+ }
65
+
66
+ constructor(cwd: URL, options: TestRunnerOptions) {
67
+ this.#cwd = cwd
68
+ this.#options = options
69
+ this.#isMetaFile = picomatch((this.#options.metaFiles || []).map(({ pattern }) => pattern))
70
+ this.#isTestFile = picomatch(
71
+ this.#options.suites
72
+ .filter((suite) => {
73
+ if (this.#options.filters.suites) {
74
+ this.#options.filters.suites.includes(suite.name)
75
+ }
76
+
77
+ return true
78
+ })
79
+ .map((suite) => suite.files)
80
+ .flat(1)
81
+ )
82
+ }
83
+
84
+ /**
85
+ * Converts all known filters to CLI args.
86
+ *
87
+ * The following code snippet may seem like repetitive code. But, it
88
+ * is done intentionally to have visibility around how each filter
89
+ * is converted to an arg.
90
+ */
91
+ #convertFiltersToArgs(filters: TestRunnerOptions['filters']): string[] {
92
+ const args: string[] = []
93
+
94
+ if (filters.suites) {
95
+ args.push(...filters.suites)
96
+ }
97
+
98
+ if (filters.files) {
99
+ args.push('--files')
100
+ args.push(filters.files.join(','))
101
+ }
102
+
103
+ if (filters.groups) {
104
+ args.push('--groups')
105
+ args.push(filters.groups.join(','))
106
+ }
107
+
108
+ if (filters.tags) {
109
+ args.push('--tags')
110
+ args.push(filters.tags.join(','))
111
+ }
112
+
113
+ if (filters.ignoreTags) {
114
+ args.push('--ignore-tags')
115
+ args.push(filters.ignoreTags.join(','))
116
+ }
117
+
118
+ if (filters.tests) {
119
+ args.push('--ignore-tests')
120
+ args.push(filters.tests.join(','))
121
+ }
122
+
123
+ if (filters.match) {
124
+ args.push('--match')
125
+ args.push(filters.match.join(','))
126
+ }
127
+
128
+ return args
129
+ }
130
+
131
+ /**
132
+ * Conditionally clear the terminal screen
133
+ */
134
+ #clearScreen() {
135
+ if (this.#options.clearScreen) {
136
+ process.stdout.write('\u001Bc')
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Runs tests
142
+ */
143
+ #runTests(port: string, filtersArgs: string[], mode: 'blocking' | 'nonblocking') {
144
+ this.#isBusy = true
145
+
146
+ this.#testScript = runNode(this.#cwd, {
147
+ script: this.#scriptFile,
148
+ env: { PORT: port, ...this.#options.env },
149
+ nodeArgs: this.#options.nodeArgs,
150
+ scriptArgs: filtersArgs.concat(this.#options.scriptArgs),
151
+ })
152
+
153
+ this.#testScript
154
+ .then((result) => {
155
+ if (mode === 'nonblocking') {
156
+ this.#onClose?.(result.exitCode)
157
+ this.#watcher?.close()
158
+ this.#assetsServer?.stop()
159
+ }
160
+ })
161
+ .catch((error) => {
162
+ this.#logger.warning(`unable to run test script "${this.#scriptFile}"`)
163
+ this.#logger.fatal(error)
164
+ this.#onError?.(error)
165
+ this.#watcher?.close()
166
+ this.#assetsServer?.stop()
167
+ })
168
+ .finally(() => {
169
+ this.#isBusy = false
170
+ })
171
+ }
172
+
173
+ /**
174
+ * Starts the assets server
175
+ */
176
+ #startAssetsServer() {
177
+ this.#assetsServer = new AssetsDevServer(this.#cwd, this.#options.assets)
178
+ this.#assetsServer.start()
179
+ }
180
+
181
+ /**
182
+ * Handles a non TypeScript file change
183
+ */
184
+ #handleFileChange(action: string, port: string, filters: string[], relativePath: string) {
185
+ if (this.#isBusy) {
186
+ return
187
+ }
188
+
189
+ if (isDotEnvFile(relativePath) || this.#isMetaFile(relativePath)) {
190
+ this.#clearScreen()
191
+ this.#logger.log(`${this.#colors.green(action)} ${relativePath}`)
192
+ this.#runTests(port, filters, 'blocking')
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Handles TypeScript source file change
198
+ */
199
+ #handleSourceFileChange(action: string, port: string, filters: string[], relativePath: string) {
200
+ if (this.#isBusy) {
201
+ return
202
+ }
203
+
204
+ this.#clearScreen()
205
+ this.#logger.log(`${this.#colors.green(action)} ${relativePath}`)
206
+
207
+ /**
208
+ * If changed file is a test file after considering the initial filters,
209
+ * then only run that file
210
+ */
211
+ if (this.#isTestFile(relativePath)) {
212
+ this.#runTests(
213
+ port,
214
+ this.#convertFiltersToArgs({
215
+ ...this.#options.filters,
216
+ files: [relativePath],
217
+ }),
218
+ 'blocking'
219
+ )
220
+ return
221
+ }
222
+
223
+ this.#runTests(port, filters, 'blocking')
224
+ }
225
+
226
+ /**
227
+ * Set a custom CLI UI logger
228
+ */
229
+ setLogger(logger: Logger) {
230
+ this.#logger = logger
231
+ this.#assetsServer?.setLogger(logger)
232
+ return this
233
+ }
234
+
235
+ /**
236
+ * Add listener to get notified when dev server is
237
+ * closed
238
+ */
239
+ onClose(callback: (exitCode: number) => any): this {
240
+ this.#onClose = callback
241
+ return this
242
+ }
243
+
244
+ /**
245
+ * Add listener to get notified when dev server exists
246
+ * with an error
247
+ */
248
+ onError(callback: (error: any) => any): this {
249
+ this.#onError = callback
250
+ return this
251
+ }
252
+
253
+ /**
254
+ * Runs tests
255
+ */
256
+ async run() {
257
+ const port = String(await getPort(this.#cwd))
258
+ const initialFilters = this.#convertFiltersToArgs(this.#options.filters)
259
+
260
+ this.#clearScreen()
261
+ this.#startAssetsServer()
262
+
263
+ this.#logger.info('booting application to run tests...')
264
+ this.#runTests(port, initialFilters, 'nonblocking')
265
+ }
266
+
267
+ /**
268
+ * Run tests in watch mode
269
+ */
270
+ async runAndWatch(ts: typeof tsStatic, options?: { poll: boolean }) {
271
+ const port = String(await getPort(this.#cwd))
272
+ const initialFilters = this.#convertFiltersToArgs(this.#options.filters)
273
+
274
+ this.#clearScreen()
275
+ this.#startAssetsServer()
276
+
277
+ this.#logger.info('booting application to run tests...')
278
+ this.#runTests(port, initialFilters, 'blocking')
279
+
280
+ /**
281
+ * Create watcher using tsconfig.json file
282
+ */
283
+ const output = watch(this.#cwd, ts, options || {})
284
+ if (!output) {
285
+ this.#onClose?.(1)
286
+ return
287
+ }
288
+
289
+ /**
290
+ * Storing reference to watcher, so that we can close it
291
+ * when HTTP server exists with error
292
+ */
293
+ this.#watcher = output.chokidar
294
+
295
+ /**
296
+ * Notify the watcher is ready
297
+ */
298
+ output.watcher.on('watcher:ready', () => {
299
+ this.#logger.info('watching file system for changes...')
300
+ })
301
+
302
+ /**
303
+ * Cleanup when watcher dies
304
+ */
305
+ output.chokidar.on('error', (error) => {
306
+ this.#logger.warning('file system watcher failure')
307
+ this.#logger.fatal(error)
308
+ this.#onError?.(error)
309
+ output.chokidar.close()
310
+ })
311
+
312
+ /**
313
+ * Changes in TypeScript source file
314
+ */
315
+ output.watcher.on('source:add', ({ relativePath }) =>
316
+ this.#handleSourceFileChange('add', port, initialFilters, relativePath)
317
+ )
318
+ output.watcher.on('source:change', ({ relativePath }) =>
319
+ this.#handleSourceFileChange('update', port, initialFilters, relativePath)
320
+ )
321
+ output.watcher.on('source:unlink', ({ relativePath }) =>
322
+ this.#handleSourceFileChange('delete', port, initialFilters, relativePath)
323
+ )
324
+
325
+ /**
326
+ * Changes in non-TypeScript source files
327
+ */
328
+ output.watcher.on('add', ({ relativePath }) =>
329
+ this.#handleFileChange('add', port, initialFilters, relativePath)
330
+ )
331
+ output.watcher.on('change', ({ relativePath }) =>
332
+ this.#handleFileChange('update', port, initialFilters, relativePath)
333
+ )
334
+ output.watcher.on('unlink', ({ relativePath }) =>
335
+ this.#handleFileChange('delete', port, initialFilters, relativePath)
336
+ )
337
+ }
338
+ }
package/src/types.ts ADDED
@@ -0,0 +1,110 @@
1
+ /*
2
+ * @adonisjs/assembler
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+
10
+ /**
11
+ * Options needed to run a script file
12
+ */
13
+ export type RunOptions = {
14
+ script: string
15
+ scriptArgs: string[]
16
+ nodeArgs: string[]
17
+ stdio?: 'pipe' | 'inherit'
18
+ env?: NodeJS.ProcessEnv
19
+ }
20
+
21
+ /**
22
+ * Watcher options
23
+ */
24
+ export type WatchOptions = {
25
+ poll?: boolean
26
+ }
27
+
28
+ /**
29
+ * Meta file config defined in ".adonisrc.json" file
30
+ */
31
+ export type MetaFile = {
32
+ pattern: string
33
+ reloadServer: boolean
34
+ }
35
+
36
+ /**
37
+ * Test suite defined in ".adonisrc.json" file
38
+ */
39
+ export type Suite = {
40
+ files: string[]
41
+ name: string
42
+ }
43
+
44
+ /**
45
+ * Options accepted by assets bundler
46
+ */
47
+ export type AssetsBundlerOptions =
48
+ | {
49
+ serve: false
50
+ args?: string[]
51
+ driver?: string
52
+ cmd?: string
53
+ }
54
+ | {
55
+ serve: true
56
+ args: string[]
57
+ driver: string
58
+ cmd: string
59
+ }
60
+
61
+ /**
62
+ * Options accepted by the dev server
63
+ */
64
+ export type DevServerOptions = {
65
+ scriptArgs: string[]
66
+ nodeArgs: string[]
67
+ clearScreen?: boolean
68
+ env?: NodeJS.ProcessEnv
69
+ metaFiles?: MetaFile[]
70
+ assets?: AssetsBundlerOptions
71
+ }
72
+
73
+ /**
74
+ * Options accepted by the test runner
75
+ */
76
+ export type TestRunnerOptions = {
77
+ /**
78
+ * Filter arguments are provided as a key-value
79
+ * pair, so that we can mutate them (if needed)
80
+ */
81
+ filters: Partial<{
82
+ tests: string[]
83
+ suites: string[]
84
+ groups: string[]
85
+ files: string[]
86
+ match: string[]
87
+ tags: string[]
88
+ ignoreTags: string[]
89
+ }>
90
+
91
+ /**
92
+ * All other tags are provided as a collection of
93
+ * arguments
94
+ */
95
+ scriptArgs: string[]
96
+ nodeArgs: string[]
97
+ clearScreen?: boolean
98
+ env?: NodeJS.ProcessEnv
99
+ metaFiles?: MetaFile[]
100
+ assets?: AssetsBundlerOptions
101
+ suites: Suite[]
102
+ }
103
+
104
+ /**
105
+ * Options accepted by the project bundler
106
+ */
107
+ export type BundlerOptions = {
108
+ metaFiles?: MetaFile[]
109
+ assets?: AssetsBundlerOptions
110
+ }
@@ -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,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
- }