stonyx 0.2.2 → 0.2.3-alpha.1

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.
@@ -0,0 +1,108 @@
1
+ # Developing Modules
2
+
3
+ Guide for building custom Stonyx modules.
4
+
5
+ ## Package Setup
6
+
7
+ Your module's `package.json` must include:
8
+
9
+ ```json
10
+ {
11
+ "name": "@stonyx/my-module",
12
+ "keywords": ["stonyx-module"],
13
+ "main": "src/index.js"
14
+ }
15
+ ```
16
+
17
+ Add `stonyx-async` to keywords if your module requires asynchronous initialization.
18
+
19
+ ## Module Class
20
+
21
+ Export a default class. Optionally define `init()`, `startup()`, and `shutdown()` methods:
22
+
23
+ ```js
24
+ export default class MyModule {
25
+ // Called during module loading (async modules only)
26
+ async init() {
27
+ // Connect to services, load resources, etc.
28
+ }
29
+
30
+ // Called after ALL modules are initialized, before app entry runs
31
+ async startup() {
32
+ // Register routes, start listeners, etc.
33
+ }
34
+
35
+ // Called on SIGTERM/SIGINT, in reverse load order
36
+ async shutdown() {
37
+ // Close connections, flush data, etc.
38
+ }
39
+ }
40
+ ```
41
+
42
+ ## Default Configuration
43
+
44
+ Async modules must include `config/environment.js` with sensible defaults:
45
+
46
+ ```js
47
+ export default {
48
+ logColor: 'cyan',
49
+ logMethod: 'myModule',
50
+ logTimestamp: true,
51
+ // Module-specific defaults...
52
+ };
53
+ ```
54
+
55
+ User project config is merged on top of these defaults.
56
+
57
+ ## Waiting for Other Modules
58
+
59
+ If your module depends on another async module being ready:
60
+
61
+ ```js
62
+ import { waitForModule } from 'stonyx';
63
+
64
+ export default class MyModule {
65
+ async init() {
66
+ await waitForModule('rest-server');
67
+ // @stonyx/rest-server is now fully initialized
68
+ }
69
+ }
70
+ ```
71
+
72
+ Pass the module name without the `@stonyx/` prefix.
73
+
74
+ ## Standalone Development
75
+
76
+ When running a module standalone (project path contains `stonyx-`), Stonyx auto-transforms the config structure. Your module's config is wrapped under its camelCase name:
77
+
78
+ ```js
79
+ // If your module is @stonyx/rest-server and config is { port: 3000 }
80
+ // Stonyx transforms it to: { restServer: { port: 3000 } }
81
+ ```
82
+
83
+ ## Custom CLI Commands
84
+
85
+ Modules can register CLI commands by adding a `./commands` export:
86
+
87
+ ```json
88
+ {
89
+ "exports": {
90
+ "./commands": "./src/commands.js"
91
+ }
92
+ }
93
+ ```
94
+
95
+ ```js
96
+ // src/commands.js
97
+ export default {
98
+ 'my-module:setup': {
99
+ description: 'Initialize module resources',
100
+ bootstrap: true,
101
+ run: async ({ args, cwd }) => {
102
+ // Command implementation
103
+ }
104
+ }
105
+ };
106
+ ```
107
+
108
+ Use namespaced command names (e.g., `my-module:setup`) to avoid conflicts with other modules. See [CLI](cli.md#module-commands) for details.
package/docs/index.md ADDED
@@ -0,0 +1,15 @@
1
+ # Stonyx Documentation
2
+
3
+ ## Guides
4
+
5
+ - [CLI](cli.md) — Commands, usage, and module-contributed commands
6
+ - [Configuration](configuration.md) — Environment config, module config, and test overrides
7
+ - [Modules](modules.md) — Module discovery, sync vs async, and official modules
8
+ - [Lifecycle](lifecycle.md) — Startup/shutdown hooks and signal handling
9
+ - [Logging](logging.md) — Color-coded logging via Chronicle
10
+ - [Testing](testing.md) — Running tests, config overrides, and integration helpers
11
+ - [Developing Modules](developing-modules.md) — Guide for building custom Stonyx modules
12
+
13
+ ## Reference
14
+
15
+ - [API Reference](api.md) — Public exports and class documentation
@@ -0,0 +1,47 @@
1
+ # Lifecycle Hooks
2
+
3
+ Stonyx modules can define `startup()` and `shutdown()` methods that run at specific points in the application lifecycle.
4
+
5
+ ## Startup Hooks
6
+
7
+ Called sequentially (in module load order) after all modules have been initialized, right before your application entry point runs.
8
+
9
+ ```js
10
+ export default class MyModule {
11
+ async startup() {
12
+ // Called after all modules are init'd, before app.js runs
13
+ }
14
+ }
15
+ ```
16
+
17
+ ## Shutdown Hooks
18
+
19
+ Called sequentially in **reverse** module load order when the process receives `SIGTERM` or `SIGINT`. Errors in one hook do not prevent other hooks from running.
20
+
21
+ ```js
22
+ export default class MyModule {
23
+ async shutdown() {
24
+ // Clean up connections, flush buffers, etc.
25
+ }
26
+ }
27
+ ```
28
+
29
+ ## Signal Handling
30
+
31
+ The `stonyx serve` command registers signal handlers automatically:
32
+
33
+ - **SIGTERM** — triggers shutdown hooks, then `process.exit(0)`
34
+ - **SIGINT** — triggers shutdown hooks, then `process.exit(0)`
35
+
36
+ Shutdown is idempotent — calling the handler multiple times only runs hooks once.
37
+
38
+ ## Using Lifecycle Hooks Directly
39
+
40
+ For advanced use cases, the lifecycle functions are available as a public export:
41
+
42
+ ```js
43
+ import { runStartupHooks, runShutdownHooks } from 'stonyx/lifecycle';
44
+
45
+ await runStartupHooks(modules); // Calls startup() on each module in order
46
+ await runShutdownHooks(modules); // Calls shutdown() on each module in reverse order
47
+ ```
@@ -0,0 +1,52 @@
1
+ # Logging
2
+
3
+ Stonyx provides centralized, color-coded logging via [Chronicle](https://github.com/abofs/chronicle).
4
+
5
+ ## Overview
6
+
7
+ Every Stonyx instance creates a Chronicle logger with a default `title` log type (green). Modules and user services can register additional log types with custom colors.
8
+
9
+ ## Module Logs
10
+
11
+ Modules that specify `logColor` in their configuration automatically get a Chronicle log type:
12
+
13
+ ```js
14
+ // config/environment.js
15
+ export default {
16
+ restServer: {
17
+ logColor: 'yellow',
18
+ logMethod: 'api', // Optional — defaults to the config key name
19
+ logTimestamp: true, // Optional — adds timestamps to log output
20
+ },
21
+ };
22
+ ```
23
+
24
+ This creates a `chronicle.api()` method that outputs in yellow with timestamps.
25
+
26
+ ## Custom Logs
27
+
28
+ You can define logs for any class or service in your project — not just Stonyx modules:
29
+
30
+ ```js
31
+ export default {
32
+ myWorker: {
33
+ logColor: 'cyan',
34
+ logMethod: 'worker',
35
+ logTimestamp: true,
36
+ },
37
+ };
38
+ ```
39
+
40
+ Any top-level config key with a `logColor` property will have a log type created automatically.
41
+
42
+ ## Accessing the Logger
43
+
44
+ ```js
45
+ import log from 'stonyx/log';
46
+
47
+ log.title('Application started');
48
+ log.api('Request received'); // If restServer config defines logMethod: 'api'
49
+ log.worker('Processing job'); // If myWorker config defines logMethod: 'worker'
50
+ ```
51
+
52
+ The `stonyx/log` export is a live reference to the Chronicle instance. It will throw if accessed before Stonyx is initialized.
@@ -0,0 +1,78 @@
1
+ # Module System
2
+
3
+ Stonyx uses a plug-and-play module architecture. Modules are automatically detected, loaded, and initialized at startup.
4
+
5
+ ## How Modules Are Discovered
6
+
7
+ Stonyx scans your project's `devDependencies` for packages prefixed with `@stonyx/`. Each matching package must include the `stonyx-module` keyword in its `package.json` to be loaded.
8
+
9
+ ```json
10
+ {
11
+ "name": "@stonyx/my-module",
12
+ "keywords": ["stonyx-module"],
13
+ "main": "src/index.js"
14
+ }
15
+ ```
16
+
17
+ ## Sync vs Async Modules
18
+
19
+ ### Sync Modules
20
+
21
+ Modules with only the `stonyx-module` keyword are treated as synchronous. They are instantiated but their promise resolves immediately — no init phase is awaited.
22
+
23
+ ### Async Modules
24
+
25
+ Modules that also include the `stonyx-async` keyword require initialization before they're ready:
26
+
27
+ ```json
28
+ {
29
+ "keywords": ["stonyx-module", "stonyx-async"]
30
+ }
31
+ ```
32
+
33
+ Async modules **must** include a `config/environment.js` with default configuration. This is merged with the user's project config before initialization.
34
+
35
+ Async modules can define an `init()` method that Stonyx awaits:
36
+
37
+ ```js
38
+ export default class MyModule {
39
+ async init() {
40
+ // Connect to database, start server, etc.
41
+ }
42
+ }
43
+ ```
44
+
45
+ All module `init()` calls run concurrently via `Promise.all`.
46
+
47
+ ## Module Lifecycle
48
+
49
+ 1. **Discovery** — scan `devDependencies` for `@stonyx/*` packages
50
+ 2. **Validation** — verify `stonyx-module` keyword exists
51
+ 3. **Config merge** — async module defaults merged with user config
52
+ 4. **Log setup** — module-specific Chronicle log created if `logColor` is set
53
+ 5. **Instantiation** — module class is `new`'d
54
+ 6. **Initialization** — `init()` called (async modules only)
55
+ 7. **Startup hooks** — `startup()` called after all modules init (see [Lifecycle](lifecycle.md))
56
+ 8. **Shutdown hooks** — `shutdown()` called on process exit (see [Lifecycle](lifecycle.md))
57
+
58
+ ## waitForModule
59
+
60
+ For submodule developers who need to ensure another async module is ready:
61
+
62
+ ```js
63
+ import { waitForModule } from 'stonyx';
64
+
65
+ await waitForModule('rest-server'); // Waits for @stonyx/rest-server
66
+ ```
67
+
68
+ > **Note:** `waitForModule` is only needed during submodule development or testing. End-user applications don't need it — the CLI ensures all modules are initialized before running your app.
69
+
70
+ ## Official Modules
71
+
72
+ | Module | Description |
73
+ |--------|-------------|
74
+ | [@stonyx/cron](https://github.com/abofs/stonyx-cron) | Lightweight async job scheduling with min-heap |
75
+ | [@stonyx/rest-server](https://github.com/abofs/stonyx-rest-server) | Dynamic REST server with auto-route registration |
76
+ | [@stonyx/orm](https://github.com/abofs/stonyx-orm) | ORM with models, relationships, serializers, and optional REST integration |
77
+
78
+ See each module's repository for its specific documentation.
@@ -0,0 +1,64 @@
1
+ # Testing
2
+
3
+ Stonyx includes built-in test infrastructure using [QUnit](https://qunitjs.com/).
4
+
5
+ ## Running Tests
6
+
7
+ ```bash
8
+ stonyx test # Runs test/**/*-test.js by default
9
+ stonyx test "test/unit/**/*.js" # Custom glob pattern
10
+ ```
11
+
12
+ The test command:
13
+ 1. Sets `NODE_ENV=test`
14
+ 2. Bootstraps Stonyx via a `--require` setup file
15
+ 3. Applies [test config overrides](configuration.md#test-environment-overrides)
16
+ 4. Runs QUnit with the specified glob
17
+
18
+ ## Test Config Overrides
19
+
20
+ Create `test/config/environment.js` to override configuration during tests:
21
+
22
+ ```js
23
+ export default {
24
+ debug: false,
25
+ restServer: { port: 0 },
26
+ };
27
+ ```
28
+
29
+ These are deep-merged into the main config. See [Configuration](configuration.md#test-environment-overrides).
30
+
31
+ ## Integration Test Helper
32
+
33
+ For tests that need Stonyx fully initialized (e.g., testing modules with database connections):
34
+
35
+ ```js
36
+ import { setupIntegrationTests } from 'stonyx/test-helpers';
37
+
38
+ const { module, test } = QUnit;
39
+
40
+ module('My Integration Test', function(hooks) {
41
+ setupIntegrationTests(hooks);
42
+
43
+ test('can access modules', function(assert) {
44
+ // Stonyx is fully initialized here
45
+ assert.ok(true);
46
+ });
47
+ });
48
+ ```
49
+
50
+ `setupIntegrationTests` adds a `before` hook that waits for `Stonyx.ready` to resolve.
51
+
52
+ ## Test File Convention
53
+
54
+ Place tests under `test/` with the `-test.js` suffix:
55
+
56
+ ```
57
+ test/
58
+ unit/
59
+ my-feature-test.js
60
+ cli/
61
+ serve-test.js
62
+ integration/
63
+ api-test.js
64
+ ```
package/package.json CHANGED
@@ -1,19 +1,26 @@
1
1
  {
2
2
  "name": "stonyx",
3
- "version": "0.2.2",
3
+ "version": "0.2.3-alpha.1",
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
+ "publishConfig": {
22
+ "provenance": true
23
+ },
17
24
  "author": "Stone Costa",
18
25
  "license": "Apache-2.0",
19
26
  "contributors": [
@@ -26,7 +33,7 @@
26
33
  "node-chronicle": "^0.2.0"
27
34
  },
28
35
  "devDependencies": {
29
- "@stonyx/utils": "^0.2.2",
36
+ "@stonyx/utils": "0.2.3-beta.5",
30
37
  "qunit": "^2.24.1",
31
38
  "sinon": "^21.0.0"
32
39
  },
@@ -2,7 +2,6 @@ import { copyFile, createDirectory } from '@stonyx/utils/file';
2
2
 
3
3
  const projectDir = process.env.INIT_CWD;
4
4
  const configDir = `${projectDir}/config`;
5
- const bootstrapFile = 'stonyx-bootstrap.cjs';
6
5
  const envFile = 'environment.js';
7
6
 
8
7
  createDirectory(configDir);
@@ -10,7 +9,3 @@ createDirectory(configDir);
10
9
  copyFile(`./config/environment copy.js`, `${configDir}/${envFile}`).then(result => {
11
10
  if (result) console.log(`Stonyx: ${envFile} has been successfully created. Please see README.md for more information.`);
12
11
  });
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
- });
@@ -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
+ }