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.
package/src/cli/new.js ADDED
@@ -0,0 +1,232 @@
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
+
39
+ function generateDbSchema() {
40
+ return `import { Model, hasMany } from '@stonyx/orm';
41
+
42
+ export default class DBModel extends Model {
43
+ // Define your collections here
44
+ // examples = hasMany('example');
45
+ }
46
+ `;
47
+ }
48
+
49
+ function generatePackageJson(name, selectedModules) {
50
+ const devDependencies = { stonyx: 'latest' };
51
+
52
+ for (const mod of selectedModules) {
53
+ devDependencies[mod.package] = 'latest';
54
+ }
55
+
56
+ // Sort dependencies alphabetically
57
+ const sorted = Object.fromEntries(
58
+ Object.entries(devDependencies).sort(([a], [b]) => a.localeCompare(b))
59
+ );
60
+
61
+ return JSON.stringify({
62
+ name,
63
+ version: '0.1.0',
64
+ type: 'module',
65
+ private: true,
66
+ scripts: {
67
+ start: 'stonyx serve',
68
+ test: 'stonyx test'
69
+ },
70
+ devDependencies: sorted
71
+ }, null, 2) + '\n';
72
+ }
73
+
74
+ function generateAppJs() {
75
+ return `import log from 'stonyx/log';
76
+
77
+ export default class App {
78
+ constructor() {
79
+ if (App.instance) return App.instance;
80
+ App.instance = this;
81
+
82
+ this.ready = this.init();
83
+ }
84
+
85
+ async init() {
86
+ log.info('Initializing Application');
87
+
88
+ // Application setup here
89
+
90
+ log.info('Application has been initialized');
91
+ }
92
+ }
93
+ `;
94
+ }
95
+
96
+ function generateEnvironmentJs() {
97
+ return `export default {
98
+ }
99
+ `;
100
+ }
101
+
102
+ function generateEnvironmentExampleJs() {
103
+ return `// Copy this file to environment.js and fill in your values
104
+ // All values should use environment variables with ?? fallback defaults
105
+
106
+ const {
107
+ NODE_ENV,
108
+ } = process.env;
109
+
110
+ const environment = NODE_ENV ?? 'development';
111
+
112
+ export default {
113
+ }
114
+ `;
115
+ }
116
+
117
+ function generateGitignore() {
118
+ return `node_modules/
119
+ .env
120
+ db.json
121
+ *.log
122
+ `;
123
+ }
124
+
125
+ function runPnpmInstall(projectDir) {
126
+ return new Promise((resolve, reject) => {
127
+ const child = spawn('pnpm', ['install'], {
128
+ cwd: projectDir,
129
+ stdio: 'inherit'
130
+ });
131
+
132
+ child.on('close', code => {
133
+ if (code === 0) resolve();
134
+ else reject(new Error(`pnpm install exited with code ${code}`));
135
+ });
136
+
137
+ child.on('error', reject);
138
+ });
139
+ }
140
+
141
+ export default async function newCommand({ args }) {
142
+ let appName = args[0];
143
+
144
+ if (!appName) {
145
+ appName = await prompt('Project name:');
146
+ }
147
+
148
+ if (!appName) {
149
+ console.error('Project name is required.');
150
+ process.exit(1);
151
+ }
152
+
153
+ const projectDir = path.resolve(process.cwd(), appName);
154
+
155
+ if (await fileExists(projectDir)) {
156
+ console.error(`Directory "${appName}" already exists.`);
157
+ process.exit(1);
158
+ }
159
+
160
+ console.log(`\nScaffolding new Stonyx project: ${appName}\n`);
161
+
162
+ // Prompt for module selection
163
+ const selectedModules = [];
164
+
165
+ for (const mod of MODULE_OPTIONS) {
166
+ if (await confirm(mod.question)) {
167
+ selectedModules.push(mod);
168
+ }
169
+ }
170
+
171
+ console.log('\nCreating project structure...\n');
172
+
173
+ // Create project directory
174
+ await createDirectory(projectDir);
175
+
176
+ // Copy .nvmrc from monorepo root
177
+ const monorepoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
178
+ const nvmrcSource = path.join(monorepoRoot, '.nvmrc');
179
+
180
+ if (await fileExists(nvmrcSource)) {
181
+ await copyFile(nvmrcSource, path.join(projectDir, '.nvmrc'));
182
+ }
183
+
184
+ // Generate core files
185
+ await createFile(path.join(projectDir, 'package.json'), generatePackageJson(appName, selectedModules));
186
+ await createFile(path.join(projectDir, 'app.js'), generateAppJs());
187
+ await createFile(path.join(projectDir, '.gitignore'), generateGitignore());
188
+
189
+ // Create config directory and files
190
+ await createFile(path.join(projectDir, 'config', 'environment.js'), generateEnvironmentJs());
191
+ await createFile(path.join(projectDir, 'config', 'environment.example.js'), generateEnvironmentExampleJs());
192
+
193
+ // Create module-specific directories and files
194
+ for (const mod of selectedModules) {
195
+ if (mod.dirs) {
196
+ for (const dir of mod.dirs) {
197
+ await createDirectory(path.join(projectDir, dir));
198
+ // Create .gitkeep so empty dirs are tracked
199
+ await createFile(path.join(projectDir, dir, '.gitkeep'), '');
200
+ }
201
+ }
202
+
203
+ if (mod.files) {
204
+ for (const [filePath, generator] of Object.entries(mod.files)) {
205
+ await createFile(path.join(projectDir, filePath), generator());
206
+ }
207
+ }
208
+ }
209
+
210
+ // Create test structure
211
+ await createDirectory(path.join(projectDir, 'test', 'unit'));
212
+ await createFile(path.join(projectDir, 'test', 'unit', '.gitkeep'), '');
213
+ await createDirectory(path.join(projectDir, 'test', 'integration'));
214
+ await createFile(path.join(projectDir, 'test', 'integration', '.gitkeep'), '');
215
+ await createDirectory(path.join(projectDir, 'test', 'acceptance'));
216
+ await createFile(path.join(projectDir, 'test', 'acceptance', '.gitkeep'), '');
217
+
218
+ // Create test config
219
+ await createFile(path.join(projectDir, 'test', 'config', 'environment.js'), `export default {\n // Test-specific config overrides\n}\n`);
220
+
221
+ console.log('Installing dependencies...\n');
222
+
223
+ try {
224
+ await runPnpmInstall(projectDir);
225
+ } catch (error) {
226
+ console.error('Failed to install dependencies. Run `pnpm install` manually in the project directory.');
227
+ }
228
+
229
+ console.log(`\n✓ Project "${appName}" created successfully!`);
230
+ console.log(`\n cd ${appName}`);
231
+ console.log(` stonyx serve\n`);
232
+ }
@@ -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
@@ -17,6 +17,7 @@
17
17
  import Chronicle from 'node-chronicle';
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
  }
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;