stonyx 0.2.3-alpha.6 → 0.2.3-alpha.60

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 (69) hide show
  1. package/README.md +6 -3
  2. package/config/{environment.js → environment copy.ts } +16 -12
  3. package/dist/cli/help.d.ts +8 -0
  4. package/dist/cli/help.js +43 -0
  5. package/dist/cli/load-commands.d.ts +10 -0
  6. package/dist/cli/load-commands.js +49 -0
  7. package/dist/cli/new.d.ts +72 -0
  8. package/dist/cli/new.js +426 -0
  9. package/dist/cli/serve.d.ts +6 -0
  10. package/dist/cli/serve.js +49 -0
  11. package/dist/cli/test-setup.d.ts +1 -0
  12. package/dist/cli/test-setup.js +30 -0
  13. package/dist/cli/test.d.ts +4 -0
  14. package/dist/cli/test.js +23 -0
  15. package/dist/cli.d.ts +2 -0
  16. package/dist/cli.js +53 -0
  17. package/dist/exports/config.d.ts +2 -0
  18. package/dist/exports/config.js +2 -0
  19. package/dist/exports/log.d.ts +2 -0
  20. package/{src → dist}/exports/log.js +1 -2
  21. package/dist/exports/test-helpers.d.ts +5 -0
  22. package/dist/exports/test-helpers.js +7 -0
  23. package/dist/lifecycle.d.ts +7 -0
  24. package/dist/lifecycle.js +18 -0
  25. package/dist/main.d.ts +22 -0
  26. package/dist/main.js +102 -0
  27. package/dist/modules.d.ts +30 -0
  28. package/dist/modules.js +363 -0
  29. package/dist/util/duplicate-core.d.ts +186 -0
  30. package/dist/util/duplicate-core.js +413 -0
  31. package/dist/util/import-config.d.ts +52 -0
  32. package/dist/util/import-config.js +256 -0
  33. package/dist/util/resolve-entry-point.d.ts +1 -0
  34. package/dist/util/resolve-entry-point.js +14 -0
  35. package/dist/util/resolve-module-name.d.ts +14 -0
  36. package/dist/util/resolve-module-name.js +33 -0
  37. package/package.json +41 -12
  38. package/scripts/postinstall.js +24 -2
  39. package/.claude/index.md +0 -96
  40. package/.github/workflows/ci.yml +0 -16
  41. package/.github/workflows/publish.yml +0 -51
  42. package/docs/api.md +0 -89
  43. package/docs/cli.md +0 -88
  44. package/docs/configuration.md +0 -72
  45. package/docs/conventions/discord-conventions.md +0 -62
  46. package/docs/conventions/framework-modules.md +0 -127
  47. package/docs/conventions/index.md +0 -24
  48. package/docs/conventions/orm-conventions.md +0 -158
  49. package/docs/conventions/project-structure.md +0 -105
  50. package/docs/conventions/rest-conventions.md +0 -96
  51. package/docs/conventions/testing-conventions.md +0 -56
  52. package/docs/developing-modules.md +0 -108
  53. package/docs/index.md +0 -15
  54. package/docs/lifecycle.md +0 -47
  55. package/docs/logging.md +0 -52
  56. package/docs/modules.md +0 -82
  57. package/docs/testing.md +0 -64
  58. package/src/cli/help.js +0 -48
  59. package/src/cli/load-commands.js +0 -56
  60. package/src/cli/new.js +0 -237
  61. package/src/cli/serve.js +0 -38
  62. package/src/cli/test-setup.js +0 -8
  63. package/src/cli/test.js +0 -27
  64. package/src/cli.js +0 -63
  65. package/src/exports/config.js +0 -3
  66. package/src/exports/test-helpers.js +0 -8
  67. package/src/lifecycle.js +0 -17
  68. package/src/main.js +0 -101
  69. package/src/modules.js +0 -112
