UNPKG

12.4 kBTypeScriptView Raw
1/// <reference types="node" resolution-mode="require"/>
2import { EventEmitter } from 'node:events';
3import { type Store } from 'mem-fs';
4import type { BaseEnvironmentOptions, BaseGenerator, GetGeneratorConstructor, GetGeneratorOptions, PromptAnswers, LookupOptions } from '@yeoman/types';
5import { type MemFsEditorFile, type MemFsEditor } from 'mem-fs-editor';
6import type { DefaultGeneratorApi, DefaultEnvironmentApi } from '../types/type-helpers.js';
7import RunResult, { type RunResultOptions } from './run-result.js';
8import { type CreateEnv, type Dependency, type YeomanTest } from './helpers.js';
9import { type AskedQuestions, type DummyPromptOptions, type TestAdapterOptions } from './adapter.js';
10/**
11 * Provides settings for creating a `RunContext`.
12 */
13export type RunContextSettings = {
14 /**
15 * Automatically run this generator in a tmp dir
16 * @default true
17 */
18 tmpdir?: boolean;
19 cwd?: string;
20 oldCwd?: string;
21 forwardCwd?: boolean;
22 autoCleanup?: boolean;
23 memFs?: Store<MemFsEditorFile>;
24 /**
25 * File path to the generator (only used if Generator is a constructor)
26 */
27 resolved?: string;
28 /**
29 * Namespace (only used if Generator is a constructor)
30 * @default 'gen:test'
31 */
32 namespace?: string;
33};
34type PromiseRunResult<GeneratorType extends BaseGenerator> = Promise<RunResult<GeneratorType>>;
35type MockedGeneratorFactory<GenParameter extends BaseGenerator = DefaultGeneratorApi> = (GeneratorClass?: GetGeneratorConstructor<GenParameter>) => GetGeneratorConstructor<GenParameter>;
36type EnvOptions = BaseEnvironmentOptions & {
37 createEnv?: CreateEnv;
38};
39export declare class RunContextBase<GeneratorType extends BaseGenerator = DefaultGeneratorApi> extends EventEmitter {
40 readonly mockedGenerators: Record<string, BaseGenerator>;
41 env: DefaultEnvironmentApi;
42 generator: GeneratorType;
43 readonly settings: RunContextSettings;
44 readonly envOptions: EnvOptions;
45 completed: boolean;
46 targetDirectory?: string;
47 editor: MemFsEditor;
48 memFs: Store<MemFsEditorFile>;
49 spawnStub?: any;
50 mockedGeneratorFactory: MockedGeneratorFactory;
51 readonly askedQuestions: AskedQuestions;
52 protected environmentPromise?: PromiseRunResult<GeneratorType>;
53 private args;
54 private options;
55 private answers?;
56 private readonly adapterOptions?;
57 private keepFsState?;
58 private readonly onGeneratorCallbacks;
59 private readonly onTargetDirectoryCallbacks;
60 private readonly onEnvironmentCallbacks;
61 private readonly inDirCallbacks;
62 private readonly Generator?;
63 private readonly helpers;
64 private readonly temporaryDir;
65 private oldCwd?;
66 private eventListenersSet;
67 private envCB;
68 private built;
69 private ran;
70 private errored;
71 private readonly beforePrepareCallbacks;
72 /**
73 * This class provide a run context object to façade the complexity involved in setting
74 * up a generator for testing
75 * @constructor
76 * @param Generator - Namespace or generator constructor. If the later
77 * is provided, then namespace is assumed to be
78 * 'gen:test' in all cases
79 * @param settings
80 * @return {this}
81 */
82 constructor(generatorType?: string | GetGeneratorConstructor<GeneratorType>, settings?: RunContextSettings, envOptions?: EnvOptions, helpers?: YeomanTest);
83 /**
84 * Run the generator on the environment and promises a RunResult instance.
85 * @return {PromiseRunResult} Promise a RunResult instance.
86 */
87 run(): PromiseRunResult<GeneratorType>;
88 on(eventName: string | symbol, listener: (...args: any[]) => void): this;
89 /**
90 * @deprecated
91 * Clean the provided directory, then change directory into it
92 * @param dirPath - Directory path (relative to CWD). Prefer passing an absolute
93 * file path for predictable results
94 * @param [cb] - callback who'll receive the folder path as argument
95 * @return run context instance
96 */
97 inDir(dirPath: string, cb?: (folderPath: string) => void): this;
98 /**
99 * Register an callback to prepare the destination folder.
100 * @param [cb] - callback who'll receive the folder path as argument
101 * @return this - run context instance
102 */
103 doInDir(cb: (folderPath: string) => void): this;
104 /**
105 * @deprecated
106 * Change directory without deleting directory content.
107 * @param dirPath - Directory path (relative to CWD). Prefer passing an absolute
108 * file path for predictable results
109 * @return run context instance
110 */
111 cd(dirPath: string): this;
112 /**
113 * Cleanup a temporary directory and change the CWD into it
114 *
115 * This method is called automatically when creating a RunContext. Only use it if you need
116 * to use the callback.
117 *
118 * @param [cb] - callback who'll receive the folder path as argument
119 * @return this - run context instance
120 */
121 inTmpDir(cb?: (folderPath: string) => void): this;
122 /**
123 * Restore cwd to initial cwd.
124 * @return {this} run context instance
125 */
126 restore(): this;
127 /**
128 * Clean the directory used for tests inside inDir/inTmpDir
129 * @param {Boolean} force - force directory cleanup for not tmpdir
130 */
131 cleanup(): void;
132 /**
133 * Clean the directory used for tests inside inDir/inTmpDir
134 * @param {Boolean} force - force directory cleanup for not tmpdir
135 */
136 cleanupTemporaryDir(): void;
137 /**
138 * Clean the directory used for tests inside inDir/inTmpDir
139 * @param force - force directory cleanup for not tmpdir
140 */
141 cleanTestDirectory(force?: boolean): void;
142 /**
143 * TestAdapter options.
144 */
145 withAdapterOptions(options: Omit<TestAdapterOptions, 'mockedAnswers'>): this;
146 /**
147 * Create an environment
148 *
149 * This method is called automatically when creating a RunContext. Only use it if you need
150 * to use the callback.
151 *
152 * @param {Function} [cb] - callback who'll receive the folder path as argument
153 * @return {this} run context instance
154 */
155 withEnvironment(cb: any): this;
156 /**
157 * Run lookup on the environment.
158 *
159 * @param lookups - lookup to run.
160 */
161 withLookups(lookups: LookupOptions | LookupOptions[]): this;
162 /**
163 * Provide arguments to the run context
164 * @param args - command line arguments as Array or space separated string
165 */
166 withArguments(args: string | string[]): this;
167 /**
168 * Provide options to the run context
169 * @param {Object} options - command line options (e.g. `--opt-one=foo`)
170 * @return {this}
171 */
172 withOptions(options: Partial<Omit<GetGeneratorOptions<GeneratorType>, 'env' | 'namespace' | 'resolved'>>): this;
173 /**
174 * @deprecated
175 * Mock the prompt with dummy answers
176 * @param answers - Answers to the prompt questions
177 * @param options - Options or callback.
178 * @param {Function} [options.callback] - Callback.
179 * @param {Boolean} [options.throwOnMissingAnswer] - Throw if a answer is missing.
180 * @return {this}
181 */
182 withPrompts(answers: PromptAnswers, options?: Omit<DummyPromptOptions, 'mockedAnswers'>): this;
183 /**
184 * Mock answers for prompts
185 * @param answers - Answers to the prompt questions
186 * @param options - Options or callback.
187 * @return {this}
188 */
189 withAnswers(answers: PromptAnswers, options?: Omit<DummyPromptOptions, 'mockedAnswers'>): this;
190 /**
191 * Provide dependent generators
192 * @param {Array} dependencies - paths to the generators dependencies
193 * @return {this}
194 * @example
195 * var angular = new RunContext('../../app');
196 * angular.withGenerators([
197 * '../../common',
198 * '../../controller',
199 * '../../main',
200 * [helpers.createDummyGenerator(), 'testacular:app']
201 * ]);
202 * angular.on('end', function () {
203 * // assert something
204 * });
205 */
206 withGenerators(dependencies: Dependency[]): this;
207 withSpawnMock(options?: ((...args: any[]) => any) | {
208 stub?: (...args: any[]) => any;
209 registerSinonDefaults?: boolean;
210 callback?: (stub: any) => void | Promise<void>;
211 }): this;
212 withMockedGeneratorFactory(mockedGeneratorFactory: MockedGeneratorFactory): this;
213 /**
214 * Create mocked generators
215 * @param namespaces - namespaces of mocked generators
216 * @return this
217 * @example
218 * var angular = helpers
219 * .create('../../app')
220 * .withMockedGenerators([
221 * 'foo:app',
222 * 'foo:bar',
223 * ])
224 * .run()
225 * .then(runResult => assert(runResult
226 * .mockedGenerators['foo:app']
227 .calledOnce));
228 */
229 withMockedGenerators(namespaces: string[]): this;
230 /**
231 * Mock the local configuration with the provided config
232 * @param localConfig - should look just like if called config.getAll()
233 */
234 withLocalConfig(localConfig: any): this;
235 /**
236 * Don't reset mem-fs state cleared to aggregate snapshots from multiple runs.
237 */
238 withKeepFsState(): this;
239 /**
240 * Add files to mem-fs.
241 * Files will be resolved relative to targetDir.
242 *
243 * Files with Object content will be merged to existing content.
244 * To avoid merging, `JSON.stringify` the content.
245 */
246 withFiles(files: Record<string, string | Record<string, unknown>>): this;
247 withFiles(relativePath: string, files: Record<string, string | Record<string, unknown>>): this;
248 /**
249 * Add .yo-rc.json to mem-fs.
250 *
251 * @param content
252 * @returns
253 */
254 withYoRc(content: string | Record<string, unknown>): this;
255 /**
256 * Add a generator config to .yo-rc.json
257 */
258 withYoRcConfig(key: string, content: Record<string, unknown>): this;
259 /**
260 * Commit mem-fs files.
261 */
262 commitFiles(): this;
263 /**
264 * Execute callback after targetDirectory is set
265 * @param callback
266 * @returns
267 */
268 onTargetDirectory(callback: (this: this, targetDirectory: string) => any): this;
269 /**
270 * Execute callback after generator is ready
271 * @param callback
272 * @returns
273 */
274 onGenerator(callback: (this: this, generator: GeneratorType) => any): this;
275 /**
276 * Execute callback prefore parepare
277 * @param callback
278 * @returns
279 */
280 onBeforePrepare(callback: (this: this) => void | Promise<void>): this;
281 /**
282 * Execute callback after environment is ready
283 * @param callback
284 * @returns
285 */
286 onEnvironment(callback: (this: this, env: DefaultEnvironmentApi) => any): this;
287 prepare(): Promise<void>;
288 protected assertNotBuild(): void;
289 /**
290 * Build the generator and the environment.
291 * @return {RunContext|false} this
292 */
293 build(): Promise<void>;
294 /**
295 * Return a promise representing the generator run process
296 * @return Promise resolved on end or rejected on error
297 */
298 protected toPromise(): PromiseRunResult<GeneratorType>;
299 protected _createRunResultOptions(): RunResultOptions<GeneratorType>;
300 /**
301 * Keeps compatibility with events
302 */
303 private setupEventListeners;
304 /**
305 * Set the target directory.
306 * @private
307 * @param {String} dirPath - Directory path (relative to CWD). Prefer passing an absolute
308 * file path for predictable results
309 * @return {this} run context instance
310 */
311 private setDir;
312}
313export default class RunContext<GeneratorType extends BaseGenerator = BaseGenerator> extends RunContextBase<GeneratorType> implements Promise<RunResult<GeneratorType>> {
314 then<TResult1 = RunResult<GeneratorType>, TResult2 = never>(onfulfilled?: ((value: RunResult<GeneratorType>) => TResult1 | PromiseLike<TResult1>) | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined): Promise<TResult1 | TResult2>;
315 catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined): Promise<RunResult<GeneratorType> | TResult>;
316 finally(onfinally?: (() => void) | undefined): Promise<RunResult<GeneratorType>>;
317 get [Symbol.toStringTag](): string;
318}
319export declare class BasicRunContext<GeneratorType extends BaseGenerator = BaseGenerator> extends RunContext<GeneratorType> {
320 run(): PromiseRunResult<any>;
321}
322export {};
323
\No newline at end of file