@morojs/moro 1.8.10 → 1.8.11

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.
@@ -1 +1 @@
1
- {"version":3,"file":"package-utils.js","sourceRoot":"","sources":["../../../src/core/utilities/package-utils.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,2EAA2E;AAE3E,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAmB;IACpD,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,cAAc,CAAC,CAAC,CAAC;QACvE,WAAW,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAmB;IACpD,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,cAAc,CAAC,CAAC,CAAC;IACvE,OAAO,WAAW,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;AAC1C,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,iBAAiB;IAC/B,OAAO,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,cAAc,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED,8EAA8E;AAC9E,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AQ,CAAC;IAClB,CAAC;IAED,qDAAqD;IACrD,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;IACpD,MAAM,iBAAiB,GAAG,wBAAwB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAElE,qDAAqD;IACrD,MAAM,cAAc,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhD,oDAAoD;IACpD,MAAM,YAAY,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAEjD,sCAAsC;IACtC,IAAI,iBAAiB,IAAI,cAAc,IAAI,YAAY,EAAE,CAAC;QACxD,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;IACtC,CAAC;IAED,2DAA2D;IAC3D,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Package and Module Resolution Utilities\n// ESM-compatible helpers for detecting and resolving optional dependencies\n\nimport { createRequire } from 'module';\nimport { dirname, join } from 'path';\nimport { existsSync, realpathSync } from 'fs';\nimport { pathToFileURL } from 'url';\nimport { selfRequire } from './self-require.js';\n\n/**\n * Check if a package is available in the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to check (e.g., 'socket.io', 'zod')\n * @returns true if the package is installed, false otherwise\n *\n * @example\n * if (isPackageAvailable('socket.io')) {\n * // socket.io is installed, safe to import\n * const { Server } = await import('socket.io');\n * }\n */\nexport function isPackageAvailable(packageName: string): boolean {\n try {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n userRequire.resolve(packageName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a package path from the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to resolve\n * @returns The resolved package path\n * @throws Error if the package is not found\n *\n * @example\n * const socketIOPath = resolveUserPackage('socket.io');\n * const { Server } = await import(socketIOPath);\n */\nexport function resolveUserPackage(packageName: string): string {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n return userRequire.resolve(packageName);\n}\n\n/**\n * Create a require function for the user's working directory\n * Useful for resolving packages installed by the user, not in Moro's dependencies\n *\n * @returns A require function scoped to the user's working directory\n *\n * @example\n * const userRequire = createUserRequire();\n * const packagePath = userRequire.resolve('some-package');\n */\nexport function createUserRequire() {\n return createRequire(join(process.cwd(), 'package.json'));\n}\n\n// ---------------------------------------------------------------------------\n// Native HTTP engine loading\n// ---------------------------------------------------------------------------\n\n/**\n * Package names probed for the native HTTP engine, in priority order.\n * '@morojs/engine' is Moro's own engine (installed as an optionalDependency of\n * the framework); 'uWebSockets.js' is honored as a legacy user-installed peer.\n */\nexport const NATIVE_ENGINE_PACKAGES = ['@morojs/engine', 'uWebSockets.js'] as const;\n\nconst FRAMEWORK_PACKAGE_NAME = '@morojs/moro';\n\n/** Feature flags the framework gates option-passing on, so it never hands a\n * serve() option to an engine build that predates it. Everything defaults\n * false, so an older engine behaves exactly as it did before these existed. */\nexport interface EngineCapabilities {\n /** The full serve() limit surface is parsed (engine >= 1.1.0). */\n limits: boolean;\n /** In-process TLS termination via options.ssl (engine >= 1.1.x). */\n tls: boolean;\n /** ALPN HTTP/2 via options.http2 (reserved). */\n http2: boolean;\n /** WebSocket permessage-deflate via options.wsDeflate. */\n wsDeflate: boolean;\n /** responseTimeoutMs / responseBackpressureLimit / maxUriSize are parsed. */\n responseLimits: boolean;\n /** ssl.ciphers / ssl.ciphersuites / ssl.ecdhCurve are parsed. */\n tlsPolicy: boolean;\n /** setStaticRoute()/clearStaticRoutes() exist (not used by the framework:\n * a static route bypasses middleware and hooks, so exposing it is an API\n * decision, not an adapter one). */\n staticRoutes: boolean;\n /** prepareResponse()/respondPrepared()/respondPreparedEmpty()/endWith()\n * exist (engine >= 1.1.6): the adapter replays prepared header blocks for\n * the responses it emits itself. */\n responseTemplates: boolean;\n /** onAborted/onWritable are delivered on a later loop turn, never from\n * inside respond()/write()/end() (engine >= 1.1.6). */\n asyncNotify: boolean;\n /** A server left open at environment teardown is closed by the engine's\n * cleanup hook, so the engine may run inside worker threads that can be\n * terminate()d (engine >= 1.1.6). Gates thread-based clustering. */\n workerThreads: boolean;\n /** V8 fast API calls are installed on the hot entry points (informational). */\n fastCalls: boolean;\n /** Batched pipelined dispatch (onRequestBatch / getBatchBuffers / getPath). */\n batchDispatch: boolean;\n /** I/O transport in use ('uv', 'uring'), when the engine reports it. */\n transport?: string;\n}\n\n// One place to name every boolean flag: getEngineCapabilities coerces each\n// with `=== true`, and NO_CAPABILITIES is derived from the same list, so a\n// flag added here can never be read on one path and forgotten on the other.\nconst CAP_KEYS = [\n 'limits',\n 'tls',\n 'http2',\n 'wsDeflate',\n 'responseLimits',\n 'tlsPolicy',\n 'staticRoutes',\n 'responseTemplates',\n 'asyncNotify',\n 'workerThreads',\n 'fastCalls',\n 'batchDispatch',\n] as const;\n\nexport interface NativeEngineLoadResult {\n /** The loaded engine module (CJS namespace: App, SSLApp, ...) */\n module: any;\n /** Which package satisfied the load */\n source: string;\n /** The engine package's version, when its package.json is resolvable */\n version?: string;\n /** Feature flags (Moro-shaped engine only; all-false for uWS or an\n * engine too old to advertise them). */\n capabilities?: EngineCapabilities;\n}\n\nconst NO_CAPABILITIES: EngineCapabilities = Object.freeze(\n Object.fromEntries(CAP_KEYS.map(k => [k, false]))\n) as unknown as EngineCapabilities;\n\nconst capabilitiesCache = new WeakMap<object, EngineCapabilities>();\n\n/**\n * Feature-detect a loaded engine module. Reads probe().capabilities when the\n * engine exposes it (>= 1.1.0); otherwise everything is false so the framework\n * passes only the options an older engine understood. uWS-style modules (no\n * probe/serve) report all-false — their SSL/limits go through the uWS-specific\n * paths, not these flags.\n */\nexport function getEngineCapabilities(module: any): EngineCapabilities {\n const surface = module?.default || module;\n if (!surface || typeof surface !== 'object') return NO_CAPABILITIES;\n const cached = capabilitiesCache.get(surface);\n if (cached) return cached;\n\n let caps: EngineCapabilities = NO_CAPABILITIES;\n try {\n if (typeof surface.probe === 'function') {\n const probe = surface.probe();\n const c = probe?.capabilities;\n if (c && typeof c === 'object') {\n const next: Record<string, boolean | string> = {};\n for (const key of CAP_KEYS) next[key] = c[key] === true;\n if (typeof probe.transport === 'string') next.transport = probe.transport;\n caps = next as unknown as EngineCapabilities;\n }\n }\n } catch {\n caps = NO_CAPABILITIES;\n }\n capabilitiesCache.set(surface, caps);\n return caps;\n}\n\n// undefined = never attempted, null = attempted and failed\nlet cachedEngine: NativeEngineLoadResult | null | undefined;\nlet engineLoadErrors: string[] = [];\n\n/**\n * Locate the installed framework package directory so the engine (a dependency\n * of moro, not of the user's app) resolves under strict layouts like pnpm's.\n * Walks up from cwd looking for node_modules/@morojs/moro, resolving symlinks\n * so pnpm's store-linked layout anchors requires next to moro's own deps.\n * Inside the framework repo itself (tests, examples) cwd is the framework dir.\n */\nfunction findFrameworkAnchor(): ReturnType<typeof createRequire> | null {\n // Primary: anchor to moro's OWN compiled location, so moro's `@morojs/engine`\n // dependency resolves relative to where moro is installed regardless of\n // `process.cwd()` (Docker WORKDIR, supervisord, pm2, a subdirectory, …). The\n // cwd-based walk below is a defensive fallback for exotic layouts.\n if (selfRequire) return selfRequire;\n\n try {\n const cwdPackageJson = join(process.cwd(), 'package.json');\n if (existsSync(cwdPackageJson)) {\n const require = createRequire(cwdPackageJson);\n const name = require(cwdPackageJson)?.name;\n if (name === FRAMEWORK_PACKAGE_NAME) {\n return require;\n }\n }\n } catch {\n // fall through to the node_modules walk\n }\n\n let dir = process.cwd();\n for (;;) {\n const packageJson = join(dir, 'node_modules', '@morojs', 'moro', 'package.json');\n try {\n if (existsSync(packageJson)) {\n return createRequire(join(realpathSync(dirname(packageJson)), 'package.json'));\n }\n } catch {\n // unreadable/broken link - keep walking up\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * Synchronously load the native HTTP engine, trying '@morojs/engine' first and\n * falling back to a user-installed 'uWebSockets.js'. Loading is require-based\n * (both packages are CJS at their core - .node addon loading is require-based),\n * so the instance is shared with any later import() via the CJS module cache.\n *\n * The default call is memoized: the engine either loads once per process or it\n * doesn't. Failure details are retained for logging via\n * getNativeEngineLoadErrors().\n *\n * @param options.candidates - Override the probed package names (testing).\n * When provided, the call bypasses the cache.\n * @returns The loaded engine and its source package, or null if none loads\n */\nexport function loadNativeEngine(options?: {\n candidates?: readonly string[];\n /** When provided, every per-attempt failure message is appended here, so a\n * candidate-override caller (which bypasses the memoized diagnostics) can\n * still report exactly WHY the engine didn't load — not just \"not installed\". */\n collectErrors?: string[];\n}): NativeEngineLoadResult | null {\n const useCache = !options?.candidates;\n if (useCache && cachedEngine !== undefined) {\n if (options?.collectErrors && !cachedEngine) {\n options.collectErrors.push(...engineLoadErrors);\n }\n return cachedEngine;\n }\n\n const candidates = options?.candidates ?? NATIVE_ENGINE_PACKAGES;\n const errors: string[] = [];\n let result: NativeEngineLoadResult | null = null;\n\n const frameworkRequire = findFrameworkAnchor();\n const userRequire = createUserRequire();\n\n for (const candidate of candidates) {\n // Moro's own engine lives in moro's dependencies (framework anchor first);\n // the legacy uWS peer dep lives in the user's node_modules (cwd first).\n const anchors =\n candidate === 'uWebSockets.js'\n ? [userRequire, frameworkRequire]\n : [frameworkRequire, userRequire];\n\n for (const anchor of anchors) {\n if (!anchor) continue;\n try {\n const module = anchor(candidate);\n // Capability check: the HTTP server needs either a uWS-style App()\n // factory or the Moro-shaped engine surface (serve()/respond()).\n // A package that loads but can't serve (e.g. a pre-M1 @morojs/engine\n // that only exposes probe()) must not shadow a usable alternative.\n const surface = module?.default || module;\n const uwsStyle = typeof surface?.App === 'function';\n const moroStyle =\n !uwsStyle &&\n typeof surface?.serve === 'function' &&\n typeof surface?.respond === 'function';\n if (!uwsStyle && !moroStyle) {\n errors.push(\n `${candidate}: loaded but provides neither App() nor serve()/respond() - not a usable HTTP engine`\n );\n continue;\n }\n let version: string | undefined;\n try {\n // May be blocked by the package's exports map - version is optional\n version = anchor(`${candidate}/package.json`)?.version;\n } catch {\n version = undefined;\n }\n result = {\n module,\n source: candidate,\n ...(version !== undefined ? { version } : {}),\n capabilities: moroStyle ? getEngineCapabilities(module) : NO_CAPABILITIES,\n };\n break;\n } catch (error) {\n const message = error instanceof Error ? error.message.split('\\n')[0] : String(error);\n errors.push(`${candidate}: ${message}`);\n }\n }\n if (result) break;\n }\n\n // Candidate-override probes (e.g. the clustering worker's uWS-only check)\n // must not clobber the diagnostics of the real default load, which\n // framework startup logging reads via getNativeEngineLoadErrors().\n if (useCache) {\n engineLoadErrors = result ? [] : [...new Set(errors)];\n cachedEngine = result;\n }\n // Hand this specific call's failure detail back to a caller that asked for it,\n // regardless of caching (so 'moro'/'uws' fallback reasons are precise).\n if (options?.collectErrors && !result) {\n options.collectErrors.push(...new Set(errors));\n }\n return result;\n}\n\n/**\n * Failure details from the most recent unsuccessful loadNativeEngine() call,\n * one entry per package/anchor attempt. Empty after a successful load.\n */\nexport function getNativeEngineLoadErrors(): readonly string[] {\n return engineLoadErrors;\n}\n\n/**\n * Clear the memoized engine load result. Testing only.\n */\nexport function resetNativeEngineLoaderForTesting(): void {\n cachedEngine = undefined;\n engineLoadErrors = [];\n}\n\n/**\n * Convert a file path to a file URL for ESM dynamic imports\n * This is required on Windows where absolute paths like C:\\path\\to\\module\n * need to be converted to file:/// URLs for dynamic import() to work\n *\n * @param filePath - The file path to convert (absolute or relative)\n * @returns A proper URL string for ESM import() that works cross-platform\n *\n * @example\n * const modulePath = 'C:\\\\Users\\\\project\\\\module.js';\n * const module = await import(filePathToImportURL(modulePath));\n */\nexport function filePathToImportURL(filePath: string): string {\n if (!filePath) {\n return filePath;\n }\n\n // If it's already a URL (starts with file:// or http(s)://), return as-is\n if (\n filePath.startsWith('file://') ||\n filePath.startsWith('http://') ||\n filePath.startsWith('https://')\n ) {\n return filePath;\n }\n\n // Check if it's a Windows absolute path (C:\\ or C:/)\n const windowsAbsolutePathRegex = /^[A-Za-z]:[\\\\//]/;\n const isWindowsAbsolute = windowsAbsolutePathRegex.test(filePath);\n\n // Check if it's a Unix absolute path (starts with /)\n const isUnixAbsolute = filePath.startsWith('/');\n\n // Check if it's a Windows UNC path (\\\\server\\share)\n const isWindowsUNC = filePath.startsWith('\\\\\\\\');\n\n // Convert absolute paths to file URLs\n if (isWindowsAbsolute || isUnixAbsolute || isWindowsUNC) {\n return pathToFileURL(filePath).href;\n }\n\n // For relative paths, return as-is (they work in import())\n return filePath;\n}\n"]}
1
+ {"version":3,"file":"package-utils.js","sourceRoot":"","sources":["../../../src/core/utilities/package-utils.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,2EAA2E;AAE3E,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAmB;IACpD,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,cAAc,CAAC,CAAC,CAAC;QACvE,WAAW,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAmB;IACpD,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,cAAc,CAAC,CAAC,CAAC;IACvE,OAAO,WAAW,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;AAC1C,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,iBAAiB;IAC/B,O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;QAC9B,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC;QAC9B,QAAQ,CAAC,UAAU,CAAC,UAAU,CAAC,EAC/B,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,qDAAqD;IACrD,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;IACpD,MAAM,iBAAiB,GAAG,wBAAwB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAElE,qDAAqD;IACrD,MAAM,cAAc,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhD,oDAAoD;IACpD,MAAM,YAAY,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAEjD,sCAAsC;IACtC,IAAI,iBAAiB,IAAI,cAAc,IAAI,YAAY,EAAE,CAAC;QACxD,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;IACtC,CAAC;IAED,2DAA2D;IAC3D,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Package and Module Resolution Utilities\n// ESM-compatible helpers for detecting and resolving optional dependencies\n\nimport { createRequire } from 'module';\nimport { dirname, join } from 'path';\nimport { existsSync, realpathSync } from 'fs';\nimport { pathToFileURL } from 'url';\nimport { selfRequire } from './self-require.js';\n\n/**\n * Check if a package is available in the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to check (e.g., 'socket.io', 'zod')\n * @returns true if the package is installed, false otherwise\n *\n * @example\n * if (isPackageAvailable('socket.io')) {\n * // socket.io is installed, safe to import\n * const { Server } = await import('socket.io');\n * }\n */\nexport function isPackageAvailable(packageName: string): boolean {\n try {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n userRequire.resolve(packageName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a package path from the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to resolve\n * @returns The resolved package path\n * @throws Error if the package is not found\n *\n * @example\n * const socketIOPath = resolveUserPackage('socket.io');\n * const { Server } = await import(socketIOPath);\n */\nexport function resolveUserPackage(packageName: string): string {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n return userRequire.resolve(packageName);\n}\n\n/**\n * Create a require function for the user's working directory\n * Useful for resolving packages installed by the user, not in Moro's dependencies\n *\n * @returns A require function scoped to the user's working directory\n *\n * @example\n * const userRequire = createUserRequire();\n * const packagePath = userRequire.resolve('some-package');\n */\nexport function createUserRequire() {\n return createRequire(join(process.cwd(), 'package.json'));\n}\n\n// ---------------------------------------------------------------------------\n// Native HTTP engine loading\n// ---------------------------------------------------------------------------\n\n/**\n * Package names probed for the native HTTP engine, in priority order.\n * '@morojs/engine' is Moro's own engine (installed as an optionalDependency of\n * the framework); 'uWebSockets.js' is honored as a legacy user-installed peer.\n */\nexport const NATIVE_ENGINE_PACKAGES = ['@morojs/engine', 'uWebSockets.js'] as const;\n\nconst FRAMEWORK_PACKAGE_NAME = '@morojs/moro';\n\n/** Feature flags the framework gates option-passing on, so it never hands a\n * serve() option to an engine build that predates it. Everything defaults\n * false, so an older engine behaves exactly as it did before these existed. */\nexport interface EngineCapabilities {\n /** The full serve() limit surface is parsed (engine >= 1.1.0). */\n limits: boolean;\n /** In-process TLS termination via options.ssl (engine >= 1.1.x). */\n tls: boolean;\n /** ALPN HTTP/2 via options.http2 (reserved). */\n http2: boolean;\n /** WebSocket permessage-deflate via options.wsDeflate. */\n wsDeflate: boolean;\n /** responseTimeoutMs / responseBackpressureLimit / maxUriSize are parsed. */\n responseLimits: boolean;\n /** ssl.ciphers / ssl.ciphersuites / ssl.ecdhCurve are parsed. */\n tlsPolicy: boolean;\n /** setStaticRoute()/clearStaticRoutes() exist. Used for a literal body\n * given to the route builder's .handler() when the route has nothing\n * else configured, because a static route bypasses middleware, hooks,\n * auth and validation by design. */\n staticRoutes: boolean;\n /** prepareResponse()/respondPrepared()/respondPreparedEmpty()/endWith()\n * exist (engine >= 1.1.6): the adapter replays prepared header blocks for\n * the responses it emits itself. */\n responseTemplates: boolean;\n /** onAborted/onWritable are delivered on a later loop turn, never from\n * inside respond()/write()/end() (engine >= 1.1.6). */\n asyncNotify: boolean;\n /** A server left open at environment teardown is closed by the engine's\n * cleanup hook, so the engine may run inside worker threads that can be\n * terminate()d (engine >= 1.1.6). Gates thread-based clustering. */\n workerThreads: boolean;\n /** V8 fast API calls are installed on the hot entry points (informational). */\n fastCalls: boolean;\n /** Batched pipelined dispatch (onRequestBatch / getBatchBuffers / getPath). */\n batchDispatch: boolean;\n /** I/O transport in use ('uv', 'uring'), when the engine reports it. */\n transport?: string;\n}\n\n// One place to name every boolean flag: getEngineCapabilities coerces each\n// with `=== true`, and NO_CAPABILITIES is derived from the same list, so a\n// flag added here can never be read on one path and forgotten on the other.\nconst CAP_KEYS = [\n 'limits',\n 'tls',\n 'http2',\n 'wsDeflate',\n 'responseLimits',\n 'tlsPolicy',\n 'staticRoutes',\n 'responseTemplates',\n 'asyncNotify',\n 'workerThreads',\n 'fastCalls',\n 'batchDispatch',\n] as const;\n\nexport interface NativeEngineLoadResult {\n /** The loaded engine module (CJS namespace: App, SSLApp, ...) */\n module: any;\n /** Which package satisfied the load */\n source: string;\n /** The engine package's version, when its package.json is resolvable */\n version?: string;\n /** Feature flags (Moro-shaped engine only; all-false for uWS or an\n * engine too old to advertise them). */\n capabilities?: EngineCapabilities;\n}\n\nconst NO_CAPABILITIES: EngineCapabilities = Object.freeze(\n Object.fromEntries(CAP_KEYS.map(k => [k, false]))\n) as unknown as EngineCapabilities;\n\nconst capabilitiesCache = new WeakMap<object, EngineCapabilities>();\n\n/**\n * Feature-detect a loaded engine module. Reads probe().capabilities when the\n * engine exposes it (>= 1.1.0); otherwise everything is false so the framework\n * passes only the options an older engine understood. uWS-style modules (no\n * probe/serve) report all-false — their SSL/limits go through the uWS-specific\n * paths, not these flags.\n */\nexport function getEngineCapabilities(module: any): EngineCapabilities {\n const surface = module?.default || module;\n if (!surface || typeof surface !== 'object') return NO_CAPABILITIES;\n const cached = capabilitiesCache.get(surface);\n if (cached) return cached;\n\n let caps: EngineCapabilities = NO_CAPABILITIES;\n try {\n if (typeof surface.probe === 'function') {\n const probe = surface.probe();\n const c = probe?.capabilities;\n if (c && typeof c === 'object') {\n const next: Record<string, boolean | string> = {};\n for (const key of CAP_KEYS) next[key] = c[key] === true;\n if (typeof probe.transport === 'string') next.transport = probe.transport;\n caps = next as unknown as EngineCapabilities;\n }\n }\n } catch {\n caps = NO_CAPABILITIES;\n }\n capabilitiesCache.set(surface, caps);\n return caps;\n}\n\n// undefined = never attempted, null = attempted and failed\nlet cachedEngine: NativeEngineLoadResult | null | undefined;\nlet engineLoadErrors: string[] = [];\n\n/**\n * Locate the installed framework package directory so the engine (a dependency\n * of moro, not of the user's app) resolves under strict layouts like pnpm's.\n * Walks up from cwd looking for node_modules/@morojs/moro, resolving symlinks\n * so pnpm's store-linked layout anchors requires next to moro's own deps.\n * Inside the framework repo itself (tests, examples) cwd is the framework dir.\n */\nfunction findFrameworkAnchor(): ReturnType<typeof createRequire> | null {\n // Primary: anchor to moro's OWN compiled location, so moro's `@morojs/engine`\n // dependency resolves relative to where moro is installed regardless of\n // `process.cwd()` (Docker WORKDIR, supervisord, pm2, a subdirectory, …). The\n // cwd-based walk below is a defensive fallback for exotic layouts.\n if (selfRequire) return selfRequire;\n\n try {\n const cwdPackageJson = join(process.cwd(), 'package.json');\n if (existsSync(cwdPackageJson)) {\n const require = createRequire(cwdPackageJson);\n const name = require(cwdPackageJson)?.name;\n if (name === FRAMEWORK_PACKAGE_NAME) {\n return require;\n }\n }\n } catch {\n // fall through to the node_modules walk\n }\n\n let dir = process.cwd();\n for (;;) {\n const packageJson = join(dir, 'node_modules', '@morojs', 'moro', 'package.json');\n try {\n if (existsSync(packageJson)) {\n return createRequire(join(realpathSync(dirname(packageJson)), 'package.json'));\n }\n } catch {\n // unreadable/broken link - keep walking up\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * Synchronously load the native HTTP engine, trying '@morojs/engine' first and\n * falling back to a user-installed 'uWebSockets.js'. Loading is require-based\n * (both packages are CJS at their core - .node addon loading is require-based),\n * so the instance is shared with any later import() via the CJS module cache.\n *\n * The default call is memoized: the engine either loads once per process or it\n * doesn't. Failure details are retained for logging via\n * getNativeEngineLoadErrors().\n *\n * @param options.candidates - Override the probed package names (testing).\n * When provided, the call bypasses the cache.\n * @returns The loaded engine and its source package, or null if none loads\n */\nexport function loadNativeEngine(options?: {\n candidates?: readonly string[];\n /** When provided, every per-attempt failure message is appended here, so a\n * candidate-override caller (which bypasses the memoized diagnostics) can\n * still report exactly WHY the engine didn't load — not just \"not installed\". */\n collectErrors?: string[];\n}): NativeEngineLoadResult | null {\n const useCache = !options?.candidates;\n if (useCache && cachedEngine !== undefined) {\n if (options?.collectErrors && !cachedEngine) {\n options.collectErrors.push(...engineLoadErrors);\n }\n return cachedEngine;\n }\n\n const candidates = options?.candidates ?? NATIVE_ENGINE_PACKAGES;\n const errors: string[] = [];\n let result: NativeEngineLoadResult | null = null;\n\n const frameworkRequire = findFrameworkAnchor();\n const userRequire = createUserRequire();\n\n for (const candidate of candidates) {\n // Moro's own engine lives in moro's dependencies (framework anchor first);\n // the legacy uWS peer dep lives in the user's node_modules (cwd first).\n const anchors =\n candidate === 'uWebSockets.js'\n ? [userRequire, frameworkRequire]\n : [frameworkRequire, userRequire];\n\n for (const anchor of anchors) {\n if (!anchor) continue;\n try {\n const module = anchor(candidate);\n // Capability check: the HTTP server needs either a uWS-style App()\n // factory or the Moro-shaped engine surface (serve()/respond()).\n // A package that loads but can't serve (e.g. a pre-M1 @morojs/engine\n // that only exposes probe()) must not shadow a usable alternative.\n const surface = module?.default || module;\n const uwsStyle = typeof surface?.App === 'function';\n const moroStyle =\n !uwsStyle &&\n typeof surface?.serve === 'function' &&\n typeof surface?.respond === 'function';\n if (!uwsStyle && !moroStyle) {\n errors.push(\n `${candidate}: loaded but provides neither App() nor serve()/respond() - not a usable HTTP engine`\n );\n continue;\n }\n let version: string | undefined;\n try {\n // May be blocked by the package's exports map - version is optional\n version = anchor(`${candidate}/package.json`)?.version;\n } catch {\n version = undefined;\n }\n result = {\n module,\n source: candidate,\n ...(version !== undefined ? { version } : {}),\n capabilities: moroStyle ? getEngineCapabilities(module) : NO_CAPABILITIES,\n };\n break;\n } catch (error) {\n const message = error instanceof Error ? error.message.split('\\n')[0] : String(error);\n errors.push(`${candidate}: ${message}`);\n }\n }\n if (result) break;\n }\n\n // Candidate-override probes (e.g. the clustering worker's uWS-only check)\n // must not clobber the diagnostics of the real default load, which\n // framework startup logging reads via getNativeEngineLoadErrors().\n if (useCache) {\n engineLoadErrors = result ? [] : [...new Set(errors)];\n cachedEngine = result;\n }\n // Hand this specific call's failure detail back to a caller that asked for it,\n // regardless of caching (so 'moro'/'uws' fallback reasons are precise).\n if (options?.collectErrors && !result) {\n options.collectErrors.push(...new Set(errors));\n }\n return result;\n}\n\n/**\n * Failure details from the most recent unsuccessful loadNativeEngine() call,\n * one entry per package/anchor attempt. Empty after a successful load.\n */\nexport function getNativeEngineLoadErrors(): readonly string[] {\n return engineLoadErrors;\n}\n\n/**\n * Clear the memoized engine load result. Testing only.\n */\nexport function resetNativeEngineLoaderForTesting(): void {\n cachedEngine = undefined;\n engineLoadErrors = [];\n}\n\n/**\n * Convert a file path to a file URL for ESM dynamic imports\n * This is required on Windows where absolute paths like C:\\path\\to\\module\n * need to be converted to file:/// URLs for dynamic import() to work\n *\n * @param filePath - The file path to convert (absolute or relative)\n * @returns A proper URL string for ESM import() that works cross-platform\n *\n * @example\n * const modulePath = 'C:\\\\Users\\\\project\\\\module.js';\n * const module = await import(filePathToImportURL(modulePath));\n */\nexport function filePathToImportURL(filePath: string): string {\n if (!filePath) {\n return filePath;\n }\n\n // If it's already a URL (starts with file:// or http(s)://), return as-is\n if (\n filePath.startsWith('file://') ||\n filePath.startsWith('http://') ||\n filePath.startsWith('https://')\n ) {\n return filePath;\n }\n\n // Check if it's a Windows absolute path (C:\\ or C:/)\n const windowsAbsolutePathRegex = /^[A-Za-z]:[\\\\//]/;\n const isWindowsAbsolute = windowsAbsolutePathRegex.test(filePath);\n\n // Check if it's a Unix absolute path (starts with /)\n const isUnixAbsolute = filePath.startsWith('/');\n\n // Check if it's a Windows UNC path (\\\\server\\share)\n const isWindowsUNC = filePath.startsWith('\\\\\\\\');\n\n // Convert absolute paths to file URLs\n if (isWindowsAbsolute || isUnixAbsolute || isWindowsUNC) {\n return pathToFileURL(filePath).href;\n }\n\n // For relative paths, return as-is (they work in import())\n return filePath;\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -61,7 +61,7 @@ export type { WebSocketAdapter, WebSocketAdapterOptions, WebSocketNamespace, Web
61
61
  export { SocketIOAdapter, WSAdapter, UWebSocketsAdapter, } from './core/networking/adapters/index.js';
62
62
  export { createRoute, defineRoute, EXECUTION_PHASES } from './core/routing/index.js';
63
63
  export { IntelligentRoutingManager, RouteRegistry } from './core/routing/app-integration.js';
64
- export type { RouteBuilder, RouteSchema, CompiledRoute, HttpMethod, AuthConfig, RateLimitConfig, CacheConfig, MiddlewarePhases, ExecutionPhase, } from './core/routing/index.js';
64
+ export type { RouteBuilder, RouteSchema, CompiledRoute, HttpMethod, AuthConfig, RateLimitConfig, CacheConfig, MiddlewarePhases, ExecutionPhase, StaticBody, StaticResponse, } from './core/routing/index.js';
65
65
  export { DocumentationSystem, AppDocumentationManager, createDocumentationSystem, generateDocsFromIntelligentRoutes, } from './core/docs/index.js';
66
66
  export type { DocsConfig } from './core/docs/index.js';
67
67
  export { getConfig, createModuleConfig, getEnvVar, getEnvArray, getEnvJson, isDevelopment, isProduction, isStaging, requireEnvVars, envVar, getConfigValue, } from './core/config/utils.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,OAAO,EACL,IAAI,EACJ,IAAI,IAAI,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AAC;AAC9D,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,eAAe,EACf,UAAU,EACV,aAAa,GACd,MAAM,+BAA+B,CAAC","sourcesContent":["// MoroJS Framework - Main Entry Point\nexport {\n Moro,\n Moro as MoroCore,\n createApp,\n createAppNode,\n createAppEdge,\n createAppLambda,\n createAppWorker,\n getApp,\n RouteGroup,\n} from './moro.js';\n\nexport type { MoroOptions } from './core/framework.js';\n\n// Export auth types and middleware\nexport type {\n AuthOptions,\n AuthProvider,\n AuthUser,\n AuthSession,\n AuthRequest,\n AuthAccount,\n AuthJWT,\n AuthCallbacks,\n AuthEvents,\n AuthPages,\n AuthAdapter,\n OAuthProvider,\n CredentialsProvider,\n EmailProvider,\n SignInOptions,\n SignOutOptions,\n} from './types/auth.js';\n\n// Export native @auth/morojs adapter\nexport { createAuthMiddleware, MoroJSAuth } from './core/auth/morojs-adapter.js';\n\n// Export Auth middleware and providers\nexport {\n auth,\n providers,\n twoFactor,\n organization,\n anonymous,\n accountLinking,\n rateLimit,\n bearerToken,\n // Route guards and helpers (referenced by the auth docs as package-root\n // imports; must be re-exported here to be part of the public API).\n requireAuth,\n requireRole,\n requirePermission,\n requireAdmin,\n authUtils,\n authResponses,\n extendedProviders,\n enterpriseProviders,\n} from './core/middleware/built-in/auth/index.js';\nexport type {\n TwoFactorAuthOptions,\n OrganizationOptions,\n AnonymousOptions,\n AccountLinkingOptions,\n RateLimitOptions,\n BearerTokenOptions,\n} from './core/middleware/built-in/auth/index.js';\n\n// Runtime system exports\nexport type {\n RuntimeType,\n RuntimeAdapter,\n RuntimeConfig,\n RuntimeHttpResponse,\n} from './types/runtime.js';\n\nexport {\n NodeRuntimeAdapter,\n VercelEdgeAdapter,\n AWSLambdaAdapter,\n CloudflareWorkersAdapter,\n createRuntimeAdapter,\n createNodeHandler,\n createEdgeHandler,\n createLambdaHandler,\n createWorkerHandler,\n} from './core/runtime/index.js';\n\n// Runtime-specific types\nexport type {\n LambdaEvent,\n LambdaContext,\n LambdaResponse,\n} from './core/runtime/aws-lambda-adapter.js';\nexport type { WorkersEnv, WorkersContext } from './core/runtime/cloudflare-workers-adapter.js';\n\n// Core exports\nexport { MoroHttpServer, UWebSocketsHttpServer, MoroEngineServer } from './core/http/index.js';\nexport { middleware } from './core/middleware/built-in/index.js';\n\n// Re-declared (not re-exported) so the @deprecated tag reaches consumers:\n// TypeScript does not propagate deprecation through `export { x } from '...'`,\n// only through an actual declaration. Framework-internal code imports\n// builtInMiddleware from ./core/middleware/built-in/index.js directly, where\n// the declaration carries no tag, so this flags user code only.\nimport { builtInMiddleware as builtInMiddlewareImpl } from './core/middleware/built-in/index.js';\n/** @deprecated Use `middleware` instead. `builtInMiddleware` will be removed in a future release. */\nexport const builtInMiddleware = builtInMiddlewareImpl;\n\n// Worker Threads (CPU-intensive task offloading)\nexport { WorkerManager, getWorkerManager, workerTasks } from './core/workers/index.js';\nexport type { WorkerTask, WorkerResult } from './core/workers/index.js';\n\n// Object Pooling & Caching\nexport { ObjectPool, LRUCache, ObjectPoolManager } from './core/pooling/index.js';\n\n// Networking System\nexport { WebSocketManager, ServiceRegistry } from './core/networking/index.js';\nexport type { ServiceInfo, ServiceDiscoveryOptions } from './core/networking/service-discovery.js';\n\n// Utilities and Container System\nexport {\n Container,\n FunctionalContainer,\n TypedServiceReference,\n ServiceScope,\n ServiceLifecycle,\n withLogging,\n withCaching,\n withRetry,\n withTimeout,\n CircuitBreaker,\n HookManager,\n HOOK_EVENTS,\n isPackageAvailable,\n resolveUserPackage,\n createUserRequire,\n // Standardized Response Helpers (namespace object only)\n response,\n ResponseBuilder,\n} from './core/utilities/index.js';\n\n// Response helper types\nexport type {\n ApiSuccessResponse,\n ApiErrorResponse,\n ApiResponse,\n ResponseValidationErrorDetail,\n} from './core/utilities/index.js';\n\n// Event System\nexport { MoroEventBus } from './core/events/index.js';\nexport type {\n EventContext,\n EventPayload,\n EventBusOptions,\n ModuleEventBus,\n GlobalEventBus,\n EventMetrics,\n SystemEvents,\n EventHandler,\n} from './types/events.js';\n\n// Logger System\nexport { createFrameworkLogger, logger } from './core/logger/index.js';\n\n// Universal Validation System\nexport {\n validate,\n body,\n query,\n params,\n combineSchemas,\n z,\n handleValidationError,\n normalizeErrors,\n} from './core/validation/index.js';\n\nexport type {\n ValidationConfig,\n ValidationResult,\n ValidationErrorDetail,\n ValidatedRequest,\n ValidationErrorHandler,\n ValidationErrorContext,\n ValidationErrorResponse,\n ValidationErrorDetailType,\n} from './core/validation/index.js';\n\n// Validation Interfaces and Adapters\nexport type {\n ValidationSchema,\n ValidationError,\n InferSchemaType,\n} from './core/validation/schema-interface.js';\nexport { normalizeValidationError } from './core/validation/schema-interface.js';\nexport { joi, yup, fn as customValidator, classValidator } from './core/validation/adapters.js';\n\n// Module System\nexport {\n defineModule,\n ModuleLoader,\n ModuleDiscovery,\n autoDiscoverModuleDirectories,\n} from './core/modules/index.js';\nexport type { ModuleDefinition, ModuleRoute, ModuleSocket, ModuleConfig } from './types/module.js';\n\n// WebSocket Adapter System\nexport type {\n WebSocketAdapter,\n WebSocketAdapterOptions,\n WebSocketNamespace,\n WebSocketConnection,\n WebSocketEmitter,\n WebSocketMiddleware,\n WebSocketEventHandler,\n} from './core/networking/websocket-adapter.js';\n\n// Built-in WebSocket Adapters\nexport {\n SocketIOAdapter,\n WSAdapter,\n UWebSocketsAdapter,\n} from './core/networking/adapters/index.js';\n\n// Intelligent Routing System\nexport { createRoute, defineRoute, EXECUTION_PHASES } from './core/routing/index.js';\nexport { IntelligentRoutingManager, RouteRegistry } from './core/routing/app-integration.js';\nexport type {\n RouteBuilder,\n RouteSchema,\n CompiledRoute,\n HttpMethod,\n AuthConfig,\n RateLimitConfig,\n CacheConfig,\n MiddlewarePhases,\n ExecutionPhase,\n} from './core/routing/index.js';\n\n// Documentation System\nexport {\n DocumentationSystem,\n AppDocumentationManager,\n createDocumentationSystem,\n generateDocsFromIntelligentRoutes,\n} from './core/docs/index.js';\nexport type { DocsConfig } from './core/docs/index.js';\n\n// Configuration utilities\nexport {\n getConfig,\n createModuleConfig,\n getEnvVar,\n getEnvArray,\n getEnvJson,\n isDevelopment,\n isProduction,\n isStaging,\n requireEnvVars,\n envVar,\n getConfigValue,\n} from './core/config/utils.js';\n\nexport {\n initializeConfig,\n getGlobalConfig,\n isConfigInitialized,\n resetConfig,\n} from './core/config/index.js';\n\n// Export configuration types for TypeScript users\nexport type { AppConfig, DeepPartial, OriginFunction } from './core/config/index.js';\n\n// GraphQL System - Only export types and adapter\n// The core classes are lazy-loaded internally via app.graphqlInit()\nexport type {\n GraphQLContext,\n GraphQLResolver,\n GraphQLSubscriptionResolver,\n GraphQLSchemaBuilderOptions,\n GraphQLResolvers,\n GraphQLExecutionOptions,\n GraphQLOptions,\n GraphQLPlugin,\n GraphQLRequestContext,\n GraphQLRequestListener,\n GraphQLRequest,\n GraphQLResponse,\n GraphQLMetrics,\n GraphQLSubscriptionOptions,\n DataLoaderOptions,\n ComplexityEstimator,\n QueryComplexityOptions,\n DepthLimitOptions,\n} from './core/graphql/types.js';\n\nexport type { GraphQLAdapter, GraphQLStats } from './core/graphql/adapter.js';\nexport { GraphQLJsAdapter } from './core/graphql/adapters/graphql-js-adapter.js';\n\n// GraphQL helpers (these don't import graphql directly at module level)\nexport {\n createPothosBuilder,\n isPothosAvailable,\n isPothosSchema,\n pothosToSchema,\n createComplexityPlugin,\n createDepthLimitPlugin,\n createDataLoader,\n} from './core/middleware/built-in/graphql/helpers.js';\n\n// Job System\nexport {\n JobScheduler,\n JobHealthChecker,\n CronParser,\n parseInterval,\n formatDuration,\n everyInterval,\n cronSchedule,\n oneTimeAt,\n createJob,\n} from './core/jobs/index.js';\n\nexport type {\n JobSchedule,\n JobOptions,\n SimpleJobOptions,\n JobFunction,\n JobMetrics,\n SchedulerStats,\n JobHealth,\n JobHealthStatus,\n JobContext,\n JobExecution,\n JobState,\n JobSchedulerOptions,\n ExecutionContext,\n ExecutionResult,\n} from './core/jobs/index.js';\n\n// Middleware System\nexport { MiddlewareManager } from './core/middleware/index.js';\nexport type { MiddlewareInterface, MoroMiddleware } from './core/middleware/index.js';\n\n// Body parsers\nexport { json, urlencoded } from './core/middleware/built-in/body-parsers/index.js';\n\n// Standalone router — `createRouter()` is the canonical factory; `Router` is an\n// alias kept callable without `new` so Express-style named imports\n// (`import { Router } from '...'`; `const r = Router();`) work unchanged.\nexport { createRouter, createRouter as Router, MoroRouter } from './core/routing/create-router.js';\n\n// Types\nexport type * from './types/core.js';\nexport type * from './types/http.js';\nexport type * from './types/hooks.js';\nexport type * from './types/cache.js';\nexport type * from './types/cdn.js';\nexport type * from './types/database.js';\nexport type * from './types/logger.js';\nexport type * from './types/session.js';\nexport type * from './types/discovery.js';\n\n// Adapters\nexport * from './core/middleware/built-in/cache/adapters/index.js';\nexport * from './core/middleware/built-in/cdn/adapters/index.js';\nexport * from './core/database/adapters/index.js';\n\n// Re-export commonly used types for convenience\nexport type { CacheAdapter, CacheOptions, CacheStrategy } from './types/cache.js';\nexport type { CDNAdapter, CDNOptions } from './types/cdn.js';\nexport type { DatabaseAdapter, DatabaseTransaction, DatabaseConfig } from './types/database.js';\nexport type { CookieOptions } from './types/http.js';\n\n// gRPC System - Lazy loaded, only types exported\nexport type {\n GrpcOptions,\n GrpcCall,\n GrpcCallback,\n GrpcMetadata,\n GrpcError,\n GrpcStatusCode,\n GrpcCredentials,\n GrpcServer,\n GrpcClient,\n GrpcClientOptions,\n GrpcInterceptor,\n ServiceImplementation,\n ServiceDefinition,\n ServiceRegistration,\n MethodDefinition,\n UnaryHandler,\n ServerStreamingHandler,\n ClientStreamingHandler,\n BidirectionalStreamingHandler,\n GrpcHandler,\n GrpcStats,\n HealthCheckStatus,\n HealthCheckResponse,\n ProtoLoadOptions,\n} from './core/grpc/types.js';\n\nexport type { GrpcAdapter } from './core/grpc/grpc-adapter.js';\nexport { GrpcJsAdapter } from './core/grpc/adapters/index.js';\n\n// gRPC Middleware\nexport {\n grpcAuth,\n grpcRequirePermission,\n grpcRequireRole,\n extractTokenFromMetadata,\n grpcLogger,\n grpcSimpleLogger,\n grpcDetailedLogger,\n grpcValidate,\n grpcValidateHandler,\n} from './core/grpc/index.js';\n\n// Mail System - Lazy loaded, only types exported\nexport type {\n MailConfig,\n MailOptions,\n MailResult,\n MailAdapter,\n MailAdapterType,\n EmailAddress,\n EmailAttachment,\n TemplateConfig,\n TemplateEngine,\n MailQueueConfig,\n NodemailerConnection,\n SendGridConnection,\n SESConnection,\n ResendConnection,\n} from './core/mail/types.js';\n\nexport { BaseMailAdapter } from './core/mail/mail-adapter.js';\nexport {\n ConsoleAdapter,\n NodemailerAdapter,\n SendGridAdapter,\n SESAdapter,\n ResendAdapter,\n} from './core/mail/adapters/index.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,OAAO,EACL,IAAI,EACJ,IAAI,IAAI,QAAQ,EAChB,SAAS,EACT,aAAa,EACb,aAAa,EACb,eAAe,EACf,eAAe,EACf,MAAM,EACN,UAAU,GACX,MAAM,WAAW,CAAC;AAwBnB,qCAAqC;AACrC,OAAO,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAEjF,uCAAuC;AACvC,OAAO,EACL,IAAI,EACJ,SAAS,EACT,SAAS,EACT,YAAY,EACZ,SAAS,EACT,cAAc,EACd,SAAS,EACT,WAAW;AACX,wEAAwE;AACxE,mEAAmE;AACnE,WAAW,EACX,WAAW,EACX,iBAAiB,EACjB,YAAY,EACZ,SAAS,EACT,aAAa,EACb,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,0CAA0C,CAAC;AAkBlD,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,wBAAwB,EACxB,oBAAoB,EACpB,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,yBAAyB,CAAC;AAUjC,eAAe;AACf,OAAO,EAAE,cAAc,E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AG/D,eAAe;AACf,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,kDAAkD,CAAC;AAEpF,gFAAgF;AAChF,mEAAmE;AACnE,0EAA0E;AAC1E,OAAO,EAAE,YAAY,EAAE,YAAY,IAAI,MAAM,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAanG,WAAW;AACX,cAAc,oDAAoD,CAAC;AACnE,cAAc,kDAAkD,CAAC;AACjE,cAAc,mCAAmC,CAAC;AAqClD,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE9D,kBAAkB;AAClB,OAAO,EACL,QAAQ,EACR,qBAAqB,EACrB,eAAe,EACf,wBAAwB,EACxB,UAAU,EACV,gBAAgB,EAChB,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,GACpB,MAAM,sBAAsB,CAAC;AAoB9B,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,eAAe,EACf,UAAU,EACV,aAAa,GACd,MAAM,+BAA+B,CAAC","sourcesContent":["// MoroJS Framework - Main Entry Point\nexport {\n Moro,\n Moro as MoroCore,\n createApp,\n createAppNode,\n createAppEdge,\n createAppLambda,\n createAppWorker,\n getApp,\n RouteGroup,\n} from './moro.js';\n\nexport type { MoroOptions } from './core/framework.js';\n\n// Export auth types and middleware\nexport type {\n AuthOptions,\n AuthProvider,\n AuthUser,\n AuthSession,\n AuthRequest,\n AuthAccount,\n AuthJWT,\n AuthCallbacks,\n AuthEvents,\n AuthPages,\n AuthAdapter,\n OAuthProvider,\n CredentialsProvider,\n EmailProvider,\n SignInOptions,\n SignOutOptions,\n} from './types/auth.js';\n\n// Export native @auth/morojs adapter\nexport { createAuthMiddleware, MoroJSAuth } from './core/auth/morojs-adapter.js';\n\n// Export Auth middleware and providers\nexport {\n auth,\n providers,\n twoFactor,\n organization,\n anonymous,\n accountLinking,\n rateLimit,\n bearerToken,\n // Route guards and helpers (referenced by the auth docs as package-root\n // imports; must be re-exported here to be part of the public API).\n requireAuth,\n requireRole,\n requirePermission,\n requireAdmin,\n authUtils,\n authResponses,\n extendedProviders,\n enterpriseProviders,\n} from './core/middleware/built-in/auth/index.js';\nexport type {\n TwoFactorAuthOptions,\n OrganizationOptions,\n AnonymousOptions,\n AccountLinkingOptions,\n RateLimitOptions,\n BearerTokenOptions,\n} from './core/middleware/built-in/auth/index.js';\n\n// Runtime system exports\nexport type {\n RuntimeType,\n RuntimeAdapter,\n RuntimeConfig,\n RuntimeHttpResponse,\n} from './types/runtime.js';\n\nexport {\n NodeRuntimeAdapter,\n VercelEdgeAdapter,\n AWSLambdaAdapter,\n CloudflareWorkersAdapter,\n createRuntimeAdapter,\n createNodeHandler,\n createEdgeHandler,\n createLambdaHandler,\n createWorkerHandler,\n} from './core/runtime/index.js';\n\n// Runtime-specific types\nexport type {\n LambdaEvent,\n LambdaContext,\n LambdaResponse,\n} from './core/runtime/aws-lambda-adapter.js';\nexport type { WorkersEnv, WorkersContext } from './core/runtime/cloudflare-workers-adapter.js';\n\n// Core exports\nexport { MoroHttpServer, UWebSocketsHttpServer, MoroEngineServer } from './core/http/index.js';\nexport { middleware } from './core/middleware/built-in/index.js';\n\n// Re-declared (not re-exported) so the @deprecated tag reaches consumers:\n// TypeScript does not propagate deprecation through `export { x } from '...'`,\n// only through an actual declaration. Framework-internal code imports\n// builtInMiddleware from ./core/middleware/built-in/index.js directly, where\n// the declaration carries no tag, so this flags user code only.\nimport { builtInMiddleware as builtInMiddlewareImpl } from './core/middleware/built-in/index.js';\n/** @deprecated Use `middleware` instead. `builtInMiddleware` will be removed in a future release. */\nexport const builtInMiddleware = builtInMiddlewareImpl;\n\n// Worker Threads (CPU-intensive task offloading)\nexport { WorkerManager, getWorkerManager, workerTasks } from './core/workers/index.js';\nexport type { WorkerTask, WorkerResult } from './core/workers/index.js';\n\n// Object Pooling & Caching\nexport { ObjectPool, LRUCache, ObjectPoolManager } from './core/pooling/index.js';\n\n// Networking System\nexport { WebSocketManager, ServiceRegistry } from './core/networking/index.js';\nexport type { ServiceInfo, ServiceDiscoveryOptions } from './core/networking/service-discovery.js';\n\n// Utilities and Container System\nexport {\n Container,\n FunctionalContainer,\n TypedServiceReference,\n ServiceScope,\n ServiceLifecycle,\n withLogging,\n withCaching,\n withRetry,\n withTimeout,\n CircuitBreaker,\n HookManager,\n HOOK_EVENTS,\n isPackageAvailable,\n resolveUserPackage,\n createUserRequire,\n // Standardized Response Helpers (namespace object only)\n response,\n ResponseBuilder,\n} from './core/utilities/index.js';\n\n// Response helper types\nexport type {\n ApiSuccessResponse,\n ApiErrorResponse,\n ApiResponse,\n ResponseValidationErrorDetail,\n} from './core/utilities/index.js';\n\n// Event System\nexport { MoroEventBus } from './core/events/index.js';\nexport type {\n EventContext,\n EventPayload,\n EventBusOptions,\n ModuleEventBus,\n GlobalEventBus,\n EventMetrics,\n SystemEvents,\n EventHandler,\n} from './types/events.js';\n\n// Logger System\nexport { createFrameworkLogger, logger } from './core/logger/index.js';\n\n// Universal Validation System\nexport {\n validate,\n body,\n query,\n params,\n combineSchemas,\n z,\n handleValidationError,\n normalizeErrors,\n} from './core/validation/index.js';\n\nexport type {\n ValidationConfig,\n ValidationResult,\n ValidationErrorDetail,\n ValidatedRequest,\n ValidationErrorHandler,\n ValidationErrorContext,\n ValidationErrorResponse,\n ValidationErrorDetailType,\n} from './core/validation/index.js';\n\n// Validation Interfaces and Adapters\nexport type {\n ValidationSchema,\n ValidationError,\n InferSchemaType,\n} from './core/validation/schema-interface.js';\nexport { normalizeValidationError } from './core/validation/schema-interface.js';\nexport { joi, yup, fn as customValidator, classValidator } from './core/validation/adapters.js';\n\n// Module System\nexport {\n defineModule,\n ModuleLoader,\n ModuleDiscovery,\n autoDiscoverModuleDirectories,\n} from './core/modules/index.js';\nexport type { ModuleDefinition, ModuleRoute, ModuleSocket, ModuleConfig } from './types/module.js';\n\n// WebSocket Adapter System\nexport type {\n WebSocketAdapter,\n WebSocketAdapterOptions,\n WebSocketNamespace,\n WebSocketConnection,\n WebSocketEmitter,\n WebSocketMiddleware,\n WebSocketEventHandler,\n} from './core/networking/websocket-adapter.js';\n\n// Built-in WebSocket Adapters\nexport {\n SocketIOAdapter,\n WSAdapter,\n UWebSocketsAdapter,\n} from './core/networking/adapters/index.js';\n\n// Intelligent Routing System\nexport { createRoute, defineRoute, EXECUTION_PHASES } from './core/routing/index.js';\nexport { IntelligentRoutingManager, RouteRegistry } from './core/routing/app-integration.js';\nexport type {\n RouteBuilder,\n RouteSchema,\n CompiledRoute,\n HttpMethod,\n AuthConfig,\n RateLimitConfig,\n CacheConfig,\n MiddlewarePhases,\n ExecutionPhase,\n StaticBody,\n StaticResponse,\n} from './core/routing/index.js';\n\n// Documentation System\nexport {\n DocumentationSystem,\n AppDocumentationManager,\n createDocumentationSystem,\n generateDocsFromIntelligentRoutes,\n} from './core/docs/index.js';\nexport type { DocsConfig } from './core/docs/index.js';\n\n// Configuration utilities\nexport {\n getConfig,\n createModuleConfig,\n getEnvVar,\n getEnvArray,\n getEnvJson,\n isDevelopment,\n isProduction,\n isStaging,\n requireEnvVars,\n envVar,\n getConfigValue,\n} from './core/config/utils.js';\n\nexport {\n initializeConfig,\n getGlobalConfig,\n isConfigInitialized,\n resetConfig,\n} from './core/config/index.js';\n\n// Export configuration types for TypeScript users\nexport type { AppConfig, DeepPartial, OriginFunction } from './core/config/index.js';\n\n// GraphQL System - Only export types and adapter\n// The core classes are lazy-loaded internally via app.graphqlInit()\nexport type {\n GraphQLContext,\n GraphQLResolver,\n GraphQLSubscriptionResolver,\n GraphQLSchemaBuilderOptions,\n GraphQLResolvers,\n GraphQLExecutionOptions,\n GraphQLOptions,\n GraphQLPlugin,\n GraphQLRequestContext,\n GraphQLRequestListener,\n GraphQLRequest,\n GraphQLResponse,\n GraphQLMetrics,\n GraphQLSubscriptionOptions,\n DataLoaderOptions,\n ComplexityEstimator,\n QueryComplexityOptions,\n DepthLimitOptions,\n} from './core/graphql/types.js';\n\nexport type { GraphQLAdapter, GraphQLStats } from './core/graphql/adapter.js';\nexport { GraphQLJsAdapter } from './core/graphql/adapters/graphql-js-adapter.js';\n\n// GraphQL helpers (these don't import graphql directly at module level)\nexport {\n createPothosBuilder,\n isPothosAvailable,\n isPothosSchema,\n pothosToSchema,\n createComplexityPlugin,\n createDepthLimitPlugin,\n createDataLoader,\n} from './core/middleware/built-in/graphql/helpers.js';\n\n// Job System\nexport {\n JobScheduler,\n JobHealthChecker,\n CronParser,\n parseInterval,\n formatDuration,\n everyInterval,\n cronSchedule,\n oneTimeAt,\n createJob,\n} from './core/jobs/index.js';\n\nexport type {\n JobSchedule,\n JobOptions,\n SimpleJobOptions,\n JobFunction,\n JobMetrics,\n SchedulerStats,\n JobHealth,\n JobHealthStatus,\n JobContext,\n JobExecution,\n JobState,\n JobSchedulerOptions,\n ExecutionContext,\n ExecutionResult,\n} from './core/jobs/index.js';\n\n// Middleware System\nexport { MiddlewareManager } from './core/middleware/index.js';\nexport type { MiddlewareInterface, MoroMiddleware } from './core/middleware/index.js';\n\n// Body parsers\nexport { json, urlencoded } from './core/middleware/built-in/body-parsers/index.js';\n\n// Standalone router — `createRouter()` is the canonical factory; `Router` is an\n// alias kept callable without `new` so Express-style named imports\n// (`import { Router } from '...'`; `const r = Router();`) work unchanged.\nexport { createRouter, createRouter as Router, MoroRouter } from './core/routing/create-router.js';\n\n// Types\nexport type * from './types/core.js';\nexport type * from './types/http.js';\nexport type * from './types/hooks.js';\nexport type * from './types/cache.js';\nexport type * from './types/cdn.js';\nexport type * from './types/database.js';\nexport type * from './types/logger.js';\nexport type * from './types/session.js';\nexport type * from './types/discovery.js';\n\n// Adapters\nexport * from './core/middleware/built-in/cache/adapters/index.js';\nexport * from './core/middleware/built-in/cdn/adapters/index.js';\nexport * from './core/database/adapters/index.js';\n\n// Re-export commonly used types for convenience\nexport type { CacheAdapter, CacheOptions, CacheStrategy } from './types/cache.js';\nexport type { CDNAdapter, CDNOptions } from './types/cdn.js';\nexport type { DatabaseAdapter, DatabaseTransaction, DatabaseConfig } from './types/database.js';\nexport type { CookieOptions } from './types/http.js';\n\n// gRPC System - Lazy loaded, only types exported\nexport type {\n GrpcOptions,\n GrpcCall,\n GrpcCallback,\n GrpcMetadata,\n GrpcError,\n GrpcStatusCode,\n GrpcCredentials,\n GrpcServer,\n GrpcClient,\n GrpcClientOptions,\n GrpcInterceptor,\n ServiceImplementation,\n ServiceDefinition,\n ServiceRegistration,\n MethodDefinition,\n UnaryHandler,\n ServerStreamingHandler,\n ClientStreamingHandler,\n BidirectionalStreamingHandler,\n GrpcHandler,\n GrpcStats,\n HealthCheckStatus,\n HealthCheckResponse,\n ProtoLoadOptions,\n} from './core/grpc/types.js';\n\nexport type { GrpcAdapter } from './core/grpc/grpc-adapter.js';\nexport { GrpcJsAdapter } from './core/grpc/adapters/index.js';\n\n// gRPC Middleware\nexport {\n grpcAuth,\n grpcRequirePermission,\n grpcRequireRole,\n extractTokenFromMetadata,\n grpcLogger,\n grpcSimpleLogger,\n grpcDetailedLogger,\n grpcValidate,\n grpcValidateHandler,\n} from './core/grpc/index.js';\n\n// Mail System - Lazy loaded, only types exported\nexport type {\n MailConfig,\n MailOptions,\n MailResult,\n MailAdapter,\n MailAdapterType,\n EmailAddress,\n EmailAttachment,\n TemplateConfig,\n TemplateEngine,\n MailQueueConfig,\n NodemailerConnection,\n SendGridConnection,\n SESConnection,\n ResendConnection,\n} from './core/mail/types.js';\n\nexport { BaseMailAdapter } from './core/mail/mail-adapter.js';\nexport {\n ConsoleAdapter,\n NodemailerAdapter,\n SendGridAdapter,\n SESAdapter,\n ResendAdapter,\n} from './core/mail/adapters/index.js';\n"]}
package/dist/moro.js CHANGED
@@ -344,7 +344,7 @@ export class Moro extends EventEmitter {
344
344
  };
345
345
  }
