@biorate/hygen 0.0.0-stage → 0.2.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.
Files changed (104) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +146 -2
  3. package/dist/cjs/bin.js +26 -0
  4. package/dist/cjs/index.js +17 -0
  5. package/dist/cjs/package.json +3 -0
  6. package/dist/cjs/src/cli-help.js +19 -0
  7. package/dist/cjs/src/config-resolver.js +66 -0
  8. package/dist/cjs/src/config.js +37 -0
  9. package/dist/cjs/src/context.js +37 -0
  10. package/dist/cjs/src/engine.js +149 -0
  11. package/dist/cjs/src/errors.js +116 -0
  12. package/dist/cjs/src/execute.js +48 -0
  13. package/dist/cjs/src/help.js +89 -0
  14. package/dist/cjs/src/helpers.js +24 -0
  15. package/dist/cjs/src/index.js +42 -0
  16. package/dist/cjs/src/logger.js +28 -0
  17. package/dist/cjs/src/newline.js +13 -0
  18. package/dist/cjs/src/ops/add.js +74 -0
  19. package/dist/cjs/src/ops/anchors.js +45 -0
  20. package/dist/cjs/src/ops/echo.js +17 -0
  21. package/dist/cjs/src/ops/index.js +51 -0
  22. package/dist/cjs/src/ops/inject.js +37 -0
  23. package/dist/cjs/src/ops/injector.js +49 -0
  24. package/dist/cjs/src/ops/result.js +9 -0
  25. package/dist/cjs/src/ops/setup.js +52 -0
  26. package/dist/cjs/src/ops/shell.js +38 -0
  27. package/dist/cjs/src/params.js +77 -0
  28. package/dist/cjs/src/path-macros.js +30 -0
  29. package/dist/cjs/src/prompt.js +111 -0
  30. package/dist/cjs/src/render.js +189 -0
  31. package/dist/cjs/src/runner.js +38 -0
  32. package/dist/cjs/src/types.js +2 -0
  33. package/dist/cjs/templates/init/repo/new-repo.ejs.t +4 -0
  34. package/dist/cjs/templates/init/self/new-generator-help.ejs.t +8 -0
  35. package/dist/cjs/templates/init/self/new-generator-with-prompt.ejs.t +21 -0
  36. package/dist/cjs/templates/init/self/new-generator-with-prompt.prompt.ejs.t +17 -0
  37. package/dist/cjs/templates/init/self/new-generator.ejs.t +21 -0
  38. package/dist/cjs/templates/init/self/new-repo.ejs.t +7 -0
  39. package/dist/esm/bin.js +21 -0
  40. package/dist/esm/index.js +1 -0
  41. package/dist/esm/package.json +3 -0
  42. package/dist/esm/src/cli-help.js +14 -0
  43. package/dist/esm/src/config-resolver.js +37 -0
  44. package/dist/esm/src/config.js +29 -0
  45. package/dist/esm/src/context.js +32 -0
  46. package/dist/esm/src/engine.js +118 -0
  47. package/dist/esm/src/errors.js +98 -0
  48. package/dist/esm/src/execute.js +41 -0
  49. package/dist/esm/src/help.js +78 -0
  50. package/dist/esm/src/helpers.js +19 -0
  51. package/dist/esm/src/index.js +6 -0
  52. package/dist/esm/src/logger.js +23 -0
  53. package/dist/esm/src/newline.js +11 -0
  54. package/dist/esm/src/ops/add.js +69 -0
  55. package/dist/esm/src/ops/anchors.js +41 -0
  56. package/dist/esm/src/ops/echo.js +12 -0
  57. package/dist/esm/src/ops/index.js +26 -0
  58. package/dist/esm/src/ops/inject.js +32 -0
  59. package/dist/esm/src/ops/injector.js +44 -0
  60. package/dist/esm/src/ops/result.js +7 -0
  61. package/dist/esm/src/ops/setup.js +47 -0
  62. package/dist/esm/src/ops/shell.js +33 -0
  63. package/dist/esm/src/params.js +71 -0
  64. package/dist/esm/src/path-macros.js +24 -0
  65. package/dist/esm/src/prompt.js +81 -0
  66. package/dist/esm/src/render.js +182 -0
  67. package/dist/esm/src/runner.js +32 -0
  68. package/dist/esm/src/types.js +1 -0
  69. package/dist/esm/templates/init/repo/new-repo.ejs.t +4 -0
  70. package/dist/esm/templates/init/self/new-generator-help.ejs.t +8 -0
  71. package/dist/esm/templates/init/self/new-generator-with-prompt.ejs.t +21 -0
  72. package/dist/esm/templates/init/self/new-generator-with-prompt.prompt.ejs.t +17 -0
  73. package/dist/esm/templates/init/self/new-generator.ejs.t +21 -0
  74. package/dist/esm/templates/init/self/new-repo.ejs.t +7 -0
  75. package/dist/types/bin.d.ts +2 -0
  76. package/dist/types/index.d.ts +1 -0
  77. package/dist/types/src/cli-help.d.ts +3 -0
  78. package/dist/types/src/config-resolver.d.ts +4 -0
  79. package/dist/types/src/config.d.ts +14 -0
  80. package/dist/types/src/context.d.ts +12 -0
  81. package/dist/types/src/engine.d.ts +6 -0
  82. package/dist/types/src/errors.d.ts +50 -0
  83. package/dist/types/src/execute.d.ts +5 -0
  84. package/dist/types/src/help.d.ts +8 -0
  85. package/dist/types/src/helpers.d.ts +22 -0
  86. package/dist/types/src/index.d.ts +6 -0
  87. package/dist/types/src/logger.d.ts +10 -0
  88. package/dist/types/src/newline.d.ts +2 -0
  89. package/dist/types/src/ops/add.d.ts +3 -0
  90. package/dist/types/src/ops/anchors.d.ts +4 -0
  91. package/dist/types/src/ops/echo.d.ts +3 -0
  92. package/dist/types/src/ops/index.d.ts +4 -0
  93. package/dist/types/src/ops/inject.d.ts +3 -0
  94. package/dist/types/src/ops/injector.d.ts +3 -0
  95. package/dist/types/src/ops/result.d.ts +3 -0
  96. package/dist/types/src/ops/setup.d.ts +3 -0
  97. package/dist/types/src/ops/shell.d.ts +3 -0
  98. package/dist/types/src/params.d.ts +4 -0
  99. package/dist/types/src/path-macros.d.ts +3 -0
  100. package/dist/types/src/prompt.d.ts +8 -0
  101. package/dist/types/src/render.d.ts +2 -0
  102. package/dist/types/src/runner.d.ts +3 -0
  103. package/dist/types/src/types.d.ts +94 -0
  104. package/package.json +82 -4
