stonyx 0.2.3-alpha.0 → 0.2.3-alpha.10

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
@@ -1,206 +1,56 @@
1
1
  # Stonyx
2
2
 
3
- **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 integration of asynchronous modules, making development faster, cleaner, and more maintainable.
3
+ **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
4
 
5
- ### Highlights
6
-
7
- * ✅ 100% JavaScript
8
- * ✅ Drop-in file system for most modules
9
- * ✅ Don’t even hit the ground — just fly
10
- * ✅ High performance
11
-
12
- Stonyx acts as a **base application host**, allowing you to add official modules (`@stonyx/*`) or your own custom modules without boilerplate initialization.
13
-
14
- ---
5
+ - 100% JavaScript (ES Modules)
6
+ - Drop-in module system — no boilerplate
7
+ - Automatic async module loading and initialization
8
+ - Built-in CLI for scaffolding, bootstrapping, and testing
15
9
 
16
10
  ## Quick Start
17
11
 
18
- ### ESM Usage (Application Startup)
19
-
20
- For standard applications, the **bootstrap file** ensures that the Stonyx framework and all submodules are fully loaded before your application code runs:
21
-
22
- ```js
23
- // index.js - your project's entry point
24
- import Stonyx from './stonyx-bootstrap.cjs';
25
- await Stonyx.ready; // wait until all modules are initialized
26
-
27
- const { default: App } = await import('./app.js'); // your application
28
- new App();
29
- ```
30
-
31
- ### CommonJS Bootstrap Helper
32
- Auto-generated and added to your project post installation
33
-
34
- ```js
35
- // stonyx-bootstrap.cjs
36
- const Stonyx = require('stonyx').default;
37
- const config = require('./config/environment.js').default;
38
-
39
- new Stonyx(config, __dirname);
40
- ```
41
-
42
- ---
43
-
44
- ## Core Features
45
-
46
- ### 1. **Modular Architecture**
47
-
48
- * Automatically detects modules in `devDependencies` prefixed with `@stonyx/`.
49
- * Supports async initialization with `stonyx-async` modules.
50
- * Safe module sequencing for submodule development with `waitForModule()`.
51
-
52
- ### 2. **Color-Coded Logging**
53
-
54
- * Centralized logging via [Chronicle](https://github.com/abofs/chronicle).
55
- * Module-specific logs configurable in `environment.js`:
56
-
57
- ```js
58
- restServer: { logColor: 'yellow', logMethod: 'api', logTimestamp: true }
59
- ```
60
-
61
- * Create custom logs for any class with minimal configuration.
62
-
63
- ### 3. **Singleton Design**
64
-
65
- * Only one instance of Stonyx exists per project.
66
- * Ensures consistent access to modules, logs, and configuration.
67
-
68
- ### 4. **Plug-and-Play Module Loading**
69
-
70
- * Modules with `stonyx-module` keyword in `package.json` are auto-initialized.
71
- * Modules with `stonyx-async` keyword are awaited automatically before usage.
72
-
73
- ---
74
-
75
- ## Official Modules
76
-
77
- ### **[@stonyx/cron](https://github.com/abofs/stonyx-cron)**
78
-
79
- Lightweight asynchronous job scheduling utility.
80
-
81
- ```js
82
- import Cron from '@stonyx/cron';
83
-
84
- const cron = new Cron();
85
- cron.register('exampleJob', async () => console.log('Job executed!'), 5, true);
86
- ```
87
-
88
- * Efficient scheduling using a min-heap.
89
- * Optional logging via `config.cron`.
90
-
91
- ---
92
-
93
- ### **[@stonyx/events](https://github.com/abofs/stonyx-events)**
94
-
95
- Lightweight pub/sub event system for application-wide event handling.
96
-
97
- ```js
98
- import Events from '@stonyx/events';
99
-
100
- const events = new Events();
101
-
102
- // Register available events
103
- events.setup(['userLogin', 'userLogout', 'dataChange']);
104
-
105
- // Subscribe to events
106
- events.subscribe('userLogin', (user) => {
107
- console.log(`${user.name} logged in`);
108
- });
109
-
110
- // Emit events
111
- events.emit('userLogin', { name: 'Alice' });
112
- ```
113
-
114
- * Singleton pattern for shared event bus
115
- * Async support with error isolation
116
- * Type-safe event registration
117
-
118
- ---
119
-
120
- ### **[@stonyx/rest-server](https://github.com/abofs/stonyx-rest-server)**
121
-
122
- Dynamic REST server module with auto-route registration.
123
-
124
- ```js
125
- import Stonyx from 'stonyx';
126
- import config from './config/environment.js';
127
-
128
- new Stonyx(config);
129
- ```
130
-
131
- * Zero configuration for routes: drop request classes into the `requests` directory.
132
- * Automatic path generation, JSON parsing, and CORS handling.
133
- * Supports per-route authentication hooks.
134
-
135
- ---
136
-
137
- ### **[@stonyx/orm](https://github.com/abofs/stonyx-orm)**
138
-
139
- Lightweight ORM with model definitions, relationships, serializers, and optional REST integration.
140
-
141
- ```js
142
- import Stonyx from 'stonyx';
143
- import config from './config/environment.js';
144
-
145
- new Stonyx(config);
146
-
147
- // Define models
148
- import { Model, attr, hasMany, belongsTo } from '@stonyx/orm';
149
-
150
- class Owner extends Model {
151
- id = attr('string');
152
- pets = hasMany('animal');
153
- }
154
- ```
155
-
156
- * Auto-loads models, serializers, transforms, and access classes.
157
- * Optional JSON file persistence with auto-save intervals.
158
- * Integrates with `@stonyx/rest-server` for automatic route setup.
159
-
160
- ---
161
-
162
- ## Configuration
163
-
164
- All modules are configurable via `config/environment.js`:
165
-
166
- ```js
167
- export default {
168
- restServer: { logColor: 'yellow', port: 3000 },
169
- orm: { logColor: 'white', db: { file: './db.json', autosave: true } },
170
- cron: { log: true }
171
- };
12
+ ```bash
13
+ npm install -g stonyx
14
+ stonyx new my-app
15
+ cd my-app
16
+ stonyx serve
172
17
  ```
173
18
 
174
- ---
175
-
176
- ## Running the Application
19
+ The `new` command walks you through module selection and generates a ready-to-run project. From there, the CLI handles bootstrapping:
177
20
 
178
21
  ```bash
179
- node . # Start the main app
180
- npm start # Run using npm script
22
+ stonyx serve # Bootstrap + run app.js
23
+ stonyx test # Bootstrap + run tests
24
+ stonyx help # Show all available commands
181
25
  ```
182
26
 
183
- ---
184
-
185
- ## Developing Submodules
27
+ Stonyx reads `config/environment.js`, initializes all `@stonyx/*` modules from your `devDependencies`, and runs your application.
186
28
 
187
- For developers building new Stonyx modules or experimenting with async modules:
29
+ ## Documentation
188
30
 
189
- ```js
190
- import Stonyx, { waitForModule } from 'stonyx';
191
- import config from './config/environment.js';
31
+ | Section | Description |
32
+ |---------|-------------|
33
+ | [CLI](docs/cli.md) | Commands, aliases, and module commands |
34
+ | [Configuration](docs/configuration.md) | Environment config, module config, test overrides |
35
+ | [Modules](docs/modules.md) | Module architecture, async loading, official modules |
36
+ | [Logging](docs/logging.md) | Chronicle integration and custom log types |
37
+ | [Lifecycle](docs/lifecycle.md) | Startup and shutdown hooks |
38
+ | [Testing](docs/testing.md) | Test runner, helpers, and conventions |
39
+ | [Developing Modules](docs/developing-modules.md) | Guide for building custom Stonyx modules |
40
+ | [API Reference](docs/api.md) | Public exports and class documentation |
192
41
 
193
- const app = new Stonyx(config, __dirname);
194
-
195
- // Wait for specific async module readiness
196
- await waitForModule('restServer');
197
- ```
198
-
199
- * Use `waitForModule()` **only for submodule development**, testing, or when you need to ensure a specific module is fully initialized before continuing.
200
- * Official modules automatically initialize during normal application startup, so end-users do **not** need to call `waitForModule()`.
42
+ ## Official Modules
201
43
 
202
- ---
44
+ | Module | Description |
45
+ |--------|-------------|
46
+ | [@stonyx/cron](https://github.com/abofs/stonyx-cron) | Lightweight async job scheduling |
47
+ | [@stonyx/discord](https://github.com/abofs/stonyx-discord) | Discord bot with command and event handler auto-discovery |
48
+ | [@stonyx/events](https://github.com/abofs/stonyx-events) | Pub/sub event system |
49
+ | [@stonyx/oauth](https://github.com/abofs/stonyx-oauth) | OAuth provider integration |
50
+ | [@stonyx/orm](https://github.com/abofs/stonyx-orm) | ORM with models, relationships, and serializers |
51
+ | [@stonyx/rest-server](https://github.com/abofs/stonyx-rest-server) | Dynamic REST server with auto-route registration |
52
+ | [@stonyx/sockets](https://github.com/abofs/stonyx-sockets) | WebSocket server and client |
203
53
 
204
54
  ## License
205
55
 
206
- Apache 2.0 — do what you want, just keep attribution.
56
+ Apache 2.0
@@ -4,8 +4,7 @@ const {
4
4
  NODE_ENV,
5
5
  } = process.env;
6
6
 
7
- const isTest = typeof QUnit !== 'undefined';
8
- const environment = isTest ? 'test' : (NODE_ENV ?? 'development');
7
+ const environment = NODE_ENV ?? 'development';
9
8
 
10
9
  export default {
11
10
  environment,
@@ -4,8 +4,7 @@ const {
4
4
  NODE_ENV,
5
5
  } = process.env;
6
6
 
7
- const isTest = typeof QUnit !== 'undefined';
8
- const environment = isTest ? 'test' : (NODE_ENV ?? 'development');
7
+ const environment = NODE_ENV ?? 'development';
9
8
 
10
9
  export default {
11
10
  environment,
package/package.json CHANGED
@@ -1,19 +1,28 @@
1
1
  {
2
2
  "name": "stonyx",
3
- "version": "0.2.3-alpha.0",
3
+ "version": "0.2.3-alpha.10",
4
4
  "description": "Base stonyx framework module",
5
5
  "main": "main.js",
6
6
  "type": "module",
7
+ "bin": {
8
+ "stonyx": "./src/cli.js"
9
+ },
7
10
  "exports": {
8
11
  ".": "./src/main.js",
9
12
  "./config": "./src/exports/config.js",
10
13
  "./log": "./src/exports/log.js",
11
- "./test-helpers": "./src/exports/test-helpers.js"
14
+ "./test-helpers": "./src/exports/test-helpers.js",
15
+ "./lifecycle": "./src/lifecycle.js"
12
16
  },
13
17
  "repository": {
14
18
  "type": "git",
15
19
  "url": "git+https://github.com/abofs/stonyx.git"
16
20
  },
21
+ "files": [
22
+ "src",
23
+ "config",
24
+ "README.md"
25
+ ],
17
26
  "publishConfig": {
18
27
  "provenance": true
19
28
  },
@@ -26,10 +35,10 @@
26
35
  "url": "https://github.com/abofs/stonyx/issues"
27
36
  },
28
37
  "dependencies": {
29
- "node-chronicle": "^0.2.0"
38
+ "@stonyx/utils": "0.2.3-beta.7",
39
+ "@stonyx/logs": "^1.0.0"
30
40
  },
31
41
  "devDependencies": {
32
- "@stonyx/utils": "^0.2.2",
33
42
  "qunit": "^2.24.1",
34
43
  "sinon": "^21.0.0"
35
44
  },
@@ -0,0 +1,48 @@
1
+ export default async function help({ args, builtInCommands, loadModuleCommands } = {}) {
2
+ console.log('\nUsage: stonyx <command> [...args]\n');
3
+ console.log('Commands:\n');
4
+
5
+ if (builtInCommands) {
6
+ for (const [name, { description }] of Object.entries(builtInCommands)) {
7
+ console.log(` ${name.padEnd(20)} ${description}`);
8
+ }
9
+ }
10
+
11
+ if (loadModuleCommands) {
12
+ try {
13
+ const moduleCommands = await loadModuleCommands();
14
+ const entries = Object.entries(moduleCommands);
15
+
16
+ if (entries.length) {
17
+ console.log('\nModule commands:\n');
18
+
19
+ for (const [name, { description }] of entries) {
20
+ console.log(` ${name.padEnd(20)} ${description}`);
21
+ }
22
+ }
23
+ } catch {
24
+ // Module commands not available (e.g., no project context)
25
+ }
26
+ }
27
+
28
+ console.log('\nAliases: s=serve, t=test, n=new, h=help\n');
29
+
30
+ console.log('Project conventions:\n');
31
+ console.log(' Entry point: app.js');
32
+ console.log(' Config: config/environment.js');
33
+ console.log(' DB schema: config/db-schema.js');
34
+ console.log(' Models: models/');
35
+ console.log(' Serializers: serializers/');
36
+ console.log(' Access control: access/');
37
+ console.log(' Transforms: transforms/');
38
+ console.log(' Hooks: hooks/');
39
+ console.log(' REST requests: requests/');
40
+ console.log(' Cron jobs: crons/');
41
+ console.log(' Tests: test/{unit,integration,acceptance}/');
42
+ console.log('');
43
+ console.log(' Logging: import log from \'stonyx/log\' (never console.log)');
44
+ console.log(' Utilities: import from \'@stonyx/utils/*\' (never raw fs)');
45
+ console.log(' Lint config: import from \'@abofs/code-conventions\'');
46
+ console.log(' Package manager: pnpm');
47
+ console.log('');
48
+ }
@@ -0,0 +1,56 @@
1
+ import { readFile } from 'fs/promises';
2
+ import path from 'path';
3
+
4
+ export default async function loadModuleCommands() {
5
+ const cwd = process.cwd();
6
+ const commands = {};
7
+
8
+ let projectPackage;
9
+
10
+ try {
11
+ const raw = await readFile(path.join(cwd, 'package.json'), 'utf8');
12
+ projectPackage = JSON.parse(raw);
13
+ } catch {
14
+ return commands;
15
+ }
16
+
17
+ const allDeps = {
18
+ ...projectPackage.dependencies,
19
+ ...projectPackage.devDependencies
20
+ };
21
+
22
+ const stonyxModules = Object.keys(allDeps).filter(name => name.startsWith('@stonyx/'));
23
+
24
+ for (const moduleName of stonyxModules) {
25
+ let modulePackage;
26
+
27
+ try {
28
+ const raw = await readFile(path.join(cwd, 'node_modules', moduleName, 'package.json'), 'utf8');
29
+ modulePackage = JSON.parse(raw);
30
+ } catch {
31
+ continue;
32
+ }
33
+
34
+ const { exports: moduleExports } = modulePackage;
35
+
36
+ if (!moduleExports || !moduleExports['./commands']) continue;
37
+
38
+ try {
39
+ const commandsModule = await import(path.join(cwd, 'node_modules', moduleName, moduleExports['./commands']));
40
+ const moduleCommands = commandsModule.default;
41
+
42
+ for (const [name, command] of Object.entries(moduleCommands)) {
43
+ if (commands[name]) {
44
+ console.warn(`Warning: Command "${name}" from ${moduleName} conflicts with existing command. Skipping.`);
45
+ continue;
46
+ }
47
+
48
+ commands[name] = { ...command, module: moduleName };
49
+ }
50
+ } catch {
51
+ continue;
52
+ }
53
+ }
54
+
55
+ return commands;
56
+ }
package/src/cli/new.js ADDED
@@ -0,0 +1,237 @@
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 path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ 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.js': 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
+
44
+ function generateDbSchema() {
45
+ return `import { Model, hasMany } from '@stonyx/orm';
46
+
47
+ export default class DBModel extends Model {
48
+ // Define your collections here
49
+ // examples = hasMany('example');
50
+ }
51
+ `;
52
+ }
53
+
54
+ function generatePackageJson(name, selectedModules) {
55
+ const devDependencies = { stonyx: 'latest' };
56
+
57
+ for (const mod of selectedModules) {
58
+ devDependencies[mod.package] = 'latest';
59
+ }
60
+
61
+ // Sort dependencies alphabetically
62
+ const sorted = Object.fromEntries(
63
+ Object.entries(devDependencies).sort(([a], [b]) => a.localeCompare(b))
64
+ );
65
+
66
+ return JSON.stringify({
67
+ name,
68
+ version: '0.1.0',
69
+ type: 'module',
70
+ private: true,
71
+ scripts: {
72
+ start: 'stonyx serve',
73
+ test: 'stonyx test'
74
+ },
75
+ devDependencies: sorted
76
+ }, null, 2) + '\n';
77
+ }
78
+
79
+ function generateAppJs() {
80
+ return `import log from 'stonyx/log';
81
+
82
+ export default class App {
83
+ constructor() {
84
+ if (App.instance) return App.instance;
85
+ App.instance = this;
86
+
87
+ this.ready = this.init();
88
+ }
89
+
90
+ async init() {
91
+ log.info('Initializing Application');
92
+
93
+ // Application setup here
94
+
95
+ log.info('Application has been initialized');
96
+ }
97
+ }
98
+ `;
99
+ }
100
+
101
+ function generateEnvironmentJs() {
102
+ return `export default {
103
+ }
104
+ `;
105
+ }
106
+
107
+ function generateEnvironmentExampleJs() {
108
+ return `// Copy this file to environment.js and fill in your values
109
+ // All values should use environment variables with ?? fallback defaults
110
+
111
+ const {
112
+ NODE_ENV,
113
+ } = process.env;
114
+
115
+ const environment = NODE_ENV ?? 'development';
116
+
117
+ export default {
118
+ }
119
+ `;
120
+ }
121
+
122
+ function generateGitignore() {
123
+ return `node_modules/
124
+ .env
125
+ db.json
126
+ *.log
127
+ `;
128
+ }
129
+
130
+ function runPnpmInstall(projectDir) {
131
+ return new Promise((resolve, reject) => {
132
+ const child = spawn('pnpm', ['install'], {
133
+ cwd: projectDir,
134
+ stdio: 'inherit'
135
+ });
136
+
137
+ child.on('close', code => {
138
+ if (code === 0) resolve();
139
+ else reject(new Error(`pnpm install exited with code ${code}`));
140
+ });
141
+
142
+ child.on('error', reject);
143
+ });
144
+ }
145
+
146
+ export default async function newCommand({ args }) {
147
+ let appName = args[0];
148
+
149
+ if (!appName) {
150
+ appName = await prompt('Project name:');
151
+ }
152
+
153
+ if (!appName) {
154
+ console.error('Project name is required.');
155
+ process.exit(1);
156
+ }
157
+
158
+ const projectDir = path.resolve(process.cwd(), appName);
159
+
160
+ if (await fileExists(projectDir)) {
161
+ console.error(`Directory "${appName}" already exists.`);
162
+ process.exit(1);
163
+ }
164
+
165
+ console.log(`\nScaffolding new Stonyx project: ${appName}\n`);
166
+
167
+ // Prompt for module selection
168
+ const selectedModules = [];
169
+
170
+ for (const mod of MODULE_OPTIONS) {
171
+ if (await confirm(mod.question)) {
172
+ selectedModules.push(mod);
173
+ }
174
+ }
175
+
176
+ console.log('\nCreating project structure...\n');
177
+
178
+ // Create project directory
179
+ await createDirectory(projectDir);
180
+
181
+ // Copy .nvmrc from monorepo root
182
+ const monorepoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
183
+ const nvmrcSource = path.join(monorepoRoot, '.nvmrc');
184
+
185
+ if (await fileExists(nvmrcSource)) {
186
+ await copyFile(nvmrcSource, path.join(projectDir, '.nvmrc'));
187
+ }
188
+
189
+ // Generate core files
190
+ await createFile(path.join(projectDir, 'package.json'), generatePackageJson(appName, selectedModules));
191
+ await createFile(path.join(projectDir, 'app.js'), generateAppJs());
192
+ await createFile(path.join(projectDir, '.gitignore'), generateGitignore());
193
+
194
+ // Create config directory and files
195
+ await createFile(path.join(projectDir, 'config', 'environment.js'), generateEnvironmentJs());
196
+ await createFile(path.join(projectDir, 'config', 'environment.example.js'), generateEnvironmentExampleJs());
197
+
198
+ // Create module-specific directories and files
199
+ for (const mod of selectedModules) {
200
+ if (mod.dirs) {
201
+ for (const dir of mod.dirs) {
202
+ await createDirectory(path.join(projectDir, dir));
203
+ // Create .gitkeep so empty dirs are tracked
204
+ await createFile(path.join(projectDir, dir, '.gitkeep'), '');
205
+ }
206
+ }
207
+
208
+ if (mod.files) {
209
+ for (const [filePath, generator] of Object.entries(mod.files)) {
210
+ await createFile(path.join(projectDir, filePath), generator());
211
+ }
212
+ }
213
+ }
214
+
215
+ // Create test structure
216
+ await createDirectory(path.join(projectDir, 'test', 'unit'));
217
+ await createFile(path.join(projectDir, 'test', 'unit', '.gitkeep'), '');
218
+ await createDirectory(path.join(projectDir, 'test', 'integration'));
219
+ await createFile(path.join(projectDir, 'test', 'integration', '.gitkeep'), '');
220
+ await createDirectory(path.join(projectDir, 'test', 'acceptance'));
221
+ await createFile(path.join(projectDir, 'test', 'acceptance', '.gitkeep'), '');
222
+
223
+ // Create test config
224
+ await createFile(path.join(projectDir, 'test', 'config', 'environment.js'), `export default {\n // Test-specific config overrides\n}\n`);
225
+
226
+ console.log('Installing dependencies...\n');
227
+
228
+ try {
229
+ await runPnpmInstall(projectDir);
230
+ } catch (error) {
231
+ console.error('Failed to install dependencies. Run `pnpm install` manually in the project directory.');
232
+ }
233
+
234
+ console.log(`\n✓ Project "${appName}" created successfully!`);
235
+ console.log(`\n cd ${appName}`);
236
+ console.log(` stonyx serve\n`);
237
+ }
@@ -0,0 +1,38 @@
1
+ import { runStartupHooks, runShutdownHooks } from '../lifecycle.js';
2
+
3
+ export function createShutdownHandler(modules) {
4
+ let shuttingDown = false;
5
+ return async () => {
6
+ if (shuttingDown) return;
7
+ shuttingDown = true;
8
+
9
+ await runShutdownHooks(modules);
10
+ process.exit(0);
11
+ };
12
+ }
13
+
14
+ export default async function serve({ args }) {
15
+ const cwd = process.cwd();
16
+ const entryFlag = args.indexOf('--entry');
17
+ const entryPoint = entryFlag !== -1 ? args[entryFlag + 1] : 'app.js';
18
+
19
+ const { default: config } = await import(`${cwd}/config/environment.js`);
20
+ const { default: Stonyx } = await import('../main.js');
21
+
22
+ new Stonyx(config, cwd);
23
+ await Stonyx.ready;
24
+
25
+ const { modules } = Stonyx.instance;
26
+ await runStartupHooks(modules);
27
+
28
+ const shutdown = createShutdownHandler(modules);
29
+
30
+ process.on('SIGTERM', shutdown);
31
+ process.on('SIGINT', shutdown);
32
+
33
+ const entryModule = await import(`${cwd}/${entryPoint}`);
34
+
35
+ if (entryModule.default) {
36
+ new entryModule.default();
37
+ }
38
+ }
@@ -0,0 +1,8 @@
1
+ import { pathToFileURL } from 'url';
2
+
3
+ const cwd = process.cwd();
4
+
5
+ const { default: Stonyx } = await import('stonyx');
6
+ const { default: config } = await import(pathToFileURL(`${cwd}/config/environment.js`));
7
+
8
+ new Stonyx(config, cwd);
@@ -0,0 +1,27 @@
1
+ import { spawn } from 'child_process';
2
+ import { fileURLToPath, pathToFileURL } from 'url';
3
+ import path from 'path';
4
+
5
+ export default async function test({ args }) {
6
+ const cwd = process.cwd();
7
+ const setupFile = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'test-setup.js');
8
+ const setupFileUrl = pathToFileURL(setupFile).href;
9
+ const qunitBin = path.resolve(cwd, 'node_modules/qunit/bin/qunit.js');
10
+
11
+ // Default to conventional test glob if no args provided
12
+ const testArgs = args.length > 0 ? args : ['test/**/*-test.js'];
13
+
14
+ const child = spawn(process.execPath, [
15
+ '--import', setupFileUrl,
16
+ qunitBin,
17
+ ...testArgs
18
+ ], {
19
+ cwd,
20
+ stdio: 'inherit',
21
+ env: { ...process.env, NODE_ENV: 'test' }
22
+ });
23
+
24
+ child.on('close', (code) => {
25
+ process.exit(code);
26
+ });
27
+ }
package/src/cli.js ADDED
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+
3
+ import serve from './cli/serve.js';
4
+ import test from './cli/test.js';
5
+ import help from './cli/help.js';
6
+ import newCommand from './cli/new.js';
7
+ import loadModuleCommands from './cli/load-commands.js';
8
+
9
+ try { process.loadEnvFile(); } catch { /* no .env file */ }
10
+
11
+ const aliases = { s: 'serve', t: 'test', h: 'help', n: 'new' };
12
+
13
+ const builtInCommands = {
14
+ serve: { description: 'Bootstrap Stonyx and run the app', run: serve },
15
+ test: { description: 'Bootstrap Stonyx in test mode and run tests', run: test },
16
+ new: { description: 'Scaffold a new Stonyx project', run: newCommand },
17
+ help: { description: 'Show available commands', run: help }
18
+ };
19
+
20
+ const args = process.argv.slice(2);
21
+ const commandName = aliases[args[0]] || args[0];
22
+ const commandArgs = args.slice(1);
23
+
24
+ async function main() {
25
+ if (!commandName || commandName === 'help') {
26
+ await help({ args: commandArgs, builtInCommands, loadModuleCommands });
27
+ return;
28
+ }
29
+
30
+ const builtIn = builtInCommands[commandName];
31
+
32
+ if (builtIn) {
33
+ await builtIn.run({ args: commandArgs });
34
+ return;
35
+ }
36
+
37
+ // Search module commands
38
+ const moduleCommands = await loadModuleCommands();
39
+ const moduleCommand = moduleCommands[commandName];
40
+
41
+ if (moduleCommand) {
42
+ const cwd = process.cwd();
43
+
44
+ if (moduleCommand.bootstrap) {
45
+ const { default: config } = await import(`${cwd}/config/environment.js`);
46
+ const { default: Stonyx } = await import('./main.js');
47
+ new Stonyx(config, cwd);
48
+ await Stonyx.ready;
49
+ }
50
+
51
+ await moduleCommand.run({ args: commandArgs, cwd });
52
+ return;
53
+ }
54
+
55
+ console.error(`Unknown command: ${args[0]}\n`);
56
+ await help({ args: [], builtInCommands, loadModuleCommands });
57
+ process.exit(1);
58
+ }
59
+
60
+ main().catch(error => {
61
+ console.error(error);
62
+ process.exit(1);
63
+ });
@@ -0,0 +1,17 @@
1
+ export async function runStartupHooks(modules) {
2
+ for (const module of modules) {
3
+ if (typeof module.startup === 'function') await module.startup();
4
+ }
5
+ }
6
+
7
+ export async function runShutdownHooks(modules) {
8
+ for (const module of [...modules].reverse()) {
9
+ if (typeof module.shutdown === 'function') {
10
+ try {
11
+ await module.shutdown();
12
+ } catch (error) {
13
+ console.error('Error during module shutdown:', error);
14
+ }
15
+ }
16
+ }
17
+ }
package/src/main.js CHANGED
@@ -14,9 +14,10 @@
14
14
  * limitations under the License.
