@biorate/hygen 0.2.0 → 0.4.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.
@@ -29,6 +29,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.KeepGoingError = exports.ShowHelpError = exports.engine = void 0;
30
30
  const path_1 = __importDefault(require("path"));
31
31
  const fs_extra_1 = __importDefault(require("fs-extra"));
32
+ const context_1 = __importDefault(require("./context"));
32
33
  const params_1 = __importDefault(require("./params"));
33
34
  const prompt_1 = __importStar(require("./prompt"));
34
35
  const errors_1 = require("./errors");
@@ -40,6 +41,7 @@ const isInteractive = ({ interactive }) => interactive === true
40
41
  : interactive === false
41
42
  ? false
42
43
  : Boolean(process.stdin.isTTY && process.stdout.isTTY);
44
+ const RUN_SCOPE = '*';
43
45
  const engine = async (argv, config) => {
44
46
  const { cwd, templates, logger } = config;
45
47
  let base = Object.assign(await (0, params_1.default)(config, argv), { cwd });
@@ -67,23 +69,72 @@ const engine = async (argv, config) => {
67
69
  logger.log(`Loaded templates: ${templates.replace(`${cwd}/`, '')}`);
68
70
  const nameList = names ?? [undefined];
69
71
  const keepGoing = Boolean(cleanArgv['keep-going']);
72
+ const singleRunAll = nameList.length === 1 && actions.length === 1;
70
73
  const failures = [];
71
74
  const results = [];
72
75
  const statuses = [];
73
76
  const execute = (await Promise.resolve().then(() => __importStar(require('./execute')))).execute;
74
77
  const render = (await Promise.resolve().then(() => __importStar(require('./render')))).render;
75
- for (const name of nameList) {
76
- for (const action of actions) {
77
- const [mainAction, subaction] = action.split(':');
78
- const actionfolder = path_1.default.join(base.templates, generator, mainAction);
79
- const pairLabel = `action '${action}'${name !== undefined ? ` for name '${name}'` : ''}`;
80
- const statusPair = {
81
- action,
82
- ...(name !== undefined ? { name } : {}),
83
- };
84
- const singleRun = nameList.length === 1 && actions.length === 1;
85
- if (!(await fs_extra_1.default.pathExists(actionfolder))) {
86
- const err = new errors_1.ShowHelpError(`I can't find action '${action}' for generator '${generator}'.
78
+ const projectHooks = (0, prompt_1.normalizeProjectHooks)(config.hooks, logger);
79
+ let hookHelpers;
80
+ const getHookHelpers = () => (hookHelpers ?? (hookHelpers = (0, context_1.default)({ _: base._, ...cleanArgv }, config).h));
81
+ const hookCache = new Map();
82
+ const actionStates = new Map();
83
+ const makeCtx = (action, name, subaction, args) => ({
84
+ cwd,
85
+ templates: base.templates,
86
+ generator: generator,
87
+ action,
88
+ ...(subaction !== undefined ? { subaction } : {}),
89
+ ...(name !== undefined ? { name } : {}),
90
+ args,
91
+ get h() {
92
+ return getHookHelpers();
93
+ },
94
+ logger,
95
+ dry: Boolean(base.dry),
96
+ });
97
+ const actionState = (action, subaction) => {
98
+ let state = actionStates.get(action);
99
+ if (!state) {
100
+ state = { started: false, hooks: {}, subaction, results: [] };
101
+ actionStates.set(action, state);
102
+ }
103
+ return state;
104
+ };
105
+ const reportPairError = (error, pair, pairLabel) => {
106
+ if (singleRunAll)
107
+ throw error;
108
+ if (!keepGoing)
109
+ throw new errors_1.ShowHelpError(`${pairLabel} failed: ${error.message}`);
110
+ failures.push({ ...pair, error: error.message });
111
+ statuses.push({ ...pair, status: 'failed' });
112
+ };
113
+ let projectBeforeAllError;
114
+ try {
115
+ await projectHooks.beforeAll?.(makeCtx(RUN_SCOPE, undefined, undefined, { ...cleanArgv }));
116
+ }
117
+ catch (err) {
118
+ projectBeforeAllError = err;
119
+ }
120
+ let pendingError;
121
+ const afterAllErrors = [];
122
+ try {
123
+ for (const name of nameList) {
124
+ for (const action of actions) {
125
+ const [mainAction, subaction] = action.split(':');
126
+ const actionfolder = path_1.default.join(base.templates, generator, mainAction);
127
+ const pairLabel = `action '${action}'${name !== undefined ? ` for name '${name}'` : ''}`;
128
+ const pair = {
129
+ action,
130
+ ...(name !== undefined ? { name } : {}),
131
+ };
132
+ const pairStatus = {
133
+ action,
134
+ ...(name !== undefined ? { name } : {}),
135
+ };
136
+ if (!(await fs_extra_1.default.pathExists(actionfolder))) {
137
+ const err = new errors_1.ShowHelpError(`I can't find action '${action}' for generator '${generator}'.
87
138
 
88
139
  You can try:
89
140
  1. 'hygen init self' to initialize your project, and
@@ -91,55 +142,162 @@ const engine = async (argv, config) => {
91
142
 
92
143
  Check out the quickstart for more: http://www.hygen.io/docs/quick-start
93
144
  `);
94
- if (singleRun)
95
- throw err;
96
- if (!keepGoing)
97
- throw err;
98
- failures.push({
99
- action,
100
- ...(name !== undefined ? { name } : {}),
101
- error: err.message,
102
- });
103
- statuses.push({ ...statusPair, status: 'failed' });
104
- continue;
105
- }
106
- try {
107
- const promptArgs = await (0, prompt_1.default)(config.createPrompter, actionfolder, {
145
+ if (singleRunAll)
146
+ throw err;
147
+ if (!keepGoing)
148
+ throw err;
149
+ failures.push({ ...pair, error: err.message });
150
+ statuses.push({ ...pairStatus, status: 'failed' });
151
+ continue;
152
+ }
153
+ if (projectBeforeAllError) {
154
+ reportPairError(projectBeforeAllError, pair, pairLabel);
155
+ continue;
156
+ }
157
+ const state = actionState(action, subaction);
158
+ if (!state.started) {
159
+ state.started = true;
160
+ try {
161
+ state.hooks = (await (0, prompt_1.resolveActionHooks)(actionfolder, hookCache)).instance;
162
+ await state.hooks.beforeAll?.(makeCtx(action, undefined, subaction, { ...cleanArgv }));
163
+ }
164
+ catch (err) {
165
+ state.beforeAllError = err;
166
+ }
167
+ }
168
+ if (state.beforeAllError) {
169
+ reportPairError(state.beforeAllError, pair, pairLabel);
170
+ continue;
171
+ }
172
+ const hookArgs = {
108
173
  ...(name ? { name } : {}),
109
174
  ...cleanArgv,
110
- });
111
- const args = Object.assign({
112
- templates: base.templates,
113
- actionfolder,
114
- generator,
115
- action,
116
- subaction,
117
- }, { _: base._, ts: base.ts }, cleanArgv, name ? { name } : {}, promptArgs);
118
- const el = await execute(await render(args, config), args, config);
119
- for (const pairResult of el.results) {
120
- results.push({
121
- ...pairResult,
122
- action,
123
- ...(name !== undefined ? { name } : {}),
124
- });
175
+ };
176
+ const pairResults = [];
177
+ const afterErrors = [];
178
+ let pairStatuses = [];
179
+ let pairError;
180
+ for (const run of [
181
+ projectHooks.beforeEach
182
+ ? () => projectHooks.beforeEach(makeCtx(action, name, subaction, hookArgs))
183
+ : undefined,
184
+ state.hooks.beforeEach
185
+ ? () => state.hooks.beforeEach(makeCtx(action, name, subaction, hookArgs))
186
+ : undefined,
187
+ ]) {
188
+ if (!run)
189
+ continue;
190
+ try {
191
+ await run();
192
+ }
193
+ catch (err) {
194
+ pairError = err;
195
+ break;
196
+ }
197
+ }
198
+ if (!pairError) {
199
+ try {
200
+ const promptArgs = await (0, prompt_1.default)(config.createPrompter, actionfolder, hookArgs, {
201
+ h: getHookHelpers,
202
+ cache: hookCache,
203
+ });
204
+ const args = Object.assign({
205
+ templates: base.templates,
206
+ actionfolder,
207
+ generator,
208
+ action,
209
+ subaction,
210
+ }, { _: base._, ts: base.ts }, cleanArgv, name ? { name } : {}, promptArgs);
211
+ const el = await execute(await render(args, config), args, config);
212
+ for (const pairResult of el.results) {
213
+ const annotated = {
214
+ ...pairResult,
215
+ action,
216
+ ...(name !== undefined ? { name } : {}),
217
+ };
218
+ results.push(annotated);
219
+ pairResults.push(annotated);
220
+ }
221
+ pairStatuses = el.statuses;
222
+ }
223
+ catch (err) {
224
+ pairError = err;
225
+ }
125
226
  }
126
- statuses.push(...el.statuses);
227
+ for (const run of [
228
+ state.hooks.afterEach
229
+ ? () => state.hooks.afterEach(makeCtx(action, name, subaction, hookArgs), pairResults)
230
+ : undefined,
231
+ projectHooks.afterEach
232
+ ? () => projectHooks.afterEach(makeCtx(action, name, subaction, hookArgs), pairResults)
233
+ : undefined,
234
+ ]) {
235
+ if (!run)
236
+ continue;
237
+ try {
238
+ await run();
239
+ }
240
+ catch (err) {
241
+ afterErrors.push(err);
242
+ }
243
+ }
244
+ state.results.push(...pairResults);
245
+ if (pairError) {
246
+ reportPairError(pairError, pair, pairLabel);
247
+ if (keepGoing) {
248
+ for (const err of afterErrors)
249
+ failures.push({ ...pair, error: err.message });
250
+ }
251
+ }
252
+ else if (afterErrors.length > 0) {
253
+ statuses.push(...pairStatuses);
254
+ reportPairError(afterErrors[0], pair, pairLabel);
255
+ if (keepGoing) {
256
+ for (const err of afterErrors.slice(1))
257
+ failures.push({ ...pair, error: err.message });
258
+ }
259
+ }
260
+ else {
261
+ statuses.push(...pairStatuses);
262
+ }
263
+ }
264
+ }
265
+ }
266
+ catch (err) {
267
+ pendingError = err;
268
+ }
269
+ finally {
270
+ for (const [action, state] of actionStates) {
271
+ if (!state.started)
272
+ continue;
273
+ try {
274
+ await state.hooks.afterAll?.(makeCtx(action, undefined, state.subaction, { ...cleanArgv }), state.results);
127
275
  }
128
276
  catch (err) {
129
- const e = err;
130
- if (singleRun)
131
- throw err;
132
- if (!keepGoing) {
133
- throw new errors_1.ShowHelpError(`${pairLabel} failed: ${e.message}`);
134
- }
135
- failures.push({
136
- action,
137
- ...(name !== undefined ? { name } : {}),
138
- error: e.message,
139
- });
140
- statuses.push({ ...statusPair, status: 'failed' });
277
+ afterAllErrors.push(err);
141
278
  }
142
279
  }
280
+ try {
281
+ await projectHooks.afterAll?.(makeCtx(RUN_SCOPE, undefined, undefined, { ...cleanArgv }), results);
282
+ }
283
+ catch (err) {
284
+ afterAllErrors.push(err);
285
+ }
286
+ }
287
+ if (pendingError) {
288
+ for (const err of afterAllErrors)
289
+ logger.err(`afterAll failed: ${err.message}`);
290
+ throw pendingError;
291
+ }
292
+ if (afterAllErrors.length > 0) {
293
+ if (singleRunAll)
294
+ throw afterAllErrors[0];
295
+ if (!keepGoing)
296
+ throw new errors_1.ShowHelpError(`afterAll failed: ${afterAllErrors[0].message}`);
297
+ for (const err of afterAllErrors) {
298
+ failures.push({ action: RUN_SCOPE, error: err.message });
299
+ statuses.push({ action: RUN_SCOPE, status: 'failed' });
300
+ }
143
301
  }
144
302
  if (failures.length > 0) {
145
303
  throw new errors_1.KeepGoingError(failures, results, statuses);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NameFlagRemovedError = exports.CliArgumentError = exports.SetupRepositoryError = exports.UnknownTransformError = exports.ConfigTsNodeError = exports.GlobMirrorConflictError = exports.PathMacroResolutionError = exports.ShellCommandError = exports.TemplateConfigError = exports.InjectionAnchorNotFoundError = exports.InjectionTargetNotFoundError = exports.TemplateNotFoundError = exports.TemplateRenderError = exports.KeepGoingError = exports.ShowHelpError = void 0;
3
+ exports.NameFlagRemovedError = exports.CliArgumentError = exports.SetupRepositoryError = exports.UnknownTransformError = exports.HookModuleError = exports.HookTsNodeError = exports.ConfigTsNodeError = exports.GlobMirrorConflictError = exports.PathMacroResolutionError = exports.ShellCommandError = exports.TemplateConfigError = exports.InjectionAnchorNotFoundError = exports.InjectionTargetNotFoundError = exports.TemplateNotFoundError = exports.TemplateRenderError = exports.KeepGoingError = exports.ShowHelpError = void 0;
4
4
  const errors_1 = require("@biorate/errors");
5
5
  class ShowHelpError extends errors_1.BaseError {
6
6
  constructor(message) {
@@ -83,6 +83,21 @@ class ConfigTsNodeError extends errors_1.BaseError {
83
83
  }
84
84
  }
85
85
  exports.ConfigTsNodeError = ConfigTsNodeError;
86
+ class HookTsNodeError extends errors_1.BaseError {
87
+ constructor(file, cause) {
88
+ super('TypeScript hook [%s] requires ts-node: install it with `npm i -D ts-node` (error: [%s])', [file, cause?.message ?? cause]);
89
+ }
90
+ }
91
+ exports.HookTsNodeError = HookTsNodeError;
92
+ class HookModuleError extends errors_1.BaseError {
93
+ constructor(file, detail) {
94
+ super('Hook file [%s] must export a class as its default export (received [%s])', [
95
+ file,
96
+ detail,
97
+ ]);
98
+ }
99
+ }
100
+ exports.HookModuleError = HookModuleError;
86
101
  class UnknownTransformError extends errors_1.BaseError {
87
102
  constructor(name) {
88
103
  super('Unknown transform [%s]: register it under the `transforms` config key', [
@@ -26,40 +26,123 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.pickGeneratorAction = void 0;
29
+ exports.pickGeneratorAction = exports.normalizeProjectHooks = exports.resolveActionHooks = exports.HOOK_FILES = exports.LEGACY_HOOK_FILES = exports.ACTION_HOOK_FILES = void 0;
30
30
  const path_1 = __importDefault(require("path"));
31
31
  const fs_1 = __importDefault(require("fs"));
32
32
  const helpers_1 = __importDefault(require("./helpers"));
33
33
  const help_1 = require("./help");
34
- const hooksfiles = ['index.js', 'index.ts', 'prompt.cjs', 'prompt.js', 'prompt.ts'];
35
- const prompt = async (createPrompter, actionfolder, args) => {
36
- const hooksfile = hooksfiles
37
- .map((f) => path_1.default.resolve(path_1.default.join(actionfolder, f)))
38
- .find((f) => fs_1.default.existsSync(f));
39
- if (!hooksfile) {
40
- return Promise.resolve({});
34
+ const errors_1 = require("./errors");
35
+ exports.ACTION_HOOK_FILES = ['hooks.ts', 'hooks.js', 'hooks.mjs', 'hooks.cjs'];
36
+ exports.LEGACY_HOOK_FILES = [
37
+ 'index.js',
38
+ 'index.ts',
39
+ 'prompt.cjs',
40
+ 'prompt.js',
41
+ 'prompt.ts',
42
+ ];
43
+ exports.HOOK_FILES = [...exports.ACTION_HOOK_FILES, ...exports.LEGACY_HOOK_FILES];
44
+ const LIFECYCLE_METHODS = ['beforeAll', 'beforeEach', 'afterEach', 'afterAll'];
45
+ const loadHookModule = async (file) => {
46
+ if (/\.ts$/.test(file)) {
47
+ try {
48
+ await Promise.resolve().then(() => __importStar(require('ts-node/register/transpile-only')));
49
+ }
50
+ catch (cause) {
51
+ throw new errors_1.HookTsNodeError(file, cause);
52
+ }
41
53
  }
42
- const isTypeScriptHook = /\.ts$/.test(hooksfile);
43
- if (isTypeScriptHook) {
44
- require('ts-node/register/transpile-only');
54
+ return (await Promise.resolve(`${file}`).then(s => __importStar(require(s))));
55
+ };
56
+ const legacyAdapter = (raw) => ({
57
+ prompt: async ({ prompter, args }) => {
58
+ if (raw?.params)
59
+ return raw.params({ args, h: helpers_1.default });
60
+ if (raw?.prompt) {
61
+ return raw.prompt({ prompter, inquirer: prompter, args, h: helpers_1.default });
62
+ }
63
+ return prompter.prompt(raw.filter((p) => args[p.name] === undefined ||
64
+ args[p.name] === null ||
65
+ args[p.name]?.length === 0));
66
+ },
67
+ });
68
+ const loadResolvedHooks = async (actionfolder) => {
69
+ const file = exports.HOOK_FILES.map((f) => path_1.default.resolve(path_1.default.join(actionfolder, f))).find((f) => fs_1.default.existsSync(f));
70
+ if (!file)
71
+ return { instance: {}, kind: 'none' };
72
+ const isClassFile = exports.ACTION_HOOK_FILES.includes(path_1.default.basename(file));
73
+ const module = await loadHookModule(file);
74
+ if (!isClassFile) {
75
+ const raw = module.default ?? module;
76
+ return { instance: legacyAdapter(raw), kind: 'legacy', file, source: raw };
45
77
  }
46
- let hooksModule = await Promise.resolve(`${hooksfile}`).then(s => __importStar(require(s)));
47
- if (hooksModule.default) {
48
- hooksModule = hooksModule.default;
78
+ const exported = module.default;
79
+ if (typeof exported !== 'function') {
80
+ throw new errors_1.HookModuleError(file, exported === undefined
81
+ ? 'no default export'
82
+ : `default export is ${typeof exported}`);
49
83
  }
50
- if (hooksModule.params) {
51
- return hooksModule.params({ args, h: helpers_1.default });
84
+ try {
85
+ return {
86
+ instance: new exported(),
87
+ kind: 'class',
88
+ file,
89
+ };
52
90
  }
53
- const prompter = createPrompter();
54
- if (hooksModule.prompt) {
55
- return hooksModule.prompt({
56
- prompter,
57
- inquirer: prompter,
58
- args,
59
- h: helpers_1.default,
60
- });
91
+ catch (cause) {
92
+ throw new errors_1.HookModuleError(file, `default export could not be constructed: ${cause?.message ?? cause}`);
93
+ }
94
+ };
95
+ const resolveActionHooks = (actionfolder, cache) => {
96
+ const key = path_1.default.resolve(actionfolder);
97
+ if (!cache)
98
+ return loadResolvedHooks(key);
99
+ const cached = cache.get(key);
100
+ if (cached)
101
+ return cached;
102
+ const pending = loadResolvedHooks(key);
103
+ cache.set(key, pending);
104
+ return pending;
105
+ };
106
+ exports.resolveActionHooks = resolveActionHooks;
107
+ const normalizeProjectHooks = (hooks, logger) => {
108
+ if (!hooks || typeof hooks !== 'object')
109
+ return {};
110
+ const normalized = {};
111
+ for (const [key, value] of Object.entries(hooks)) {
112
+ if (!LIFECYCLE_METHODS.includes(key)) {
113
+ logger.warn(`Ignoring unknown project hook '${key}' in .hygen.* configuration.`);
114
+ continue;
115
+ }
116
+ if (typeof value !== 'function') {
117
+ logger.warn(`Ignoring non-function project hook '${key}' in .hygen.* configuration.`);
118
+ continue;
119
+ }
120
+ normalized[key] = value;
121
+ }
122
+ return normalized;
123
+ };
124
+ exports.normalizeProjectHooks = normalizeProjectHooks;
125
+ const prompt = async (createPrompter, actionfolder, args, options = {}) => {
126
+ const resolved = await (0, exports.resolveActionHooks)(actionfolder, options.cache);
127
+ const legacy = resolved.source;
128
+ if (resolved.kind === 'legacy' && legacy?.params) {
129
+ return legacy.params({ args, h: helpers_1.default });
61
130
  }
62
- return prompter.prompt(hooksModule.filter((p) => args[p.name] === undefined || args[p.name] === null || args[p.name].length === 0));
131
+ if (!resolved.instance.prompt)
132
+ return {};
133
+ const prompter = createPrompter();
134
+ const lazyHelpers = options.h;
135
+ return resolved.instance.prompt({
136
+ prompter,
137
+ args,
138
+ get h() {
139
+ if (resolved.kind !== 'class')
140
+ return helpers_1.default;
141
+ if (typeof lazyHelpers === 'function')
142
+ return lazyHelpers();
143
+ return lazyHelpers ?? helpers_1.default;
144
+ },
145
+ });
63
146
  };
64
147
  const answerValue = (answer, name) => {
65
148
  const value = answer[name];
@@ -33,6 +33,10 @@ const evaluateSkip = (rendered) => {
33
33
  const map = (f) => (arr) => arr.map(f);
34
34
  const filter = (f) => (arr) => arr.filter(f);
35
35
  const ignores = [
36
+ 'hooks.ts',
37
+ 'hooks.js',
38
+ 'hooks.mjs',
39
+ 'hooks.cjs',
36
40
  'prompt.js',
37
41
  'index.js',
38
42
  'prompt.ts',
@@ -1,7 +1,8 @@
1
1
  import path from 'path';
2
2
  import fs from 'fs-extra';
3
+ import context from './context.js';
3
4
  import params from './params.js';
4
- import prompt, { pickGeneratorAction } from './prompt.js';
5
+ import prompt, { normalizeProjectHooks, pickGeneratorAction, resolveActionHooks, } from './prompt.js';
5
6
  import { ShowHelpError, KeepGoingError } from './errors.js';
6
7
  import { isHelpFlag, printUsage } from './cli-help.js';
7
8
  const isInteractive = ({ interactive }) => interactive === true
@@ -9,6 +10,7 @@ const isInteractive = ({ interactive }) => interactive === true
9
10
  : interactive === false
10
11
  ? false
11
12
  : Boolean(process.stdin.isTTY && process.stdout.isTTY);
13
+ const RUN_SCOPE = '*';
12
14
  const engine = async (argv, config) => {
13
15
  const { cwd, templates, logger } = config;
14
16
  let base = Object.assign(await params(config, argv), { cwd });
@@ -36,23 +38,72 @@ const engine = async (argv, config) => {
36
38
  logger.log(`Loaded templates: ${templates.replace(`${cwd}/`, '')}`);
37
39
  const nameList = names ?? [undefined];
38
40
  const keepGoing = Boolean(cleanArgv['keep-going']);
41
+ const singleRunAll = nameList.length === 1 && actions.length === 1;
39
42
  const failures = [];
40
43
  const results = [];
41
44
  const statuses = [];
42
45
  const execute = (await import('./execute.js')).execute;
43
46
  const render = (await import('./render.js')).render;
44
- for (const name of nameList) {
45
- for (const action of actions) {
46
- const [mainAction, subaction] = action.split(':');
47
- const actionfolder = path.join(base.templates, generator, mainAction);
48
- const pairLabel = `action '${action}'${name !== undefined ? ` for name '${name}'` : ''}`;
49
- const statusPair = {
50
- action,
51
- ...(name !== undefined ? { name } : {}),
52
- };
53
- const singleRun = nameList.length === 1 && actions.length === 1;
54
- if (!(await fs.pathExists(actionfolder))) {
55
- const err = new ShowHelpError(`I can't find action '${action}' for generator '${generator}'.
47
+ const projectHooks = normalizeProjectHooks(config.hooks, logger);
48
+ let hookHelpers;
49
+ const getHookHelpers = () => (hookHelpers ?? (hookHelpers = context({ _: base._, ...cleanArgv }, config).h));
50
+ const hookCache = new Map();
51
+ const actionStates = new Map();
52
+ const makeCtx = (action, name, subaction, args) => ({
53
+ cwd,
54
+ templates: base.templates,
55
+ generator: generator,
56
+ action,
57
+ ...(subaction !== undefined ? { subaction } : {}),
58
+ ...(name !== undefined ? { name } : {}),
59
+ args,
60
+ get h() {
61
+ return getHookHelpers();
62
+ },
63
+ logger,
64
+ dry: Boolean(base.dry),
65
+ });
66
+ const actionState = (action, subaction) => {
67
+ let state = actionStates.get(action);
68
+ if (!state) {
69
+ state = { started: false, hooks: {}, subaction, results: [] };
70
+ actionStates.set(action, state);
71
+ }
72
+ return state;
73
+ };
74
+ const reportPairError = (error, pair, pairLabel) => {
75
+ if (singleRunAll)
76
+ throw error;
77
+ if (!keepGoing)
78
+ throw new ShowHelpError(`${pairLabel} failed: ${error.message}`);
79
+ failures.push({ ...pair, error: error.message });
80
+ statuses.push({ ...pair, status: 'failed' });
81
+ };
82
+ let projectBeforeAllError;
83
+ try {
84
+ await projectHooks.beforeAll?.(makeCtx(RUN_SCOPE, undefined, undefined, { ...cleanArgv }));
85
+ }
86
+ catch (err) {
87
+ projectBeforeAllError = err;
88
+ }
89
+ let pendingError;
90
+ const afterAllErrors = [];
91
+ try {
92
+ for (const name of nameList) {
93
+ for (const action of actions) {
94
+ const [mainAction, subaction] = action.split(':');
95
+ const actionfolder = path.join(base.templates, generator, mainAction);
96
+ const pairLabel = `action '${action}'${name !== undefined ? ` for name '${name}'` : ''}`;
97
+ const pair = {
98
+ action,
99
+ ...(name !== undefined ? { name } : {}),
100
+ };
101
+ const pairStatus = {
102
+ action,
103
+ ...(name !== undefined ? { name } : {}),
104
+ };
105
+ if (!(await fs.pathExists(actionfolder))) {
106
+ const err = new ShowHelpError(`I can't find action '${action}' for generator '${generator}'.
56
107
 
57
108
  You can try:
58
109
  1. 'hygen init self' to initialize your project, and
@@ -60,55 +111,162 @@ const engine = async (argv, config) => {
60
111
 
61
112
  Check out the quickstart for more: http://www.hygen.io/docs/quick-start
62
113
  `);
63
- if (singleRun)
64
- throw err;
65
- if (!keepGoing)
66
- throw err;
67
- failures.push({
68
- action,
69
- ...(name !== undefined ? { name } : {}),
70
- error: err.message,
71
- });
72
- statuses.push({ ...statusPair, status: 'failed' });
73
- continue;
74
- }
75
- try {
76
- const promptArgs = await prompt(config.createPrompter, actionfolder, {
114
+ if (singleRunAll)
115
+ throw err;
116
+ if (!keepGoing)
117
+ throw err;
118
+ failures.push({ ...pair, error: err.message });
119
+ statuses.push({ ...pairStatus, status: 'failed' });
120
+ continue;
121
+ }
122
+ if (projectBeforeAllError) {
123
+ reportPairError(projectBeforeAllError, pair, pairLabel);
124
+ continue;
125
+ }
126
+ const state = actionState(action, subaction);
127
+ if (!state.started) {
128
+ state.started = true;
129
+ try {
130
+ state.hooks = (await resolveActionHooks(actionfolder, hookCache)).instance;
131
+ await state.hooks.beforeAll?.(makeCtx(action, undefined, subaction, { ...cleanArgv }));
132
+ }
133
+ catch (err) {
134
+ state.beforeAllError = err;
135
+ }
136
+ }
137
+ if (state.beforeAllError) {
138
+ reportPairError(state.beforeAllError, pair, pairLabel);
139
+ continue;
140
+ }
141
+ const hookArgs = {
77
142
  ...(name ? { name } : {}),
78
143
  ...cleanArgv,
79
- });
80
- const args = Object.assign({
81
- templates: base.templates,
82
- actionfolder,
83
- generator,
84
- action,
85
- subaction,
86
- }, { _: base._, ts: base.ts }, cleanArgv, name ? { name } : {}, promptArgs);
87
- const el = await execute(await render(args, config), args, config);
88
- for (const pairResult of el.results) {
89
- results.push({
90
- ...pairResult,
91
- action,
92
- ...(name !== undefined ? { name } : {}),
93
- });
144
+ };
145
+ const pairResults = [];
146
+ const afterErrors = [];
147
+ let pairStatuses = [];
148
+ let pairError;
149
+ for (const run of [
150
+ projectHooks.beforeEach
151
+ ? () => projectHooks.beforeEach(makeCtx(action, name, subaction, hookArgs))
152
+ : undefined,
153
+ state.hooks.beforeEach
154
+ ? () => state.hooks.beforeEach(makeCtx(action, name, subaction, hookArgs))
155
+ : undefined,
156
+ ]) {
157
+ if (!run)
158
+ continue;
159
+ try {
160
+ await run();
161
+ }
162
+ catch (err) {
163
+ pairError = err;
164
+ break;
165
+ }
166
+ }
167
+ if (!pairError) {
168
+ try {
169
+ const promptArgs = await prompt(config.createPrompter, actionfolder, hookArgs, {
170
+ h: getHookHelpers,
171
+ cache: hookCache,
172
+ });
173
+ const args = Object.assign({
174
+ templates: base.templates,
175
+ actionfolder,
176
+ generator,
177
+ action,
178
+ subaction,
179
+ }, { _: base._, ts: base.ts }, cleanArgv, name ? { name } : {}, promptArgs);
180
+ const el = await execute(await render(args, config), args, config);
181
+ for (const pairResult of el.results) {
182
+ const annotated = {
183
+ ...pairResult,
184
+ action,
185
+ ...(name !== undefined ? { name } : {}),
186
+ };
187
+ results.push(annotated);
188
+ pairResults.push(annotated);
189
+ }
190
+ pairStatuses = el.statuses;
191
+ }
192
+ catch (err) {
193
+ pairError = err;
194
+ }
94
195
  }
95
- statuses.push(...el.statuses);
196
+ for (const run of [
197
+ state.hooks.afterEach
198
+ ? () => state.hooks.afterEach(makeCtx(action, name, subaction, hookArgs), pairResults)
199
+ : undefined,
200
+ projectHooks.afterEach
201
+ ? () => projectHooks.afterEach(makeCtx(action, name, subaction, hookArgs), pairResults)
202
+ : undefined,
203
+ ]) {
204
+ if (!run)
205
+ continue;
206
+ try {
207
+ await run();
208
+ }
209
+ catch (err) {
210
+ afterErrors.push(err);
211
+ }
212
+ }
213
+ state.results.push(...pairResults);
214
+ if (pairError) {
215
+ reportPairError(pairError, pair, pairLabel);
216
+ if (keepGoing) {
217
+ for (const err of afterErrors)
218
+ failures.push({ ...pair, error: err.message });
219
+ }
220
+ }
221
+ else if (afterErrors.length > 0) {
222
+ statuses.push(...pairStatuses);
223
+ reportPairError(afterErrors[0], pair, pairLabel);
224
+ if (keepGoing) {
225
+ for (const err of afterErrors.slice(1))
226
+ failures.push({ ...pair, error: err.message });
227
+ }
228
+ }
229
+ else {
230
+ statuses.push(...pairStatuses);
231
+ }
232
+ }
233
+ }
234
+ }
235
+ catch (err) {
236
+ pendingError = err;
237
+ }
238
+ finally {
239
+ for (const [action, state] of actionStates) {
240
+ if (!state.started)
241
+ continue;
242
+ try {
243
+ await state.hooks.afterAll?.(makeCtx(action, undefined, state.subaction, { ...cleanArgv }), state.results);
96
244
  }
97
245
  catch (err) {
98
- const e = err;
99
- if (singleRun)
100
- throw err;
101
- if (!keepGoing) {
102
- throw new ShowHelpError(`${pairLabel} failed: ${e.message}`);
103
- }
104
- failures.push({
105
- action,
106
- ...(name !== undefined ? { name } : {}),
107
- error: e.message,
108
- });
109
- statuses.push({ ...statusPair, status: 'failed' });
246
+ afterAllErrors.push(err);
110
247
  }
111
248
  }
249
+ try {
250
+ await projectHooks.afterAll?.(makeCtx(RUN_SCOPE, undefined, undefined, { ...cleanArgv }), results);
251
+ }
252
+ catch (err) {
253
+ afterAllErrors.push(err);
254
+ }
255
+ }
256
+ if (pendingError) {
257
+ for (const err of afterAllErrors)
258
+ logger.err(`afterAll failed: ${err.message}`);
259
+ throw pendingError;
260
+ }
261
+ if (afterAllErrors.length > 0) {
262
+ if (singleRunAll)
263
+ throw afterAllErrors[0];
264
+ if (!keepGoing)
265
+ throw new ShowHelpError(`afterAll failed: ${afterAllErrors[0].message}`);
266
+ for (const err of afterAllErrors) {
267
+ failures.push({ action: RUN_SCOPE, error: err.message });
268
+ statuses.push({ action: RUN_SCOPE, status: 'failed' });
269
+ }
112
270
  }
113
271
  if (failures.length > 0) {
114
272
  throw new KeepGoingError(failures, results, statuses);
@@ -69,6 +69,19 @@ export class ConfigTsNodeError extends BaseError {
69
69
  super('TypeScript config [%s] requires ts-node: install it with `npm i -D ts-node` (error: [%s])', [file, cause?.message ?? cause]);
70
70
  }
71
71
  }
72
+ export class HookTsNodeError extends BaseError {
73
+ constructor(file, cause) {
74
+ super('TypeScript hook [%s] requires ts-node: install it with `npm i -D ts-node` (error: [%s])', [file, cause?.message ?? cause]);
75
+ }
76
+ }
77
+ export class HookModuleError extends BaseError {
78
+ constructor(file, detail) {
79
+ super('Hook file [%s] must export a class as its default export (received [%s])', [
80
+ file,
81
+ detail,
82
+ ]);
83
+ }
84
+ }
72
85
  export class UnknownTransformError extends BaseError {
73
86
  constructor(name) {
74
87
  super('Unknown transform [%s]: register it under the `transforms` config key', [
@@ -2,35 +2,116 @@ import path from 'path';
2
2
  import fs from 'fs';
3
3
  import helpers from './helpers.js';
4
4
  import { pickableGenerators, generatorActions } from './help.js';
5
- const hooksfiles = ['index.js', 'index.ts', 'prompt.cjs', 'prompt.js', 'prompt.ts'];
6
- const prompt = async (createPrompter, actionfolder, args) => {
7
- const hooksfile = hooksfiles
8
- .map((f) => path.resolve(path.join(actionfolder, f)))
9
- .find((f) => fs.existsSync(f));
10
- if (!hooksfile) {
11
- return Promise.resolve({});
5
+ import { HookModuleError, HookTsNodeError } from './errors.js';
6
+ export const ACTION_HOOK_FILES = ['hooks.ts', 'hooks.js', 'hooks.mjs', 'hooks.cjs'];
7
+ export const LEGACY_HOOK_FILES = [
8
+ 'index.js',
9
+ 'index.ts',
10
+ 'prompt.cjs',
11
+ 'prompt.js',
12
+ 'prompt.ts',
13
+ ];
14
+ export const HOOK_FILES = [...ACTION_HOOK_FILES, ...LEGACY_HOOK_FILES];
15
+ const LIFECYCLE_METHODS = ['beforeAll', 'beforeEach', 'afterEach', 'afterAll'];
16
+ const loadHookModule = async (file) => {
17
+ if (/\.ts$/.test(file)) {
18
+ try {
19
+ await import('ts-node/register/transpile-only');
20
+ }
21
+ catch (cause) {
22
+ throw new HookTsNodeError(file, cause);
23
+ }
12
24
  }
13
- const isTypeScriptHook = /\.ts$/.test(hooksfile);
14
- if (isTypeScriptHook) {
15
- require('ts-node/register/transpile-only');
25
+ return (await import(file));
26
+ };
27
+ const legacyAdapter = (raw) => ({
28
+ prompt: async ({ prompter, args }) => {
29
+ if (raw?.params)
30
+ return raw.params({ args, h: helpers });
31
+ if (raw?.prompt) {
32
+ return raw.prompt({ prompter, inquirer: prompter, args, h: helpers });
33
+ }
34
+ return prompter.prompt(raw.filter((p) => args[p.name] === undefined ||
35
+ args[p.name] === null ||
36
+ args[p.name]?.length === 0));
37
+ },
38
+ });
39
+ const loadResolvedHooks = async (actionfolder) => {
40
+ const file = HOOK_FILES.map((f) => path.resolve(path.join(actionfolder, f))).find((f) => fs.existsSync(f));
41
+ if (!file)
42
+ return { instance: {}, kind: 'none' };
43
+ const isClassFile = ACTION_HOOK_FILES.includes(path.basename(file));
44
+ const module = await loadHookModule(file);
45
+ if (!isClassFile) {
46
+ const raw = module.default ?? module;
47
+ return { instance: legacyAdapter(raw), kind: 'legacy', file, source: raw };
16
48
  }
17
- let hooksModule = await import(hooksfile);
18
- if (hooksModule.default) {
19
- hooksModule = hooksModule.default;
49
+ const exported = module.default;
50
+ if (typeof exported !== 'function') {
51
+ throw new HookModuleError(file, exported === undefined
52
+ ? 'no default export'
53
+ : `default export is ${typeof exported}`);
20
54
  }
21
- if (hooksModule.params) {
22
- return hooksModule.params({ args, h: helpers });
55
+ try {
56
+ return {
57
+ instance: new exported(),
58
+ kind: 'class',
59
+ file,
60
+ };
23
61
  }
24
- const prompter = createPrompter();
25
- if (hooksModule.prompt) {
26
- return hooksModule.prompt({
27
- prompter,
28
- inquirer: prompter,
29
- args,
30
- h: helpers,
31
- });
62
+ catch (cause) {
63
+ throw new HookModuleError(file, `default export could not be constructed: ${cause?.message ?? cause}`);
64
+ }
65
+ };
66
+ export const resolveActionHooks = (actionfolder, cache) => {
67
+ const key = path.resolve(actionfolder);
68
+ if (!cache)
69
+ return loadResolvedHooks(key);
70
+ const cached = cache.get(key);
71
+ if (cached)
72
+ return cached;
73
+ const pending = loadResolvedHooks(key);
74
+ cache.set(key, pending);
75
+ return pending;
76
+ };
77
+ export const normalizeProjectHooks = (hooks, logger) => {
78
+ if (!hooks || typeof hooks !== 'object')
79
+ return {};
80
+ const normalized = {};
81
+ for (const [key, value] of Object.entries(hooks)) {
82
+ if (!LIFECYCLE_METHODS.includes(key)) {
83
+ logger.warn(`Ignoring unknown project hook '${key}' in .hygen.* configuration.`);
84
+ continue;
85
+ }
86
+ if (typeof value !== 'function') {
87
+ logger.warn(`Ignoring non-function project hook '${key}' in .hygen.* configuration.`);
88
+ continue;
89
+ }
90
+ normalized[key] = value;
32
91
  }
33
- return prompter.prompt(hooksModule.filter((p) => args[p.name] === undefined || args[p.name] === null || args[p.name].length === 0));
92
+ return normalized;
93
+ };
94
+ const prompt = async (createPrompter, actionfolder, args, options = {}) => {
95
+ const resolved = await resolveActionHooks(actionfolder, options.cache);
96
+ const legacy = resolved.source;
97
+ if (resolved.kind === 'legacy' && legacy?.params) {
98
+ return legacy.params({ args, h: helpers });
99
+ }
100
+ if (!resolved.instance.prompt)
101
+ return {};
102
+ const prompter = createPrompter();
103
+ const lazyHelpers = options.h;
104
+ return resolved.instance.prompt({
105
+ prompter,
106
+ args,
107
+ get h() {
108
+ if (resolved.kind !== 'class')
109
+ return helpers;
110
+ if (typeof lazyHelpers === 'function')
111
+ return lazyHelpers();
112
+ return lazyHelpers ?? helpers;
113
+ },
114
+ });
34
115
  };
35
116
  const answerValue = (answer, name) => {
36
117
  const value = answer[name];
@@ -27,6 +27,10 @@ const evaluateSkip = (rendered) => {
27
27
  const map = (f) => (arr) => arr.map(f);
28
28
  const filter = (f) => (arr) => arr.filter(f);
29
29
  const ignores = [
30
+ 'hooks.ts',
31
+ 'hooks.js',
32
+ 'hooks.mjs',
33
+ 'hooks.cjs',
30
34
  'prompt.js',
31
35
  'index.js',
32
36
  'prompt.ts',
@@ -36,6 +36,12 @@ export declare class GlobMirrorConflictError extends BaseError {
36
36
  export declare class ConfigTsNodeError extends BaseError {
37
37
  constructor(file: string, cause: unknown);
38
38
  }
39
+ export declare class HookTsNodeError extends BaseError {
40
+ constructor(file: string, cause: unknown);
41
+ }
42
+ export declare class HookModuleError extends BaseError {
43
+ constructor(file: string, detail: string);
44
+ }
39
45
  export declare class UnknownTransformError extends BaseError {
40
46
  constructor(name: string);
41
47
  }
@@ -1,5 +1,21 @@
1
- import type { Prompter, RunnerConfig } from './types';
2
- declare const prompt: <Q, T>(createPrompter: () => Prompter<Q, T>, actionfolder: string, args: Record<string, any>) => Promise<T | object>;
1
+ import type { ActionHooks, Helpers, Prompter, ProjectHooks, RunnerConfig } from './types';
2
+ export declare const ACTION_HOOK_FILES: string[];
3
+ export declare const LEGACY_HOOK_FILES: string[];
4
+ export declare const HOOK_FILES: string[];
5
+ export type HookKind = 'class' | 'legacy' | 'none';
6
+ export interface ResolvedActionHooks {
7
+ instance: ActionHooks;
8
+ kind: HookKind;
9
+ file?: string;
10
+ source?: unknown;
11
+ }
12
+ export type HookCache = Map<string, Promise<ResolvedActionHooks>>;
13
+ export declare const resolveActionHooks: (actionfolder: string, cache?: HookCache) => Promise<ResolvedActionHooks>;
14
+ export declare const normalizeProjectHooks: (hooks: unknown, logger: RunnerConfig["logger"]) => ProjectHooks;
15
+ declare const prompt: <Q, T>(createPrompter: () => Prompter<Q, T>, actionfolder: string, args: Record<string, any>, options?: {
16
+ h?: Helpers | (() => Helpers);
17
+ cache?: HookCache;
18
+ }) => Promise<T | object>;
3
19
  export interface PickResult {
4
20
  generator: string;
5
21
  action: string;
@@ -31,6 +31,32 @@ export type Helper = (...args: unknown[]) => unknown;
31
31
  export type Helpers = Record<string, unknown>;
32
32
  export type Transform = (content: string, locals: Record<string, unknown>) => string | Promise<string>;
33
33
  export type Transforms = Record<string, Transform>;
34
+ export interface HookContext {
35
+ cwd: string;
36
+ templates: string;
37
+ generator: string;
38
+ action: string;
39
+ subaction?: string;
40
+ name?: string;
41
+ args: Record<string, unknown>;
42
+ h: Helpers;
43
+ logger: Logger;
44
+ dry: boolean;
45
+ }
46
+ export type HookMethod = (ctx: HookContext) => unknown | Promise<unknown>;
47
+ export interface ProjectHooks {
48
+ beforeAll?: HookMethod;
49
+ beforeEach?: HookMethod;
50
+ afterEach?: (ctx: HookContext, results: ActionResult[]) => unknown | Promise<unknown>;
51
+ afterAll?: (ctx: HookContext, results: ActionResult[]) => unknown | Promise<unknown>;
52
+ }
53
+ export interface ActionHooks extends ProjectHooks {
54
+ prompt?: (input: {
55
+ prompter: Prompter<any, any>;
56
+ args: Record<string, unknown>;
57
+ h: Helpers;
58
+ }) => unknown;
59
+ }
34
60
  export interface RunnerConfig {
35
61
  exec: (sh: string, body: string) => void;
36
62
  templates?: string;
@@ -40,6 +66,7 @@ export interface RunnerConfig {
40
66
  debug?: boolean;
41
67
  helpers?: Helpers | ((locals: Record<string, unknown>, config: RunnerContextConfig) => Helpers);
42
68
  transforms?: Transforms;
69
+ hooks?: ProjectHooks;
43
70
  localsDefaults?: Record<string, unknown>;
44
71
  createPrompter: <Q, T>() => Prompter<Q, T>;
45
72
  legacyNameFlag?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@biorate/hygen",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "The scalable code generator that saves you time. Fork of jondot/hygen",
5
5
  "keywords": [
6
6
  "template",
@@ -80,5 +80,5 @@
80
80
  "@types/inflection": "1.13.0",
81
81
  "@types/yargs-parser": "21.0.3"
82
82
  },
83
- "gitHead": "0768d737d2355377d0d27e36a716ea27f89b6b1d"
83
+ "gitHead": "da6d2c63dddd28bcc5aef105cf6697b4669733ea"
84
84
  }