package/README.md CHANGED
@@ -1,8 +1,11 @@
1
+ [![CI](https://github.com/abofs/stonyx/actions/workflows/ci.yml/badge.svg)](https://github.com/abofs/stonyx/actions/workflows/ci.yml)
2
+ [![npm version](https://img.shields.io/npm/v/stonyx.svg)](https://www.npmjs.com/package/stonyx)
3
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
4
+
1
5
  # Stonyx
2
6
 
3
7
  **Stonyx** is a lightweight, modular framework for building modern Node.js applications. It provides a plug-and-play architecture, centralized color-coded logging, and seamless async module integration.
4
8
 
5
- - 100% JavaScript (ES Modules)
6
9
  - Drop-in module system — no boilerplate
7
10
  - Automatic async module loading and initialization
8
11
  - Built-in CLI for scaffolding, bootstrapping, and testing
@@ -19,12 +22,12 @@ stonyx serve
19
22
  The `new` command walks you through module selection and generates a ready-to-run project. From there, the CLI handles bootstrapping:
20
23
 
21
24
  ```bash
22
- stonyx serve # Bootstrap + run app.js
25
+ stonyx serve # Bootstrap + run app.ts (or app.js)
23
26
  stonyx test # Bootstrap + run tests
24
27
  stonyx help # Show all available commands
25
28
  ```
26
29
 
27
- Stonyx reads `config/environment.js`, initializes all `@stonyx/*` modules from your `devDependencies`, and runs your application.
30
+ Stonyx reads `config/environment.ts` (preferred) or `config/environment.js`, loads the `@stonyx/*` modules declared in your `dependencies` or `devDependencies` (initializing the async ones), and runs your application.
28
31
 
29
32
  ## Documentation
30
33
 
@@ -1,12 +1,16 @@
1
- // project configuration, override-able by listed environment variables
2
- const {
3
- DEBUG,
4
- NODE_ENV,
5
- } = process.env;
6
-
7
- const environment = NODE_ENV ?? 'development';
8
-
9
- export default {
10
- environment,
11
- debug: DEBUG ?? environment === 'development',
12
- }
1
+ import type { StoynxConfig } from 'stonyx';
2
+
3
+ // project configuration, override-able by listed environment variables
4
+ const {
5
+ DEBUG,
6
+ NODE_ENV,
7
+ } = process.env;
8
+
9
+ const environment = NODE_ENV ?? 'development';
10
+
11
+ const config: StoynxConfig = {
12
+ environment,
13
+ debug: DEBUG ?? environment === 'development',
14
+ };
15
+
16
+ export default config;
@@ -0,0 +1,8 @@
1
+ import type { CommandDefinition } from './load-commands.js';
2
+ interface HelpOptions {
3
+ args?: string[];
4
+ builtInCommands?: Record<string, CommandDefinition>;
5
+ loadModuleCommands?: () => Promise<Record<string, CommandDefinition>>;
6
+ }
7
+ export default function help({ args, builtInCommands, loadModuleCommands }?: HelpOptions): Promise<void>;
8
+ export {};
@@ -0,0 +1,43 @@
1
+ export default async function help({ args, builtInCommands, loadModuleCommands } = {}) {
2
+ console.log('\nUsage: stonyx <command> [...args]\n');
3
+ console.log('Commands:\n');
4
+ if (builtInCommands) {
5
+ for (const [name, { description }] of Object.entries(builtInCommands)) {
6
+ console.log(` ${name.padEnd(20)} ${description}`);
7
+ }
8
+ }
9
+ if (loadModuleCommands) {
10
+ try {
11
+ const moduleCommands = await loadModuleCommands();
12
+ const entries = Object.entries(moduleCommands);
13
+ if (entries.length) {
14
+ console.log('\nModule commands:\n');
15
+ for (const [name, { description }] of entries) {
16
+ console.log(` ${name.padEnd(20)} ${description}`);
17
+ }
18
+ }
19
+ }
20
+ catch {
21
+ // Module commands not available (e.g., no project context)
22
+ }
23
+ }
24
+ console.log('\nAliases: s=serve, t=test, n=new, h=help\n');
25
+ console.log('Project conventions:\n');
26
+ console.log(' Entry point: app.ts (or app.js)');
27
+ console.log(' Config: config/environment.ts (or .js)');
28
+ console.log(' DB schema: config/db-schema.js');
29
+ console.log(' Models: models/');
30
+ console.log(' Serializers: serializers/');
31
+ console.log(' Access control: access/');
32
+ console.log(' Transforms: transforms/');
33
+ console.log(' Hooks: hooks/');
34
+ console.log(' REST requests: requests/');
35
+ console.log(' Cron jobs: crons/');
36
+ console.log(' Tests: test/{unit,integration,acceptance}/');
37
+ console.log('');
38
+ console.log(' Logging: import log from \'stonyx/log\' (never console.log)');
39
+ console.log(' Utilities: import from \'@stonyx/utils/*\' (never raw fs)');
40
+ console.log(' Lint config: import from \'@abofs/code-conventions\'');
41
+ console.log(' Package manager: pnpm');
42
+ console.log('');
43
+ }
@@ -0,0 +1,10 @@
1
+ export interface CommandDefinition {
2
+ description: string;
3
+ run: (ctx: {
4
+ args: string[];
5
+ cwd?: string;
6
+ }) => Promise<void>;
7
+ bootstrap?: boolean;
8
+ module?: string;
9
+ }
10
+ export default function loadModuleCommands(): Promise<Record<string, CommandDefinition>>;
@@ -0,0 +1,49 @@
1
+ import { readFile } from 'fs/promises';
2
+ import path from 'path';
3
+ export default async function loadModuleCommands() {
4
+ const cwd = process.cwd();
5
+ const commands = {};
6
+ let projectPackage;
7
+ try {
8
+ const raw = await readFile(path.join(cwd, 'package.json'), 'utf8');
9
+ projectPackage = JSON.parse(raw);
10
+ }
11
+ catch {
12
+ return commands;
13
+ }
14
+ const allDeps = {
15
+ ...projectPackage.dependencies,
16
+ ...projectPackage.devDependencies
17
+ };
18
+ const stonyxModules = Object.keys(allDeps).filter(name => name.startsWith('@stonyx/'));
19
+ for (const moduleName of stonyxModules) {
20
+ let modulePackage;
21
+ try {
22
+ const raw = await readFile(path.join(cwd, 'node_modules', moduleName, 'package.json'), 'utf8');
23
+ modulePackage = JSON.parse(raw);
24
+ }
25
+ catch {
26
+ continue;
27
+ }
28
+ const moduleExports = modulePackage.exports;
29
+ if (!moduleExports || !moduleExports['./commands'])
30
+ continue;
31
+ try {
32
+ const commandsModule = await import(path.join(cwd, 'node_modules', moduleName, moduleExports['./commands']));
33
+ if (!commandsModule.default || typeof commandsModule.default !== 'object')
34
+ continue;
35
+ const moduleCommands = commandsModule.default;
36
+ for (const [name, command] of Object.entries(moduleCommands)) {
37
+ if (commands[name]) {
38
+ console.warn(`Warning: Command "${name}" from ${moduleName} conflicts with existing command. Skipping.`);
39
+ continue;
40
+ }
41
+ commands[name] = { ...command, module: moduleName };
42
+ }
43
+ }
44
+ catch {
45
+ continue;
46
+ }
47
+ }
48
+ return commands;
49
+ }
@@ -0,0 +1,72 @@
1
+ interface ModuleOption {
2
+ question: string;
3
+ package: string;
4
+ dirs?: string[];
5
+ files?: Record<string, () => string>;
6
+ }
7
+ export declare const MODULE_OPTIONS: ModuleOption[];
8
+ export declare function generateDbSchema(): string;
9
+ /**
10
+ * The version of the `stonyx` package running this generator, read from its own
11
+ * `package.json` at call time.
12
+ *
13
+ * Read rather than hardcoded on purpose: a literal would be correct on the day
14
+ * it was written and silently stale on every day after (abofs/stonyx#113).
15
+ */
16
+ export declare function readCoreVersion(): string;
17
+ /**
18
+ * The npm dist-tag naming the release line a version belongs to:
19
+ * `0.2.3-beta.96` -> `beta`, `0.2.3-alpha.4` -> `alpha`, `0.2.2` -> `latest`.
20
+ *
21
+ * Every scaffolded `@stonyx/*` module is requested on the same line as the core
22
+ * that scaffolded it, so the generated project cannot mix a prerelease core with
23
+ * modules from the stable line (or the reverse).
24
+ *
25
+ * Throws, rather than guessing, when the prerelease identifier is not usable as a
26
+ * dist-tag. Returning it verbatim was only safe for *alphabetic* identifiers: npm
27
+ * parses a numeric or wildcard identifier as a version **range**, so `0.2.3-0`
28
+ * emitted `"0"` and `0.2.3-x` emitted `"x"`, both of which install with rc=0 and
29
+ * silently resolve the module's `latest` release -- for `@stonyx/orm` that is
30
+ * `0.3.1`, which pins `stonyx@0.2.3-beta.11` and so reproduces abofs/stonyx#113
31
+ * through a different door, with no error. `0.2.3-0` is reachable from this
32
+ * repo's own `publish.yml` `custom-version` dispatch input, which accepts any
33
+ * semver string and also expands the keyword `prerelease` to `x.y.z-0`.
34
+ *
35
+ * Two bounds remain, both loud rather than silent:
36
+ *
37
+ * - An alphabetic identifier is assumed to also be a published dist-tag name.
38
+ * True for `beta` and `alpha`, the only two lines the fleet publishes; a core
39
+ * released as e.g. `0.2.3-rc.1` with no `rc` dist-tag scaffolds an unresolvable
40
+ * module specifier, which fails `pnpm install` with
41
+ * `ERR_PNPM_NO_MATCHING_VERSION`. The tag has to exist on every package in
42
+ * `MODULE_OPTIONS`, not only on the core.
43
+ * - On the stable line this returns `latest`, the correct tag for that line -- but
44
+ * only useful once the *modules* have advanced their own `latest` tags. Today
45
+ * `@stonyx/orm@latest` is `0.3.1` and pins `stonyx@0.2.3-beta.11`, so the module
46
+ * `latest` tags must advance before the core's does (abofs/stonyx#115).
47
+ */
48
+ export declare function releaseTagFor(version: string): string;
49
+ export declare function generatePackageJson(name: string, selectedModules: ModuleOption[], coreVersion?: string): string;
50
+ export declare function generateAppTs(): string;
51
+ export declare function generateEnvironmentTs(): string;
52
+ export declare function generateTestEnvironmentTs(): string;
53
+ export declare function generateSetupTs(): string;
54
+ export declare function generateZzExitTestTs(): string;
55
+ export declare function generateEnvironmentExampleTs(): string;
56
+ export declare function generateGitignore(): string;
57
+ export declare function generateTsConfig(): string;
58
+ /**
59
+ * Rejects when `pnpm install` fails, either by exiting non-zero or by failing to
60
+ * spawn. Exported so the rejection path is testable without a network round-trip.
61
+ */
62
+ export declare function runPnpmInstall(projectDir: string): Promise<void>;
63
+ /**
64
+ * Write every scaffolded file to disk given a resolved project directory,
65
+ * app name, and pre-selected module options. Factored out of `newCommand`
66
+ * so tests can exercise the file-writing path without interactive prompts.
67
+ */
68
+ export declare function scaffoldProject(projectDir: string, appName: string, selectedModules: ModuleOption[]): Promise<void>;
69
+ export default function newCommand({ args }: {
70
+ args: string[];
71
+ }): Promise<void>;
72
+ export {};
@@ -0,0 +1,426 @@
1
+ import { confirm, prompt } from '@stonyx/utils/prompt';
2
+ import { createFile, createDirectory, copyFile, fileExists } from '@stonyx/utils/file';
3
+ import { spawn } from 'child_process';
4
+ import { readFileSync } from 'fs';
5
+ import path from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ export const MODULE_OPTIONS = [
8
+ {
9
+ question: 'Will this project need a REST server?',
10
+ package: '@stonyx/rest-server',
11
+ dirs: ['requests']
12
+ },
13
+ {
14
+ question: 'Will this project need WebSockets?',
15
+ package: '@stonyx/sockets',
16
+ dirs: ['socket-handlers']
17
+ },
18
+ {
19
+ question: 'Will this project need data management?',
20
+ package: '@stonyx/orm',
21
+ dirs: ['models', 'serializers', 'access', 'transforms', 'hooks'],
22
+ files: { 'config/db-schema.ts': generateDbSchema }
23
+ },
24
+ {
25
+ question: 'Will this project need scheduled tasks (cron)?',
26
+ package: '@stonyx/cron',
27
+ dirs: ['crons']
28
+ },
29
+ {
30
+ question: 'Will this project need OAuth?',
31
+ package: '@stonyx/oauth'
32
+ },
33
+ {
34
+ question: 'Will this project need pub/sub events?',
35
+ package: '@stonyx/events'
36
+ },
37
+ {
38
+ question: 'Will this project need a Discord bot?',
39
+ package: '@stonyx/discord',
40
+ dirs: ['discord-commands', 'discord-events']
41
+ }
42
+ ];
43
+ export function generateDbSchema() {
44
+ return `import { Model, hasMany, type HasMany } from '@stonyx/orm';
45
+
46
+ export default class DBModel extends Model {
47
+ // Define your collections here
48
+ // examples: HasMany = hasMany('example');
49
+ }
50
+ `;
51
+ }
52
+ /**
53
+ * The npm dist-tag that points at a package's stable release line. Only ever
54
+ * used as a *release line* selector for `@stonyx/*` modules (see
55
+ * `releaseTagFor`) -- never as the specifier for the core, which is always
56
+ * pinned exactly.
57
+ */
58
+ const STABLE_DIST_TAG = 'latest';
59
+ /** Absolute path to this package's own root, from both `src/` and `dist/`. */
60
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
61
+ /** A full semver version: `major.minor.patch`, optional prerelease, optional build. */
62
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
63
+ /**
64
+ * A string npm accepts as a *dist-tag* and never reinterprets as a version range.
65
+ * npm requires a tag to be non-numeric, and `x`/`X` are semver wildcards rather
66
+ * than tag names, so both are rejected in `releaseTagFor`.
67
+ */
68
+ const DIST_TAG = /^[A-Za-z][0-9A-Za-z-]*$/;
69
+ /**
70
+ * Rejects any version this generator must not emit.
71
+ *
72
+ * `readCoreVersion` used to check only that the field was a non-empty string, so
73
+ * `"garbage"`, `"0.2"` and `"latest"` all flowed through to the manifest verbatim
74
+ * and made `releaseTagFor` fall through to `latest` -- the one specifier
75
+ * abofs/stonyx#113 exists to stop emitting.
76
+ */
77
+ function assertVersionShape(version, source) {
78
+ if (typeof version !== 'string' || !version) {
79
+ throw new Error(`Could not read the stonyx version from ${source}`);
80
+ }
81
+ if (!SEMVER.test(version)) {
82
+ throw new Error(`The stonyx version from ${source} is not a semver version: "${version}"`);
83
+ }
84
+ }
85
+ /**
86
+ * The version of the `stonyx` package running this generator, read from its own
87
+ * `package.json` at call time.
88
+ *
89
+ * Read rather than hardcoded on purpose: a literal would be correct on the day
90
+ * it was written and silently stale on every day after (abofs/stonyx#113).
91
+ */
92
+ export function readCoreVersion() {
93
+ const manifest = path.join(packageRoot, 'package.json');
94
+ const raw = readFileSync(manifest, 'utf8');
95
+ const version = JSON.parse(raw).version;
96
+ assertVersionShape(version, manifest);
97
+ return version;
98
+ }
99
+ /**
100
+ * The npm dist-tag naming the release line a version belongs to:
101
+ * `0.2.3-beta.96` -> `beta`, `0.2.3-alpha.4` -> `alpha`, `0.2.2` -> `latest`.
102
+ *
103
+ * Every scaffolded `@stonyx/*` module is requested on the same line as the core
104
+ * that scaffolded it, so the generated project cannot mix a prerelease core with
105
+ * modules from the stable line (or the reverse).
106
+ *
107
+ * Throws, rather than guessing, when the prerelease identifier is not usable as a
108
+ * dist-tag. Returning it verbatim was only safe for *alphabetic* identifiers: npm
109
+ * parses a numeric or wildcard identifier as a version **range**, so `0.2.3-0`
110
+ * emitted `"0"` and `0.2.3-x` emitted `"x"`, both of which install with rc=0 and
111
+ * silently resolve the module's `latest` release -- for `@stonyx/orm` that is
112
+ * `0.3.1`, which pins `stonyx@0.2.3-beta.11` and so reproduces abofs/stonyx#113
113
+ * through a different door, with no error. `0.2.3-0` is reachable from this
114
+ * repo's own `publish.yml` `custom-version` dispatch input, which accepts any
115
+ * semver string and also expands the keyword `prerelease` to `x.y.z-0`.
116
+ *
117
+ * Two bounds remain, both loud rather than silent:
118
+ *
119
+ * - An alphabetic identifier is assumed to also be a published dist-tag name.
120
+ * True for `beta` and `alpha`, the only two lines the fleet publishes; a core
121
+ * released as e.g. `0.2.3-rc.1` with no `rc` dist-tag scaffolds an unresolvable
122
+ * module specifier, which fails `pnpm install` with
123
+ * `ERR_PNPM_NO_MATCHING_VERSION`. The tag has to exist on every package in
124
+ * `MODULE_OPTIONS`, not only on the core.
125
+ * - On the stable line this returns `latest`, the correct tag for that line -- but
126
+ * only useful once the *modules* have advanced their own `latest` tags. Today
127
+ * `@stonyx/orm@latest` is `0.3.1` and pins `stonyx@0.2.3-beta.11`, so the module
128
+ * `latest` tags must advance before the core's does (abofs/stonyx#115).
129
+ */
130
+ export function releaseTagFor(version) {
131
+ // Fail closed, not open. Without this the exported function still answered
132
+ // `latest` for `"garbage"`, `"0.2"`, `""` and `"latest"` itself -- the same
133
+ // fall-through-to-`latest` shape this change exists to remove, one level down
134
+ // from the emission path that `generatePackageJson` already guards.
135
+ assertVersionShape(version, 'the supplied version');
136
+ const prerelease = /^\d+\.\d+\.\d+-(.*)$/.exec(version);
137
+ if (!prerelease)
138
+ return STABLE_DIST_TAG;
139
+ const identifier = prerelease[1].split('.')[0];
140
+ if (!DIST_TAG.test(identifier) || /^[xX]$/.test(identifier)) {
141
+ throw new Error(`Cannot derive a dist-tag from the prerelease identifier "${identifier}" in version "${version}": ` +
142
+ 'npm reads it as a version range, not a tag.');
143
+ }
144
+ if (identifier === STABLE_DIST_TAG) {
145
+ throw new Error(`A prerelease core must not request modules at "${STABLE_DIST_TAG}" (version "${version}").`);
146
+ }
147
+ return identifier;
148
+ }
149
+ export function generatePackageJson(name, selectedModules, coreVersion = readCoreVersion()) {
150
+ // Resolved first, before anything is emitted, and unconditionally -- deliberately
151
+ // not inside the module loop below. `releaseTagFor` asserts the version's shape as
152
+ // its first act, so this one call is also what stops an injected non-semver
153
+ // `coreVersion` from reaching the manifest verbatim.
154
+ //
155
+ // A second `assertVersionShape(coreVersion, ...)` stood at the top of this function
156
+ // until abofs/stonyx#118's review: deleting it left the suite green, because this
157
+ // call already rejects the same value on every path. It was removed rather than
158
+ // left as decoration. The invariant that replaces it is positional -- keep this
159
+ // call above the emission and the guard stays load-bearing; push it under an
160
+ // `if (selectedModules.length)` and the core becomes unvalidated again.
161
+ const moduleTag = releaseTagFor(coreVersion);
162
+ // The framework is a runtime dependency of the application, pinned exactly to
163
+ // the core that generated the project.
164
+ const dependencies = { stonyx: coreVersion };
165
+ const devDependencies = {
166
+ qunit: '^2.24.1',
167
+ tsx: '^4.21.0',
168
+ typescript: '^5.8.3'
169
+ };
170
+ // The scaffolder writes modules to `devDependencies` because that remains
171
+ // the conventional placement for an application — NOT because it is the only
172
+ // one discovery sees. Since abofs/stonyx#106 rule 3 the loader scans the
173
+ // de-duplicated union of `dependencies` and `devDependencies`, so either
174
+ // placement is discovered (see docs/modules.md). Requested on the core's own
175
+ // release line rather than at `latest`.
176
+ for (const mod of selectedModules) {
177
+ devDependencies[mod.package] = moduleTag;
178
+ }
179
+ // Sort dependencies alphabetically
180
+ const sorted = Object.fromEntries(Object.entries(devDependencies).sort(([a], [b]) => a.localeCompare(b)));
181
+ return JSON.stringify({
182
+ name,
183
+ version: '0.1.0',
184
+ type: 'module',
185
+ private: true,
186
+ scripts: {
187
+ build: 'tsc',
188
+ serve: 'stonyx serve',
189
+ start: 'stonyx serve',
190
+ test: "NODE_ENV=test node --import tsx/esm --import ./test/setup.ts node_modules/qunit/bin/qunit.js 'test/**/*-test.ts'"
191
+ },
192
+ dependencies,
193
+ devDependencies: sorted
194
+ }, null, 2) + '\n';
195
+ }
196
+ export function generateAppTs() {
197
+ return `import log from 'stonyx/log';
198
+
199
+ export default class App {
200
+ static instance: App;
201
+ ready: Promise<void>;
202
+
203
+ constructor() {
204
+ if (App.instance) return App.instance;
205
+ App.instance = this;
206
+
207
+ this.ready = this.init();
208
+ }
209
+
210
+ async init(): Promise<void> {
211
+ log.info('Initializing Application');
212
+
213
+ // Application setup here
214
+
215
+ log.info('Application has been initialized');
216
+ }
217
+ }
218
+ `;
219
+ }
220
+ export function generateEnvironmentTs() {
221
+ return `import type { StoynxConfig } from 'stonyx';
222
+
223
+ const config: StoynxConfig = {
224
+ };
225
+
226
+ export default config;
227
+ `;
228
+ }
229
+ export function generateTestEnvironmentTs() {
230
+ return `import type { StoynxConfig } from 'stonyx';
231
+
232
+ // Test-specific config overrides
233
+ const config: Partial<StoynxConfig> = {
234
+ };
235
+
236
+ export default config;
237
+ `;
238
+ }
239
+ export function generateSetupTs() {
240
+ return `// Test setup: bootstrap Stonyx with the consumer config before qunit runs.
241
+ // Sprint 44 pattern — loaded via \`node --import ./test/setup.ts\`.
242
+ import { pathToFileURL } from 'url';
243
+
244
+ const cwd = process.cwd();
245
+
246
+ const { default: Stonyx } = await import('stonyx');
247
+ const { default: config } = await import(pathToFileURL(\`\${cwd}/config/environment.ts\`).href);
248
+
249
+ new Stonyx(config, cwd);
250
+
251
+ await Stonyx.ready;
252
+ `;
253
+ }
254
+ export function generateZzExitTestTs() {
255
+ return `// Force-exit hook for qunit runs.
256
+ //
257
+ // Stonyx modules may keep listeners/servers open that would otherwise
258
+ // block the process from exiting after tests complete, causing CI to
259
+ // hit timeouts even though all tests passed.
260
+ //
261
+ // Named \`zz-\` so alphabetical test-file order places it last, after
262
+ // all real test files have registered with QUnit.
263
+ import QUnit from 'qunit';
264
+
265
+ QUnit.on('runEnd', () => {
266
+ setImmediate(() => process.exit(process.exitCode ?? 0));
267
+ });
268
+ `;
269
+ }
270
+ export function generateEnvironmentExampleTs() {
271
+ return `// Copy this file to environment.ts and fill in your values
272
+ // All values should use environment variables with ?? fallback defaults
273
+
274
+ const {
275
+ NODE_ENV,
276
+ } = process.env;
277
+
278
+ const environment: string = NODE_ENV ?? 'development';
279
+
280
+ export default {
281
+ }
282
+ `;
283
+ }
284
+ export function generateGitignore() {
285
+ return `node_modules/
286
+ .env
287
+ db.json
288
+ *.log
289
+
290
+ # Compiled TypeScript output (tsc compiles .ts to .js in-place)
291
+ *.js
292
+ *.d.ts
293
+ *.js.map
294
+ `;
295
+ }
296
+ export function generateTsConfig() {
297
+ return JSON.stringify({
298
+ compilerOptions: {
299
+ strict: true,
300
+ target: 'ES2022',
301
+ module: 'NodeNext',
302
+ moduleResolution: 'NodeNext',
303
+ outDir: '.',
304
+ rootDir: '.',
305
+ esModuleInterop: true,
306
+ skipLibCheck: true,
307
+ forceConsistentCasingInFileNames: true
308
+ },
309
+ include: ['**/*.ts'],
310
+ exclude: ['node_modules', 'test']
311
+ }, null, 2) + '\n';
312
+ }
313
+ /**
314
+ * Rejects when `pnpm install` fails, either by exiting non-zero or by failing to
315
+ * spawn. Exported so the rejection path is testable without a network round-trip.
316
+ */
317
+ export function runPnpmInstall(projectDir) {
318
+ return new Promise((resolve, reject) => {
319
+ const child = spawn('pnpm', ['install'], {
320
+ cwd: projectDir,
321
+ stdio: 'inherit'
322
+ });
323
+ child.on('close', code => {
324
+ if (code === 0)
325
+ resolve();
326
+ else
327
+ reject(new Error(`pnpm install exited with code ${code}`));
328
+ });
329
+ child.on('error', reject);
330
+ });
331
+ }
332
+ /**
333
+ * Write every scaffolded file to disk given a resolved project directory,
334
+ * app name, and pre-selected module options. Factored out of `newCommand`
335
+ * so tests can exercise the file-writing path without interactive prompts.
336
+ */
337
+ export async function scaffoldProject(projectDir, appName, selectedModules) {
338
+ // Create project directory
339
+ await createDirectory(projectDir);
340
+ // Copy .nvmrc from monorepo root
341
+ const monorepoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
342
+ const nvmrcSource = path.join(monorepoRoot, '.nvmrc');
343
+ if (await fileExists(nvmrcSource)) {
344
+ await copyFile(nvmrcSource, path.join(projectDir, '.nvmrc'));
345
+ }
346
+ // Generate core files
347
+ await createFile(path.join(projectDir, 'package.json'), generatePackageJson(appName, selectedModules));
348
+ await createFile(path.join(projectDir, 'app.ts'), generateAppTs());
349
+ await createFile(path.join(projectDir, 'tsconfig.json'), generateTsConfig());
350
+ await createFile(path.join(projectDir, '.gitignore'), generateGitignore());
351
+ // Create config directory and files
352
+ await createFile(path.join(projectDir, 'config', 'environment.ts'), generateEnvironmentTs());
353
+ await createFile(path.join(projectDir, 'config', 'environment.example.ts'), generateEnvironmentExampleTs());
354
+ // Create module-specific directories and files
355
+ for (const mod of selectedModules) {
356
+ if (mod.dirs) {
357
+ for (const dir of mod.dirs) {
358
+ await createDirectory(path.join(projectDir, dir));
359
+ // Create .gitkeep so empty dirs are tracked
360
+ await createFile(path.join(projectDir, dir, '.gitkeep'), '');
361
+ }
362
+ }
363
+ if (mod.files) {
364
+ for (const [filePath, generator] of Object.entries(mod.files)) {
365
+ await createFile(path.join(projectDir, filePath), generator());
366
+ }
367
+ }
368
+ }
369
+ // Create test structure
370
+ await createDirectory(path.join(projectDir, 'test', 'unit'));
371
+ await createFile(path.join(projectDir, 'test', 'unit', '.gitkeep'), '');
372
+ await createDirectory(path.join(projectDir, 'test', 'integration'));
373
+ await createFile(path.join(projectDir, 'test', 'integration', '.gitkeep'), '');
374
+ await createDirectory(path.join(projectDir, 'test', 'acceptance'));
375
+ await createFile(path.join(projectDir, 'test', 'acceptance', '.gitkeep'), '');
376
+ // Create test config (TS)
377
+ await createFile(path.join(projectDir, 'test', 'config', 'environment.ts'), generateTestEnvironmentTs());
378
+ // Create Sprint 44 test harness files (setup bootstraps Stonyx, zz-exit-test drains event loop)
379
+ await createFile(path.join(projectDir, 'test', 'setup.ts'), generateSetupTs());
380
+ await createFile(path.join(projectDir, 'test', 'zz-exit-test.ts'), generateZzExitTestTs());
381
+ }
382
+ export default async function newCommand({ args }) {
383
+ let appName = args[0];
384
+ if (!appName) {
385
+ appName = await prompt('Project name:');
386
+ }
387
+ if (!appName) {
388
+ console.error('Project name is required.');
389
+ process.exit(1);
390
+ }
391
+ const projectDir = path.resolve(process.cwd(), appName);
392
+ if (await fileExists(projectDir)) {
393
+ console.error(`Directory "${appName}" already exists.`);
394
+ process.exit(1);
395
+ }
396
+ console.log(`\nScaffolding new Stonyx project: ${appName}\n`);
397
+ // Prompt for module selection
398
+ const selectedModules = [];
399
+ for (const mod of MODULE_OPTIONS) {
400
+ if (await confirm(mod.question)) {
401
+ selectedModules.push(mod);
402
+ }
403
+ }
404
+ console.log('\nCreating project structure...\n');
405
+ await scaffoldProject(projectDir, appName, selectedModules);
406
+ console.log('Installing dependencies...\n');
407
+ try {
408
+ await runPnpmInstall(projectDir);
409
+ }
410
+ catch (error) {
411
+ // `pnpm`'s own diagnostic already reached the terminal via stdio: 'inherit'.
412
+ // What used to be missing is the exit code: this catch discarded `error` and
413
+ // fell through to the success banner, so `stonyx new` announced success and
414
+ // exited 0 on a project with no node_modules -- loud to a human, silent to any
415
+ // supervisor, CI job or wrapper reading the status.
416
+ console.error(error instanceof Error ? error.message : String(error));
417
+ console.error(`\n✗ Project "${appName}" was created, but its dependencies are NOT installed.`);
418
+ console.error(`\n cd ${appName}`);
419
+ console.error(' pnpm install\n');
420
+ process.exitCode = 1;
421
+ return;
422
+ }
423
+ console.log(`\n✓ Project "${appName}" created successfully!`);
424
+ console.log(`\n cd ${appName}`);
425
+ console.log(` stonyx serve\n`);
426
+ }
@@ -0,0 +1,6 @@
1
+ import { type StoynxModule } from '../lifecycle.js';
2
+ export declare function createShutdownHandler(modules: StoynxModule[]): () => Promise<void>;
3
+ export declare function maybeRegisterAppShutdown(modules: StoynxModule[], appInstance: unknown, originalShutdown: () => Promise<void>): void;
4
+ export default function serve({ args }: {
5
+ args: string[];
6
+ }): Promise<void>;