15
15
  */
16
16
 
17
- import Chronicle from 'node-chronicle';
17
+ import Chronicle from '@stonyx/logs';
18
18
  import loadModules from './modules.js';
19
19
  import { kebabCaseToCamelCase } from '@stonyx/utils/string';
20
+ import { mergeObject } from '@stonyx/utils/object';
20
21
 
21
22
  export default class Stonyx {
22
23
  static initialized = false
@@ -45,6 +46,16 @@ export default class Stonyx {
45
46
 
46
47
  Stonyx.initialized = true;
47
48
 
49
+ // Auto-merge test environment overrides (after initialized flag, before modules load)
50
+ // Uses in-place mutation to preserve existing references (e.g. stonyx/config export cache)
51
+ if (process.env.NODE_ENV === 'test') {
52
+ try {
53
+ const { default: testOverrides } = await import(`${rootPath}/test/config/environment.js`);
54
+ const merged = mergeObject(config, testOverrides);
55
+ Object.assign(config, merged);
56
+ } catch { /* no test overrides found */ }
57
+ }
58
+
48
59
  this.modules = await loadModules(config, rootPath, this.chronicle);
49
60
  this.configureUserLogs();
50
61
  }
@@ -1,36 +0,0 @@
1
- name: CI
2
-
3
- on:
4
- pull_request:
5
- branches:
6
- - dev
7
- - main
8
-
9
- concurrency:
10
- group: ci-${{ github.head_ref || github.ref }}
11
- cancel-in-progress: true
12
-
13
- jobs:
14
- test:
15
- runs-on: ubuntu-latest
16
-
17
- steps:
18
- - name: Checkout code
19
- uses: actions/checkout@v3
20
-
21
- - name: Setup pnpm
22
- uses: pnpm/action-setup@v4
23
- with:
24
- version: 9
25
-
26
- - name: Set up Node.js
27
- uses: actions/setup-node@v3
28
- with:
29
- node-version: 24.13.0
30
- cache: 'pnpm'
31
-
32
- - name: Install dependencies
33
- run: pnpm install --frozen-lockfile
34
-
35
- - name: Run tests
36
- run: pnpm test
@@ -1,143 +0,0 @@
1
- name: Publish to NPM
2
-
3
- on:
4
- # Manual trigger (kept for flexibility)
5
- workflow_dispatch:
6
- inputs:
7
- version-type:
8
- description: 'Version type'
9
- required: true
10
- type: choice
11
- options:
12
- - alpha
13
- - patch
14
- - minor
15
- - major
16
- custom-version:
17
- description: 'Custom version (optional, overrides version-type)'
18
- required: false
19
- type: string
20
-
21
- # Auto-publish alpha on PR
22
- pull_request:
23
- types: [opened, synchronize, reopened]
24
- branches: [main, dev]
25
-
26
- # Auto-publish stable on merge to main
27
- push:
28
- branches: [main]
29
-
30
- permissions:
31
- contents: write
32
- id-token: write # Required for npm provenance
33
- pull-requests: write # For PR comments
34
-
35
- jobs:
36
- publish:
37
- runs-on: ubuntu-latest
38
-
39
- steps:
40
- - name: Checkout code
41
- uses: actions/checkout@v3
42
- with:
43
- fetch-depth: 0
44
- # For PR events, check out the PR branch
45
- ref: ${{ github.event_name == 'pull_request' && github.head_ref || github.ref }}
46
-
47
- - name: Setup pnpm
48
- uses: pnpm/action-setup@v4
49
- with:
50
- version: 9
51
-
52
- - name: Set up Node.js
53
- uses: actions/setup-node@v3
54
- with:
55
- node-version: 24.13.0
56
- cache: 'pnpm'
57
- registry-url: 'https://registry.npmjs.org'
58
-
59
- - name: Install dependencies
60
- run: pnpm install --frozen-lockfile
61
-
62
- - name: Run tests
63
- run: pnpm test
64
-
65
- - name: Configure git
66
- run: |
67
- git config user.name "github-actions[bot]"
68
- git config user.email "github-actions[bot]@users.noreply.github.com"
69
-
70
- # Determine version type based on trigger
71
- - name: Determine version bump type
72
- id: version-type
73
- run: |
74
- if [ "${{ github.event_name }}" = "pull_request" ]; then
75
- echo "type=alpha" >> $GITHUB_OUTPUT
76
- elif [ "${{ github.event_name }}" = "push" ]; then
77
- echo "type=patch" >> $GITHUB_OUTPUT
78
- elif [ "${{ github.event.inputs.custom-version }}" != "" ]; then
79
- echo "type=custom" >> $GITHUB_OUTPUT
80
- else
81
- echo "type=${{ github.event.inputs.version-type }}" >> $GITHUB_OUTPUT
82
- fi
83
-
84
- # Version bumping
85
- - name: Bump version (custom)
86
- if: steps.version-type.outputs.type == 'custom'
87
- run: pnpm version ${{ github.event.inputs.custom-version }} --no-git-tag-version
88
-
89
- - name: Bump version (alpha)
90
- if: steps.version-type.outputs.type == 'alpha'
91
- run: pnpm version prerelease --preid=alpha --no-git-tag-version
92
-
93
- - name: Bump version (patch/minor/major)
94
- if: steps.version-type.outputs.type == 'patch' || steps.version-type.outputs.type == 'minor' || steps.version-type.outputs.type == 'major'
95
- run: pnpm version ${{ steps.version-type.outputs.type }} --no-git-tag-version
96
-
97
- - name: Get package version
98
- id: package-version
99
- run: echo "version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT
100
-
101
- # Publishing
102
- - name: Publish to NPM (alpha)
103
- if: contains(steps.package-version.outputs.version, 'alpha')
104
- run: pnpm publish --tag alpha --access public --no-git-checks
105
-
106
- - name: Publish to NPM (stable)
107
- if: "!contains(steps.package-version.outputs.version, 'alpha')"
108
- run: pnpm publish --access public
109
-
110
- # Only commit and tag for stable releases (push to main or manual stable)
111
- - name: Commit version bump and create tag
112
- if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && !contains(steps.package-version.outputs.version, 'alpha'))
113
- run: |
114
- git add package.json
115
- git commit -m "chore: release v${{ steps.package-version.outputs.version }}"
116
- git tag v${{ steps.package-version.outputs.version }}
117
- git push origin main --tags
118
-
119
- - name: Create GitHub Release
120
- if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && !contains(steps.package-version.outputs.version, 'alpha'))
121
- uses: actions/create-release@v1
122
- env:
123
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
124
- with:
125
- tag_name: v${{ steps.package-version.outputs.version }}
126
- release_name: v${{ steps.package-version.outputs.version }}
127
- draft: false
128
- prerelease: false
129
-
130
- # Add PR comment with alpha version info
131
- - name: Comment on PR with alpha version
132
- if: github.event_name == 'pull_request'
133
- uses: actions/github-script@v6
134
- with:
135
- script: |
136
- const version = '${{ steps.package-version.outputs.version }}';
137
- const packageName = require('./package.json').name;
138
- github.rest.issues.createComment({
139
- issue_number: context.issue.number,
140
- owner: context.repo.owner,
141
- repo: context.repo.repo,
142
- body: `## 🚀 Alpha Version Published\n\n**Version:** \`${version}\`\n\n**Install:**\n\`\`\`bash\npnpm add ${packageName}@${version}\n# or\npnpm add ${packageName}@alpha # latest alpha\n\`\`\`\n\nThis alpha version is now available for testing!`
143
- });
@@ -1,16 +0,0 @@
1
- import { copyFile, createDirectory } from '@stonyx/utils/file';
2
-
3
- const projectDir = process.env.INIT_CWD;
4
- const configDir = `${projectDir}/config`;
5
- const bootstrapFile = 'stonyx-bootstrap.cjs';
6
- const envFile = 'environment.js';
7
-
8
- createDirectory(configDir);
9
-
10
- copyFile(`./config/environment copy.js`, `${configDir}/${envFile}`).then(result => {
11
- if (result) console.log(`Stonyx: ${envFile} has been successfully created. Please see README.md for more information.`);
12
- });
13
-
14
- copyFile(`./src/bootstrap.cjs`, `${projectDir}/${bootstrapFile}`).then(result => {
15
- if (result) console.log(`Stonyx: ${bootstrapFile} has been successfully created. Please see README.md for more information.`);
16
- });
package/src/bootstrap.cjs DELETED
@@ -1,9 +0,0 @@
1
- /**
2
- * commonJS Bootstrap loading - Stonyx must be loaded first, prior to the rest of the application
3
- */
4
- const { default:Stonyx } = require('stonyx');
5
- const { default:config } = require('./config/environment.js');
6
-
7
- new Stonyx(config, __dirname);
8
-
9
- module.exports = Stonyx;
@@ -1,9 +0,0 @@
1
- /**
2
- * commonJS Bootstrap loading - Stonyx must be loaded first, prior to the rest of the application
3
- */
4
- const { default:Stonyx } = require('stonyx');
5
- const { default:config } = require('./config/environment.js');
6
-
7
- new Stonyx(config, __dirname);
8
-
9
- module.exports = Stonyx;