package/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-present Leonid Levkin (llevkin).
4
+ Copyright (c) 2018-present, Dotan Nahum.
5
+
6
+ Based on Hygen (https://github.com/jondot/hygen), MIT licensed.
7
+ Modified and maintained by the biorate project.
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # @biorate/hygen
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The scalable code generator that lives in your project. A fork of [jondot/hygen](https://github.com/jondot/hygen) (v6.2.11, MIT), adapted to the `@biorate/*` monorepo conventions.
4
+
5
+ ## Features
6
+
7
+ - **CLI** — a project-local `hygen` binary driven by `GENERATOR ACTION` pairs, with `--version` / `-v`, `--dry` run, and `--help`.
8
+ - **EJS templates with YAML frontmatter** — template metadata lives in a `---` frontmatter block; both the frontmatter and the body are rendered by the same EJS engine, so `to:` paths, values and content can all be interpolated.
9
+ - **Add / inject / shell** — three operation families: `add` (the default, writes new files via `to:`), `inject` (inserts into an existing file), and `sh` (runs a shell command after generation).
10
+ - **Inject family** — anchor injection (`before`, `after`, `prepend`, `append`, `at_line`), guarded by `skip_if` / `skip_if_not`; create a missing target with `create_if_missing`, or replace the first anchor match with `replace`.
11
+ - **Interactive prompts** — `prompt.js` hooks (enquirer) gather values before rendering.
12
+ - **Case helpers** — `h.changeCase.*` and `h.inflection.*` transform names and strings inside templates.
13
+ - **Embeddable `runner()` API** — use it as a library with custom templates, logger, prompter and shell executor (see [Embedding API](#embedding-api)).
14
+ - **Identity escaping** — `<%= %>` does not HTML-escape (the EJS `escape` option is the identity), because the tool generates code, not HTML.
15
+ - **BaseError-based errors** — every failure is a `BaseError`-derived class from `src/errors.ts`, following the monorepo error standard.
16
+ - **`--version` flag** — `hygen --version` (or `-v`) prints `Hygen v<version>` and exits without running a generator.
17
+
18
+ ## Installation
19
+
20
+ For the CLI, install globally (or run without installing):
21
+
22
+ ```bash
23
+ npm i -g @biorate/hygen
24
+ # or without installing
25
+ npx @biorate/hygen ...
26
+ ```
27
+
28
+ For embedding in your own project:
29
+
30
+ ```bash
31
+ pnpm add @biorate/hygen
32
+ ```
33
+
34
+ ## Quick start
35
+
36
+ Initialize `hygen` in your project (once) and create a generator:
37
+
38
+ ```bash
39
+ cd your-project
40
+ hygen init self
41
+ # added: _templates/generator/with-prompt/hello.ejs.t
42
+ # added: _templates/generator/with-prompt/prompt.js
43
+ # added: _templates/generator/new/hello.ejs.t
44
+
45
+ hygen generator new mygen
46
+ # added: _templates/mygen/new/hello.ejs.t
47
+
48
+ hygen mygen new
49
+ # added: app/hello.js
50
+ ```
51
+
52
+ Templates live in the project-local `_templates` folder — check it into your project. The folder structure maps to the command structure: `hygen worker new` renders everything in `_templates/worker/new/`.
53
+
54
+ With an interactive prompt:
55
+
56
+ ```bash
57
+ hygen generator with-prompt mygen
58
+ hygen mygen with-prompt
59
+ ```
60
+
61
+ ## Embedding API
62
+
63
+ `runner(argv, config)` runs the full pipeline programmatically and returns a `RunnerResult` whose `success` flag tells you whether the run went through. It takes the same `GENERATOR ACTION` argv as the CLI plus a minimal `RunnerConfig`:
64
+
65
+ ```ts
66
+ import { runner } from '@biorate/hygen';
67
+ import * as path from 'path';
68
+
69
+ async function main() {
70
+ const result = await runner(process.argv.slice(2), {
71
+ cwd: process.cwd(),
72
+ templates: path.join(process.cwd(), 'templates'),
73
+ logger: {
74
+ ok: (msg: string) => console.log(msg),
75
+ notice: (msg: string) => console.log(msg),
76
+ warn: (msg: string) => console.warn(msg),
77
+ err: (msg: string) => console.error(msg),
78
+ log: (msg: string) => console.log(msg),
79
+ colorful: (msg: string) => console.log(msg),
80
+ },
81
+ // Provide a factory that returns a prompter with a `prompt` method.
82
+ createPrompter: <Q, T>() => ({
83
+ prompt: async (_arg0: Q) => ({} as T),
84
+ }),
85
+ // Run shell (`sh:`) commands produced by templates.
86
+ exec: (sh: string, body: string) => {
87
+ void sh;
88
+ void body;
89
+ },
90
+ });
91
+
92
+ if (!result.success) {
93
+ console.error(result.failure?.message);
94
+ process.exit(1);
95
+ }
96
+ }
97
+
98
+ void main();
99
+ ```
100
+
101
+ `RunnerConfig` requires `cwd`, `logger` (a `Logger`-shaped object), `createPrompter`, and `exec`. Everything else — `templates`, `templatesOverride`, `helpers`, `localsDefaults`, `debug` — is optional. The result (`RunnerResult`) exposes `success`, `time`, `actions`, and a `failure` block when the run fails.
102
+
103
+ For the full API reference see the [typedoc](https://biorate.github.io/core/modules/hygen.html), and the user guide under [Documentation](#documentation).
104
+
105
+ ## Documentation
106
+
107
+ The complete user guide lives in the package's local `docs/` pages. README is for the overview, quick start, and embedding; `docs/` is the full guide; typedoc is the generated API reference.
108
+
109
+ | Page | Contents |
110
+ | ---------------------------------------- | ------------------------------------------------------------------------------------------------ |
111
+ | [quick-start](./docs/quick-start.md) | CLI installation, `init`, generator creation, `--version`. |
112
+ | [templates](./docs/templates.md) | Template & frontmatter reference: `add`, `inject`, `sh`, anchors, `replace`, escaping. |
113
+ | [generators](./docs/generators.md) | Building and organizing reusable generators. |
114
+ | [prompts](./docs/prompts.md) | Prompt hooks reference: file names, `params`/`prompt`/array forms, filtering, TS. |
115
+ | [extensibility](./docs/extensibility.md) | Extending hygen via the project config file: helpers, logger, template location, shell executor. |
116
+ | [packages](./docs/packages.md) | Sharing compiled generators as publishable packages (`hygen-add`). |
117
+ | [create](./docs/create.md) | Turning existing code into a generator (`hygen-create`). |
118
+ | [faq](./docs/faq.md) | Why hygen and its position among generator toolkits. |
119
+ | [express](./docs/express.md) | Express.js app generation pattern. |
120
+ | [redux](./docs/redux.md) | Redux (ducks) app generation pattern. |
121
+ | [react-native](./docs/react-native.md) | React Native app generation pattern. |
122
+ | [standalone](./docs/standalone.md) | Standalone binary distribution. |
123
+
124
+ ## Differences from upstream
125
+
126
+ - **Identity escaping** — `<%= %>` does not HTML-escape: the EJS `escape` option is set to the identity (`(s) => s`), since the tool generates code, not HTML. `<%- %>` semantics are unchanged.
127
+ - **`--version` flag** — `hygen --version` / `hygen -v` prints `Hygen v<version>` and exits without running any generator.
128
+ - **Anchor-not-found error** — when an `inject` `before`/`after` anchor cannot be found, the injection fails with `InjectionAnchorNotFoundError` instead of silently no-oping.
129
+ - **New inject options** — `create_if_missing: true` creates a missing target before injecting; `replace: true` replaces the first `before`/`after` anchor match with the body (mutually exclusive with `inject`); `skip_if_not: true` inverts the `skip_if` guard. Upstream treats these as plain template variables.
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
+ - **`--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
+ - **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).
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).
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).
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).
137
+ - **Error classes** — errors follow the monorepo standard: `BaseError`-derived classes (`src/errors.ts`) instead of raw `Error`.
138
+ - **Strict TypeScript / Vitest** — the package is authored in strict TypeScript; the Jest tests were migrated to Vitest; metaverse tests are not included.
139
+ - **Distribution** — the CLI binary ships compiled templates (`dist/cjs/templates`); Homebrew/standalone binaries are not built.
140
+
141
+ > Note: templates are code — EJS renders arbitrary expressions, so only use templates from repositories you trust.
142
+
143
+ ## License
144
+
145
+ [MIT](https://github.com/biorate/core/blob/master/packages/%40biorate/hygen/LICENSE)
146
+
147
+ This is a fork of [jondot/hygen](https://github.com/jondot/hygen) (v6.2.11, MIT). Original work © Dotan Nahum; the upstream copyright line is preserved in the `LICENSE` file. Fork adaptations © Leonid Levkin.
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const path_1 = __importDefault(require("path"));
8
+ const logger_1 = __importDefault(require("./src/logger"));
9
+ const help_1 = require("./src/help");
10
+ const index_1 = require("./index");
11
+ const defaultTemplates = path_1.default.join(__dirname, 'templates');
12
+ if ((0, help_1.isVersionFlag)(process.argv.slice(2))) {
13
+ console.log(`Hygen v${help_1.VERSION}`);
14
+ process.exit(0);
15
+ }
16
+ (0, index_1.runner)(process.argv.slice(2), {
17
+ templates: defaultTemplates,
18
+ cwd: process.cwd(),
19
+ logger: new logger_1.default(console.log.bind(console)),
20
+ debug: !!process.env.DEBUG,
21
+ exec: (action, body) => {
22
+ const opts = body && body.length > 0 ? { input: body } : {};
23
+ return require('execa').command(action, { ...opts, shell: true });
24
+ },
25
+ createPrompter: () => require('enquirer'),
26
+ }).then(({ success }) => process.exit(success ? 0 : 1));
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./src"), exports);
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.printUsage = exports.isHelpFlag = void 0;
4
+ const USAGE = `
5
+ Usage:
6
+ hygen [option] GENERATOR ACTION[,ACTION...] [NAME[,NAME...]] [data-options]
7
+
8
+ Options:
9
+ -h, --help # Show this message and quit
10
+ --dry # Perform a dry run. Files will be generated but not saved.
11
+ --keep-going # Continue after a failed action, reporting every failure.
12
+ HYGEN_LEGACY_NAME=1 # Re-enable the removed --name flag (legacy escape).`;
13
+ const isHelpFlag = (argv) => ['-h', '--help'].includes(argv[0]);
14
+ exports.isHelpFlag = isHelpFlag;
15
+ const printUsage = (logger) => {
16
+ logger.log(USAGE);
17
+ process.exit(0);
18
+ };
19
+ exports.printUsage = printUsage;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.CONFIG_FILES = void 0;
30
+ const path_1 = __importDefault(require("path"));
31
+ const fs_extra_1 = __importDefault(require("fs-extra"));
32
+ const config_1 = require("./config");
33
+ const errors_1 = require("./errors");
34
+ exports.CONFIG_FILES = ['.hygen.js', '.hygen.cjs', '.hygen.mjs', '.hygen.ts'];
35
+ const configResolver = new config_1.ConfigResolver(exports.CONFIG_FILES, {
36
+ exists: (f) => fs_extra_1.default.pathExists(f),
37
+ load: async (f) => {
38
+ if (/\.ts$/.test(f)) {
39
+ try {
40
+ await Promise.resolve().then(() => __importStar(require('ts-node/register/transpile-only')));
41
+ }
42
+ catch (cause) {
43
+ throw new errors_1.ConfigTsNodeError(f, cause);
44
+ }
45
+ }
46
+ return await Promise.resolve(`${f}`).then(s => __importStar(require(s)));
47
+ },
48
+ none: (_) => ({}),
49
+ });
50
+ const resolve = (cwd, defaultTemplates, templatesOverride) => {
51
+ return [
52
+ templatesOverride && path_1.default.resolve(cwd, templatesOverride),
53
+ process.env.HYGEN_TMPLS,
54
+ path_1.default.resolve(cwd, '_templates'),
55
+ defaultTemplates && path_1.default.resolve(cwd, defaultTemplates),
56
+ ].find((_) => _ && fs_extra_1.default.existsSync(_));
57
+ };
58
+ exports.default = async (config) => {
59
+ const { cwd, templates: defaultTemplates, templatesOverride } = config;
60
+ const resolvedTemplates = resolve(cwd, defaultTemplates, templatesOverride);
61
+ return {
62
+ ...config,
63
+ templates: resolvedTemplates,
64
+ ...(await configResolver.resolve(cwd)),
65
+ };
66
+ };
@@ -0,0 +1,37 @@
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.reversePathsToWalk = exports.ConfigResolver = exports.configLookup = void 0;
7
+ const path_1 = __importDefault(require("path"));
8
+ const uniq = (arr) => arr.filter((elem, pos, a) => a.indexOf(elem) === pos);
9
+ const reversePathsToWalk = ({ folder, path, }) => {
10
+ const resolved = path.resolve(folder);
11
+ const parts = resolved.split(path.sep);
12
+ const results = parts.map((_, idx, arr) => arr.slice(0, idx + 1).join(path.sep));
13
+ results[0] = results[0] || '/';
14
+ return results.reverse();
15
+ };
16
+ exports.reversePathsToWalk = reversePathsToWalk;
17
+ const configLookup = (file, folder, path = path_1.default) => uniq(reversePathsToWalk({ folder, path }).map((p) => path.join(p, file)));
18
+ exports.configLookup = configLookup;
19
+ class ConfigResolver {
20
+ constructor(configFiles, io) {
21
+ this.configFiles = configFiles;
22
+ this.io = io;
23
+ }
24
+ async resolve(from) {
25
+ const { exists, load, none } = this.io;
26
+ for (const dir of reversePathsToWalk({ folder: from, path: path_1.default })) {
27
+ for (const file of this.configFiles) {
28
+ const candidate = path_1.default.join(dir, file);
29
+ if (await exists(candidate)) {
30
+ return load(candidate);
31
+ }
32
+ }
33
+ }
34
+ return none(from);
35
+ }
36
+ }
37
+ exports.ConfigResolver = ConfigResolver;
@@ -0,0 +1,37 @@
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
+ const helpers_1 = __importDefault(require("./helpers"));
7
+ const localsToCapitalize = ['name'];
8
+ const localsToPluralize = ['name'];
9
+ const localsDefaults = {
10
+ name: 'unnamed',
11
+ };
12
+ const processLocals = (hsh, [key, value]) => {
13
+ hsh[key] = value;
14
+ if (localsToCapitalize.includes(key)) {
15
+ hsh[helpers_1.default.capitalize(key)] = helpers_1.default.capitalize(value);
16
+ }
17
+ if (localsToPluralize.includes(key)) {
18
+ hsh[helpers_1.default.inflection.pluralize(key)] = helpers_1.default.inflection.pluralize(value);
19
+ hsh[helpers_1.default.capitalize(helpers_1.default.inflection.pluralize(key))] = helpers_1.default.capitalize(helpers_1.default.inflection.pluralize(value));
20
+ }
21
+ return hsh;
22
+ };
23
+ const processedLocals = (locals) => Object.entries(locals).reduce(processLocals, {});
24
+ const context = (locals, config = {}) => {
25
+ const localsWithDefaults = {
26
+ ...localsDefaults,
27
+ ...config.localsDefaults,
28
+ ...locals,
29
+ };
30
+ const configHelpers = typeof config.helpers === 'function'
31
+ ? config.helpers(locals, config)
32
+ : config.helpers ?? {};
33
+ return Object.assign(localsWithDefaults, processedLocals(localsWithDefaults), {
34
+ h: { ...helpers_1.default, ...configHelpers },
35
+ });
36
+ };
37
+ exports.default = context;
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.KeepGoingError = exports.ShowHelpError = exports.engine = void 0;
30
+ const path_1 = __importDefault(require("path"));
31
+ const fs_extra_1 = __importDefault(require("fs-extra"));
32
+ const params_1 = __importDefault(require("./params"));
33
+ const prompt_1 = __importStar(require("./prompt"));
34
+ const errors_1 = require("./errors");
35
+ Object.defineProperty(exports, "ShowHelpError", { enumerable: true, get: function () { return errors_1.ShowHelpError; } });
36
+ Object.defineProperty(exports, "KeepGoingError", { enumerable: true, get: function () { return errors_1.KeepGoingError; } });
37
+ const cli_help_1 = require("./cli-help");
38
+ const isInteractive = ({ interactive }) => interactive === true
39
+ ? true
40
+ : interactive === false
41
+ ? false
42
+ : Boolean(process.stdin.isTTY && process.stdout.isTTY);
43
+ const engine = async (argv, config) => {
44
+ const { cwd, templates, logger } = config;
45
+ let base = Object.assign(await (0, params_1.default)(config, argv), { cwd });
46
+ let { generator, actions, names } = base;
47
+ if ((0, cli_help_1.isHelpFlag)(argv)) {
48
+ (0, cli_help_1.printUsage)(logger);
49
+ }
50
+ if (!generator && isInteractive(config) && templates && fs_extra_1.default.pathExistsSync(templates)) {
51
+ const picked = await (0, prompt_1.pickGeneratorAction)(config);
52
+ if (picked) {
53
+ base = Object.assign(await (0, params_1.default)(config, [picked.generator, picked.action, ...argv]), {
54
+ cwd,
55
+ });
56
+ ({ generator, actions, names } = base);
57
+ }
58
+ }
59
+ const cleanArgv = (base.cleanArgv ?? {});
60
+ logger.log(base.dry ? '(dry mode)' : '');
61
+ if (!generator) {
62
+ throw new errors_1.ShowHelpError('please specify a generator.\n\nTip: running `hygen` with no arguments in a terminal opens an interactive generator/action picker (requires a TTY).');
63
+ }
64
+ if (!actions || actions.length === 0) {
65
+ throw new errors_1.ShowHelpError(`please specify an action for ${generator}.`);
66
+ }
67
+ logger.log(`Loaded templates: ${templates.replace(`${cwd}/`, '')}`);
68
+ const nameList = names ?? [undefined];
69
+ const keepGoing = Boolean(cleanArgv['keep-going']);
70
+ const failures = [];
71
+ const results = [];
72
+ const statuses = [];
73
+ const execute = (await Promise.resolve().then(() => __importStar(require('./execute')))).execute;
74
+ 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}'.
87
+
88
+ You can try:
89
+ 1. 'hygen init self' to initialize your project, and
90
+ 2. 'hygen generator new ${generator}' to build the generator you wanted.
91
+
92
+ Check out the quickstart for more: http://www.hygen.io/docs/quick-start
93
+ `);
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, {
108
+ ...(name ? { name } : {}),
109
+ ...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
+ });
125
+ }
126
+ statuses.push(...el.statuses);
127
+ }
128
+ 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' });
141
+ }
142
+ }
143
+ }
144
+ if (failures.length > 0) {
145
+ throw new errors_1.KeepGoingError(failures, results, statuses);
146
+ }
147
+ return Object.assign(results, { statuses });
148
+ };
149
+ exports.engine = engine;
@@ -0,0 +1,116 @@
1
+ "use strict";
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;
4
+ const errors_1 = require("@biorate/errors");
5
+ class ShowHelpError extends errors_1.BaseError {
6
+ constructor(message) {
7
+ super('%s', [message]);
8
+ }
9
+ }
10
+ exports.ShowHelpError = ShowHelpError;
11
+ class KeepGoingError extends ShowHelpError {
12
+ constructor(failures, results, statuses = []) {
13
+ super(`the run failed for ${failures.length} pair(s):\n${failures
14
+ .map((f) => `action '${f.action}'${f.name !== undefined ? ` for name '${f.name}'` : ''}: ${f.error}`)
15
+ .join('\n')}`);
16
+ this.results = results;
17
+ this.failures = failures;
18
+ this.statuses = statuses;
19
+ }
20
+ }
21
+ exports.KeepGoingError = KeepGoingError;
22
+ class TemplateRenderError extends errors_1.BaseError {
23
+ constructor(file, cause) {
24
+ super('Template render error in [%s]: [%s]', [
25
+ file,
26
+ cause?.message ?? cause,
27
+ ]);
28
+ }
29
+ }
30
+ exports.TemplateRenderError = TemplateRenderError;
31
+ class TemplateNotFoundError extends errors_1.BaseError {
32
+ constructor(generator, action) {
33
+ super(`I can't find action [%s] for generator [%s]`, [action, generator]);
34
+ }
35
+ }
36
+ exports.TemplateNotFoundError = TemplateNotFoundError;
37
+ class InjectionTargetNotFoundError extends errors_1.BaseError {
38
+ constructor(to) {
39
+ super('Cannot inject to [%s]: file does not exist', [to]);
40
+ }
41
+ }
42
+ exports.InjectionTargetNotFoundError = InjectionTargetNotFoundError;
43
+ class InjectionAnchorNotFoundError extends errors_1.BaseError {
44
+ constructor(anchor, to) {
45
+ super('Injection anchor [%s] not found in [%s]', [anchor, to]);
46
+ }
47
+ }
48
+ exports.InjectionAnchorNotFoundError = InjectionAnchorNotFoundError;
49
+ class TemplateConfigError extends errors_1.BaseError {
50
+ constructor(message) {
51
+ super('%s', [message]);
52
+ }
53
+ }
54
+ exports.TemplateConfigError = TemplateConfigError;
55
+ class ShellCommandError extends errors_1.BaseError {
56
+ constructor(command, cause) {
57
+ super('Shell command [%s] failed: [%s]', [
58
+ command,
59
+ cause?.message ?? cause,
60
+ ]);
61
+ }
62
+ }
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;
72
+ class GlobMirrorConflictError extends errors_1.BaseError {
73
+ constructor(file) {
74
+ super('Template [%s] declares both `mirror: true` and `glob:`, which are incompatible: ' +
75
+ "mirroring derives a target path from the template's own name, but a glob " +
76
+ 'expands into multiple files. Remove one of the two attributes.', [file]);
77
+ }
78
+ }
79
+ exports.GlobMirrorConflictError = GlobMirrorConflictError;
80
+ class ConfigTsNodeError extends errors_1.BaseError {
81
+ constructor(file, cause) {
82
+ super('TypeScript config [%s] requires ts-node: install it with `npm i -D ts-node` (error: [%s])', [file, cause?.message ?? cause]);
83
+ }
84
+ }
85
+ exports.ConfigTsNodeError = ConfigTsNodeError;
86
+ class UnknownTransformError extends errors_1.BaseError {
87
+ constructor(name) {
88
+ super('Unknown transform [%s]: register it under the `transforms` config key', [
89
+ name,
90
+ ]);
91
+ }
92
+ }
93
+ exports.UnknownTransformError = UnknownTransformError;
94
+ class SetupRepositoryError extends errors_1.BaseError {
95
+ constructor(setup) {
96
+ super('[%s] must be a repo', [setup]);
97
+ }
98
+ }
99
+ exports.SetupRepositoryError = SetupRepositoryError;
100
+ class CliArgumentError extends errors_1.BaseError {
101
+ constructor(message) {
102
+ super('%s', [message]);
103
+ }
104
+ }
105
+ exports.CliArgumentError = CliArgumentError;
106
+ class NameFlagRemovedError extends errors_1.BaseError {
107
+ constructor(name) {
108
+ const shown = Array.isArray(name) ? name.join(', ') : String(name);
109
+ super(`the '--name' flag is no longer supported (received '--name %s'). ` +
110
+ `Pass the name as a positional argument instead: ` +
111
+ `hygen <generator> <action[,action...]> <name[,name...]> (e.g. 'hygen mailer new fancy'). ` +
112
+ `To keep using '--name' during migration, enable the legacy escape: ` +
113
+ `set HYGEN_LEGACY_NAME=1, or pass legacyNameFlag: true in the RunnerConfig.`, [shown]);
114
+ }
115
+ }
116
+ exports.NameFlagRemovedError = NameFlagRemovedError;