346
346
  get(path, handler, options) {
347
- if (handler) {
347
+ if (handler !== undefined) {
348
348
  // Direct route registration
349
349
  return this.addRoute('GET', path, handler, options);
350
350
  }
@@ -352,7 +352,7 @@ export class Moro extends EventEmitter {
352
352
  return this.unifiedRouter.get(path);
353
353
  }
354
354
  post(path, handler, options) {
355
- if (handler) {
355
+ if (handler !== undefined) {
356
356
  // Direct route registration
357
357
  return this.addRoute('POST', path, handler, options);
358
358
  }
@@ -360,7 +360,7 @@ export class Moro extends EventEmitter {
360
360
  return this.unifiedRouter.post(path);
361
361
  }
362
362
  put(path, handler, options) {
363
- if (handler) {
363
+ if (handler !== undefined) {
364
364
  // Direct route registration
365
365
  return this.addRoute('PUT', path, handler, options);
366
366
  }
@@ -368,7 +368,7 @@ export class Moro extends EventEmitter {
368
368
  return this.unifiedRouter.put(path);
369
369
  }
370
370
  delete(path, handler, options) {
371
- if (handler) {
371
+ if (handler !== undefined) {
372
372
  // Direct route registration
373
373
  return this.addRoute('DELETE', path, handler, options);
374
374
  }
@@ -376,7 +376,7 @@ export class Moro extends EventEmitter {
376
376
  return this.unifiedRouter.delete(path);
377
377
  }
378
378
  patch(path, handler, options) {
379
- if (handler) {
379
+ if (handler !== undefined) {
380
380
  // Direct route registration
381
381
  return this.addRoute('PATCH', path, handler, options);
382
382
  }
@@ -384,13 +384,13 @@ export class Moro extends EventEmitter {
384
384
  return this.unifiedRouter.patch(path);
385
385
  }
386
386
  head(path, handler, options) {
387
- if (handler) {
387
+ if (handler !== undefined) {
388
388
  return this.addRoute('HEAD', path, handler, options);
389
389
  }
390
390
  return this.unifiedRouter.head(path);
391
391
  }
392
392
  options(path, handler, options) {
393
- if (handler) {
393
+ if (handler !== undefined) {
394
394
  return this.addRoute('OPTIONS', path, handler, options);
395
395
  }
396
396
  return this.unifiedRouter.options(path);
@@ -1237,6 +1237,23 @@ export class Moro extends EventEmitter {
1237
1237
  }
1238
1238
  // Private methods
1239
1239
  addRoute(method, path, handler, options = {}) {
1240
+ // A literal body - app.get('/', '') - is the same route the builder's
1241
+ // .handler('') registers: the unified router turns it into a handler and,
1242
+ // with nothing else configured, a reply the native engine answers itself.
1243
+ // It never enters the legacy direct-route table, whose wrapper would
1244
+ // call it as a function.
1245
+ if (typeof handler !== 'function') {
1246
+ this.unifiedRouter.registerRoute({
1247
+ method: method,
1248
+ path,
1249
+ handler: handler,
1250
+ validation: options.validation,
1251
+ rateLimit: options.rateLimit,
1252
+ cache: options.cache,
1253
+ middleware: options.middleware,
1254
+ });
1255
+ return this;
1256
+ }
1240
1257
  // Register with unified router (primary routing system)
1241
1258
  this.unifiedRouter.addRoute(method, path, handler, options.middleware || []);
1242
1259
  // Also store in legacy routes array for backward compatibility
@@ -1282,6 +1299,19 @@ export class Moro extends EventEmitter {
1282
1299
  if (httpServer && typeof httpServer.setRouterHandler === 'function') {
1283
1300
  const router = this.unifiedRouter;
1284
1301
  httpServer.setRouterHandler((req, res) => router.handleRequest(req, res));
1302
+ // A server that answers fixed replies itself (MoroEngineServer on an
1303
+ // engine with capabilities.staticRoutes) gets every route whose handler
1304
+ // is a literal body, so those requests never enter JS. The route's
1305
+ // handler stays registered: it answers HEAD, and everything on servers
1306
+ // without the capability.
1307
+ if (typeof httpServer.setStaticRoute === 'function') {
1308
+ for (const schema of router.getAllRoutes()) {
1309
+ const fixed = schema.static;
1310
+ if (fixed) {
1311
+ httpServer.setStaticRoute(schema.method, schema.path, fixed.status, fixed.headers, fixed.body);
1312
+ }
1313
+ }
1314
+ }
1285
1315
  // Servers with a native router (uWS) additionally get fast-path routes
1286
1316
  // registered directly on it - evaluated at listen so late-loaded routes
1287
1317
  // are included; error handling shares the unified router's semantics