@biorate/hygen 0.1.0 → 0.3.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/README.md CHANGED
@@ -130,6 +130,7 @@ The complete user guide lives in the package's local `docs/` pages. README is fo
130
130
  - **Composition** — the action and name positionals accept comma lists, so one command runs several actions and/or names (`hygen mailer new,html a,b`); action lists run sequentially, the name loop is name-outer, `--keep-going` collects failures without halting, and `name` is always a scalar in templates. A template with `mirror: true` (and no `to:`) writes to the path mirroring its location inside the action folder, with the trailing `.t` stripped (or `.ejs.t` behind `HYGEN_MIRROR_EJS_SUFFIX=1`). See [Multiple actions and names](./docs/generators.md#multiple-actions-and-names-in-one-run) and [Mirroring](./docs/templates.md#mirroring-the-template-layout-mirror).
131
131
  - **`--name` flag removed (breaking, semver-major)** — the `--name` flag is no longer accepted by default. Invoking it fails with `NameFlagRemovedError`, whose message names the offending flag, shows the positional equivalent (`hygen <generator> <action[,action...]> <name[,name...]>`), and points at the legacy escape. Use the positional name instead, optionally as a comma list: `hygen mailer new fancy` or `hygen mailer new a,b`. For migration, two legacy escapes restore the pre-removal behavior: set `HYGEN_LEGACY_NAME=1`, or pass `legacyNameFlag: true` in `RunnerConfig` (embedding). Under the escape the flag behaves exactly as before this change (including the repeated-flag array). Name precedence is prompt hook > positional name; the `--name` flag participates only via the legacy escape.
132
132
  - **Glob batch actions** — a template may declare `glob:` to scaffold a whole directory in one action (plop's `addMany` equivalent): the pattern resolves relative to the template's own directory, `base:`/`stripExtensions:` shape each target path, EJS renders in file names and contents, and the glob template itself writes nothing. `glob` is mutually exclusive with `mirror: true` (`GlobMirrorConflictError`). `skipIfExists: true` skips an existing target softly (no prompt, no failure) on any file-creating action. See [Glob batch actions](./docs/templates.md#glob-batch-actions-glob).
133
+ - **Path macros in mirrored targets** — any segment of a mirrored path may carry `$IDENTIFIER$` macros (e.g. `apps/$CLIENT_NAME$/src/`), substituted from the run locals (prompt answers, `name`, CLI flags, config helpers); a macro is always a scalar (one pass per name under name expansion), unknown identifiers fail fast with `PathMacroResolutionError`, and `$` is a legal filename character on Linux, macOS and Windows. `to:` and glob `destination:` remain fully EJS-rendered. See [Path macros](./docs/templates.md#path-macros-identifier).
133
134
  - **Named content transforms** — the config file may declare a `transforms` namespace of post-processors, and a template frontmatter `transform: name` (or a chained `a|b`) applies them to the rendered content before it is written or injected (formatting generated code with prettier is the canonical use). See [Content transforms](./docs/extensibility.md#content-transforms).
134
135
  - **Conditional action skipping** — a template frontmatter `skip:` (EJS-rendered with the run locals) skips the action when truthy, so a template can decide at render time whether it runs: `skip: <%= wantTests ? 'false' : 'no tests requested' %>`. Skipped actions execute no operation and are reported with a third `skipped` status in `RunnerResult.statuses` (never in `failures`). See [Conditional action skipping](./docs/templates.md#conditional-action-skipping-skip).
135
136
  - **Interactive generator/action picker** — running `hygen` with no positional arguments in a terminal offers a two-level picker (generator → action) and runs the selection exactly as if passed positionally; in non-TTY environments (CI, piped stdio) the invocation fails fast with the usual missing-arguments error plus a hint, and embedders can force/disable it via `RunnerConfig.interactive`. See [Interactive picker](./docs/generators.md#interactive-picker-no-arguments).
package/dist/cjs/bin.js CHANGED
File without changes
@@ -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,69 @@ 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
+ const hookHelpers = (0, context_1.default)({}, config).h;
80
+ const hookCache = new Map();
81
+ const actionStates = new Map();
82
+ const makeCtx = (action, name, subaction, args) => ({
83
+ cwd,
84
+ templates: base.templates,
85
+ generator: generator,
86
+ action,
87
+ ...(subaction !== undefined ? { subaction } : {}),
88
+ ...(name !== undefined ? { name } : {}),
89
+ args,
90
+ h: hookHelpers,
91
+ logger,
92
+ dry: Boolean(base.dry),
93
+ });
94
+ const actionState = (action, subaction) => {
95
+ let state = actionStates.get(action);
96
+ if (!state) {
97
+ state = { started: false, hooks: {}, subaction, results: [] };
98
+ actionStates.set(action, state);
99
+ }
100
+ return state;
101
+ };
102
+ const reportPairError = (error, pair, pairLabel) => {
103
+ if (singleRunAll)
104
+ throw error;
105
+ if (!keepGoing)
106
+ throw new errors_1.ShowHelpError(`${pairLabel} failed: ${error.message}`);
107
+ failures.push({ ...pair, error: error.message });
108
+ statuses.push({ ...pair, status: 'failed' });
109
+ };
110
+ let projectBeforeAllError;
111
+ try {
112
+ await projectHooks.beforeAll?.(makeCtx(RUN_SCOPE, undefined, undefined, { ...cleanArgv }));
113
+ }
114
+ catch (err) {
115
+ projectBeforeAllError = err;
116
+ }
117
+ let pendingError;
118
+ const afterAllErrors = [];
119
+ try {
120
+ for (const name of nameList) {
121
+ for (const action of actions) {
122
+ const [mainAction, subaction] = action.split(':');
123
+ const actionfolder = path_1.default.join(base.templates, generator, mainAction);
124
+ const pairLabel = `action '${action}'${name !== undefined ? ` for name '${name}'` : ''}`;
125
+ const pair = {
126
+ action,
127
+ ...(name !== undefined ? { name } : {}),
128
+ };
129
+ const pairStatus = {
130
+ action,
131
+ ...(name !== undefined ? { name } : {}),
132
+ };
133
+ if (!(await fs_extra_1.default.pathExists(actionfolder))) {
134
+ const err = new errors_1.ShowHelpError(`I can't find action '${action}' for generator '${generator}'.
87
135
 
88
136
  You can try:
89
137
  1. 'hygen init self' to initialize your project, and
@@ -91,55 +139,162 @@ const engine = async (argv, config) => {
91
139
 
92
140
  Check out the quickstart for more: http://www.hygen.io/docs/quick-start
93
141
  `);
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, {
142
+ if (singleRunAll)
143
+ throw err;
144
+ if (!keepGoing)
145
+ throw err;
146
+ failures.push({ ...pair, error: err.message });
147
+ statuses.push({ ...pairStatus, status: 'failed' });
148
+ continue;
149
+ }
150
+ if (projectBeforeAllError) {
151
+ reportPairError(projectBeforeAllError, pair, pairLabel);
152
+ continue;
153
+ }
154
+ const state = actionState(action, subaction);
155
+ if (!state.started) {
156
+ state.started = true;
157
+ try {
158
+ state.hooks = (await (0, prompt_1.resolveActionHooks)(actionfolder, hookCache)).instance;
159
+ await state.hooks.beforeAll?.(makeCtx(action, undefined, subaction, { ...cleanArgv }));
160
+ }
161
+ catch (err) {
162
+ state.beforeAllError = err;
163
+ }
164
+ }
165
+ if (state.beforeAllError) {
166
+ reportPairError(state.beforeAllError, pair, pairLabel);
167
+ continue;
168
+ }
169
+ const hookArgs = {
108
170
  ...(name ? { name } : {}),
109
171
  ...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
- });
172
+ };
173
+ const pairResults = [];
174
+ const afterErrors = [];
175
+ let pairStatuses = [];
176
+ let pairError;
177
+ for (const run of [
178
+ projectHooks.beforeEach
179
+ ? () => projectHooks.beforeEach(makeCtx(action, name, subaction, hookArgs))
180
+ : undefined,
181
+ state.hooks.beforeEach
182
+ ? () => state.hooks.beforeEach(makeCtx(action, name, subaction, hookArgs))
183
+ : undefined,
184
+ ]) {
185
+ if (!run)
186
+ continue;
187
+ try {
188
+ await run();
189
+ }
190
+ catch (err) {
191
+ pairError = err;
192
+ break;
193
+ }
194
+ }
195
+ if (!pairError) {
196
+ try {
197
+ const promptArgs = await (0, prompt_1.default)(config.createPrompter, actionfolder, hookArgs, {
198
+ h: hookHelpers,
199
+ cache: hookCache,
200
+ });
201
+ const args = Object.assign({
202
+ templates: base.templates,
203
+ actionfolder,
204
+ generator,
205
+ action,
206
+ subaction,
207
+ }, { _: base._, ts: base.ts }, cleanArgv, name ? { name } : {}, promptArgs);
208
+ const el = await execute(await render(args, config), args, config);
209
+ for (const pairResult of el.results) {
210
+ const annotated = {
211
+ ...pairResult,
212
+ action,
213
+ ...(name !== undefined ? { name } : {}),
214
+ };
215
+ results.push(annotated);
216
+ pairResults.push(annotated);
217
+ }
218
+ pairStatuses = el.statuses;
219
+ }
220
+ catch (err) {
221
+ pairError = err;
222
+ }
125
223
  }
126
- statuses.push(...el.statuses);
224
+ for (const run of [
225
+ state.hooks.afterEach
226
+ ? () => state.hooks.afterEach(makeCtx(action, name, subaction, hookArgs), pairResults)
227
+ : undefined,
228
+ projectHooks.afterEach
229
+ ? () => projectHooks.afterEach(makeCtx(action, name, subaction, hookArgs), pairResults)
230
+ : undefined,
231
+ ]) {
232
+ if (!run)
233
+ continue;
234
+ try {
235
+ await run();
236
+ }
237
+ catch (err) {
238
+ afterErrors.push(err);
239
+ }
240
+ }
241
+ state.results.push(...pairResults);
242
+ if (pairError) {
243
+ reportPairError(pairError, pair, pairLabel);
244
+ if (keepGoing) {
245
+ for (const err of afterErrors)
246
+ failures.push({ ...pair, error: err.message });
247
+ }
248
+ }
249
+ else if (afterErrors.length > 0) {
250
+ statuses.push(...pairStatuses);
251
+ reportPairError(afterErrors[0], pair, pairLabel);
252
+ if (keepGoing) {
253
+ for (const err of afterErrors.slice(1))
254
+ failures.push({ ...pair, error: err.message });
255
+ }
256
+ }
257
+ else {
258
+ statuses.push(...pairStatuses);
259
+ }
260
+ }
261
+ }
262
+ }
263
+ catch (err) {
264
+ pendingError = err;
265
+ }
266
+ finally {
267
+ for (const [action, state] of actionStates) {
268
+ if (!state.started)
269
+ continue;
270
+ try {
271
+ await state.hooks.afterAll?.(makeCtx(action, undefined, state.subaction, { ...cleanArgv }), state.results);
127
272
  }
128
273
  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' });
274
+ afterAllErrors.push(err);
141
275
  }
142
276
  }
277
+ try {
278
+ await projectHooks.afterAll?.(makeCtx(RUN_SCOPE, undefined, undefined, { ...cleanArgv }), results);
279
+ }
280
+ catch (err) {
281
+ afterAllErrors.push(err);
282
+ }
283
+ }
284
+ if (pendingError) {
285
+ for (const err of afterAllErrors)
286
+ logger.err(`afterAll failed: ${err.message}`);
287
+ throw pendingError;
288
+ }
289
+ if (afterAllErrors.length > 0) {
290
+ if (singleRunAll)
291
+ throw afterAllErrors[0];
292
+ if (!keepGoing)
293
+ throw new errors_1.ShowHelpError(`afterAll failed: ${afterAllErrors[0].message}`);
294
+ for (const err of afterAllErrors) {
295
+ failures.push({ action: RUN_SCOPE, error: err.message });
296
+ statuses.push({ action: RUN_SCOPE, status: 'failed' });
297
+ }
143
298
  }
144
299
  if (failures.length > 0) {
145
300
  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.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) {
@@ -61,6 +61,14 @@ class ShellCommandError extends errors_1.BaseError {
61
61
  }
62
62
  }
63
63
  exports.ShellCommandError = ShellCommandError;
64
+ class PathMacroResolutionError extends errors_1.BaseError {
65
+ constructor(file, segment, identifier) {
66
+ super('Template [%s] has a mirrored path segment [%s] with the macro $%s$, which ' +
67
+ 'cannot be resolved from the run locals. Define it in the prompt hook, pass ' +
68
+ 'it as a CLI flag, or export it from the config helpers factory.', [file, segment, identifier]);
69
+ }
70
+ }
71
+ exports.PathMacroResolutionError = PathMacroResolutionError;
64
72
  class GlobMirrorConflictError extends errors_1.BaseError {
65
73
  constructor(file) {
66
74
  super('Template [%s] declares both `mirror: true` and `glob:`, which are incompatible: ' +
@@ -75,6 +83,21 @@ class ConfigTsNodeError extends errors_1.BaseError {
75
83
  }
76
84
  }
77
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;
78
101
  class UnknownTransformError extends errors_1.BaseError {
79
102
  constructor(name) {
80
103
  super('Unknown transform [%s]: register it under the `transforms` config key', [
@@ -7,21 +7,24 @@ const path_1 = __importDefault(require("path"));
7
7
  const fs_extra_1 = __importDefault(require("fs-extra"));
8
8
  const chalk_1 = require("chalk");
9
9
  const result_1 = __importDefault(require("./result"));
10
- const targetPath = (action, actionfolder) => {
10
+ const path_macros_1 = require("../path-macros");
11
+ const targetPath = (action, args, config) => {
11
12
  const { attributes } = action;
12
13
  if (attributes.to)
13
14
  return attributes.to;
14
15
  if (attributes.mirror !== true || attributes.sh !== undefined || !action.file) {
15
16
  return undefined;
16
17
  }
17
- const rel = path_1.default.relative(actionfolder, action.file);
18
- return process.env.HYGEN_MIRROR_EJS_SUFFIX === '1'
18
+ const rel = path_1.default.relative(args.actionfolder, action.file);
19
+ const stripped = process.env.HYGEN_MIRROR_EJS_SUFFIX === '1'
19
20
  ? rel.replace(/\.ejs\.t$/, '')
20
21
  : rel.replace(/\.t$/, '');
22
+ return (0, path_macros_1.resolvePathMacros)(stripped, args, config, action.file);
21
23
  };
22
- const add = async (action, args, { logger, cwd, createPrompter }) => {
24
+ const add = async (action, args, config) => {
25
+ const { logger, cwd, createPrompter } = config;
23
26
  const { attributes: { inject, unless_exists, force, from, skip_if, skipIfExists }, } = action;
24
- const to = targetPath(action, args.actionfolder);
27
+ const to = targetPath(action, args, config);
25
28
  const result = (0, result_1.default)('add', to);
26
29
  const prompter = createPrompter();
27
30
  if (!to || inject) {
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.resolvePathMacros = void 0;
7
+ const path_1 = __importDefault(require("path"));
8
+ const errors_1 = require("./errors");
9
+ const context_1 = __importDefault(require("./context"));
10
+ const MACRO_PATTERN = /\$([A-Za-z_][A-Za-z0-9_]*)\$/g;
11
+ const macroDictionary = (args, config) => {
12
+ const ctx = (0, context_1.default)(args, config);
13
+ return { ...ctx, ...ctx.h };
14
+ };
15
+ const resolvePathMacros = (rel, args, config, file) => {
16
+ if (!rel.includes('$'))
17
+ return rel;
18
+ const dict = macroDictionary(args, config);
19
+ return rel
20
+ .split(path_1.default.sep)
21
+ .map((segment) => segment.replace(MACRO_PATTERN, (_match, identifier) => {
22
+ const value = dict[identifier];
23
+ if (value === undefined || value === null) {
24
+ throw new errors_1.PathMacroResolutionError(file, segment, identifier);
25
+ }
26
+ return String(value);
27
+ }))
28
+ .join(path_1.default.sep);
29
+ };
30
+ exports.resolvePathMacros = resolvePathMacros;
@@ -26,40 +26,116 @@ 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
+ return resolved.instance.prompt({
135
+ prompter,
136
+ args,
137
+ h: resolved.kind === 'class' ? options.h ?? helpers_1.default : helpers_1.default,
138
+ });
63
139
  };
64
140
  const answerValue = (answer, name) => {
65
141
  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,69 @@ 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
+ const hookHelpers = context({}, config).h;
49
+ const hookCache = new Map();
50
+ const actionStates = new Map();
51
+ const makeCtx = (action, name, subaction, args) => ({
52
+ cwd,
53
+ templates: base.templates,
54
+ generator: generator,
55
+ action,
56
+ ...(subaction !== undefined ? { subaction } : {}),
57
+ ...(name !== undefined ? { name } : {}),
58
+ args,
59
+ h: hookHelpers,
60
+ logger,
61
+ dry: Boolean(base.dry),
62
+ });
63
+ const actionState = (action, subaction) => {
64
+ let state = actionStates.get(action);
65
+ if (!state) {
66
+ state = { started: false, hooks: {}, subaction, results: [] };
67
+ actionStates.set(action, state);
68
+ }
69
+ return state;
70
+ };
71
+ const reportPairError = (error, pair, pairLabel) => {
72
+ if (singleRunAll)
73
+ throw error;
74
+ if (!keepGoing)
75
+ throw new ShowHelpError(`${pairLabel} failed: ${error.message}`);
76
+ failures.push({ ...pair, error: error.message });
77
+ statuses.push({ ...pair, status: 'failed' });
78
+ };
79
+ let projectBeforeAllError;
80
+ try {
81
+ await projectHooks.beforeAll?.(makeCtx(RUN_SCOPE, undefined, undefined, { ...cleanArgv }));
82
+ }
83
+ catch (err) {
84
+ projectBeforeAllError = err;
85
+ }
86
+ let pendingError;
87
+ const afterAllErrors = [];
88
+ try {
89
+ for (const name of nameList) {
90
+ for (const action of actions) {
91
+ const [mainAction, subaction] = action.split(':');
92
+ const actionfolder = path.join(base.templates, generator, mainAction);
93
+ const pairLabel = `action '${action}'${name !== undefined ? ` for name '${name}'` : ''}`;
94
+ const pair = {
95
+ action,
96
+ ...(name !== undefined ? { name } : {}),
97
+ };
98
+ const pairStatus = {
99
+ action,
100
+ ...(name !== undefined ? { name } : {}),
101
+ };
102
+ if (!(await fs.pathExists(actionfolder))) {
103
+ const err = new ShowHelpError(`I can't find action '${action}' for generator '${generator}'.
56
104
 
57
105
  You can try:
58
106
  1. 'hygen init self' to initialize your project, and
@@ -60,55 +108,162 @@ const engine = async (argv, config) => {
60
108
 
61
109
  Check out the quickstart for more: http://www.hygen.io/docs/quick-start
62
110
  `);
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, {
111
+ if (singleRunAll)
112
+ throw err;
113
+ if (!keepGoing)
114
+ throw err;
115
+ failures.push({ ...pair, error: err.message });
116
+ statuses.push({ ...pairStatus, status: 'failed' });
117
+ continue;
118
+ }
119
+ if (projectBeforeAllError) {
120
+ reportPairError(projectBeforeAllError, pair, pairLabel);
121
+ continue;
122
+ }
123
+ const state = actionState(action, subaction);
124
+ if (!state.started) {
125
+ state.started = true;
126
+ try {
127
+ state.hooks = (await resolveActionHooks(actionfolder, hookCache)).instance;
128
+ await state.hooks.beforeAll?.(makeCtx(action, undefined, subaction, { ...cleanArgv }));
129
+ }
130
+ catch (err) {
131
+ state.beforeAllError = err;
132
+ }
133
+ }
134
+ if (state.beforeAllError) {
135
+ reportPairError(state.beforeAllError, pair, pairLabel);
136
+ continue;
137
+ }
138
+ const hookArgs = {
77
139
  ...(name ? { name } : {}),
78
140
  ...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
- });
141
+ };
142
+ const pairResults = [];
143
+ const afterErrors = [];
144
+ let pairStatuses = [];
145
+ let pairError;
146
+ for (const run of [
147
+ projectHooks.beforeEach
148
+ ? () => projectHooks.beforeEach(makeCtx(action, name, subaction, hookArgs))
149
+ : undefined,
150
+ state.hooks.beforeEach
151
+ ? () => state.hooks.beforeEach(makeCtx(action, name, subaction, hookArgs))
152
+ : undefined,
153
+ ]) {
154
+ if (!run)
155
+ continue;
156
+ try {
157
+ await run();
158
+ }
159
+ catch (err) {
160
+ pairError = err;
161
+ break;
162
+ }
163
+ }
164
+ if (!pairError) {
165
+ try {
166
+ const promptArgs = await prompt(config.createPrompter, actionfolder, hookArgs, {
167
+ h: hookHelpers,
168
+ cache: hookCache,
169
+ });
170
+ const args = Object.assign({
171
+ templates: base.templates,
172
+ actionfolder,
173
+ generator,
174
+ action,
175
+ subaction,
176
+ }, { _: base._, ts: base.ts }, cleanArgv, name ? { name } : {}, promptArgs);
177
+ const el = await execute(await render(args, config), args, config);
178
+ for (const pairResult of el.results) {
179
+ const annotated = {
180
+ ...pairResult,
181
+ action,
182
+ ...(name !== undefined ? { name } : {}),
183
+ };
184
+ results.push(annotated);
185
+ pairResults.push(annotated);
186
+ }
187
+ pairStatuses = el.statuses;
188
+ }
189
+ catch (err) {
190
+ pairError = err;
191
+ }
94
192
  }
95
- statuses.push(...el.statuses);
193
+ for (const run of [
194
+ state.hooks.afterEach
195
+ ? () => state.hooks.afterEach(makeCtx(action, name, subaction, hookArgs), pairResults)
196
+ : undefined,
197
+ projectHooks.afterEach
198
+ ? () => projectHooks.afterEach(makeCtx(action, name, subaction, hookArgs), pairResults)
199
+ : undefined,
200
+ ]) {
201
+ if (!run)
202
+ continue;
203
+ try {
204
+ await run();
205
+ }
206
+ catch (err) {
207
+ afterErrors.push(err);
208
+ }
209
+ }
210
+ state.results.push(...pairResults);
211
+ if (pairError) {
212
+ reportPairError(pairError, pair, pairLabel);
213
+ if (keepGoing) {
214
+ for (const err of afterErrors)
215
+ failures.push({ ...pair, error: err.message });
216
+ }
217
+ }
218
+ else if (afterErrors.length > 0) {
219
+ statuses.push(...pairStatuses);
220
+ reportPairError(afterErrors[0], pair, pairLabel);
221
+ if (keepGoing) {
222
+ for (const err of afterErrors.slice(1))
223
+ failures.push({ ...pair, error: err.message });
224
+ }
225
+ }
226
+ else {
227
+ statuses.push(...pairStatuses);
228
+ }
229
+ }
230
+ }
231
+ }
232
+ catch (err) {
233
+ pendingError = err;
234
+ }
235
+ finally {
236
+ for (const [action, state] of actionStates) {
237
+ if (!state.started)
238
+ continue;
239
+ try {
240
+ await state.hooks.afterAll?.(makeCtx(action, undefined, state.subaction, { ...cleanArgv }), state.results);
96
241
  }
97
242
  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' });
243
+ afterAllErrors.push(err);
110
244
  }
111
245
  }
246
+ try {
247
+ await projectHooks.afterAll?.(makeCtx(RUN_SCOPE, undefined, undefined, { ...cleanArgv }), results);
248
+ }
249
+ catch (err) {
250
+ afterAllErrors.push(err);
251
+ }
252
+ }
253
+ if (pendingError) {
254
+ for (const err of afterAllErrors)
255
+ logger.err(`afterAll failed: ${err.message}`);
256
+ throw pendingError;
257
+ }
258
+ if (afterAllErrors.length > 0) {
259
+ if (singleRunAll)
260
+ throw afterAllErrors[0];
261
+ if (!keepGoing)
262
+ throw new ShowHelpError(`afterAll failed: ${afterAllErrors[0].message}`);
263
+ for (const err of afterAllErrors) {
264
+ failures.push({ action: RUN_SCOPE, error: err.message });
265
+ statuses.push({ action: RUN_SCOPE, status: 'failed' });
266
+ }
112
267
  }
113
268
  if (failures.length > 0) {
114
269
  throw new KeepGoingError(failures, results, statuses);
@@ -50,6 +50,13 @@ export class ShellCommandError extends BaseError {
50
50
  ]);
51
51
  }
52
52
  }
53
+ export class PathMacroResolutionError extends BaseError {
54
+ constructor(file, segment, identifier) {
55
+ super('Template [%s] has a mirrored path segment [%s] with the macro $%s$, which ' +
56
+ 'cannot be resolved from the run locals. Define it in the prompt hook, pass ' +
57
+ 'it as a CLI flag, or export it from the config helpers factory.', [file, segment, identifier]);
58
+ }
59
+ }
53
60
  export class GlobMirrorConflictError extends BaseError {
54
61
  constructor(file) {
55
62
  super('Template [%s] declares both `mirror: true` and `glob:`, which are incompatible: ' +
@@ -62,6 +69,19 @@ export class ConfigTsNodeError extends BaseError {
62
69
  super('TypeScript config [%s] requires ts-node: install it with `npm i -D ts-node` (error: [%s])', [file, cause?.message ?? cause]);
63
70
  }
64
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
+ }
65
85
  export class UnknownTransformError extends BaseError {
66
86
  constructor(name) {
67
87
  super('Unknown transform [%s]: register it under the `transforms` config key', [
@@ -2,21 +2,24 @@ import path from 'path';
2
2
  import fs from 'fs-extra';
3
3
  import { red } from 'chalk';
4
4
  import createResult from './result.js';
5
- const targetPath = (action, actionfolder) => {
5
+ import { resolvePathMacros } from '../path-macros.js';
6
+ const targetPath = (action, args, config) => {
6
7
  const { attributes } = action;
7
8
  if (attributes.to)
8
9
  return attributes.to;
9
10
  if (attributes.mirror !== true || attributes.sh !== undefined || !action.file) {
10
11
  return undefined;
11
12
  }
12
- const rel = path.relative(actionfolder, action.file);
13
- return process.env.HYGEN_MIRROR_EJS_SUFFIX === '1'
13
+ const rel = path.relative(args.actionfolder, action.file);
14
+ const stripped = process.env.HYGEN_MIRROR_EJS_SUFFIX === '1'
14
15
  ? rel.replace(/\.ejs\.t$/, '')
15
16
  : rel.replace(/\.t$/, '');
17
+ return resolvePathMacros(stripped, args, config, action.file);
16
18
  };
17
- const add = async (action, args, { logger, cwd, createPrompter }) => {
19
+ const add = async (action, args, config) => {
20
+ const { logger, cwd, createPrompter } = config;
18
21
  const { attributes: { inject, unless_exists, force, from, skip_if, skipIfExists }, } = action;
19
- const to = targetPath(action, args.actionfolder);
22
+ const to = targetPath(action, args, config);
20
23
  const result = createResult('add', to);
21
24
  const prompter = createPrompter();
22
25
  if (!to || inject) {
@@ -0,0 +1,24 @@
1
+ import path from 'path';
2
+ import { PathMacroResolutionError } from './errors.js';
3
+ import context from './context.js';
4
+ const MACRO_PATTERN = /\$([A-Za-z_][A-Za-z0-9_]*)\$/g;
5
+ const macroDictionary = (args, config) => {
6
+ const ctx = context(args, config);
7
+ return { ...ctx, ...ctx.h };
8
+ };
9
+ const resolvePathMacros = (rel, args, config, file) => {
10
+ if (!rel.includes('$'))
11
+ return rel;
12
+ const dict = macroDictionary(args, config);
13
+ return rel
14
+ .split(path.sep)
15
+ .map((segment) => segment.replace(MACRO_PATTERN, (_match, identifier) => {
16
+ const value = dict[identifier];
17
+ if (value === undefined || value === null) {
18
+ throw new PathMacroResolutionError(file, segment, identifier);
19
+ }
20
+ return String(value);
21
+ }))
22
+ .join(path.sep);
23
+ };
24
+ export { resolvePathMacros };
@@ -2,35 +2,109 @@ 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
+ return resolved.instance.prompt({
104
+ prompter,
105
+ args,
106
+ h: resolved.kind === 'class' ? options.h ?? helpers : helpers,
107
+ });
34
108
  };
35
109
  const answerValue = (answer, name) => {
36
110
  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',
@@ -27,12 +27,21 @@ export declare class TemplateConfigError extends BaseError {
27
27
  export declare class ShellCommandError extends BaseError {
28
28
  constructor(command: string, cause: unknown);
29
29
  }
30
+ export declare class PathMacroResolutionError extends BaseError {
31
+ constructor(file: string, segment: string, identifier: string);
32
+ }
30
33
  export declare class GlobMirrorConflictError extends BaseError {
31
34
  constructor(file: string);
32
35
  }
33
36
  export declare class ConfigTsNodeError extends BaseError {
34
37
  constructor(file: string, cause: unknown);
35
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
+ }
36
45
  export declare class UnknownTransformError extends BaseError {
37
46
  constructor(name: string);
38
47
  }
@@ -1,3 +1,3 @@
1
1
  import type { ActionResult, RenderedAction, RunnerConfig } from '../types';
2
- declare const add: (action: RenderedAction, args: Record<string, any>, { logger, cwd, createPrompter }: RunnerConfig) => Promise<ActionResult>;
2
+ declare const add: (action: RenderedAction, args: Record<string, any>, config: RunnerConfig) => Promise<ActionResult>;
3
3
  export default add;
@@ -0,0 +1,3 @@
1
+ import type { RunnerConfig } from './types';
2
+ declare const resolvePathMacros: (rel: string, args: Record<string, any>, config: RunnerConfig, file: string) => string;
3
+ export { resolvePathMacros };
@@ -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;
17
+ cache?: HookCache;
18
+ }) => Promise<T | object>;
3
19
  export interface PickResult {
4
20
  generator: string;
5
21
  action: string;
@@ -28,9 +28,35 @@ export interface RenderedAction {
28
28
  skip?: true | string;
29
29
  }
30
30
  export type Helper = (...args: unknown[]) => unknown;
31
- export type Helpers = Record<string, Helper>;
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.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "The scalable code generator that saves you time. Fork of jondot/hygen",
5
5
  "keywords": [
6
6
  "template",
@@ -38,7 +38,25 @@
38
38
  "README.md",
39
39
  "LICENSE"
40
40
  ],
41
+ "scripts": {
42
+ "clean": "cleanup dist",
43
+ "build:cjs": "npx tsc -p ./tsconfig.build.cjs.json",
44
+ "build:esm": "npx tsc -p ./tsconfig.build.esm.json",
45
+ "build:types": "npx tsc -p ./tsconfig.build.types.json",
46
+ "build": "pnpm run clean && pnpm run build:cjs && pnpm run build:esm && pnpm run build:types",
47
+ "docs": "node .scripts/build-hygen-docs.js",
48
+ "demo": "pnpm run docs",
49
+ "postbuild:cjs": "node ../../../.scripts/write-package-type.js dist/cjs commonjs && cp -r src/templates dist/cjs/templates",
50
+ "postbuild:esm": "tsc-esm-fix --tsconfig=./tsconfig.build.esm.json --target=./dist/esm && node ../../../.scripts/write-package-type.js dist/esm module && cp -r src/templates dist/esm/templates",
51
+ "format": "prettier --check src",
52
+ "lint": "eslint src --ext .ts",
53
+ "format:fix": "prettier --write src",
54
+ "lint:fix": "eslint src --ext .ts --fix",
55
+ "test": "npx vitest run --coverage",
56
+ "prepublishOnly": "pnpm run build"
57
+ },
41
58
  "dependencies": {
59
+ "@biorate/errors": "3.1.2",
42
60
  "chalk": "4.1.2",
43
61
  "change-case": "3.1.0",
44
62
  "debug": "4.3.3",
@@ -52,8 +70,7 @@
52
70
  "ignore-walk": "4.0.1",
53
71
  "inflection": "1.12.0",
54
72
  "ora": "5.4.1",
55
- "yargs-parser": "21.0.0",
56
- "@biorate/errors": "3.1.2"
73
+ "yargs-parser": "21.0.0"
57
74
  },
58
75
  "devDependencies": {
59
76
  "@types/debug": "4.1.7",
@@ -63,20 +80,5 @@
63
80
  "@types/inflection": "1.13.0",
64
81
  "@types/yargs-parser": "21.0.3"
65
82
  },
66
- "scripts": {
67
- "clean": "cleanup dist",
68
- "build:cjs": "npx tsc -p ./tsconfig.build.cjs.json",
69
- "build:esm": "npx tsc -p ./tsconfig.build.esm.json",
70
- "build:types": "npx tsc -p ./tsconfig.build.types.json",
71
- "build": "pnpm run clean && pnpm run build:cjs && pnpm run build:esm && pnpm run build:types",
72
- "docs": "node .scripts/build-hygen-docs.js",
73
- "demo": "pnpm run docs",
74
- "postbuild:cjs": "node ../../../.scripts/write-package-type.js dist/cjs commonjs && cp -r src/templates dist/cjs/templates",
75
- "postbuild:esm": "tsc-esm-fix --tsconfig=./tsconfig.build.esm.json --target=./dist/esm && node ../../../.scripts/write-package-type.js dist/esm module && cp -r src/templates dist/esm/templates",
76
- "format": "prettier --check src",
77
- "lint": "eslint src --ext .ts",
78
- "format:fix": "prettier --write src",
79
- "lint:fix": "eslint src --ext .ts --fix",
80
- "test": "npx vitest run --coverage"
81
- }
82
- }
83
+ "gitHead": "d73673a1ec66c0aa22f95373b958ea5c98adbfa4"
84
+ }