@weconjs/core 0.1.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,98 @@
1
+ /**
2
+ * @weconjs/core - i18n Loader
3
+ *
4
+ * Auto-discovers and loads translation files from module i18n/ directories.
5
+ */
6
+ import { glob } from "glob";
7
+ import { basename, dirname } from "path";
8
+ import { readFileSync } from "fs";
9
+ /**
10
+ * Load translations from all module i18n directories
11
+ *
12
+ * @param modulesDir - Path to the modules directory
13
+ * @returns Loaded translation resources
14
+ */
15
+ export async function loadI18nResources(modulesDir) {
16
+ const resources = {};
17
+ try {
18
+ // Find all translation files
19
+ const files = await glob("**/i18n/*.translation.json", {
20
+ cwd: modulesDir,
21
+ absolute: true,
22
+ });
23
+ for (const file of files) {
24
+ try {
25
+ // Extract module name and language
26
+ // e.g., auth/i18n/en.translation.json -> namespace: auth, lang: en
27
+ const fileName = basename(file); // en.translation.json
28
+ const language = fileName.replace(".translation.json", "");
29
+ const moduleDir = dirname(dirname(file)); // auth/
30
+ const namespace = basename(moduleDir);
31
+ // Load translation file
32
+ const content = readFileSync(file, "utf-8");
33
+ const translations = JSON.parse(content);
34
+ // Add to resources
35
+ if (!resources[namespace]) {
36
+ resources[namespace] = {};
37
+ }
38
+ resources[namespace][language] = translations;
39
+ }
40
+ catch (err) {
41
+ console.warn(`[Wecon] Failed to load translation file ${file}:`, err);
42
+ }
43
+ }
44
+ }
45
+ catch (err) {
46
+ console.warn("[Wecon] Failed to discover translation files:", err);
47
+ }
48
+ return resources;
49
+ }
50
+ /**
51
+ * Create i18n middleware for Express
52
+ *
53
+ * @param resources - Loaded translation resources
54
+ * @param defaultLanguage - Default language code
55
+ * @returns Express middleware function
56
+ */
57
+ export function createI18nMiddleware(resources, defaultLanguage = "en") {
58
+ return (req, res, next) => {
59
+ // Get language from header or query
60
+ const lang = req.headers["accept-language"]?.split(",")[0]?.split("-")[0] ||
61
+ req.query.lang ||
62
+ defaultLanguage;
63
+ // Add translation function to request
64
+ req.t = (key, options) => {
65
+ const [namespace, ...keyParts] = key.split(".");
66
+ const actualKey = keyParts.join(".");
67
+ const translations = resources[namespace]?.[lang] || resources[namespace]?.[defaultLanguage];
68
+ if (!translations) {
69
+ return key; // Return key if no translations found
70
+ }
71
+ let value = translations;
72
+ for (const part of actualKey.split(".")) {
73
+ value = value?.[part];
74
+ }
75
+ if (typeof value !== "string") {
76
+ return key;
77
+ }
78
+ // Simple interpolation
79
+ if (options) {
80
+ return value.replace(/\{\{(\w+)\}\}/g, (_, k) => String(options[k] ?? `{{${k}}}`));
81
+ }
82
+ return value;
83
+ };
84
+ next();
85
+ };
86
+ }
87
+ /**
88
+ * Initialize i18n for a Wecon application
89
+ *
90
+ * @param modulesDir - Path to modules directory
91
+ * @param defaultLanguage - Default language
92
+ * @returns Express middleware
93
+ */
94
+ export async function initI18n(modulesDir, defaultLanguage = "en") {
95
+ const resources = await loadI18nResources(modulesDir);
96
+ return createI18nMiddleware(resources, defaultLanguage);
97
+ }
98
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/i18n/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAQ,QAAQ,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAWlC;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,UAAkB;IACxD,MAAM,SAAS,GAAkB,EAAE,CAAC;IAEpC,IAAI,CAAC;QACH,6BAA6B;QAC7B,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,4BAA4B,EAAE;YACrD,GAAG,EAAE,UAAU;YACf,QAAQ,EAAE,IAAI;SACf,CAAC,CAAC;QAEH,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,C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AU,QAAQ,CAAC,UAAkB,EAAE,kBAA0B,IAAI;IAC/E,MAAM,SAAS,GAAG,MAAM,iBAAiB,CAAC,UAAU,CAAC,CAAC;IACtD,OAAO,oBAAoB,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC;AAC1D,CAAC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @wecon/core
3
+ *
4
+ * Core package for the Wecon framework.
5
+ * Provides configuration, module system, and runtime utilities.
6
+ */
7
+ export { defineConfig, resolveConfig, loadConfig } from "./config.js";
8
+ export { defineModule, loadModule, discoverSocketHandlers, discoverSocketMiddleware, resolveModuleDependencies, } from "./module.js";
9
+ export { createContext, createLogger } from "./context.js";
10
+ export { createWecon } from "./server/index.js";
11
+ export type { CreateWeconOptions, WeconApp } from "./server/index.js";
12
+ export { loadI18nResources, createI18nMiddleware, initI18n } from "./i18n/index.js";
13
+ export type { I18nResources } from "./i18n/index.js";
14
+ export { createDatabaseConnection } from "./database/index.js";
15
+ export type { DatabaseOptions, DatabaseConnection } from "./database/index.js";
16
+ export { createSocketServer, discoverSocketHandlers as discoverSocketHandlersFromModules, discoverSocketMiddleware as discoverSocketMiddlewareFromModules, initializeSocket, setupSocketIO, } from "./socket/index.js";
17
+ export type { SocketServer, SocketInstance, SocketHandler as SocketHandlerFn, SocketMiddleware as SocketMiddlewareFn, DiscoveredSocketHandler, SocketOptions, } from "./socket/index.js";
18
+ export type { WeconConfig, ResolvedConfig, AppConfig, DatabaseConfig, LoggingConfig, HttpsConfig, SocketConfig, FeaturesConfig, ModeConfig, WeconHooks, ModuleDefinition, ModuleConfigDefinition, WeconModule, SocketHandler, SocketMiddleware, WeconContext, WeconLogger, WeconServices, Authenticable, AuthConfig, WeconRequest, WeconResponse, RouteHandler, WeconMiddleware, } from "./types.js";
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;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 +1,21 @@
1
+ /**
2
+ * @wecon/core
3
+ *
4
+ * Core package for the Wecon framework.
5
+ * Provides configuration, module system, and runtime utilities.
6
+ */
7
+ // Configuration
8
+ export { defineConfig, resolveConfig, loadConfig } from "./config.js";
9
+ // Module System
10
+ export { defineModule, loadModule, discoverSocketHandlers, discoverSocketMiddleware, resolveModuleDependencies, } from "./module.js";
11
+ // Context
12
+ export { createContext, createLogger } from "./context.js";
13
+ // Server
14
+ export { createWecon } from "./server/index.js";
15
+ // i18n
16
+ export { loadI18nResources, createI18nMiddleware, initI18n } from "./i18n/index.js";
17
+ // Database
18
+ export { createDatabaseConnection } from "./database/index.js";
19
+ // Socket.IO
20
+ export { createSocketServer, discoverSocketHandlers as discoverSocketHandlersFromModules, discoverSocketMiddleware as discoverSocketMiddlewareFromModules, initializeSocket, setupSocketIO, } from "./socket/index.js";
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,gBAAgB;AAChB,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEtE,gBAAgB;AAChB,OAAO,EACL,YAAY,EACZ,UAAU,EACV,sBAAsB,EACtB,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,aAAa,CAAC;AAErB,UAAU;AACV,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE3D,SAAS;AACT,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO;AACP,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAGpF,WAAW;AACX,OAAO,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAG/D,YAAY;AACZ,OAAO,EACL,kBAAkB,EAClB,sBAAsB,IAAI,iCAAiC,EAC3D,wBAAwB,IAAI,mCAAmC,EAC/D,gBAAgB,EAChB,aAAa,GACd,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @wecon/core - defineModule
3
+ *
4
+ * Creates a type-safe module definition for the Wecon framework.
5
+ * Modules are self-contained units with routes, config, and lifecycle hooks.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { defineModule } from '@wecon/core';
10
+ * import { authRoutes } from './routes';
11
+ * import { authConfig } from './auth.config';
12
+ *
13
+ * export default defineModule({
14
+ * name: 'auth',
15
+ * config: authConfig,
16
+ * routes: authRoutes,
17
+ * imports: ['users'],
18
+ * exports: ['AuthService', 'JwtService'],
19
+ * onInit: async (ctx) => {
20
+ * ctx.logger.info('Auth module initialized');
21
+ * },
22
+ * });
23
+ * ```
24
+ */
25
+ import type { ModuleDefinition, WeconModule, SocketHandler, SocketMiddleware } from "./types.js";
26
+ /**
27
+ * Define a Wecon module
28
+ *
29
+ * @param definition - The module definition
30
+ * @returns The validated module with computed defaults
31
+ */
32
+ export declare function defineModule(definition: ModuleDefinition): WeconModule;
33
+ /**
34
+ * Discover socket handlers in a module directory
35
+ *
36
+ * Scans the module's `socket/` folder for `*.socket.ts` files and loads them.
37
+ *
38
+ * @param modulePath - Absolute path to the module directory
39
+ * @returns Array of socket handler functions
40
+ */
41
+ export declare function discoverSocketHandlers(modulePath: string): Promise<{
42
+ name: string;
43
+ handler: SocketHandler;
44
+ }[]>;
45
+ /**
46
+ * Discover socket middleware in a module directory
47
+ *
48
+ * Loads `socket/socket.middleware.ts` if it exists.
49
+ *
50
+ * @param modulePath - Absolute path to the module directory
51
+ * @returns Array of socket middleware functions
52
+ */
53
+ export declare function discoverSocketMiddleware(modulePath: string): Promise<SocketMiddleware[]>;
54
+ /**
55
+ * Load a module from a path and discover its socket handlers
56
+ *
57
+ * @param modulePath - Path to the module (can be relative or package name)
58
+ * @param baseDir - Base directory for resolving relative paths
59
+ */
60
+ export declare function loadModule(modulePath: string, baseDir: string): Promise<WeconModule>;
61
+ /**
62
+ * Resolve module dependencies using topological sort
63
+ *
64
+ * @param modules - Map of module name to module
65
+ * @returns Ordered array of modules (dependencies first)
66
+ */
67
+ export declare function resolveModuleDependencies(modules: Map<string, WeconModule>): WeconModule[];
68
+ //# sourceMappingURL=module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.d.ts","sourceRoot":"","sources":["../src/module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,KAAK,EACV,gBAAgB,EAChB,WAAW,EACX,aAAa,EACb,gBAAgB,EACjB,MAAM,YAAY,CAAC;AA6BpB;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,UAAU,EAAE,gBAAgB,GAAG,WAAW,CAiCtE;AAED;;;;;;;GAOG;AACH,wBAAsB,sBAAsB,CAC1C,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,aAAa,CAAA;CAAE,EAAE,CAAC,CAmCrD;AAED;;;;;;;GAOG;AACH,wBAAsB,wBAAwB,CAC5C,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,gBAAgB,EAAE,CAAC,CA8B7B;AAED;;;;;GAKG;AACH,wBAAsB,UAAU,CAC9B,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,WAAW,CAAC,CA+CtB;AAED;;;;;GAKG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,GAChC,WAAW,EAAE,CAiCf"}
package/dist/module.js ADDED
@@ -0,0 +1,237 @@
1
+ /**
2
+ * @wecon/core - defineModule
3
+ *
4
+ * Creates a type-safe module definition for the Wecon framework.
5
+ * Modules are self-contained units with routes, config, and lifecycle hooks.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { defineModule } from '@wecon/core';
10
+ * import { authRoutes } from './routes';
11
+ * import { authConfig } from './auth.config';
12
+ *
13
+ * export default defineModule({
14
+ * name: 'auth',
15
+ * config: authConfig,
16
+ * routes: authRoutes,
17
+ * imports: ['users'],
18
+ * exports: ['AuthService', 'JwtService'],
19
+ * onInit: async (ctx) => {
20
+ * ctx.logger.info('Auth module initialized');
21
+ * },
22
+ * });
23
+ * ```
24
+ */
25
+ import { glob } from "glob";
26
+ import { join, basename } from "path";
27
+ /**
28
+ * Recursively set namespace in meta for all routes
29
+ * This enables automatic i18n namespace detection.
30
+ *
31
+ * @param routes - Route or Routes instance
32
+ * @param namespace - The module namespace
33
+ */
34
+ function setNamespaceMeta(routes, namespace) {
35
+ if (!routes || typeof routes !== "object")
36
+ return;
37
+ const routeObj = routes;
38
+ // Set namespace in meta
39
+ if ("meta" in routeObj) {
40
+ routeObj.meta = { ...routeObj.meta, namespace };
41
+ }
42
+ // Recursively process child routes
43
+ if ("routes" in routeObj && Array.isArray(routeObj.routes)) {
44
+ for (const child of routeObj.routes) {
45
+ setNamespaceMeta(child, namespace);
46
+ }
47
+ }
48
+ }
49
+ /**
50
+ * Define a Wecon module
51
+ *
52
+ * @param definition - The module definition
53
+ * @returns The validated module with computed defaults
54
+ */
55
+ export function defineModule(definition) {
56
+ // Validate required fields
57
+ if (!definition.name) {
58
+ throw new Error("[Wecon] Module name is required");
59
+ }
60
+ // Validate name format (lowercase, alphanumeric, hyphens)
61
+ if (!/^[a-z][a-z0-9-]*$/.test(definition.name)) {
62
+ throw new Error(`[Wecon] Invalid module name "${definition.name}". Must be lowercase, start with a letter, and contain only alphanumeric characters and hyphens.`);
63
+ }
64
+ const namespace = definition.namespace ?? definition.name;
65
+ // Inject namespace into all routes meta for i18n detection
66
+ if (definition.routes) {
67
+ setNamespaceMeta(definition.routes, namespace);
68
+ }
69
+ return {
70
+ name: definition.name,
71
+ namespace,
72
+ description: definition.description ?? "",
73
+ config: definition.config,
74
+ routes: definition.routes,
75
+ imports: definition.imports ?? [],
76
+ exports: definition.exports ?? [],
77
+ onInit: definition.onInit,
78
+ onDestroy: definition.onDestroy,
79
+ socketHandlers: [],
80
+ socketMiddleware: [],
81
+ };
82
+ }
83
+ /**
84
+ * Discover socket handlers in a module directory
85
+ *
86
+ * Scans the module's `socket/` folder for `*.socket.ts` files and loads them.
87
+ *
88
+ * @param modulePath - Absolute path to the module directory
89
+ * @returns Array of socket handler functions
90
+ */
91
+ export async function discoverSocketHandlers(modulePath) {
92
+ const socketDir = join(modulePath, "socket");
93
+ const handlers = [];
94
+ try {
95
+ // Find all *.socket.ts files
96
+ const files = await glob("*.socket.{ts,js}", {
97
+ cwd: socketDir,
98
+ absolute: true,
99
+ });
100
+ for (const file of files) {
101
+ try {
102
+ const module = await import(file);
103
+ const handler = module.default;
104
+ if (typeof handler !== "function") {
105
+ console.warn(`[Wecon] Socket file ${basename(file)} must export a default function`);
106
+ continue;
107
+ }
108
+ // Extract handler name from filename (e.g., "chat.socket.ts" -> "chat")
109
+ const name = basename(file).replace(/\.socket\.(ts|js)$/, "");
110
+ handlers.push({ name, handler });
111
+ }
112
+ catch (err) {
113
+ console.error(`[Wecon] Failed to load socket handler ${file}:`, err);
114
+ }
115
+ }
116
+ }
117
+ catch {
118
+ // Socket directory doesn't exist - that's fine
119
+ }
120
+ return handlers;
121
+ }
122
+ /**
123
+ * Discover socket middleware in a module directory
124
+ *
125
+ * Loads `socket/socket.middleware.ts` if it exists.
126
+ *
127
+ * @param modulePath - Absolute path to the module directory
128
+ * @returns Array of socket middleware functions
129
+ */
130
+ export async function discoverSocketMiddleware(modulePath) {
131
+ const middlewarePath = join(modulePath, "socket", "socket.middleware");
132
+ try {
133
+ // Try .ts first, then .js
134
+ let module;
135
+ try {
136
+ module = await import(`${middlewarePath}.ts`);
137
+ }
138
+ catch {
139
+ module = await import(`${middlewarePath}.js`);
140
+ }
141
+ const middleware = module.default;
142
+ if (Array.isArray(middleware)) {
143
+ return middleware.filter((m) => typeof m === "function");
144
+ }
145
+ if (typeof middleware === "function") {
146
+ return [middleware];
147
+ }
148
+ console.warn(`[Wecon] socket.middleware.ts must export an array of middleware functions or a single function`);
149
+ return [];
150
+ }
151
+ catch {
152
+ // Middleware file doesn't exist - that's fine
153
+ return [];
154
+ }
155
+ }
156
+ /**
157
+ * Load a module from a path and discover its socket handlers
158
+ *
159
+ * @param modulePath - Path to the module (can be relative or package name)
160
+ * @param baseDir - Base directory for resolving relative paths
161
+ */
162
+ export async function loadModule(modulePath, baseDir) {
163
+ let absolutePath;
164
+ // Resolve the module path
165
+ if (modulePath.startsWith("./") || modulePath.startsWith("../")) {
166
+ absolutePath = join(baseDir, modulePath);
167
+ }
168
+ else if (modulePath.startsWith("@wecon/")) {
169
+ // Built-in module - resolve from node_modules
170
+ absolutePath = join(baseDir, "node_modules", modulePath);
171
+ }
172
+ else {
173
+ absolutePath = modulePath;
174
+ }
175
+ // Load the module definition
176
+ const moduleFile = join(absolutePath, `${basename(absolutePath)}.module`);
177
+ let module;
178
+ try {
179
+ // Try .ts first, then .js
180
+ let moduleExport;
181
+ try {
182
+ moduleExport = await import(`${moduleFile}.ts`);
183
+ }
184
+ catch {
185
+ moduleExport = await import(`${moduleFile}.js`);
186
+ }
187
+ module = moduleExport.default ?? moduleExport;
188
+ }
189
+ catch (err) {
190
+ throw new Error(`[Wecon] Failed to load module from ${modulePath}: ${err instanceof Error ? err.message : err}`);
191
+ }
192
+ // Discover socket handlers and middleware
193
+ const [socketHandlers, socketMiddleware] = await Promise.all([
194
+ discoverSocketHandlers(absolutePath),
195
+ discoverSocketMiddleware(absolutePath),
196
+ ]);
197
+ return {
198
+ ...module,
199
+ socketHandlers: socketHandlers.map((h) => h.handler),
200
+ socketMiddleware,
201
+ };
202
+ }
203
+ /**
204
+ * Resolve module dependencies using topological sort
205
+ *
206
+ * @param modules - Map of module name to module
207
+ * @returns Ordered array of modules (dependencies first)
208
+ */
209
+ export function resolveModuleDependencies(modules) {
210
+ const resolved = [];
211
+ const seen = new Set();
212
+ const visiting = new Set();
213
+ function visit(name) {
214
+ if (seen.has(name))
215
+ return;
216
+ if (visiting.has(name)) {
217
+ throw new Error(`[Wecon] Circular module dependency detected: ${name}`);
218
+ }
219
+ const module = modules.get(name);
220
+ if (!module) {
221
+ throw new Error(`[Wecon] Module "${name}" not found`);
222
+ }
223
+ visiting.add(name);
224
+ // Visit dependencies first
225
+ for (const dep of module.imports ?? []) {
226
+ visit(dep);
227
+ }
228
+ visiting.delete(name);
229
+ seen.add(name);
230
+ resolved.push(module);
231
+ }
232
+ for (const name of modules.keys()) {
233
+ visit(name);
234
+ }
235
+ return resolved;
236
+ }
237
+ //# sourceMappingURL=module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.js","sourceRoot":"","sources":["../src/module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAQH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AAEtC;;;;;;GAMG;AACH,SAAS,gBAAgB,CAAC,MAAe,EAAE,SAAiB;IAC1D,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ;QAAE,OAAO;IAElD,MAAM,QAAQ,GAAG,MAAiC,CAAC;IAEnD,wBAAwB;IACxB,IAAI,MAAM,IAAI,QAAQ,EAAE,CAAC;QACvB,QAAQ,CAAC,IAAI,GAAG,EAAE,GAAI,QAAQ,CAAC,IAAe,EAAE,SAAS,EAAE,CAAC;IAC9D,CAAC;IAED,mCAAmC;IACnC,IAAI,QAAQ,IAAI,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QAC3D,KAAK,MAAM,KAAK,IAAI,QAAQ,CAAC,MAAM,EAAE,CAAC;YACpC,gBAAgB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM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AAM,EAAE,CAAC;YACZ,MAAM,IAAI,KAAK,CAAC,mBAAmB,IAAI,aAAa,CAAC,CAAC;QACxD,CAAC;QAED,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAEnB,2BAA2B;QAC3B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,OAAO,IAAI,EAAE,EAAE,CAAC;YACvC,KAAK,CAAC,GAAG,CAAC,CAAC;QACb,CAAC;QAED,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACf,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACxB,CAAC;IAED,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC;QAClC,KAAK,CAAC,IAAI,CAAC,CAAC;IACd,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @weconjs/core - Server Factory
3
+ *
4
+ * Creates and configures the Express application with all framework features.
5
+ * This is the main entry point for the Wecon framework.
6
+ */
7
+ import type { Application, Request, Response, NextFunction } from "express";
8
+ import type { ResolvedConfig, WeconModule } from "../types.js";
9
+ /**
10
+ * Options for creating a Wecon application
11
+ */
12
+ export interface CreateWeconOptions {
13
+ /**
14
+ * Resolved configuration from wecon.config.ts
15
+ */
16
+ config: ResolvedConfig;
17
+ /**
18
+ * Registered modules
19
+ */
20
+ modules: WeconModule[];
21
+ /**
22
+ * Custom middleware to apply
23
+ */
24
+ middleware?: Array<(req: Request, res: Response, next: NextFunction) => void>;
25
+ /**
26
+ * Lifecycle hooks
27
+ */
28
+ hooks?: {
29
+ /**
30
+ * Called before server starts
31
+ */
32
+ onBoot?: () => Promise<void> | void;
33
+ /**
34
+ * Called when server is shutting down
35
+ */
36
+ onShutdown?: () => Promise<void> | void;
37
+ /**
38
+ * Called after each module is initialized
39
+ */
40
+ onModuleInit?: (module: WeconModule) => Promise<void> | void;
41
+ };
42
+ }
43
+ /**
44
+ * Wecon application instance
45
+ */
46
+ export interface WeconApp {
47
+ /**
48
+ * The underlying Express application
49
+ */
50
+ app: Application;
51
+ /**
52
+ * Start the server
53
+ */
54
+ start: (port?: number) => Promise<void>;
55
+ /**
56
+ * Gracefully shutdown the server
57
+ */
58
+ shutdown: () => Promise<void>;
59
+ }
60
+ /**
61
+ * Create a Wecon application
62
+ *
63
+ * This factory function sets up Express with all Wecon features:
64
+ * - Database connection
65
+ * - i18n initialization
66
+ * - Module loading
67
+ * - Error handling
68
+ *
69
+ * @param options - Configuration options
70
+ * @returns Wecon application instance
71
+ */
72
+ export declare function createWecon(options: CreateWeconOptions): Promise<WeconApp>;
73
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC5E,OAAO,KAAK,EAAe,cAAc,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE5E;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;OAEG;IACH,MAAM,EAAE,cAAc,CAAC;IAEvB;;OAEG;IACH,OAAO,EAAE,WAAW,EAAE,CAAC;IAEvB;;OAEG;IACH,UAAU,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,KAAK,IAAI,CAAC,CAAC;IAE9E;;OAEG;IACH,KAAK,CAAC,EAAE;QACN;;WAEG;QACH,MAAM,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;QAEpC;;WAEG;QACH,UAAU,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;QAExC;;WAEG;QACH,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;KAC9D,CAAC;CACH;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB;;OAEG;IACH,GAAG,EAAE,WAAW,CAAC;IAEjB;;OAEG;IACH,KAAK,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAExC;;OAEG;IACH,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6FhF"}
@@ -0,0 +1,99 @@
1
+ /**
2
+ * @weconjs/core - Server Factory
3
+ *
4
+ * Creates and configures the Express application with all framework features.
5
+ * This is the main entry point for the Wecon framework.
6
+ */
7
+ /**
8
+ * Create a Wecon application
9
+ *
10
+ * This factory function sets up Express with all Wecon features:
11
+ * - Database connection
12
+ * - i18n initialization
13
+ * - Module loading
14
+ * - Error handling
15
+ *
16
+ * @param options - Configuration options
17
+ * @returns Wecon application instance
18
+ */
19
+ export async function createWecon(options) {
20
+ // Dynamic import to avoid bundling issues
21
+ const express = (await import("express")).default;
22
+ const app = express();
23
+ const { config, modules, middleware = [], hooks = {} } = options;
24
+ // Apply default middleware
25
+ app.use(express.json());
26
+ app.use(express.urlencoded({ extended: true }));
27
+ // Apply custom middleware
28
+ for (const mw of middleware) {
29
+ app.use(mw);
30
+ }
31
+ // Health check endpoint
32
+ app.get("/health", (_req, res) => {
33
+ res.json({
34
+ status: "ok",
35
+ timestamp: new Date().toISOString(),
36
+ environment: config.mode,
37
+ app: config.app.name,
38
+ version: config.app.version,
39
+ });
40
+ });
41
+ // Initialize modules
42
+ for (const mod of modules) {
43
+ if (mod.onInit) {
44
+ await mod.onInit({}); // Context will be passed properly
45
+ }
46
+ if (hooks.onModuleInit) {
47
+ await hooks.onModuleInit(mod);
48
+ }
49
+ }
50
+ // Global error handler
51
+ app.use((err, _req, res, _next) => {
52
+ console.error("[Wecon] Error:", err.message);
53
+ res.status(500).json({
54
+ success: false,
55
+ message: err.message || "Internal Server Error",
56
+ });
57
+ });
58
+ let server = null;
59
+ return {
60
+ app,
61
+ async start(port) {
62
+ const serverPort = port ?? config.port ?? 3000;
63
+ // Call onBoot hook
64
+ if (hooks.onBoot) {
65
+ await hooks.onBoot();
66
+ }
67
+ return new Promise((resolve) => {
68
+ server = app.listen(serverPort, () => {
69
+ console.log(`\n[Wecon] ${config.app.name} v${config.app.version}`);
70
+ console.log(`[Wecon] Running on http://localhost:${serverPort}`);
71
+ console.log(`[Wecon] Mode: ${config.mode}\n`);
72
+ resolve();
73
+ });
74
+ });
75
+ },
76
+ async shutdown() {
77
+ // Call onShutdown hook
78
+ if (hooks.onShutdown) {
79
+ await hooks.onShutdown();
80
+ }
81
+ // Destroy modules
82
+ for (const mod of modules) {
83
+ if (mod.onDestroy) {
84
+ await mod.onDestroy({});
85
+ }
86
+ }
87
+ // Close server
88
+ if (server) {
89
+ return new Promise((resolve) => {
90
+ server.close(() => {
91
+ console.log("[Wecon] Server shut down gracefully");
92
+ resolve();
93
+ });
94
+ });
95
+ }
96
+ },
97
+ };
98
+ }
99
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAiEH;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,OAA2B;IAC3D,0CAA0C;IAC1C,MAAM,OAAO,GAAG,CAAC,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC;IAElD,MAAM,GAAG,GAAG,OAAO,EAAE,CAAC;IACtB,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,GAAG,EAA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