@warlock.js/core 5.2.3 → 5.2.4
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/CHANGELOG.md +6 -0
- package/esm/application/application.d.mts.map +1 -1
- package/esm/application/application.mjs.map +1 -1
- package/esm/benchmark/benchmark-snapshots.d.mts.map +1 -1
- package/esm/benchmark/benchmark.d.mts.map +1 -1
- package/esm/benchmark/channels/console.channel.mjs.map +1 -1
- package/esm/benchmark/channels/noop.channel.d.mts.map +1 -1
- package/esm/benchmark/profiler.d.mts.map +1 -1
- package/esm/benchmark/profiler.mjs.map +1 -1
- package/esm/bootstrap/setup.d.mts.map +1 -1
- package/esm/bootstrap/setup.mjs.map +1 -1
- package/esm/bootstrap.d.mts.map +1 -1
- package/esm/cache/database-cache-driver.d.mts.map +1 -1
- package/esm/cache/database-cache-driver.mjs.map +1 -1
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/cli-commands.utils.mjs.map +1 -1
- package/esm/cli/commands/doctor/boot-for-diagnostics.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/connectors.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/handler-signature.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/health.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/routes.check.mjs.map +1 -1
- package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/column-dsl-parser.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
- package/esm/cli/commands/generate/utils/name-parser.mjs.map +1 -1
- package/esm/cli/commands/generate/utils/prompt.mjs.map +1 -1
- package/esm/cli/commands/routes/diff-page-routes.mjs.map +1 -1
- package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -1
- package/esm/cli/commands/routes/route-row.mjs.map +1 -1
- package/esm/cli/commands/routes/routes-command.action.mjs.map +1 -1
- package/esm/cli/commands/routes/routes-diff.action.mjs.map +1 -1
- package/esm/cli/commands/storage-put.action.mjs.map +1 -1
- package/esm/cli/commands/typings-generator.command.mjs.map +1 -1
- package/esm/cli/commands-loader.mjs.map +1 -1
- package/esm/cli/start.mjs.map +1 -1
- package/esm/cli/string-similarity.mjs.map +1 -1
- package/esm/commands/cli-command.mjs.map +1 -1
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/config/config-setter.d.mts.map +1 -1
- package/esm/config/load-config-files.mjs.map +1 -1
- package/esm/connectors/access-connector.d.mts.map +1 -1
- package/esm/connectors/ai-connector.d.mts.map +1 -1
- package/esm/connectors/assert-no-reserved-connector-names.mjs.map +1 -1
- package/esm/connectors/assert-unique-connector-names.mjs.map +1 -1
- package/esm/connectors/base-connector.d.mts.map +1 -1
- package/esm/connectors/base-connector.mjs.map +1 -1
- package/esm/connectors/cache-connector.d.mts.map +1 -1
- package/esm/connectors/connectors-manager.d.mts.map +1 -1
- package/esm/connectors/connectors-manager.mjs.map +1 -1
- package/esm/connectors/database-connector.d.mts.map +1 -1
- package/esm/connectors/describe-server-address.mjs.map +1 -1
- package/esm/connectors/herald-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/connectors/logger-connector.d.mts.map +1 -1
- package/esm/connectors/mail-connector.d.mts.map +1 -1
- package/esm/connectors/notifications-connector.d.mts.map +1 -1
- package/esm/connectors/register-configured-connectors.mjs.map +1 -1
- package/esm/connectors/socket-connector.d.mts.map +1 -1
- package/esm/connectors/socket-connector.mjs.map +1 -1
- package/esm/connectors/storage.connector.d.mts.map +1 -1
- package/esm/container/index.d.mts.map +1 -1
- package/esm/database/create-database-action.mjs.map +1 -1
- package/esm/database/drop-tables-action.mjs.map +1 -1
- package/esm/database/migrate-action.mjs.map +1 -1
- package/esm/database/seed-command-action.mjs.map +1 -1
- package/esm/database/seeds/seed-records-table-migration.mjs.map +1 -1
- package/esm/database/seeds/seeders.manager.mjs.map +1 -1
- package/esm/database/seeds/seeds-table-migration.mjs.map +1 -1
- package/esm/dev-server/check-for-updates.mjs.map +1 -1
- package/esm/dev-server/dependency-graph.d.mts.map +1 -1
- package/esm/dev-server/dependency-graph.mjs.map +1 -1
- package/esm/dev-server/dev-logger.mjs.map +1 -1
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/file-event-handler.mjs.map +1 -1
- package/esm/dev-server/file-manager.d.mts.map +1 -1
- package/esm/dev-server/file-manager.mjs.map +1 -1
- package/esm/dev-server/file-operations.d.mts.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/files-watcher.mjs.map +1 -1
- package/esm/dev-server/health-checker/checkers/eslint-health-checker.mjs.map +1 -1
- package/esm/dev-server/health-checker/checkers/typescript-health-checker.mjs.map +1 -1
- package/esm/dev-server/health-checker/file-health-result.d.mts.map +1 -1
- package/esm/dev-server/health-checker/file-health-result.mjs.map +1 -1
- package/esm/dev-server/health-checker/files-healthcare.manager.mjs.map +1 -1
- package/esm/dev-server/layer-executor.mjs.map +1 -1
- package/esm/dev-server/loader/hook-thread.d.mts.map +1 -1
- package/esm/dev-server/loader/own-resolver.mjs.map +1 -1
- package/esm/dev-server/loader/register-loader.mjs.map +1 -1
- package/esm/dev-server/loader/resolve-hook.mjs.map +1 -1
- package/esm/dev-server/loader/source-slug.mjs.map +1 -1
- package/esm/dev-server/loader/transpile-cache.mjs.map +1 -1
- package/esm/dev-server/loader/version-registry.mjs.map +1 -1
- package/esm/dev-server/manifest-manager.d.mts.map +1 -1
- package/esm/dev-server/manifest-manager.mjs.map +1 -1
- package/esm/dev-server/module-loader.mjs.map +1 -1
- package/esm/dev-server/package-json-manager.mjs.map +1 -1
- package/esm/dev-server/parse-imports.mjs.map +1 -1
- package/esm/dev-server/ready-block.mjs.map +1 -1
- package/esm/dev-server/special-files-collector.d.mts.map +1 -1
- package/esm/dev-server/special-files-collector.mjs.map +1 -1
- package/esm/dev-server/tsconfig-manager.mjs.map +1 -1
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/dev-server/utils.mjs.map +1 -1
- package/esm/encryption/encrypt.mjs.map +1 -1
- package/esm/encryption/hash.mjs.map +1 -1
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/features/shadcn.feature.mjs.map +1 -1
- package/esm/generations/features/shared/migration-timestamp.mjs.map +1 -1
- package/esm/generations/features/tailwind.feature.mjs.map +1 -1
- package/esm/generations/features/web.feature.mjs +2 -1
- package/esm/generations/features/web.feature.mjs.map +1 -1
- package/esm/generations/stubs.mjs +40 -29
- package/esm/generations/stubs.mjs.map +1 -1
- package/esm/http/boot-port-preflight.d.mts.map +1 -1
- package/esm/http/context/request-context.d.mts.map +1 -1
- package/esm/http/context/request-context.mjs.map +1 -1
- package/esm/http/context/request-memo.d.mts.map +1 -1
- package/esm/http/context/request-memo.mjs.map +1 -1
- package/esm/http/createHttpApplication.d.mts.map +1 -1
- package/esm/http/createHttpApplication.mjs.map +1 -1
- package/esm/http/health.d.mts.map +1 -1
- package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
- package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
- package/esm/http/ready-report.d.mts.map +1 -1
- package/esm/http/request-controller.d.mts.map +1 -1
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.d.mts.map +1 -1
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/server.d.mts.map +1 -1
- package/esm/http/server.mjs.map +1 -1
- package/esm/http/uploaded-file.d.mts.map +1 -1
- package/esm/http/uploaded-file.mjs.map +1 -1
- package/esm/http/uploads-config.d.mts.map +1 -1
- package/esm/image/image.d.mts.map +1 -1
- package/esm/image/image.mjs.map +1 -1
- package/esm/logger/logger.mjs.map +1 -1
- package/esm/mail/config.d.mts.map +1 -1
- package/esm/mail/events.d.mts.map +1 -1
- package/esm/mail/mail.d.mts.map +1 -1
- package/esm/mail/mail.mjs.map +1 -1
- package/esm/mail/mailer-pool.d.mts.map +1 -1
- package/esm/mail/mailer-pool.mjs.map +1 -1
- package/esm/mail/send-mail.mjs.map +1 -1
- package/esm/mail/test-mailbox.d.mts.map +1 -1
- package/esm/mail/test-mailbox.mjs.map +1 -1
- package/esm/production/assert-generated-imports.mjs.map +1 -1
- package/esm/production/build-app-production.mjs.map +1 -1
- package/esm/production/dist-build-manifest.mjs.map +1 -1
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/production-supervisor.mjs.map +1 -1
- package/esm/production/promote-dist.mjs.map +1 -1
- package/esm/production/resolve-build-config.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-adapter.d.mts.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-adapter.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
- package/esm/repositories/repository.manager.d.mts.map +1 -1
- package/esm/repositories/repository.manager.mjs.map +1 -1
- package/esm/resource/register-resource.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.mjs.map +1 -1
- package/esm/resource/resource.d.mts.map +1 -1
- package/esm/resource/resource.mjs.map +1 -1
- package/esm/restful/restful.d.mts.map +1 -1
- package/esm/restful/restful.mjs.map +1 -1
- package/esm/router/log-request-lifecycle.mjs.map +1 -1
- package/esm/router/normalize-route-path.d.mts.map +1 -1
- package/esm/router/positional-handler-diagnostics.d.mts.map +1 -1
- package/esm/router/positional-handler-diagnostics.mjs.map +1 -1
- package/esm/router/route-registry.d.mts.map +1 -1
- package/esm/router/route-registry.mjs.map +1 -1
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs.map +1 -1
- package/esm/socket/utils.d.mts.map +1 -1
- package/esm/storage/config.d.mts.map +1 -1
- package/esm/storage/context/storage-driver-context.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
- package/esm/storage/drivers/do-spaces-driver.d.mts.map +1 -1
- package/esm/storage/drivers/local-driver.d.mts.map +1 -1
- package/esm/storage/drivers/local-driver.mjs.map +1 -1
- package/esm/storage/drivers/r2-driver.d.mts.map +1 -1
- package/esm/storage/scoped-storage.d.mts.map +1 -1
- package/esm/storage/scoped-storage.mjs.map +1 -1
- package/esm/storage/storage-file.d.mts.map +1 -1
- package/esm/storage/storage-file.mjs.map +1 -1
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/utils/safe-fetch.mjs.map +1 -1
- package/esm/tests/start-http-development-server.d.mts.map +1 -1
- package/esm/tests/test-connectors-selection.mjs.map +1 -1
- package/esm/tests/test-helpers.d.mts.map +1 -1
- package/esm/tests/test-setup-timeout.mjs.map +1 -1
- package/esm/tests/vitest-setup.d.mts.map +1 -1
- package/esm/tests/vitest-setup.mjs.map +1 -1
- package/esm/updater/update-warlock-packages.mjs.map +1 -1
- package/esm/use-cases/use-case-broadcast.d.mts.map +1 -1
- package/esm/use-cases/use-case-events.d.mts.map +1 -1
- package/esm/use-cases/use-case-pipeline.d.mts.map +1 -1
- package/esm/use-cases/use-case.d.mts.map +1 -1
- package/esm/use-cases/use-cases-registry.d.mts.map +1 -1
- package/esm/use-cases/use-cases-registry.mjs.map +1 -1
- package/esm/utils/database-log.d.mts.map +1 -1
- package/esm/utils/database-log.mjs.map +1 -1
- package/esm/utils/environment.d.mts.map +1 -1
- package/esm/utils/framework-vesion.mjs.map +1 -1
- package/esm/utils/get-localized.mjs.map +1 -1
- package/esm/utils/load-environment.mjs.map +1 -1
- package/esm/utils/normalized-path.d.mts.map +1 -1
- package/esm/utils/paths.d.mts.map +1 -1
- package/esm/utils/promise-all-object.d.mts.map +1 -1
- package/esm/utils/promise-all-object.mjs.map +1 -1
- package/esm/utils/sluggable.mjs.map +1 -1
- package/esm/utils/version-compare.mjs.map +1 -1
- package/esm/validation/database/exists-except-current-id.mjs.map +1 -1
- package/esm/validation/database/exists-except-current-user.mjs.map +1 -1
- package/esm/validation/database/unique-except-current-id.mjs.map +1 -1
- package/esm/validation/plugins/localized-plugin.mjs.map +1 -1
- package/esm/validation/validators/file-validator.mjs.map +1 -1
- package/esm/vite/lower-stage3-decorators.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
- package/llms-full.txt +4 -1
- package/llms.txt +1 -1
- package/package.json +12 -12
- package/skills/README.md +1 -1
- package/skills/write-cli-command/SKILL.md +4 -1
package/esm/image/image.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image.mjs","names":[],"sources":["../../../../../../../core/src/image/image.ts"],"sourcesContent":["import { http } from \"@mongez/http\";\r\nimport { createRequire } from \"node:module\";\r\nimport type sharp from \"sharp\";\r\nimport type { FormatEnum } from \"sharp\";\r\n\r\n// ============================================================\r\n// Lazily Resolved Sharp Module\r\n// ============================================================\r\n\r\n/**\r\n * Installation instructions for sharp\r\n */\r\nconst SHARP_INSTALL_INSTRUCTIONS = `\r\nImage processing requires the sharp package.\r\nInstall it with:\r\n\r\n warlock add image\r\n\r\nOr manually:\r\n\r\n npm install sharp\r\n pnpm add sharp\r\n yarn add sharp\r\n`.trim();\r\n\r\n/**\r\n * Cached sharp function, populated by the first `resolveSharp()` call\r\n */\r\nlet sharpFn: typeof sharp | null = null;\r\n\r\n/**\r\n * Whether the resolution attempt already ran (success or failure)\r\n */\r\nlet sharpResolved = false;\r\n\r\n/**\r\n * Why the resolution failed, when it failed for a reason other than absence.\r\n *\r\n * Cached and re-thrown on every later call: the resolution attempt runs exactly\r\n * once, so without this the second construction would fall through to the\r\n * \"not installed\" branch and report a different, wrong cause.\r\n */\r\nlet sharpLoadError: Error | null = null;\r\n\r\n/**\r\n * `new Error(message, { cause })` is ES2022, and this package still compiles\r\n * against the ES2020 lib (see #16), where `Error` is typed as taking a message\r\n * only. Node has supported the option since v16, so this is the type layer\r\n * catching up with the runtime, not a change in what the code does.\r\n */\r\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\r\n\r\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\r\n\r\n/**\r\n * Whether `error` says sharp itself is absent, as opposed to present but broken.\r\n *\r\n * Both halves are load-bearing. `MODULE_NOT_FOUND` alone is not enough: a\r\n * dependency missing *inside* sharp raises the very same code (`Cannot find\r\n * module 'color'`), and treating that as absence would tell the operator to\r\n * install a package they already have. So the message has to name the specifier\r\n * `'sharp'` exactly — quoted, which is also what keeps `'sharp-cli'` and friends\r\n * from matching.\r\n */\r\nfunction isSharpMissing(error: unknown): boolean {\r\n if (!(error instanceof Error)) return false;\r\n\r\n return (\r\n (error as NodeJS.ErrnoException).code === \"MODULE_NOT_FOUND\" &&\r\n error.message.includes(\"Cannot find module 'sharp'\")\r\n );\r\n}\r\n\r\n/**\r\n * Resolve sharp synchronously, on first use.\r\n *\r\n * Resolution is deliberately *lazy* and *synchronous*:\r\n *\r\n * - Lazy, because a top-level require would drag sharp's native binary into\r\n * every `import \"@warlock.js/core\"`, including apps that never touch images.\r\n * - Synchronous, because the `Image` constructor is synchronous. An async\r\n * import kicked off at module load leaves a window in which the module is\r\n * neither loaded nor known to be missing, and a constructor running inside\r\n * that window has no correct answer to give.\r\n *\r\n * `createRequire` gives an ESM-safe `require`, and the outcome — module, absence\r\n * or load failure — is cached, so the resolution runs exactly once per process.\r\n * The failure *reason* is cached too, not just the fact of it: every call after\r\n * a failed load has to report the same cause as the first one.\r\n *\r\n * @throws when sharp is not installed, or is installed but cannot be loaded\r\n */\r\nfunction resolveSharp(): typeof sharp {\r\n if (!sharpResolved) {\r\n sharpResolved = true;\r\n\r\n try {\r\n const require = createRequire(import.meta.url);\r\n const module = require(\"sharp\");\r\n sharpFn = (module.default ?? module) as typeof sharp;\r\n } catch (error) {\r\n sharpFn = null;\r\n\r\n if (!isSharpMissing(error)) {\r\n // sharp is there, it just would not load — almost always a binary built\r\n // for another platform. Its own error names the runtime and the fix, so\r\n // it is inlined *and* chained: a terminal that never prints `cause`\r\n // must still show the text that actually helps.\r\n sharpLoadError = new ErrorWithCause(\r\n `Failed to load \"sharp\": ${(error as Error).message}`,\r\n { cause: error },\r\n );\r\n }\r\n }\r\n }\r\n\r\n if (sharpLoadError) {\r\n throw sharpLoadError;\r\n }\r\n\r\n if (!sharpFn) {\r\n throw new Error(`sharp is not installed.\\n\\n${SHARP_INSTALL_INSTRUCTIONS}`);\r\n }\r\n\r\n return sharpFn;\r\n}\r\n\r\n// ============================================================\r\n// Types\r\n// ============================================================\r\n\r\nexport type ImageFormat = keyof FormatEnum;\r\n\r\nexport type ImageInput = string | Buffer | Uint8Array | ArrayBuffer;\r\n\r\n/**\r\n * Watermark configuration for deferred execution\r\n */\r\nexport type WatermarkConfig = {\r\n image: ImageInput | Image;\r\n options: sharp.OverlayOptions;\r\n};\r\n\r\n/**\r\n * Operation descriptor for deferred pipeline execution.\r\n * All operations are stored and executed at save/toBuffer time.\r\n */\r\ntype ImageOperation =\r\n | { type: \"resize\"; options: sharp.ResizeOptions }\r\n | { type: \"crop\"; options: sharp.Region }\r\n | { type: \"rotate\"; angle: number }\r\n | { type: \"flip\" }\r\n | { type: \"flop\" }\r\n | { type: \"blur\"; sigma: number }\r\n | { type: \"sharpen\"; options?: sharp.SharpenOptions }\r\n | { type: \"blackAndWhite\" }\r\n | { type: \"opacity\"; value: number }\r\n | { type: \"negate\"; options?: sharp.NegateOptions }\r\n | { type: \"tint\"; color: sharp.Color }\r\n | { type: \"trim\"; options?: sharp.TrimOptions }\r\n | { type: \"watermark\"; config: WatermarkConfig }\r\n | { type: \"watermarks\"; configs: WatermarkConfig[] };\r\n\r\n/**\r\n * Transformation options that can be applied in batch via `apply()` method.\r\n *\r\n * **Execution Order (when using apply()):**\r\n * 1. resize - Resize first to work with correct dimensions\r\n * 2. crop - Crop after resize to extract the desired region\r\n * 3. rotate - Rotation after sizing\r\n * 4. flip/flop - Mirror operations\r\n * 5. blackAndWhite/grayscale - Color space conversion\r\n * 6. blur - Blur effect\r\n * 7. sharpen - Sharpen effect\r\n * 8. tint - Color overlay\r\n * 9. negate - Invert colors\r\n * 10. opacity - Transparency (applied via composite)\r\n * 11. format/quality - Applied on save/export\r\n */\r\nexport type ImageTransformOptions = {\r\n /**\r\n * Output quality (1-100), applied based on final format\r\n */\r\n quality?: number;\r\n /**\r\n * Output format (jpeg, png, webp, avif, etc.)\r\n */\r\n format?: ImageFormat;\r\n /**\r\n * Resize options\r\n */\r\n resize?: sharp.ResizeOptions;\r\n /**\r\n * Crop/extract region\r\n */\r\n crop?: sharp.Region;\r\n /**\r\n * Rotation angle in degrees\r\n */\r\n rotate?: number;\r\n /**\r\n * Flip vertically (top to bottom)\r\n */\r\n flip?: boolean;\r\n /**\r\n * Flop horizontally (left to right)\r\n */\r\n flop?: boolean;\r\n /**\r\n * Convert to black and white\r\n */\r\n blackAndWhite?: boolean;\r\n /**\r\n * Alias for blackAndWhite\r\n */\r\n grayscale?: boolean;\r\n /**\r\n * Blur sigma (must be >= 0.3)\r\n */\r\n blur?: number;\r\n /**\r\n * Sharpen options\r\n */\r\n sharpen?: sharp.SharpenOptions | boolean;\r\n /**\r\n * Tint color\r\n */\r\n tint?: sharp.Color;\r\n /**\r\n * Negate/invert colors\r\n */\r\n negate?: sharp.NegateOptions | boolean;\r\n /**\r\n * Opacity (0-100)\r\n */\r\n opacity?: number;\r\n /**\r\n * Trim options\r\n */\r\n trim?: sharp.TrimOptions | boolean;\r\n /**\r\n * Single watermark\r\n */\r\n watermark?: WatermarkConfig;\r\n /**\r\n * Multiple watermarks\r\n */\r\n watermarks?: WatermarkConfig[];\r\n};\r\n\r\n/**\r\n * Internal options stored for deferred application\r\n */\r\ntype InternalOptions = {\r\n quality?: number;\r\n format?: ImageFormat;\r\n};\r\n\r\n/**\r\n * Image manipulation class with deferred pipeline execution.\r\n *\r\n * **Important:** This class requires the `sharp` package to be installed.\r\n * Install it with: `warlock add image` or `npm install sharp`\r\n *\r\n * Sharp is resolved synchronously on the first construction that needs it, so\r\n * the constructor and all chainable methods remain synchronous, and a missing\r\n * sharp throws at construction rather than at some later await.\r\n *\r\n * All operations are synchronous and stored as descriptors.\r\n * The pipeline is executed only when calling output methods:\r\n * - `save()` - Save to file\r\n * - `toBuffer()` - Get as buffer\r\n * - `toBase64()` - Get as base64 string\r\n * - `toDataUrl()` - Get as data URL\r\n *\r\n * @example\r\n * ```typescript\r\n * // All chaining is synchronous - single await at the end\r\n * await new Image(\"photo.jpg\")\r\n * .resize({ width: 800 })\r\n * .watermark(\"logo.png\", { gravity: \"southeast\" })\r\n * .quality(85)\r\n * .save(\"output.jpg\");\r\n * ```\r\n */\r\nexport class Image {\r\n /**\r\n * Image options that will be applied on save/export\r\n */\r\n protected options: InternalOptions = {};\r\n\r\n /**\r\n * Deferred operations pipeline\r\n */\r\n protected operations: ImageOperation[] = [];\r\n\r\n /**\r\n * Cached metadata to avoid repeated async calls\r\n */\r\n protected cachedMetadata: sharp.Metadata | null = null;\r\n\r\n /**\r\n * Whether the pipeline has been executed\r\n */\r\n protected pipelineExecuted = false;\r\n\r\n /**\r\n * Sharp image object\r\n */\r\n public readonly image: sharp.Sharp;\r\n\r\n /**\r\n * Formats that support quality option\r\n */\r\n protected static readonly QUALITY_FORMATS = [\"jpeg\", \"jpg\", \"webp\", \"avif\", \"tiff\", \"heif\"];\r\n\r\n /**\r\n * Constructor\r\n */\r\n public constructor(image: ImageInput | sharp.Sharp) {\r\n // An existing sharp instance carries its own module — short-circuit before\r\n // resolving sharp, so cloning never pays for (or fails on) a module load.\r\n if (image instanceof Object && \"clone\" in image && typeof image.clone === \"function\") {\r\n this.image = image as sharp.Sharp;\r\n } else {\r\n this.image = resolveSharp()(image as ImageInput);\r\n }\r\n }\r\n\r\n /**\r\n * Create image instance from file path\r\n */\r\n public static fromFile(path: string): Image {\r\n return new Image(path);\r\n }\r\n\r\n /**\r\n * Create image instance from buffer\r\n */\r\n public static fromBuffer(buffer: Buffer): Image {\r\n return new Image(buffer);\r\n }\r\n\r\n /**\r\n * Create image instance from url\r\n */\r\n public static async fromUrl(url: string): Promise<Image> {\r\n const { data, error } = await http.get<ArrayBuffer>(url, {\r\n responseType: \"arrayBuffer\",\r\n });\r\n\r\n if (error || !data) {\r\n throw new Error(\r\n `Failed to load image from URL \"${url}\": ${error?.message ?? \"Empty response received\"}`,\r\n );\r\n }\r\n\r\n return new Image(Buffer.from(data));\r\n }\r\n\r\n /**\r\n * Add an operation to the deferred pipeline\r\n */\r\n protected addOperation(operation: ImageOperation): this {\r\n this.operations.push(operation);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Apply multiple transformations at once with a predefined execution order.\r\n *\r\n * This method ensures transformations are applied in a logical order:\r\n * resize → crop → rotate → flip/flop → colorspace → effects → opacity → format\r\n *\r\n * For custom ordering, use individual chained methods instead.\r\n */\r\n public apply(options: ImageTransformOptions): this {\r\n // 1. Resize first to work with correct dimensions\r\n if (options.resize) {\r\n this.resize(options.resize);\r\n }\r\n\r\n // 2. Crop after resize\r\n if (options.crop) {\r\n this.crop(options.crop);\r\n }\r\n\r\n // 3. Rotation\r\n if (options.rotate !== undefined) {\r\n this.rotate(options.rotate);\r\n }\r\n\r\n // 4. Mirror operations\r\n if (options.flip) {\r\n this.flip();\r\n }\r\n\r\n if (options.flop) {\r\n this.flop();\r\n }\r\n\r\n // 5. Color space conversion\r\n if (options.blackAndWhite || options.grayscale) {\r\n this.blackAndWhite();\r\n }\r\n\r\n // 6. Blur effect\r\n if (options.blur !== undefined) {\r\n this.blur(options.blur);\r\n }\r\n\r\n // 7. Sharpen effect\r\n if (options.sharpen) {\r\n const sharpenOptions = typeof options.sharpen === \"boolean\" ? undefined : options.sharpen;\r\n this.sharpen(sharpenOptions);\r\n }\r\n\r\n // 8. Tint color\r\n if (options.tint) {\r\n this.tint(options.tint);\r\n }\r\n\r\n // 9. Negate/invert\r\n if (options.negate) {\r\n const negateOptions = typeof options.negate === \"boolean\" ? undefined : options.negate;\r\n this.negate(negateOptions);\r\n }\r\n\r\n // 10. Trim edges\r\n if (options.trim) {\r\n const trimOptions = typeof options.trim === \"boolean\" ? undefined : options.trim;\r\n this.trim(trimOptions);\r\n }\r\n\r\n // 11. Watermarks\r\n if (options.watermark) {\r\n this.watermark(options.watermark.image, options.watermark.options);\r\n }\r\n\r\n if (options.watermarks) {\r\n this.watermarks(options.watermarks);\r\n }\r\n\r\n // 12. Opacity (applied via composite)\r\n if (options.opacity !== undefined) {\r\n this.opacity(options.opacity);\r\n }\r\n\r\n // 13. Store format/quality for deferred application\r\n if (options.format) {\r\n this.format(options.format);\r\n }\r\n\r\n if (options.quality !== undefined) {\r\n this.quality(options.quality);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set image opacity (0-100)\r\n */\r\n public opacity(value: number): this {\r\n if (value < 0 || value > 100) {\r\n throw new Error(\"Opacity must be between 0 and 100\");\r\n }\r\n\r\n return this.addOperation({ type: \"opacity\", value });\r\n }\r\n\r\n /**\r\n * Convert image to black and white\r\n */\r\n public blackAndWhite(): this {\r\n return this.addOperation({ type: \"blackAndWhite\" });\r\n }\r\n\r\n /**\r\n * Alias for blackAndWhite\r\n */\r\n public grayscale(): this {\r\n return this.blackAndWhite();\r\n }\r\n\r\n /**\r\n * Get image dimensions (cached after first call)\r\n */\r\n public async dimensions(): Promise<{\r\n width: number | undefined;\r\n height: number | undefined;\r\n }> {\r\n const metadata = await this.metadata();\r\n\r\n return { width: metadata.width, height: metadata.height };\r\n }\r\n\r\n /**\r\n * Get image metadata (cached after first call)\r\n *\r\n * The metadata is cached to avoid repeated async operations.\r\n * Use `refreshMetadata()` to force a fresh fetch.\r\n */\r\n public async metadata(): Promise<sharp.Metadata> {\r\n if (!this.cachedMetadata) {\r\n this.cachedMetadata = await this.image.metadata();\r\n }\r\n\r\n return this.cachedMetadata;\r\n }\r\n\r\n /**\r\n * Force refresh of cached metadata\r\n *\r\n * Call this after transformations if you need updated metadata.\r\n */\r\n public async refreshMetadata(): Promise<sharp.Metadata> {\r\n this.cachedMetadata = await this.image.metadata();\r\n\r\n return this.cachedMetadata;\r\n }\r\n\r\n /**\r\n * Clear cached metadata\r\n */\r\n public clearMetadataCache(): this {\r\n this.cachedMetadata = null;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Resize image\r\n */\r\n public resize(options: sharp.ResizeOptions): this {\r\n if (typeof options.width !== \"undefined\" && !options.width) {\r\n delete options.width;\r\n }\r\n\r\n if (typeof options.height !== \"undefined\" && !options.height) {\r\n delete options.height;\r\n }\r\n\r\n return this.addOperation({ type: \"resize\", options });\r\n }\r\n\r\n /**\r\n * Crop/extract a region from the image\r\n */\r\n public crop(options: sharp.Region): this {\r\n return this.addOperation({ type: \"crop\", options });\r\n }\r\n\r\n /**\r\n * Set image quality (1-100)\r\n * Quality is stored and applied when saving/exporting\r\n * based on the final format.\r\n */\r\n public quality(quality: number): this {\r\n if (quality < 1 || quality > 100) {\r\n throw new Error(\"Quality must be between 1 and 100\");\r\n }\r\n\r\n this.options.quality = quality;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Execute the deferred pipeline - apply all stored operations\r\n */\r\n protected async executePipeline(): Promise<sharp.Sharp> {\r\n if (this.pipelineExecuted) {\r\n return this.image;\r\n }\r\n\r\n for (const operation of this.operations) {\r\n await this.executeOperation(this.image, operation);\r\n }\r\n\r\n await this.applyFormatAndQuality(this.image);\r\n\r\n this.pipelineExecuted = true;\r\n\r\n return this.image;\r\n }\r\n\r\n /**\r\n * Execute a single operation\r\n */\r\n protected async executeOperation(image: sharp.Sharp, operation: ImageOperation): Promise<void> {\r\n switch (operation.type) {\r\n case \"resize\":\r\n image.resize(operation.options);\r\n break;\r\n\r\n case \"crop\":\r\n image.extract(operation.options);\r\n break;\r\n\r\n case \"rotate\":\r\n image.rotate(operation.angle);\r\n break;\r\n\r\n case \"flip\":\r\n image.flip();\r\n break;\r\n\r\n case \"flop\":\r\n image.flop();\r\n break;\r\n\r\n case \"blur\":\r\n image.blur(operation.sigma);\r\n break;\r\n\r\n case \"sharpen\":\r\n image.sharpen(operation.options);\r\n break;\r\n\r\n case \"blackAndWhite\":\r\n image.toColourspace(\"b-w\");\r\n break;\r\n\r\n case \"opacity\": {\r\n const alpha = Math.round((operation.value / 100) * 255);\r\n const alphaPixel = Buffer.from([255, 255, 255, alpha]);\r\n image.composite([\r\n {\r\n blend: \"dest-in\",\r\n input: alphaPixel,\r\n },\r\n ]);\r\n break;\r\n }\r\n\r\n case \"negate\":\r\n image.negate(operation.options);\r\n break;\r\n\r\n case \"tint\":\r\n image.tint(operation.color);\r\n break;\r\n\r\n case \"trim\":\r\n image.trim(operation.options);\r\n break;\r\n\r\n case \"watermark\": {\r\n const buffer = await this.resolveImageBuffer(operation.config.image);\r\n image.composite([\r\n {\r\n input: buffer,\r\n ...operation.config.options,\r\n },\r\n ]);\r\n break;\r\n }\r\n\r\n case \"watermarks\": {\r\n const buffers = await Promise.all(\r\n operation.configs.map((config) => this.resolveImageBuffer(config.image)),\r\n );\r\n image.composite(\r\n operation.configs.map((config, index) => ({\r\n input: buffers[index],\r\n ...config.options,\r\n })),\r\n );\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Resolve an image input to a buffer\r\n */\r\n protected async resolveImageBuffer(input: ImageInput | Image): Promise<Buffer> {\r\n if (input instanceof Image) {\r\n // For Image instances, get buffer without applying options (raw buffer)\r\n return input.image.toBuffer();\r\n }\r\n\r\n // For other inputs (path, buffer, etc.), create temp sharp instance\r\n const tempImage = resolveSharp()(input);\r\n\r\n return tempImage.toBuffer();\r\n }\r\n\r\n /**\r\n * Apply format and quality options.\r\n * If no format is explicitly set, preserves the original format and applies\r\n * quality appropriately based on the format type.\r\n */\r\n protected async applyFormatAndQuality(image: sharp.Sharp): Promise<void> {\r\n const { quality, format } = this.options;\r\n\r\n if (format) {\r\n // Explicit format specified\r\n const formatOptions = quality ? { quality } : undefined;\r\n image.toFormat(format, formatOptions);\r\n return;\r\n }\r\n\r\n if (quality === undefined) {\r\n // No quality or format set, nothing to apply\r\n return;\r\n }\r\n\r\n // Quality is set but no format specified - detect original format\r\n const metadata = await this.metadata();\r\n const originalFormat = metadata.format;\r\n\r\n if (!originalFormat) {\r\n // Cannot detect format, default to webp with quality\r\n image.webp({ quality });\r\n return;\r\n }\r\n\r\n // Apply quality based on original format\r\n if (Image.QUALITY_FORMATS.includes(originalFormat)) {\r\n // Format supports quality option\r\n image.toFormat(originalFormat as ImageFormat, { quality });\r\n } else if (originalFormat === \"png\") {\r\n // PNG uses compressionLevel (0-9) instead of quality\r\n // Map quality 1-100 to compressionLevel 9-0 (higher quality = lower compression)\r\n const compressionLevel = Math.round(9 - (quality / 100) * 9);\r\n image.png({ compressionLevel });\r\n } else if (originalFormat === \"gif\") {\r\n // GIF doesn't support quality, just preserve format\r\n image.gif();\r\n }\r\n // Unknown format: preserve as-is (no quality applied)\r\n }\r\n\r\n /**\r\n * Save to file\r\n */\r\n public async save(path: string): Promise<sharp.OutputInfo> {\r\n const image = await this.executePipeline();\r\n\r\n return image.toFile(path);\r\n }\r\n\r\n /**\r\n * Convert to webp and save to file\r\n */\r\n public async saveAsWebp(path: string): Promise<sharp.OutputInfo> {\r\n // Override format to webp\r\n this.options.format = \"webp\";\r\n const image = await this.executePipeline();\r\n\r\n return image.toFile(path);\r\n }\r\n\r\n /**\r\n * Change the file format\r\n */\r\n public format(format: ImageFormat): this {\r\n this.options.format = format;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Add watermark (deferred - executed at save time)\r\n */\r\n public watermark(image: ImageInput | Image, options: sharp.OverlayOptions = {}): this {\r\n return this.addOperation({\r\n type: \"watermark\",\r\n config: { image, options },\r\n });\r\n }\r\n\r\n /**\r\n * Add multiple watermarks (deferred - executed at save time)\r\n */\r\n public watermarks(configs: WatermarkConfig[]): this {\r\n return this.addOperation({\r\n type: \"watermarks\",\r\n configs,\r\n });\r\n }\r\n\r\n /**\r\n * Rotate image\r\n */\r\n public rotate(angle: number): this {\r\n return this.addOperation({ type: \"rotate\", angle });\r\n }\r\n\r\n /**\r\n * Flip image vertically (top to bottom)\r\n */\r\n public flip(): this {\r\n return this.addOperation({ type: \"flip\" });\r\n }\r\n\r\n /**\r\n * Flop image horizontally (left to right)\r\n */\r\n public flop(): this {\r\n return this.addOperation({ type: \"flop\" });\r\n }\r\n\r\n /**\r\n * Blur image\r\n */\r\n public blur(sigma: number): this {\r\n if (sigma < 0.3) {\r\n throw new Error(\"Blur sigma must be at least 0.3\");\r\n }\r\n\r\n return this.addOperation({ type: \"blur\", sigma });\r\n }\r\n\r\n /**\r\n * Convert to base64\r\n */\r\n public async toBase64(): Promise<string> {\r\n const image = await this.executePipeline();\r\n const buffer = await image.toBuffer();\r\n\r\n return buffer.toString(\"base64\");\r\n }\r\n\r\n /**\r\n * Convert to data URL (base64 with mime type prefix)\r\n */\r\n public async toDataUrl(): Promise<string> {\r\n const metadata = await this.metadata();\r\n const format = this.options.format || metadata.format || \"png\";\r\n const mimeType = `image/${format === \"jpg\" ? \"jpeg\" : format}`;\r\n const base64 = await this.toBase64();\r\n\r\n return `data:${mimeType};base64,${base64}`;\r\n }\r\n\r\n /**\r\n * Sharpen image\r\n */\r\n public sharpen(options?: sharp.SharpenOptions): this {\r\n return this.addOperation({ type: \"sharpen\", options });\r\n }\r\n\r\n /**\r\n * Negate/invert image colors\r\n */\r\n public negate(options?: sharp.NegateOptions): this {\r\n return this.addOperation({ type: \"negate\", options });\r\n }\r\n\r\n /**\r\n * Tint image with a color\r\n */\r\n public tint(color: sharp.Color): this {\r\n return this.addOperation({ type: \"tint\", color });\r\n }\r\n\r\n /**\r\n * Trim edges from the image\r\n */\r\n public trim(options?: sharp.TrimOptions): this {\r\n return this.addOperation({ type: \"trim\", options });\r\n }\r\n\r\n /**\r\n * Convert to buffer\r\n */\r\n public async toBuffer(): Promise<Buffer> {\r\n const image = await this.executePipeline();\r\n\r\n return image.toBuffer();\r\n }\r\n\r\n /**\r\n * Clone the image for separate transformations\r\n */\r\n public clone(): Image {\r\n const clonedImage = new Image(this.image.clone());\r\n clonedImage.options = { ...this.options };\r\n clonedImage.operations = [...this.operations];\r\n clonedImage.cachedMetadata = this.cachedMetadata ? { ...this.cachedMetadata } : null;\r\n\r\n return clonedImage;\r\n }\r\n\r\n /**\r\n * Get the current stored options\r\n */\r\n public getOptions(): Readonly<InternalOptions> {\r\n return { ...this.options };\r\n }\r\n\r\n /**\r\n * Get the pending operations count\r\n */\r\n public getPendingOperationsCount(): number {\r\n return this.operations.length;\r\n }\r\n\r\n /**\r\n * Reset all stored options\r\n */\r\n public resetOptions(): this {\r\n this.options = {};\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Clear all pending operations\r\n */\r\n public clearOperations(): this {\r\n this.operations = [];\r\n this.pipelineExecuted = false;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Reset the image to its initial state (clear operations and options)\r\n */\r\n public reset(): this {\r\n this.operations = [];\r\n this.options = {};\r\n this.pipelineExecuted = false;\r\n this.cachedMetadata = null;\r\n\r\n return this;\r\n }\r\n}\r\n"],"mappings":";;;;;;;AAYA,MAAM,6BAA6B;;;;;;;;;;;EAWjC,KAAK;;;;AAKP,IAAI,UAA+B;;;;AAKnC,IAAI,gBAAgB;;;;;;;;AASpB,IAAI,iBAA+B;AAUnC,MAAM,iBAAiB;;;;;;;;;;;AAYvB,SAAS,eAAe,OAAyB;CAC/C,IAAI,EAAE,iBAAiB,QAAQ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C,GAAG,KAAK,UAAU;EAC5C,YAAY,iBAAiB,KAAK,iBAAiB,EAAE,GAAG,KAAK,eAAe,IAAI;EAEhF,OAAO;CACT;;;;CAKA,AAAO,aAAwC;EAC7C,OAAO,EAAE,GAAG,KAAK,QAAQ;CAC3B;;;;CAKA,AAAO,4BAAoC;EACzC,OAAO,KAAK,WAAW;CACzB;;;;CAKA,AAAO,eAAqB;EAC1B,KAAK,UAAU,CAAC;EAEhB,OAAO;CACT;;;;CAKA,AAAO,kBAAwB;EAC7B,KAAK,aAAa,CAAC;EACnB,KAAK,mBAAmB;EAExB,OAAO;CACT;;;;CAKA,AAAO,QAAc;EACnB,KAAK,aAAa,CAAC;EACnB,KAAK,UAAU,CAAC;EAChB,KAAK,mBAAmB;EACxB,KAAK,iBAAiB;EAEtB,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"image.mjs","names":[],"sources":["../../../../../../../core/src/image/image.ts"],"sourcesContent":["import { http } from \"@mongez/http\";\r\nimport { createRequire } from \"node:module\";\r\nimport type sharp from \"sharp\";\r\nimport type { FormatEnum } from \"sharp\";\r\n\r\n// ============================================================\r\n// Lazily Resolved Sharp Module\r\n// ============================================================\r\n\r\n/**\r\n * Installation instructions for sharp\r\n */\r\nconst SHARP_INSTALL_INSTRUCTIONS = `\r\nImage processing requires the sharp package.\r\nInstall it with:\r\n\r\n warlock add image\r\n\r\nOr manually:\r\n\r\n npm install sharp\r\n pnpm add sharp\r\n yarn add sharp\r\n`.trim();\r\n\r\n/**\r\n * Cached sharp function, populated by the first `resolveSharp()` call\r\n */\r\nlet sharpFn: typeof sharp | null = null;\r\n\r\n/**\r\n * Whether the resolution attempt already ran (success or failure)\r\n */\r\nlet sharpResolved = false;\r\n\r\n/**\r\n * Why the resolution failed, when it failed for a reason other than absence.\r\n *\r\n * Cached and re-thrown on every later call: the resolution attempt runs exactly\r\n * once, so without this the second construction would fall through to the\r\n * \"not installed\" branch and report a different, wrong cause.\r\n */\r\nlet sharpLoadError: Error | null = null;\r\n\r\n/**\r\n * `new Error(message, { cause })` is ES2022, and this package still compiles\r\n * against the ES2020 lib (see #16), where `Error` is typed as taking a message\r\n * only. Node has supported the option since v16, so this is the type layer\r\n * catching up with the runtime, not a change in what the code does.\r\n */\r\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\r\n\r\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\r\n\r\n/**\r\n * Whether `error` says sharp itself is absent, as opposed to present but broken.\r\n *\r\n * Both halves are load-bearing. `MODULE_NOT_FOUND` alone is not enough: a\r\n * dependency missing *inside* sharp raises the very same code (`Cannot find\r\n * module 'color'`), and treating that as absence would tell the operator to\r\n * install a package they already have. So the message has to name the specifier\r\n * `'sharp'` exactly — quoted, which is also what keeps `'sharp-cli'` and friends\r\n * from matching.\r\n */\r\nfunction isSharpMissing(error: unknown): boolean {\r\n if (!(error instanceof Error)) return false;\r\n\r\n return (\r\n (error as NodeJS.ErrnoException).code === \"MODULE_NOT_FOUND\" &&\r\n error.message.includes(\"Cannot find module 'sharp'\")\r\n );\r\n}\r\n\r\n/**\r\n * Resolve sharp synchronously, on first use.\r\n *\r\n * Resolution is deliberately *lazy* and *synchronous*:\r\n *\r\n * - Lazy, because a top-level require would drag sharp's native binary into\r\n * every `import \"@warlock.js/core\"`, including apps that never touch images.\r\n * - Synchronous, because the `Image` constructor is synchronous. An async\r\n * import kicked off at module load leaves a window in which the module is\r\n * neither loaded nor known to be missing, and a constructor running inside\r\n * that window has no correct answer to give.\r\n *\r\n * `createRequire` gives an ESM-safe `require`, and the outcome — module, absence\r\n * or load failure — is cached, so the resolution runs exactly once per process.\r\n * The failure *reason* is cached too, not just the fact of it: every call after\r\n * a failed load has to report the same cause as the first one.\r\n *\r\n * @throws when sharp is not installed, or is installed but cannot be loaded\r\n */\r\nfunction resolveSharp(): typeof sharp {\r\n if (!sharpResolved) {\r\n sharpResolved = true;\r\n\r\n try {\r\n const require = createRequire(import.meta.url);\r\n const module = require(\"sharp\");\r\n sharpFn = (module.default ?? module) as typeof sharp;\r\n } catch (error) {\r\n sharpFn = null;\r\n\r\n if (!isSharpMissing(error)) {\r\n // sharp is there, it just would not load — almost always a binary built\r\n // for another platform. Its own error names the runtime and the fix, so\r\n // it is inlined *and* chained: a terminal that never prints `cause`\r\n // must still show the text that actually helps.\r\n sharpLoadError = new ErrorWithCause(\r\n `Failed to load \"sharp\": ${(error as Error).message}`,\r\n { cause: error },\r\n );\r\n }\r\n }\r\n }\r\n\r\n if (sharpLoadError) {\r\n throw sharpLoadError;\r\n }\r\n\r\n if (!sharpFn) {\r\n throw new Error(`sharp is not installed.\\n\\n${SHARP_INSTALL_INSTRUCTIONS}`);\r\n }\r\n\r\n return sharpFn;\r\n}\r\n\r\n// ============================================================\r\n// Types\r\n// ============================================================\r\n\r\nexport type ImageFormat = keyof FormatEnum;\r\n\r\nexport type ImageInput = string | Buffer | Uint8Array | ArrayBuffer;\r\n\r\n/**\r\n * Watermark configuration for deferred execution\r\n */\r\nexport type WatermarkConfig = {\r\n image: ImageInput | Image;\r\n options: sharp.OverlayOptions;\r\n};\r\n\r\n/**\r\n * Operation descriptor for deferred pipeline execution.\r\n * All operations are stored and executed at save/toBuffer time.\r\n */\r\ntype ImageOperation =\r\n | { type: \"resize\"; options: sharp.ResizeOptions }\r\n | { type: \"crop\"; options: sharp.Region }\r\n | { type: \"rotate\"; angle: number }\r\n | { type: \"flip\" }\r\n | { type: \"flop\" }\r\n | { type: \"blur\"; sigma: number }\r\n | { type: \"sharpen\"; options?: sharp.SharpenOptions }\r\n | { type: \"blackAndWhite\" }\r\n | { type: \"opacity\"; value: number }\r\n | { type: \"negate\"; options?: sharp.NegateOptions }\r\n | { type: \"tint\"; color: sharp.Color }\r\n | { type: \"trim\"; options?: sharp.TrimOptions }\r\n | { type: \"watermark\"; config: WatermarkConfig }\r\n | { type: \"watermarks\"; configs: WatermarkConfig[] };\r\n\r\n/**\r\n * Transformation options that can be applied in batch via `apply()` method.\r\n *\r\n * **Execution Order (when using apply()):**\r\n * 1. resize - Resize first to work with correct dimensions\r\n * 2. crop - Crop after resize to extract the desired region\r\n * 3. rotate - Rotation after sizing\r\n * 4. flip/flop - Mirror operations\r\n * 5. blackAndWhite/grayscale - Color space conversion\r\n * 6. blur - Blur effect\r\n * 7. sharpen - Sharpen effect\r\n * 8. tint - Color overlay\r\n * 9. negate - Invert colors\r\n * 10. opacity - Transparency (applied via composite)\r\n * 11. format/quality - Applied on save/export\r\n */\r\nexport type ImageTransformOptions = {\r\n /**\r\n * Output quality (1-100), applied based on final format\r\n */\r\n quality?: number;\r\n /**\r\n * Output format (jpeg, png, webp, avif, etc.)\r\n */\r\n format?: ImageFormat;\r\n /**\r\n * Resize options\r\n */\r\n resize?: sharp.ResizeOptions;\r\n /**\r\n * Crop/extract region\r\n */\r\n crop?: sharp.Region;\r\n /**\r\n * Rotation angle in degrees\r\n */\r\n rotate?: number;\r\n /**\r\n * Flip vertically (top to bottom)\r\n */\r\n flip?: boolean;\r\n /**\r\n * Flop horizontally (left to right)\r\n */\r\n flop?: boolean;\r\n /**\r\n * Convert to black and white\r\n */\r\n blackAndWhite?: boolean;\r\n /**\r\n * Alias for blackAndWhite\r\n */\r\n grayscale?: boolean;\r\n /**\r\n * Blur sigma (must be >= 0.3)\r\n */\r\n blur?: number;\r\n /**\r\n * Sharpen options\r\n */\r\n sharpen?: sharp.SharpenOptions | boolean;\r\n /**\r\n * Tint color\r\n */\r\n tint?: sharp.Color;\r\n /**\r\n * Negate/invert colors\r\n */\r\n negate?: sharp.NegateOptions | boolean;\r\n /**\r\n * Opacity (0-100)\r\n */\r\n opacity?: number;\r\n /**\r\n * Trim options\r\n */\r\n trim?: sharp.TrimOptions | boolean;\r\n /**\r\n * Single watermark\r\n */\r\n watermark?: WatermarkConfig;\r\n /**\r\n * Multiple watermarks\r\n */\r\n watermarks?: WatermarkConfig[];\r\n};\r\n\r\n/**\r\n * Internal options stored for deferred application\r\n */\r\ntype InternalOptions = {\r\n quality?: number;\r\n format?: ImageFormat;\r\n};\r\n\r\n/**\r\n * Image manipulation class with deferred pipeline execution.\r\n *\r\n * **Important:** This class requires the `sharp` package to be installed.\r\n * Install it with: `warlock add image` or `npm install sharp`\r\n *\r\n * Sharp is resolved synchronously on the first construction that needs it, so\r\n * the constructor and all chainable methods remain synchronous, and a missing\r\n * sharp throws at construction rather than at some later await.\r\n *\r\n * All operations are synchronous and stored as descriptors.\r\n * The pipeline is executed only when calling output methods:\r\n * - `save()` - Save to file\r\n * - `toBuffer()` - Get as buffer\r\n * - `toBase64()` - Get as base64 string\r\n * - `toDataUrl()` - Get as data URL\r\n *\r\n * @example\r\n * ```typescript\r\n * // All chaining is synchronous - single await at the end\r\n * await new Image(\"photo.jpg\")\r\n * .resize({ width: 800 })\r\n * .watermark(\"logo.png\", { gravity: \"southeast\" })\r\n * .quality(85)\r\n * .save(\"output.jpg\");\r\n * ```\r\n */\r\nexport class Image {\r\n /**\r\n * Image options that will be applied on save/export\r\n */\r\n protected options: InternalOptions = {};\r\n\r\n /**\r\n * Deferred operations pipeline\r\n */\r\n protected operations: ImageOperation[] = [];\r\n\r\n /**\r\n * Cached metadata to avoid repeated async calls\r\n */\r\n protected cachedMetadata: sharp.Metadata | null = null;\r\n\r\n /**\r\n * Whether the pipeline has been executed\r\n */\r\n protected pipelineExecuted = false;\r\n\r\n /**\r\n * Sharp image object\r\n */\r\n public readonly image: sharp.Sharp;\r\n\r\n /**\r\n * Formats that support quality option\r\n */\r\n protected static readonly QUALITY_FORMATS = [\"jpeg\", \"jpg\", \"webp\", \"avif\", \"tiff\", \"heif\"];\r\n\r\n /**\r\n * Constructor\r\n */\r\n public constructor(image: ImageInput | sharp.Sharp) {\r\n // An existing sharp instance carries its own module — short-circuit before\r\n // resolving sharp, so cloning never pays for (or fails on) a module load.\r\n if (image instanceof Object && \"clone\" in image && typeof image.clone === \"function\") {\r\n this.image = image as sharp.Sharp;\r\n } else {\r\n this.image = resolveSharp()(image as ImageInput);\r\n }\r\n }\r\n\r\n /**\r\n * Create image instance from file path\r\n */\r\n public static fromFile(path: string): Image {\r\n return new Image(path);\r\n }\r\n\r\n /**\r\n * Create image instance from buffer\r\n */\r\n public static fromBuffer(buffer: Buffer): Image {\r\n return new Image(buffer);\r\n }\r\n\r\n /**\r\n * Create image instance from url\r\n */\r\n public static async fromUrl(url: string): Promise<Image> {\r\n const { data, error } = await http.get<ArrayBuffer>(url, {\r\n responseType: \"arrayBuffer\",\r\n });\r\n\r\n if (error || !data) {\r\n throw new Error(\r\n `Failed to load image from URL \"${url}\": ${error?.message ?? \"Empty response received\"}`,\r\n );\r\n }\r\n\r\n return new Image(Buffer.from(data));\r\n }\r\n\r\n /**\r\n * Add an operation to the deferred pipeline\r\n */\r\n protected addOperation(operation: ImageOperation): this {\r\n this.operations.push(operation);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Apply multiple transformations at once with a predefined execution order.\r\n *\r\n * This method ensures transformations are applied in a logical order:\r\n * resize → crop → rotate → flip/flop → colorspace → effects → opacity → format\r\n *\r\n * For custom ordering, use individual chained methods instead.\r\n */\r\n public apply(options: ImageTransformOptions): this {\r\n // 1. Resize first to work with correct dimensions\r\n if (options.resize) {\r\n this.resize(options.resize);\r\n }\r\n\r\n // 2. Crop after resize\r\n if (options.crop) {\r\n this.crop(options.crop);\r\n }\r\n\r\n // 3. Rotation\r\n if (options.rotate !== undefined) {\r\n this.rotate(options.rotate);\r\n }\r\n\r\n // 4. Mirror operations\r\n if (options.flip) {\r\n this.flip();\r\n }\r\n\r\n if (options.flop) {\r\n this.flop();\r\n }\r\n\r\n // 5. Color space conversion\r\n if (options.blackAndWhite || options.grayscale) {\r\n this.blackAndWhite();\r\n }\r\n\r\n // 6. Blur effect\r\n if (options.blur !== undefined) {\r\n this.blur(options.blur);\r\n }\r\n\r\n // 7. Sharpen effect\r\n if (options.sharpen) {\r\n const sharpenOptions = typeof options.sharpen === \"boolean\" ? undefined : options.sharpen;\r\n this.sharpen(sharpenOptions);\r\n }\r\n\r\n // 8. Tint color\r\n if (options.tint) {\r\n this.tint(options.tint);\r\n }\r\n\r\n // 9. Negate/invert\r\n if (options.negate) {\r\n const negateOptions = typeof options.negate === \"boolean\" ? undefined : options.negate;\r\n this.negate(negateOptions);\r\n }\r\n\r\n // 10. Trim edges\r\n if (options.trim) {\r\n const trimOptions = typeof options.trim === \"boolean\" ? undefined : options.trim;\r\n this.trim(trimOptions);\r\n }\r\n\r\n // 11. Watermarks\r\n if (options.watermark) {\r\n this.watermark(options.watermark.image, options.watermark.options);\r\n }\r\n\r\n if (options.watermarks) {\r\n this.watermarks(options.watermarks);\r\n }\r\n\r\n // 12. Opacity (applied via composite)\r\n if (options.opacity !== undefined) {\r\n this.opacity(options.opacity);\r\n }\r\n\r\n // 13. Store format/quality for deferred application\r\n if (options.format) {\r\n this.format(options.format);\r\n }\r\n\r\n if (options.quality !== undefined) {\r\n this.quality(options.quality);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set image opacity (0-100)\r\n */\r\n public opacity(value: number): this {\r\n if (value < 0 || value > 100) {\r\n throw new Error(\"Opacity must be between 0 and 100\");\r\n }\r\n\r\n return this.addOperation({ type: \"opacity\", value });\r\n }\r\n\r\n /**\r\n * Convert image to black and white\r\n */\r\n public blackAndWhite(): this {\r\n return this.addOperation({ type: \"blackAndWhite\" });\r\n }\r\n\r\n /**\r\n * Alias for blackAndWhite\r\n */\r\n public grayscale(): this {\r\n return this.blackAndWhite();\r\n }\r\n\r\n /**\r\n * Get image dimensions (cached after first call)\r\n */\r\n public async dimensions(): Promise<{\r\n width: number | undefined;\r\n height: number | undefined;\r\n }> {\r\n const metadata = await this.metadata();\r\n\r\n return { width: metadata.width, height: metadata.height };\r\n }\r\n\r\n /**\r\n * Get image metadata (cached after first call)\r\n *\r\n * The metadata is cached to avoid repeated async operations.\r\n * Use `refreshMetadata()` to force a fresh fetch.\r\n */\r\n public async metadata(): Promise<sharp.Metadata> {\r\n if (!this.cachedMetadata) {\r\n this.cachedMetadata = await this.image.metadata();\r\n }\r\n\r\n return this.cachedMetadata;\r\n }\r\n\r\n /**\r\n * Force refresh of cached metadata\r\n *\r\n * Call this after transformations if you need updated metadata.\r\n */\r\n public async refreshMetadata(): Promise<sharp.Metadata> {\r\n this.cachedMetadata = await this.image.metadata();\r\n\r\n return this.cachedMetadata;\r\n }\r\n\r\n /**\r\n * Clear cached metadata\r\n */\r\n public clearMetadataCache(): this {\r\n this.cachedMetadata = null;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Resize image\r\n */\r\n public resize(options: sharp.ResizeOptions): this {\r\n if (typeof options.width !== \"undefined\" && !options.width) {\r\n delete options.width;\r\n }\r\n\r\n if (typeof options.height !== \"undefined\" && !options.height) {\r\n delete options.height;\r\n }\r\n\r\n return this.addOperation({ type: \"resize\", options });\r\n }\r\n\r\n /**\r\n * Crop/extract a region from the image\r\n */\r\n public crop(options: sharp.Region): this {\r\n return this.addOperation({ type: \"crop\", options });\r\n }\r\n\r\n /**\r\n * Set image quality (1-100)\r\n * Quality is stored and applied when saving/exporting\r\n * based on the final format.\r\n */\r\n public quality(quality: number): this {\r\n if (quality < 1 || quality > 100) {\r\n throw new Error(\"Quality must be between 1 and 100\");\r\n }\r\n\r\n this.options.quality = quality;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Execute the deferred pipeline - apply all stored operations\r\n */\r\n protected async executePipeline(): Promise<sharp.Sharp> {\r\n if (this.pipelineExecuted) {\r\n return this.image;\r\n }\r\n\r\n for (const operation of this.operations) {\r\n await this.executeOperation(this.image, operation);\r\n }\r\n\r\n await this.applyFormatAndQuality(this.image);\r\n\r\n this.pipelineExecuted = true;\r\n\r\n return this.image;\r\n }\r\n\r\n /**\r\n * Execute a single operation\r\n */\r\n protected async executeOperation(image: sharp.Sharp, operation: ImageOperation): Promise<void> {\r\n switch (operation.type) {\r\n case \"resize\":\r\n image.resize(operation.options);\r\n break;\r\n\r\n case \"crop\":\r\n image.extract(operation.options);\r\n break;\r\n\r\n case \"rotate\":\r\n image.rotate(operation.angle);\r\n break;\r\n\r\n case \"flip\":\r\n image.flip();\r\n break;\r\n\r\n case \"flop\":\r\n image.flop();\r\n break;\r\n\r\n case \"blur\":\r\n image.blur(operation.sigma);\r\n break;\r\n\r\n case \"sharpen\":\r\n image.sharpen(operation.options);\r\n break;\r\n\r\n case \"blackAndWhite\":\r\n image.toColourspace(\"b-w\");\r\n break;\r\n\r\n case \"opacity\": {\r\n const alpha = Math.round((operation.value / 100) * 255);\r\n const alphaPixel = Buffer.from([255, 255, 255, alpha]);\r\n image.composite([\r\n {\r\n blend: \"dest-in\",\r\n input: alphaPixel,\r\n },\r\n ]);\r\n break;\r\n }\r\n\r\n case \"negate\":\r\n image.negate(operation.options);\r\n break;\r\n\r\n case \"tint\":\r\n image.tint(operation.color);\r\n break;\r\n\r\n case \"trim\":\r\n image.trim(operation.options);\r\n break;\r\n\r\n case \"watermark\": {\r\n const buffer = await this.resolveImageBuffer(operation.config.image);\r\n image.composite([\r\n {\r\n input: buffer,\r\n ...operation.config.options,\r\n },\r\n ]);\r\n break;\r\n }\r\n\r\n case \"watermarks\": {\r\n const buffers = await Promise.all(\r\n operation.configs.map((config) => this.resolveImageBuffer(config.image)),\r\n );\r\n image.composite(\r\n operation.configs.map((config, index) => ({\r\n input: buffers[index],\r\n ...config.options,\r\n })),\r\n );\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Resolve an image input to a buffer\r\n */\r\n protected async resolveImageBuffer(input: ImageInput | Image): Promise<Buffer> {\r\n if (input instanceof Image) {\r\n // For Image instances, get buffer without applying options (raw buffer)\r\n return input.image.toBuffer();\r\n }\r\n\r\n // For other inputs (path, buffer, etc.), create temp sharp instance\r\n const tempImage = resolveSharp()(input);\r\n\r\n return tempImage.toBuffer();\r\n }\r\n\r\n /**\r\n * Apply format and quality options.\r\n * If no format is explicitly set, preserves the original format and applies\r\n * quality appropriately based on the format type.\r\n */\r\n protected async applyFormatAndQuality(image: sharp.Sharp): Promise<void> {\r\n const { quality, format } = this.options;\r\n\r\n if (format) {\r\n // Explicit format specified\r\n const formatOptions = quality ? { quality } : undefined;\r\n image.toFormat(format, formatOptions);\r\n return;\r\n }\r\n\r\n if (quality === undefined) {\r\n // No quality or format set, nothing to apply\r\n return;\r\n }\r\n\r\n // Quality is set but no format specified - detect original format\r\n const metadata = await this.metadata();\r\n const originalFormat = metadata.format;\r\n\r\n if (!originalFormat) {\r\n // Cannot detect format, default to webp with quality\r\n image.webp({ quality });\r\n return;\r\n }\r\n\r\n // Apply quality based on original format\r\n if (Image.QUALITY_FORMATS.includes(originalFormat)) {\r\n // Format supports quality option\r\n image.toFormat(originalFormat as ImageFormat, { quality });\r\n } else if (originalFormat === \"png\") {\r\n // PNG uses compressionLevel (0-9) instead of quality\r\n // Map quality 1-100 to compressionLevel 9-0 (higher quality = lower compression)\r\n const compressionLevel = Math.round(9 - (quality / 100) * 9);\r\n image.png({ compressionLevel });\r\n } else if (originalFormat === \"gif\") {\r\n // GIF doesn't support quality, just preserve format\r\n image.gif();\r\n }\r\n // Unknown format: preserve as-is (no quality applied)\r\n }\r\n\r\n /**\r\n * Save to file\r\n */\r\n public async save(path: string): Promise<sharp.OutputInfo> {\r\n const image = await this.executePipeline();\r\n\r\n return image.toFile(path);\r\n }\r\n\r\n /**\r\n * Convert to webp and save to file\r\n */\r\n public async saveAsWebp(path: string): Promise<sharp.OutputInfo> {\r\n // Override format to webp\r\n this.options.format = \"webp\";\r\n const image = await this.executePipeline();\r\n\r\n return image.toFile(path);\r\n }\r\n\r\n /**\r\n * Change the file format\r\n */\r\n public format(format: ImageFormat): this {\r\n this.options.format = format;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Add watermark (deferred - executed at save time)\r\n */\r\n public watermark(image: ImageInput | Image, options: sharp.OverlayOptions = {}): this {\r\n return this.addOperation({\r\n type: \"watermark\",\r\n config: { image, options },\r\n });\r\n }\r\n\r\n /**\r\n * Add multiple watermarks (deferred - executed at save time)\r\n */\r\n public watermarks(configs: WatermarkConfig[]): this {\r\n return this.addOperation({\r\n type: \"watermarks\",\r\n configs,\r\n });\r\n }\r\n\r\n /**\r\n * Rotate image\r\n */\r\n public rotate(angle: number): this {\r\n return this.addOperation({ type: \"rotate\", angle });\r\n }\r\n\r\n /**\r\n * Flip image vertically (top to bottom)\r\n */\r\n public flip(): this {\r\n return this.addOperation({ type: \"flip\" });\r\n }\r\n\r\n /**\r\n * Flop image horizontally (left to right)\r\n */\r\n public flop(): this {\r\n return this.addOperation({ type: \"flop\" });\r\n }\r\n\r\n /**\r\n * Blur image\r\n */\r\n public blur(sigma: number): this {\r\n if (sigma < 0.3) {\r\n throw new Error(\"Blur sigma must be at least 0.3\");\r\n }\r\n\r\n return this.addOperation({ type: \"blur\", sigma });\r\n }\r\n\r\n /**\r\n * Convert to base64\r\n */\r\n public async toBase64(): Promise<string> {\r\n const image = await this.executePipeline();\r\n const buffer = await image.toBuffer();\r\n\r\n return buffer.toString(\"base64\");\r\n }\r\n\r\n /**\r\n * Convert to data URL (base64 with mime type prefix)\r\n */\r\n public async toDataUrl(): Promise<string> {\r\n const metadata = await this.metadata();\r\n const format = this.options.format || metadata.format || \"png\";\r\n const mimeType = `image/${format === \"jpg\" ? \"jpeg\" : format}`;\r\n const base64 = await this.toBase64();\r\n\r\n return `data:${mimeType};base64,${base64}`;\r\n }\r\n\r\n /**\r\n * Sharpen image\r\n */\r\n public sharpen(options?: sharp.SharpenOptions): this {\r\n return this.addOperation({ type: \"sharpen\", options });\r\n }\r\n\r\n /**\r\n * Negate/invert image colors\r\n */\r\n public negate(options?: sharp.NegateOptions): this {\r\n return this.addOperation({ type: \"negate\", options });\r\n }\r\n\r\n /**\r\n * Tint image with a color\r\n */\r\n public tint(color: sharp.Color): this {\r\n return this.addOperation({ type: \"tint\", color });\r\n }\r\n\r\n /**\r\n * Trim edges from the image\r\n */\r\n public trim(options?: sharp.TrimOptions): this {\r\n return this.addOperation({ type: \"trim\", options });\r\n }\r\n\r\n /**\r\n * Convert to buffer\r\n */\r\n public async toBuffer(): Promise<Buffer> {\r\n const image = await this.executePipeline();\r\n\r\n return image.toBuffer();\r\n }\r\n\r\n /**\r\n * Clone the image for separate transformations\r\n */\r\n public clone(): Image {\r\n const clonedImage = new Image(this.image.clone());\r\n clonedImage.options = { ...this.options };\r\n clonedImage.operations = [...this.operations];\r\n clonedImage.cachedMetadata = this.cachedMetadata ? { ...this.cachedMetadata } : null;\r\n\r\n return clonedImage;\r\n }\r\n\r\n /**\r\n * Get the current stored options\r\n */\r\n public getOptions(): Readonly<InternalOptions> {\r\n return { ...this.options };\r\n }\r\n\r\n /**\r\n * Get the pending operations count\r\n */\r\n public getPendingOperationsCount(): number {\r\n return this.operations.length;\r\n }\r\n\r\n /**\r\n * Reset all stored options\r\n */\r\n public resetOptions(): this {\r\n this.options = {};\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Clear all pending operations\r\n */\r\n public clearOperations(): this {\r\n this.operations = [];\r\n this.pipelineExecuted = false;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Reset the image to its initial state (clear operations and options)\r\n */\r\n public reset(): this {\r\n this.operations = [];\r\n this.options = {};\r\n this.pipelineExecuted = false;\r\n this.cachedMetadata = null;\r\n\r\n return this;\r\n }\r\n}\r\n"],"mappings":";;;;;;;AAYA,MAAM,6BAA6B;;;;;;;;;;;EAWjC,KAAK;;;;AAKP,IAAI,UAA+B;;;;AAKnC,IAAI,gBAAgB;;;;;;;;AASpB,IAAI,iBAA+B;AAUnC,MAAM,iBAAiB;;;;;;;;;;;AAYvB,SAAS,eAAe,OAAyB;CAC/C,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CAEtC,OACG,MAAgC,SAAS,sBAC1C,MAAM,QAAQ,SAAS,4BAA4B;AAEvD;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,eAA6B;CACpC,IAAI,CAAC,eAAe;EAClB,gBAAgB;EAEhB,IAAI;GAEF,MAAM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AAwC;EAC7C,OAAO,EAAE,GAAG,KAAK,QAAQ;CAC3B;;;;CAKA,AAAO,4BAAoC;EACzC,OAAO,KAAK,WAAW;CACzB;;;;CAKA,AAAO,eAAqB;EAC1B,KAAK,UAAU,CAAC;EAEhB,OAAO;CACT;;;;CAKA,AAAO,kBAAwB;EAC7B,KAAK,aAAa,CAAC;EACnB,KAAK,mBAAmB;EAExB,OAAO;CACT;;;;CAKA,AAAO,QAAc;EACnB,KAAK,aAAa,CAAC;EACnB,KAAK,UAAU,CAAC;EAChB,KAAK,mBAAmB;EACxB,KAAK,iBAAiB;EAEtB,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.mjs","names":[],"sources":["../../../../../../../core/src/logger/logger.ts"],"sourcesContent":["import type { LogChannel } from \"@warlock.js/logger\";\r\nimport { log } from \"@warlock.js/logger\";\r\nimport { environment } from \"../utils\";\r\nimport type { LogConfigurations } from \"./types\";\r\n\r\nexport function setLogConfigurations(options: LogConfigurations) {\r\n // log configurations\r\n const channels: LogChannel[] = [];\r\n\r\n const env = environment();\r\n\r\n const envChannels = options[env as \"development\" | \"production\"]?.channels;\r\n const defaultChannels = options.channels;\r\n\r\n if (defaultChannels) {\r\n channels.push(...defaultChannels);\r\n }\r\n\r\n if (envChannels) {\r\n channels.push(...envChannels);\r\n }\r\n\r\n log.configure({\r\n channels,\r\n });\r\n}\r\n"],"mappings":";;;;;AAKA,SAAgB,qBAAqB,SAA4B;CAE/D,MAAM,WAAyB,CAAC;CAIhC,MAAM,cAAc,QAFR,YAEkB,
|
|
1
|
+
{"version":3,"file":"logger.mjs","names":[],"sources":["../../../../../../../core/src/logger/logger.ts"],"sourcesContent":["import type { LogChannel } from \"@warlock.js/logger\";\r\nimport { log } from \"@warlock.js/logger\";\r\nimport { environment } from \"../utils\";\r\nimport type { LogConfigurations } from \"./types\";\r\n\r\nexport function setLogConfigurations(options: LogConfigurations) {\r\n // log configurations\r\n const channels: LogChannel[] = [];\r\n\r\n const env = environment();\r\n\r\n const envChannels = options[env as \"development\" | \"production\"]?.channels;\r\n const defaultChannels = options.channels;\r\n\r\n if (defaultChannels) {\r\n channels.push(...defaultChannels);\r\n }\r\n\r\n if (envChannels) {\r\n channels.push(...envChannels);\r\n }\r\n\r\n log.configure({\r\n channels,\r\n });\r\n}\r\n"],"mappings":";;;;;AAKA,SAAgB,qBAAqB,SAA4B;CAE/D,MAAM,WAAyB,CAAC;CAIhC,MAAM,cAAc,QAFR,YAEkB,EAAkC,EAAE;CAClE,MAAM,kBAAkB,QAAQ;CAEhC,IAAI,iBACF,SAAS,KAAK,GAAG,eAAe;CAGlC,IAAI,aACF,SAAS,KAAK,GAAG,WAAW;CAG9B,IAAI,UAAU,EACZ,SACF,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.mts","names":[],"sources":["../../../../../../../core/src/mail/config.ts"],"mappings":";;;;;AAuCA;;;;AAA0C;AAO1C;;;;AAAuC;AAOvC;;;;AAAgC;AAOhC;iBArBgB,WAAA,CAAY,IAAc,EAAR,QAAQ;;;AAqBT;iBAdjB,WAAA,
|
|
1
|
+
{"version":3,"file":"config.d.mts","names":[],"sources":["../../../../../../../core/src/mail/config.ts"],"mappings":";;;;;AAuCA;;;;AAA0C;AAO1C;;;;AAAuC;AAOvC;;;;AAAgC;AAOhC;iBArBgB,WAAA,CAAY,IAAc,EAAR,QAAQ;;;AAqBT;iBAdjB,WAAA,IAAe,QAAQ;;;;iBAOvB,gBAAA;AA2ChB;;;AAAA,iBApCgB,iBAAA;;;;iBAOA,UAAA;AA6BgE;AAYhF;;;;AAA0D;AAc1D;;;;AAAiE;AAsBjE;;;;;;;;;;AAGsB;AA2BtB;;;AA9EgF,iBAAhE,qBAAA,CAAsB,MAAA,EAAQ,kBAAA,GAAqB,aAAa;AAAA,iBAYhE,oBAAA,IAAwB,kBAAkB;;;;iBAc1C,eAAA,CAAgB,IAAA,WAAe,kBAAkB;;;;;iBAsBjD,iBAAA,CAAkB,OAAA;EAChC,MAAA,GAAS,kBAAA;EACT,MAAA;AAAA,IACE,kBAAkB;;;;iBA2BN,eAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.d.mts","names":[],"sources":["../../../../../../../core/src/mail/events.ts"],"mappings":";;AAMA;;iBAAgB,cAAA
|
|
1
|
+
{"version":3,"file":"events.d.mts","names":[],"sources":["../../../../../../../core/src/mail/events.ts"],"mappings":";;AAMA;;iBAAgB,cAAA;;AAAc;AAO9B;cAAa,WAAA;EAAA;;;;;;;;AAab;;;iBAAgB,gBAAA,CACd,MAAA,UACA,KAAqD;AAAA;AAkCvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAlCuD,cAkC1C,UAAA;EAsB6B;;;oCAlBN,WAAA,KAAW,IAAA;EA2BK;;;mCAnBlC,KAAA,qDACuC,IAAA;;;;+BAS1B,WAAA,EAAW,QAAA,MAAgB,IAAA,8CAAoB,iBAAA;EAgBV;;;+BAPrC,IAAA,iBAAqB,OAAA,iBAAwB,OAAA,qCAAc,iBAAA;EAcjE;;;sBAPH,IAAA,OAAW,MAAA,OAAa,KAAA,iBAAsB,OAAA,oCAAa,iBAAA;EAOT;;;yBAA/C,IAAA,OAAW,MAAA,iBAAuB,OAAA,oCAAa,iBAAA;EAOhB;;;uBAAjC,IAAA,OAAW,KAAA,iBAAsB,OAAA,oCAAa,iBAAA;;;;wCAUnD,QAAA,GACH,IAAA,iBAAqB,OAAA,iBAAwB,OAAA,qCAAc,iBAAA;EADxD;;;+BAUA,QAAA,GACH,IAAA,OAAW,MAAA,OAAa,KAAA,iBAAsB,OAAA,oCAAa,iBAAA;EAA3D;;;kCAQiB,QAAA,GAAa,IAAA,OAAW,MAAA,iBAAuB,OAAA,oCAAa,iBAAA;EAT1E;;;gCAgBY,QAAA,GAAa,IAAA,OAAW,KAAA,iBAAsB,OAAA,oCAAa,iBAAA;AAAA"}
|
package/esm/mail/mail.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mail.d.mts","names":[],"sources":["../../../../../../../core/src/mail/mail.ts"],"mappings":";;;;;;AAwCA;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,IAAA;EAAA,QACH,OAAA;EAUwC;;;EAAA,QALzC,WAAA
|
|
1
|
+
{"version":3,"file":"mail.d.mts","names":[],"sources":["../../../../../../../core/src/mail/mail.ts"],"mappings":";;;;;;AAwCA;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,IAAA;EAAA,QACH,OAAA;EAUwC;;;EAAA,QALzC,WAAA;EAe2C;;;EAAA,OAVpC,EAAA,CAAG,SAAA,sBAA+B,IAAA;EA8BzC;;;EAAA,OApBO,MAAA,CAAO,MAAA,EAAQ,kBAAA,GAAqB,IAAA;EAsC3C;;;EAAA,OA5BO,MAAA,CAAO,IAAA,WAAe,IAAA;EA8C7B;;;EApCA,EAAA,CAAG,SAAA;EA6CK;;;EApCR,EAAA,CAAG,SAAA;EAsDE;;;EA7CL,GAAA,CAAI,SAAA;EAsDM;;;EA7CV,OAAA,CAAQ,OAAA;EAsDyB;;;EA7CjC,IAAA,CAAK,OAAA,EAAS,WAAA;EA8DF;;;EArDZ,OAAA,CAAQ,OAAA;EA8EoC;;;EArE5C,IAAA,CAAK,OAAA;EAkGL;;;EAzFA,IAAA,CAAK,OAAA;EAkGE;;;EAzFP,SAAA,CAAU,OAAA,EAAS,KAAA,CAAM,YAAA;EA2GzB;;;EAlGA,MAAA,CAAO,OAAA,EAAS,MAAA,WAAiB,QAAA,UAAkB,WAAA;EAoHnD;;;EAnGA,WAAA,CAAY,WAAA,EAAa,cAAA;EA4Gd;;;;;;;;;;;;;;;;;;;EAnFX,UAAA,CAAW,IAAA,UAAc,QAAA,WAAmB,WAAA;EAwJZ;AAAA;;EApIhC,QAAA,CAAS,KAAA,EAAO,YAAA;;;;EAShB,OAAA,CAAQ,OAAA,EAAS,MAAA;;;;EASjB,MAAA,CAAO,IAAA,UAAc,KAAA;;;;EASrB,IAAA,CAAK,IAAA;;;;EASL,GAAA,CAAI,GAAA;;;;EASJ,aAAA,CAAc,EAAA;;;;EASd,UAAA,CAAW,MAAA,EAAQ,kBAAA;;;;EASnB,UAAA,CAAW,IAAA;;;;EASX,aAAA,CAAc,OAAA,EAAS,UAAA;;;;EASvB,MAAA,CAAO,OAAA,EAAS,UAAA;;;;EAShB,SAAA,CAAU,OAAA,EAAS,UAAA;;;;EASnB,OAAA,CAAQ,OAAA,EAAS,UAAA;;;;EASjB,UAAA,IAAc,OAAA,CAAQ,WAAA;;;;UAOrB,QAAA;;;;EAiBK,IAAA,IAAQ,OAAA,CAAQ,UAAA;AAAA"}
|
package/esm/mail/mail.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mail.mjs","names":[],"sources":["../../../../../../../core/src/mail/mail.ts"],"sourcesContent":["import type React from \"react\";\nimport { sendMail } from \"./send-mail\";\nimport type {\n MailAddress,\n MailAttachment,\n MailConfigurations,\n MailEvents,\n MailOptions,\n MailPriority,\n MailResult,\n} from \"./types\";\n\n/**\n * Fluent Mail Builder\n *\n * Provides a chainable API for building and sending emails.\n *\n * @example\n * ```typescript\n * await Mail.to(\"user@example.com\")\n * .subject(\"Welcome!\")\n * .component(<WelcomeEmail name=\"John\" />)\n * .send();\n *\n * // With attachments\n * await Mail.to(\"user@example.com\")\n * .cc(\"manager@example.com\")\n * .subject(\"Invoice\")\n * .component(<InvoiceEmail order={order} />)\n * .attach(pdfBuffer, \"invoice.pdf\")\n * .send();\n *\n * // Multi-tenant\n * await Mail.config(tenant.mailSettings)\n * .to(\"user@example.com\")\n * .subject(\"Hello\")\n * .html(\"<p>World</p>\")\n * .send();\n * ```\n */\nexport class Mail {\n private options: Partial<MailOptions> = {};\n\n /**\n * Private constructor - use static factory methods\n */\n private constructor() {}\n\n /**\n * Create a new mail with recipient\n */\n public static to(recipient: string | string[]): Mail {\n const mail = new Mail();\n mail.options.to = recipient;\n\n return mail;\n }\n\n /**\n * Create a new mail with custom configuration (multi-tenant)\n */\n public static config(config: MailConfigurations): Mail {\n const mail = new Mail();\n mail.options.config = config;\n\n return mail;\n }\n\n /**\n * Create a new mail with named mailer\n */\n public static mailer(name: string): Mail {\n const mail = new Mail();\n mail.options.mailer = name;\n\n return mail;\n }\n\n /**\n * Set recipient(s)\n */\n public to(recipient: string | string[]): this {\n this.options.to = recipient;\n\n return this;\n }\n\n /**\n * Set CC recipient(s)\n */\n public cc(recipient: string | string[]): this {\n this.options.cc = recipient;\n\n return this;\n }\n\n /**\n * Set BCC recipient(s)\n */\n public bcc(recipient: string | string[]): this {\n this.options.bcc = recipient;\n\n return this;\n }\n\n /**\n * Set reply-to address\n */\n public replyTo(address: string): this {\n this.options.replyTo = address;\n\n return this;\n }\n\n /**\n * Set from address\n */\n public from(address: MailAddress): this {\n this.options.from = address;\n\n return this;\n }\n\n /**\n * Set subject\n */\n public subject(subject: string): this {\n this.options.subject = subject;\n\n return this;\n }\n\n /**\n * Set HTML content\n */\n public html(content: string): this {\n this.options.html = content;\n\n return this;\n }\n\n /**\n * Set plain text content\n */\n public text(content: string): this {\n this.options.text = content;\n\n return this;\n }\n\n /**\n * Set React component as content\n */\n public component(element: React.ReactElement): this {\n this.options.component = element;\n\n return this;\n }\n\n /**\n * Add attachment\n */\n public attach(content: Buffer | string, filename: string, contentType?: string): this {\n if (!this.options.attachments) {\n this.options.attachments = [];\n }\n\n this.options.attachments.push({\n filename,\n content,\n contentType,\n });\n\n return this;\n }\n\n /**\n * Add multiple attachments\n */\n public attachments(attachments: MailAttachment[]): this {\n this.options.attachments = [...(this.options.attachments || []), ...attachments];\n\n return this;\n }\n\n /**\n * Attach a file by path\n *\n * The file will be read automatically when the email is sent.\n *\n * @param path Path to the file\n * @param filename Optional custom filename (defaults to basename of path)\n * @param contentType Optional MIME type\n *\n * @example\n * ```typescript\n * Mail.to(\"user@example.com\")\n * .subject(\"Invoice\")\n * .html(\"<p>Please see attached</p>\")\n * .attachFile(\"./invoices/2024-001.pdf\")\n * .attachFile(\"./terms.pdf\", \"terms-and-conditions.pdf\")\n * .send();\n * ```\n */\n public attachFile(path: string, filename?: string, contentType?: string): this {\n if (!this.options.attachments) {\n this.options.attachments = [];\n }\n\n // Extract filename from path if not provided\n const resolvedFilename = filename || path.split(/[/\\\\]/).pop() || \"attachment\";\n\n this.options.attachments.push({\n path,\n filename: resolvedFilename,\n contentType,\n });\n\n return this;\n }\n\n /**\n * Set priority\n */\n public priority(level: MailPriority): this {\n this.options.priority = level;\n\n return this;\n }\n\n /**\n * Set custom headers\n */\n public headers(headers: Record<string, string>): this {\n this.options.headers = { ...this.options.headers, ...headers };\n\n return this;\n }\n\n /**\n * Add a custom header\n */\n public header(name: string, value: string): this {\n this.options.headers = { ...this.options.headers, [name]: value };\n\n return this;\n }\n\n /**\n * Set tags for categorization\n */\n public tags(tags: string[]): this {\n this.options.tags = tags;\n\n return this;\n }\n\n /**\n * Add a tag\n */\n public tag(tag: string): this {\n this.options.tags = [...(this.options.tags || []), tag];\n\n return this;\n }\n\n /**\n * Set correlation ID for tracking\n */\n public correlationId(id: string): this {\n this.options.correlationId = id;\n\n return this;\n }\n\n /**\n * Set configuration (multi-tenant)\n */\n public withConfig(config: MailConfigurations): this {\n this.options.config = config;\n\n return this;\n }\n\n /**\n * Set named mailer\n */\n public withMailer(name: string): this {\n this.options.mailer = name;\n\n return this;\n }\n\n /**\n * Set beforeSending event handler\n */\n public beforeSending(handler: MailEvents[\"beforeSending\"]): this {\n this.options.beforeSending = handler;\n\n return this;\n }\n\n /**\n * Set onSent event handler\n */\n public onSent(handler: MailEvents[\"onSent\"]): this {\n this.options.onSent = handler;\n\n return this;\n }\n\n /**\n * Set onSuccess event handler\n */\n public onSuccess(handler: MailEvents[\"onSuccess\"]): this {\n this.options.onSuccess = handler;\n\n return this;\n }\n\n /**\n * Set onError event handler\n */\n public onError(handler: MailEvents[\"onError\"]): this {\n this.options.onError = handler;\n\n return this;\n }\n\n /**\n * Get the built options (for debugging)\n */\n public getOptions(): Partial<MailOptions> {\n return { ...this.options };\n }\n\n /**\n * Validate the mail before sending\n */\n private validate(): void {\n if (!this.options.to) {\n throw new Error(\"Mail recipient (to) is required\");\n }\n\n if (!this.options.subject) {\n throw new Error(\"Mail subject is required\");\n }\n\n if (!this.options.html && !this.options.text && !this.options.component) {\n throw new Error(\"Mail content (html, text, or component) is required\");\n }\n }\n\n /**\n * Send the email\n */\n public async send(): Promise<MailResult> {\n this.validate();\n\n return sendMail(this.options as MailOptions);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAa,OAAb,MAAa,KAAK;;;;CAMhB,AAAQ,cAAc;iBALkB,CAAC;CAKlB;;;;CAKvB,OAAc,GAAG,WAAoC;EACnD,MAAM,OAAO,IAAI,KAAK;EACtB,KAAK,QAAQ,KAAK;EAElB,OAAO;CACT;;;;CAKA,OAAc,OAAO,QAAkC;EACrD,MAAM,OAAO,IAAI,KAAK;EACtB,KAAK,QAAQ,SAAS;EAEtB,OAAO;CACT;;;;CAKA,OAAc,OAAO,MAAoB;EACvC,MAAM,OAAO,IAAI,KAAK;EACtB,KAAK,QAAQ,SAAS;EAEtB,OAAO;CACT;;;;CAKA,AAAO,GAAG,WAAoC;EAC5C,KAAK,QAAQ,KAAK;EAElB,OAAO;CACT;;;;CAKA,AAAO,GAAG,WAAoC;EAC5C,KAAK,QAAQ,KAAK;EAElB,OAAO;CACT;;;;CAKA,AAAO,IAAI,WAAoC;EAC7C,KAAK,QAAQ,MAAM;EAEnB,OAAO;CACT;;;;CAKA,AAAO,QAAQ,SAAuB;EACpC,KAAK,QAAQ,UAAU;EAEvB,OAAO;CACT;;;;CAKA,AAAO,KAAK,SAA4B;EACtC,KAAK,QAAQ,OAAO;EAEpB,OAAO;CACT;;;;CAKA,AAAO,QAAQ,SAAuB;EACpC,KAAK,QAAQ,UAAU;EAEvB,OAAO;CACT;;;;CAK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C,GAAI,KAAK,QAAQ,QAAQ,CAAC,GAAI,GAAG;EAEtD,OAAO;CACT;;;;CAKA,AAAO,cAAc,IAAkB;EACrC,KAAK,QAAQ,gBAAgB;EAE7B,OAAO;CACT;;;;CAKA,AAAO,WAAW,QAAkC;EAClD,KAAK,QAAQ,SAAS;EAEtB,OAAO;CACT;;;;CAKA,AAAO,WAAW,MAAoB;EACpC,KAAK,QAAQ,SAAS;EAEtB,OAAO;CACT;;;;CAKA,AAAO,cAAc,SAA4C;EAC/D,KAAK,QAAQ,gBAAgB;EAE7B,OAAO;CACT;;;;CAKA,AAAO,OAAO,SAAqC;EACjD,KAAK,QAAQ,SAAS;EAEtB,OAAO;CACT;;;;CAKA,AAAO,UAAU,SAAwC;EACvD,KAAK,QAAQ,YAAY;EAEzB,OAAO;CACT;;;;CAKA,AAAO,QAAQ,SAAsC;EACnD,KAAK,QAAQ,UAAU;EAEvB,OAAO;CACT;;;;CAKA,AAAO,aAAmC;EACxC,OAAO,EAAE,GAAG,KAAK,QAAQ;CAC3B;;;;CAKA,AAAQ,WAAiB;EACvB,IAAI,CAAC,KAAK,QAAQ,IAChB,MAAM,IAAI,MAAM,iCAAiC;EAGnD,IAAI,CAAC,KAAK,QAAQ,SAChB,MAAM,IAAI,MAAM,0BAA0B;EAG5C,IAAI,CAAC,KAAK,QAAQ,QAAQ,CAAC,KAAK,QAAQ,QAAQ,CAAC,KAAK,QAAQ,WAC5D,MAAM,IAAI,MAAM,qDAAqD;CAEzE;;;;CAKA,MAAa,OAA4B;EACvC,KAAK,SAAS;EAEd,OAAO,SAAS,KAAK,OAAsB;CAC7C;AACF"}
|
|
1
|
+
{"version":3,"file":"mail.mjs","names":[],"sources":["../../../../../../../core/src/mail/mail.ts"],"sourcesContent":["import type React from \"react\";\nimport { sendMail } from \"./send-mail\";\nimport type {\n MailAddress,\n MailAttachment,\n MailConfigurations,\n MailEvents,\n MailOptions,\n MailPriority,\n MailResult,\n} from \"./types\";\n\n/**\n * Fluent Mail Builder\n *\n * Provides a chainable API for building and sending emails.\n *\n * @example\n * ```typescript\n * await Mail.to(\"user@example.com\")\n * .subject(\"Welcome!\")\n * .component(<WelcomeEmail name=\"John\" />)\n * .send();\n *\n * // With attachments\n * await Mail.to(\"user@example.com\")\n * .cc(\"manager@example.com\")\n * .subject(\"Invoice\")\n * .component(<InvoiceEmail order={order} />)\n * .attach(pdfBuffer, \"invoice.pdf\")\n * .send();\n *\n * // Multi-tenant\n * await Mail.config(tenant.mailSettings)\n * .to(\"user@example.com\")\n * .subject(\"Hello\")\n * .html(\"<p>World</p>\")\n * .send();\n * ```\n */\nexport class Mail {\n private options: Partial<MailOptions> = {};\n\n /**\n * Private constructor - use static factory methods\n */\n private constructor() {}\n\n /**\n * Create a new mail with recipient\n */\n public static to(recipient: string | string[]): Mail {\n const mail = new Mail();\n mail.options.to = recipient;\n\n return mail;\n }\n\n /**\n * Create a new mail with custom configuration (multi-tenant)\n */\n public static config(config: MailConfigurations): Mail {\n const mail = new Mail();\n mail.options.config = config;\n\n return mail;\n }\n\n /**\n * Create a new mail with named mailer\n */\n public static mailer(name: string): Mail {\n const mail = new Mail();\n mail.options.mailer = name;\n\n return mail;\n }\n\n /**\n * Set recipient(s)\n */\n public to(recipient: string | string[]): this {\n this.options.to = recipient;\n\n return this;\n }\n\n /**\n * Set CC recipient(s)\n */\n public cc(recipient: string | string[]): this {\n this.options.cc = recipient;\n\n return this;\n }\n\n /**\n * Set BCC recipient(s)\n */\n public bcc(recipient: string | string[]): this {\n this.options.bcc = recipient;\n\n return this;\n }\n\n /**\n * Set reply-to address\n */\n public replyTo(address: string): this {\n this.options.replyTo = address;\n\n return this;\n }\n\n /**\n * Set from address\n */\n public from(address: MailAddress): this {\n this.options.from = address;\n\n return this;\n }\n\n /**\n * Set subject\n */\n public subject(subject: string): this {\n this.options.subject = subject;\n\n return this;\n }\n\n /**\n * Set HTML content\n */\n public html(content: string): this {\n this.options.html = content;\n\n return this;\n }\n\n /**\n * Set plain text content\n */\n public text(content: string): this {\n this.options.text = content;\n\n return this;\n }\n\n /**\n * Set React component as content\n */\n public component(element: React.ReactElement): this {\n this.options.component = element;\n\n return this;\n }\n\n /**\n * Add attachment\n */\n public attach(content: Buffer | string, filename: string, contentType?: string): this {\n if (!this.options.attachments) {\n this.options.attachments = [];\n }\n\n this.options.attachments.push({\n filename,\n content,\n contentType,\n });\n\n return this;\n }\n\n /**\n * Add multiple attachments\n */\n public attachments(attachments: MailAttachment[]): this {\n this.options.attachments = [...(this.options.attachments || []), ...attachments];\n\n return this;\n }\n\n /**\n * Attach a file by path\n *\n * The file will be read automatically when the email is sent.\n *\n * @param path Path to the file\n * @param filename Optional custom filename (defaults to basename of path)\n * @param contentType Optional MIME type\n *\n * @example\n * ```typescript\n * Mail.to(\"user@example.com\")\n * .subject(\"Invoice\")\n * .html(\"<p>Please see attached</p>\")\n * .attachFile(\"./invoices/2024-001.pdf\")\n * .attachFile(\"./terms.pdf\", \"terms-and-conditions.pdf\")\n * .send();\n * ```\n */\n public attachFile(path: string, filename?: string, contentType?: string): this {\n if (!this.options.attachments) {\n this.options.attachments = [];\n }\n\n // Extract filename from path if not provided\n const resolvedFilename = filename || path.split(/[/\\\\]/).pop() || \"attachment\";\n\n this.options.attachments.push({\n path,\n filename: resolvedFilename,\n contentType,\n });\n\n return this;\n }\n\n /**\n * Set priority\n */\n public priority(level: MailPriority): this {\n this.options.priority = level;\n\n return this;\n }\n\n /**\n * Set custom headers\n */\n public headers(headers: Record<string, string>): this {\n this.options.headers = { ...this.options.headers, ...headers };\n\n return this;\n }\n\n /**\n * Add a custom header\n */\n public header(name: string, value: string): this {\n this.options.headers = { ...this.options.headers, [name]: value };\n\n return this;\n }\n\n /**\n * Set tags for categorization\n */\n public tags(tags: string[]): this {\n this.options.tags = tags;\n\n return this;\n }\n\n /**\n * Add a tag\n */\n public tag(tag: string): this {\n this.options.tags = [...(this.options.tags || []), tag];\n\n return this;\n }\n\n /**\n * Set correlation ID for tracking\n */\n public correlationId(id: string): this {\n this.options.correlationId = id;\n\n return this;\n }\n\n /**\n * Set configuration (multi-tenant)\n */\n public withConfig(config: MailConfigurations): this {\n this.options.config = config;\n\n return this;\n }\n\n /**\n * Set named mailer\n */\n public withMailer(name: string): this {\n this.options.mailer = name;\n\n return this;\n }\n\n /**\n * Set beforeSending event handler\n */\n public beforeSending(handler: MailEvents[\"beforeSending\"]): this {\n this.options.beforeSending = handler;\n\n return this;\n }\n\n /**\n * Set onSent event handler\n */\n public onSent(handler: MailEvents[\"onSent\"]): this {\n this.options.onSent = handler;\n\n return this;\n }\n\n /**\n * Set onSuccess event handler\n */\n public onSuccess(handler: MailEvents[\"onSuccess\"]): this {\n this.options.onSuccess = handler;\n\n return this;\n }\n\n /**\n * Set onError event handler\n */\n public onError(handler: MailEvents[\"onError\"]): this {\n this.options.onError = handler;\n\n return this;\n }\n\n /**\n * Get the built options (for debugging)\n */\n public getOptions(): Partial<MailOptions> {\n return { ...this.options };\n }\n\n /**\n * Validate the mail before sending\n */\n private validate(): void {\n if (!this.options.to) {\n throw new Error(\"Mail recipient (to) is required\");\n }\n\n if (!this.options.subject) {\n throw new Error(\"Mail subject is required\");\n }\n\n if (!this.options.html && !this.options.text && !this.options.component) {\n throw new Error(\"Mail content (html, text, or component) is required\");\n }\n }\n\n /**\n * Send the email\n */\n public async send(): Promise<MailResult> {\n this.validate();\n\n return sendMail(this.options as MailOptions);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAa,OAAb,MAAa,KAAK;;;;CAMhB,AAAQ,cAAc;iBALkB,CAAC;CAKlB;;;;CAKvB,OAAc,GAAG,WAAoC;EACnD,MAAM,OAAO,IAAI,KAAK;EACtB,KAAK,QAAQ,KAAK;EAElB,OAAO;CACT;;;;CAKA,OAAc,OAAO,QAAkC;EACrD,MAAM,OAAO,IAAI,KAAK;EACtB,KAAK,QAAQ,SAAS;EAEtB,OAAO;CACT;;;;CAKA,OAAc,OAAO,MAAo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MAAM,IAAI,MAAM,iCAAiC;EAGnD,IAAI,CAAC,KAAK,QAAQ,SAChB,MAAM,IAAI,MAAM,0BAA0B;EAG5C,IAAI,CAAC,KAAK,QAAQ,QAAQ,CAAC,KAAK,QAAQ,QAAQ,CAAC,KAAK,QAAQ,WAC5D,MAAM,IAAI,MAAM,qDAAqD;CAEzE;;;;CAKA,MAAa,OAA4B;EACvC,KAAK,SAAS;EAEd,OAAO,SAAS,KAAK,OAAsB;CAC7C;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mailer-pool.d.mts","names":[],"sources":["../../../../../../../core/src/mail/mailer-pool.ts"],"mappings":";;;;;;AAoLA;;iBAAsB,SAAA,CAAU,MAAA,EAAQ,kBAAA,GAAqB,OAAA,CAAQ,WAAA;;;;iBA6C/C,YAAA,CAAa,MAAA,EAAQ,kBAAA,GAAqB,OAAO;;;;iBAcvD,WAAA,CAAY,MAA0B,EAAlB,kBAAkB;;;AA3D0B;iBAyEhE,eAAA
|
|
1
|
+
{"version":3,"file":"mailer-pool.d.mts","names":[],"sources":["../../../../../../../core/src/mail/mailer-pool.ts"],"mappings":";;;;;;AAoLA;;iBAAsB,SAAA,CAAU,MAAA,EAAQ,kBAAA,GAAqB,OAAA,CAAQ,WAAA;;;;iBA6C/C,YAAA,CAAa,MAAA,EAAQ,kBAAA,GAAqB,OAAO;;;;iBAcvD,WAAA,CAAY,MAA0B,EAAlB,kBAAkB;;;AA3D0B;iBAyEhE,eAAA;;;;iBAYA,YAAA;EAAkB,IAAA;EAAc,MAAM;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mailer-pool.mjs","names":[],"sources":["../../../../../../../core/src/mail/mailer-pool.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport type nodemailer from \"nodemailer\";\nimport type { Transporter } from \"nodemailer\";\nimport type { MailConfigurations, SESConfigurations, SMTPConfigurations } from \"./types\";\n\n// ============================================================\n// Eager-loaded Nodemailer Module\n// ============================================================\n\n/**\n * Installation instructions for nodemailer\n */\nconst NODEMAILER_INSTALL_INSTRUCTIONS = `\nEmail functionality requires the nodemailer package.\nInstall it with:\n\n warlock add mail\n\nOr manually:\n\n npm install nodemailer\n pnpm add nodemailer\n yarn add nodemailer\n`.trim();\n\n/**\n * Module availability flag\n */\nlet moduleExists: boolean | null = null;\n\n/**\n * Cached nodemailer module (loaded at import time)\n */\nlet nodemailerModule: typeof nodemailer;\n\nlet nodemailerLoadPromise: Promise<void> | null = null;\n\n/**\n * Eagerly load nodemailer module at import time\n */\nasync function loadNodemailerModule() {\n try {\n const module = await import(\"nodemailer\");\n nodemailerModule = module.default;\n moduleExists = true;\n } catch {\n moduleExists = false;\n }\n}\n\n// Kick off eager loading immediately\nnodemailerLoadPromise = loadNodemailerModule();\n\nconst SES_INSTALL_INSTRUCTIONS = `\nAWS SES functionality requires the @aws-sdk/client-sesv2 package.\nInstall it with:\n\n warlock add ses\n\nOr manually:\n\n npm install @aws-sdk/client-sesv2\n pnpm add @aws-sdk/client-sesv2\n yarn add @aws-sdk/client-sesv2\n`.trim();\n\nlet sesModuleExists: boolean | null = null;\n\nlet sesModule: typeof import(\"@aws-sdk/client-sesv2\");\n\nlet sesLoadPromise: Promise<void> | null = null;\n\nasync function loadSesModule() {\n try {\n const module = await import(\"@aws-sdk/client-sesv2\");\n sesModule = module.default;\n sesModuleExists = true;\n } catch {\n sesModuleExists = false;\n }\n}\n\nsesLoadPromise = loadSesModule();\n\nfunction isSesConfig(config: MailConfigurations): config is SESConfigurations {\n return \"driver\" in config && config.driver === \"ses\";\n}\n\nasync function getSesMailer(config: SESConfigurations): Promise<Transporter> {\n if (sesModuleExists === null && sesLoadPromise) {\n await sesLoadPromise;\n }\n\n if (sesModuleExists === false) {\n throw new Error(`@aws-sdk/client-sesv2 is not installed.\\n\\n${SES_INSTALL_INSTRUCTIONS}`);\n }\n\n if (moduleExists === null && nodemailerLoadPromise) {\n await nodemailerLoadPromise;\n }\n\n if (moduleExists === false) {\n throw new Error(`nodemailer is not installed.\\n\\n${NODEMAILER_INSTALL_INSTRUCTIONS}`);\n }\n\n const hash = `ses_${config.region}_${config.accessKeyId}`;\n\n const existingTransporter = mailerPool.get(hash);\n if (existingTransporter) {\n return existingTransporter;\n }\n\n log.info(\"mail\", \"pool\", `Creating new SES mailer transport (pool size: ${mailerPool.size + 1})`);\n\n const ses = new sesModule!.SESv2Client({\n region: config.region,\n credentials: {\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n },\n });\n\n const transporter = nodemailerModule.createTransport({\n SES: { sesClient: ses, SendEmailCommand: sesModule.SendEmailCommand },\n });\n\n mailerPool.set(hash, transporter);\n\n return transporter;\n}\n\n// ============================================================\n// Mailer Pool\n// ============================================================\n\n/**\n * Mailer pool for connection reuse\n * Maps config hash to transporter instance\n */\nconst mailerPool = new Map<string, Transporter>();\n\n/**\n * Create a hash from mail configuration for pooling\n */\nfunction createConfigHash(config: SMTPConfigurations): string {\n const key = JSON.stringify({\n // SMTP specific fields\n host: config.host,\n port: config.port,\n secure: config.secure,\n auth: config.auth,\n username: config.username,\n password: config.password,\n });\n\n // Simple hash function\n let hash = 0;\n for (let i = 0; i < key.length; i++) {\n const char = key.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n return `mailer_${hash}`;\n}\n\n/**\n * Get hash for any mailer config\n */\nfunction getMailerHash(config: MailConfigurations): string {\n if (isSesConfig(config)) {\n return `ses_${config.region}_${config.accessKeyId}`;\n }\n return createConfigHash(config);\n}\n\n/**\n * Get or create a mailer transporter from the pool\n * Nodemailer is eagerly loaded at import time\n */\nexport async function getMailer(config: MailConfigurations): Promise<Transporter> {\n if (moduleExists === null && nodemailerLoadPromise) {\n await nodemailerLoadPromise;\n }\n\n if (moduleExists === false) {\n throw new Error(`nodemailer is not installed.\\n\\n${NODEMAILER_INSTALL_INSTRUCTIONS}`);\n }\n\n if (isSesConfig(config)) {\n return getSesMailer(config);\n }\n\n const hash = getMailerHash(config);\n\n // Return existing transporter if available\n const existingTransporter = mailerPool.get(hash);\n\n if (existingTransporter) {\n return existingTransporter;\n }\n\n // Create new transporter\n log.info(\"mail\", \"pool\", `Creating new mailer transport (pool size: ${mailerPool.size + 1})`);\n\n const { auth, username, password, requireTLS, tls, ...transportConfig } = config;\n\n const transporter = nodemailerModule.createTransport({\n requireTLS: requireTLS ?? tls,\n auth: auth ?? {\n user: username,\n pass: password,\n },\n ...transportConfig,\n });\n\n // Store in pool\n mailerPool.set(hash, transporter);\n\n return transporter;\n}\n\n/**\n * Verify a mailer connection\n */\nexport async function verifyMailer(config: MailConfigurations): Promise<boolean> {\n const transporter = await getMailer(config);\n\n try {\n await transporter.verify();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Close a specific mailer connection\n */\nexport function closeMailer(config: MailConfigurations): void {\n const hash = getMailerHash(config);\n const transporter = mailerPool.get(hash);\n\n if (transporter) {\n transporter.close();\n mailerPool.delete(hash);\n log.info(\"mail\", \"pool\", `Closed mailer transport (pool size: ${mailerPool.size})`);\n }\n}\n\n/**\n * Close all mailer connections\n */\nexport function closeAllMailers(): void {\n for (const [hash, transporter] of mailerPool) {\n transporter.close();\n mailerPool.delete(hash);\n }\n\n log.info(\"mail\", \"pool\", \"Closed all mailer transports\");\n}\n\n/**\n * Get pool statistics\n */\nexport function getPoolStats(): { size: number; hashes: string[] } {\n return {\n size: mailerPool.size,\n hashes: Array.from(mailerPool.keys()),\n };\n}\n"],"mappings":";;;;;;AAYA,MAAM,kCAAkC;;;;;;;;;;;EAWtC,KAAK;;;;AAKP,IAAI,eAA+B;;;;AAKnC,IAAI;AAEJ,IAAI,wBAA8C;;;;AAKlD,eAAe,uBAAuB;CACpC,IAAI;EAEF,oBAAmB,MADE,OAAO,
|
|
1
|
+
{"version":3,"file":"mailer-pool.mjs","names":[],"sources":["../../../../../../../core/src/mail/mailer-pool.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport type nodemailer from \"nodemailer\";\nimport type { Transporter } from \"nodemailer\";\nimport type { MailConfigurations, SESConfigurations, SMTPConfigurations } from \"./types\";\n\n// ============================================================\n// Eager-loaded Nodemailer Module\n// ============================================================\n\n/**\n * Installation instructions for nodemailer\n */\nconst NODEMAILER_INSTALL_INSTRUCTIONS = `\nEmail functionality requires the nodemailer package.\nInstall it with:\n\n warlock add mail\n\nOr manually:\n\n npm install nodemailer\n pnpm add nodemailer\n yarn add nodemailer\n`.trim();\n\n/**\n * Module availability flag\n */\nlet moduleExists: boolean | null = null;\n\n/**\n * Cached nodemailer module (loaded at import time)\n */\nlet nodemailerModule: typeof nodemailer;\n\nlet nodemailerLoadPromise: Promise<void> | null = null;\n\n/**\n * Eagerly load nodemailer module at import time\n */\nasync function loadNodemailerModule() {\n try {\n const module = await import(\"nodemailer\");\n nodemailerModule = module.default;\n moduleExists = true;\n } catch {\n moduleExists = false;\n }\n}\n\n// Kick off eager loading immediately\nnodemailerLoadPromise = loadNodemailerModule();\n\nconst SES_INSTALL_INSTRUCTIONS = `\nAWS SES functionality requires the @aws-sdk/client-sesv2 package.\nInstall it with:\n\n warlock add ses\n\nOr manually:\n\n npm install @aws-sdk/client-sesv2\n pnpm add @aws-sdk/client-sesv2\n yarn add @aws-sdk/client-sesv2\n`.trim();\n\nlet sesModuleExists: boolean | null = null;\n\nlet sesModule: typeof import(\"@aws-sdk/client-sesv2\");\n\nlet sesLoadPromise: Promise<void> | null = null;\n\nasync function loadSesModule() {\n try {\n const module = await import(\"@aws-sdk/client-sesv2\");\n sesModule = module.default;\n sesModuleExists = true;\n } catch {\n sesModuleExists = false;\n }\n}\n\nsesLoadPromise = loadSesModule();\n\nfunction isSesConfig(config: MailConfigurations): config is SESConfigurations {\n return \"driver\" in config && config.driver === \"ses\";\n}\n\nasync function getSesMailer(config: SESConfigurations): Promise<Transporter> {\n if (sesModuleExists === null && sesLoadPromise) {\n await sesLoadPromise;\n }\n\n if (sesModuleExists === false) {\n throw new Error(`@aws-sdk/client-sesv2 is not installed.\\n\\n${SES_INSTALL_INSTRUCTIONS}`);\n }\n\n if (moduleExists === null && nodemailerLoadPromise) {\n await nodemailerLoadPromise;\n }\n\n if (moduleExists === false) {\n throw new Error(`nodemailer is not installed.\\n\\n${NODEMAILER_INSTALL_INSTRUCTIONS}`);\n }\n\n const hash = `ses_${config.region}_${config.accessKeyId}`;\n\n const existingTransporter = mailerPool.get(hash);\n if (existingTransporter) {\n return existingTransporter;\n }\n\n log.info(\"mail\", \"pool\", `Creating new SES mailer transport (pool size: ${mailerPool.size + 1})`);\n\n const ses = new sesModule!.SESv2Client({\n region: config.region,\n credentials: {\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n },\n });\n\n const transporter = nodemailerModule.createTransport({\n SES: { sesClient: ses, SendEmailCommand: sesModule.SendEmailCommand },\n });\n\n mailerPool.set(hash, transporter);\n\n return transporter;\n}\n\n// ============================================================\n// Mailer Pool\n// ============================================================\n\n/**\n * Mailer pool for connection reuse\n * Maps config hash to transporter instance\n */\nconst mailerPool = new Map<string, Transporter>();\n\n/**\n * Create a hash from mail configuration for pooling\n */\nfunction createConfigHash(config: SMTPConfigurations): string {\n const key = JSON.stringify({\n // SMTP specific fields\n host: config.host,\n port: config.port,\n secure: config.secure,\n auth: config.auth,\n username: config.username,\n password: config.password,\n });\n\n // Simple hash function\n let hash = 0;\n for (let i = 0; i < key.length; i++) {\n const char = key.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n return `mailer_${hash}`;\n}\n\n/**\n * Get hash for any mailer config\n */\nfunction getMailerHash(config: MailConfigurations): string {\n if (isSesConfig(config)) {\n return `ses_${config.region}_${config.accessKeyId}`;\n }\n return createConfigHash(config);\n}\n\n/**\n * Get or create a mailer transporter from the pool\n * Nodemailer is eagerly loaded at import time\n */\nexport async function getMailer(config: MailConfigurations): Promise<Transporter> {\n if (moduleExists === null && nodemailerLoadPromise) {\n await nodemailerLoadPromise;\n }\n\n if (moduleExists === false) {\n throw new Error(`nodemailer is not installed.\\n\\n${NODEMAILER_INSTALL_INSTRUCTIONS}`);\n }\n\n if (isSesConfig(config)) {\n return getSesMailer(config);\n }\n\n const hash = getMailerHash(config);\n\n // Return existing transporter if available\n const existingTransporter = mailerPool.get(hash);\n\n if (existingTransporter) {\n return existingTransporter;\n }\n\n // Create new transporter\n log.info(\"mail\", \"pool\", `Creating new mailer transport (pool size: ${mailerPool.size + 1})`);\n\n const { auth, username, password, requireTLS, tls, ...transportConfig } = config;\n\n const transporter = nodemailerModule.createTransport({\n requireTLS: requireTLS ?? tls,\n auth: auth ?? {\n user: username,\n pass: password,\n },\n ...transportConfig,\n });\n\n // Store in pool\n mailerPool.set(hash, transporter);\n\n return transporter;\n}\n\n/**\n * Verify a mailer connection\n */\nexport async function verifyMailer(config: MailConfigurations): Promise<boolean> {\n const transporter = await getMailer(config);\n\n try {\n await transporter.verify();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Close a specific mailer connection\n */\nexport function closeMailer(config: MailConfigurations): void {\n const hash = getMailerHash(config);\n const transporter = mailerPool.get(hash);\n\n if (transporter) {\n transporter.close();\n mailerPool.delete(hash);\n log.info(\"mail\", \"pool\", `Closed mailer transport (pool size: ${mailerPool.size})`);\n }\n}\n\n/**\n * Close all mailer connections\n */\nexport function closeAllMailers(): void {\n for (const [hash, transporter] of mailerPool) {\n transporter.close();\n mailerPool.delete(hash);\n }\n\n log.info(\"mail\", \"pool\", \"Closed all mailer transports\");\n}\n\n/**\n * Get pool statistics\n */\nexport function getPoolStats(): { size: number; hashes: string[] } {\n return {\n size: mailerPool.size,\n hashes: Array.from(mailerPool.keys()),\n };\n}\n"],"mappings":";;;;;;AAYA,MAAM,kCAAkC;;;;;;;;;;;EAWtC,KAAK;;;;AAKP,IAAI,eAA+B;;;;AAKnC,IAAI;AAEJ,IAAI,wBAA8C;;;;AAKlD,eAAe,uBAAuB;CACpC,IAAI;EAEF,oBAAmB,MADE,OAA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ACf,YAAY,MAAM;EAClB,WAAW,OAAO,IAAI;EACtB,IAAI,KAAK,QAAQ,QAAQ,uCAAuC,WAAW,KAAK,EAAE;CACpF;AACF;;;;AAKA,SAAgB,kBAAwB;CACtC,KAAK,MAAM,CAAC,MAAM,gBAAgB,YAAY;EAC5C,YAAY,MAAM;EAClB,WAAW,OAAO,IAAI;CACxB;CAEA,IAAI,KAAK,QAAQ,QAAQ,8BAA8B;AACzD;;;;AAKA,SAAgB,eAAmD;CACjE,OAAO;EACL,MAAM,WAAW;EACjB,QAAQ,MAAM,KAAK,WAAW,KAAK,CAAC;CACtC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"send-mail.mjs","names":[],"sources":["../../../../../../../core/src/mail/send-mail.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport { readFile } from \"node:fs/promises\";\nimport type { Options as NodemailerOptions } from \"nodemailer/lib/mailer\";\nimport { isDevelopmentMode, isTestMode, resolveMailConfig } from \"./config\";\nimport { MAIL_EVENTS, generateMailId, mailEvents } from \"./events\";\nimport { getMailer } from \"./mailer-pool\";\nimport { renderReactMail } from \"./react-mail\";\nimport { captureMail } from \"./test-mailbox\";\nimport {\n MailError,\n type CapturedMail,\n type MailAddress,\n type MailAttachment,\n type MailOptions,\n type MailPriority,\n type MailResult,\n type NormalizedMail,\n} from \"./types\";\n\n/**\n * Normalize email address to string\n */\nfunction addressToString(address: MailAddress): string {\n if (typeof address === \"string\") {\n return address;\n }\n\n return `\"${address.name}\" <${address.address}>`;\n}\n\n/**\n * Normalize recipients to array\n */\nfunction normalizeRecipients(recipients: string | string[] | undefined): string[] {\n if (!recipients) {\n return [];\n }\n\n return Array.isArray(recipients) ? recipients : [recipients];\n}\n\n/**\n * Map priority to nodemailer format\n */\nfunction mapPriority(priority: MailPriority): \"high\" | \"normal\" | \"low\" {\n return priority;\n}\n\n/**\n * Normalize mail options to internal format\n */\nfunction normalizeMail(options: MailOptions): NormalizedMail {\n const config = resolveMailConfig(options);\n\n return {\n to: normalizeRecipients(options.to),\n cc: normalizeRecipients(options.cc),\n bcc: normalizeRecipients(options.bcc),\n replyTo: options.replyTo,\n from: options.from || config.from || { name: \"No Reply\", address: \"noreply@localhost\" },\n subject: options.subject,\n html: options.html,\n text: options.text,\n attachments: options.attachments || [],\n priority: options.priority || \"normal\",\n headers: options.headers || {},\n tags: options.tags || [],\n correlationId: options.correlationId,\n config,\n };\n}\n\n/**\n * Resolve attachment - read file if path is provided\n */\nasync function resolveAttachment(attachment: MailAttachment): Promise<{\n filename: string;\n content: Buffer | string;\n contentType?: string;\n encoding?: string;\n cid?: string;\n}> {\n // If path is provided, read the file\n if (attachment.path) {\n try {\n const content = await readFile(attachment.path);\n return {\n filename: attachment.filename,\n content,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n } catch (error) {\n throw new MailError(\n `Failed to read attachment file \"${attachment.path}\": ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"CONFIG_ERROR\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n // Already has content\n return {\n filename: attachment.filename,\n content: attachment.content!,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n}\n\n/**\n * Build nodemailer options from normalized mail\n */\nasync function buildNodemailerOptions(normalized: NormalizedMail): Promise<NodemailerOptions> {\n const options: NodemailerOptions = {\n to: normalized.to,\n from: addressToString(normalized.from),\n subject: normalized.subject,\n priority: mapPriority(normalized.priority),\n };\n\n if (normalized.cc.length > 0) {\n options.cc = normalized.cc;\n }\n\n if (normalized.bcc.length > 0) {\n options.bcc = normalized.bcc;\n }\n\n if (normalized.replyTo) {\n options.replyTo = normalized.replyTo;\n }\n\n if (normalized.html) {\n options.html = normalized.html;\n }\n\n if (normalized.text) {\n options.text = normalized.text;\n }\n\n if (normalized.attachments.length > 0) {\n // Resolve all attachments (read files if needed)\n const resolvedAttachments = await Promise.all(\n normalized.attachments.map((att) => resolveAttachment(att as MailAttachment)),\n );\n\n options.attachments = resolvedAttachments.map((att) => ({\n filename: att.filename,\n content: att.content,\n contentType: att.contentType,\n encoding: att.encoding,\n cid: att.cid,\n }));\n }\n\n if (Object.keys(normalized.headers).length > 0) {\n options.headers = normalized.headers;\n }\n\n return options;\n}\n\n/**\n * Run per-mail event handler\n */\nasync function runMailEvent<T extends (...args: any[]) => any>(\n handler: T | undefined,\n ...args: Parameters<T>\n): Promise<ReturnType<T> | undefined> {\n if (!handler) {\n return undefined;\n }\n\n try {\n return await handler(...args);\n } catch (error) {\n log.error(\"mail\", \"event\", `Per-mail event handler error: ${error}`);\n return undefined;\n }\n}\n\n/**\n * Trigger both global and mail-specific events\n */\nasync function triggerEvents(\n mailId: string,\n event: \"beforeSending\" | \"sent\" | \"success\" | \"error\",\n ...args: any[]\n): Promise<any[]> {\n try {\n // Trigger global event (e.g., mail.success)\n const globalEventName =\n event === \"beforeSending\"\n ? \"BEFORE_SENDING\"\n : event === \"sent\"\n ? \"SENT\"\n : event === \"success\"\n ? \"SUCCESS\"\n : \"ERROR\";\n\n const globalResults = await mailEvents.trigger(\n globalEventName as keyof typeof MAIL_EVENTS,\n ...args,\n );\n\n // Trigger mail-specific event (e.g., mail.$id.success)\n const specificResults = await mailEvents.triggerForMail(mailId, event, ...args);\n\n return [...(globalResults || []), ...(specificResults || [])];\n } catch (error) {\n log.error(\"mail\", \"event\", `Event handler error: ${error}`);\n return [];\n }\n}\n\n/**\n * Send an email\n *\n * @param options Mail options including recipients, content, and configuration\n * @returns Result containing success status, message ID, and accepted/rejected recipients\n *\n * @example\n * ```typescript\n * // Basic usage\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n *\n * // With React component\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * component: <WelcomeEmail name=\"John\" />,\n * });\n *\n * // Track specific mail with events\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => {\n * console.log(\"This specific mail was sent!\");\n * });\n * await sendMail({ id: mailId, to: \"...\", subject: \"...\", html: \"...\" });\n * ```\n */\nexport async function sendMail(options: MailOptions): Promise<MailResult> {\n // Generate or use provided mail ID\n const mailId = options.id || generateMailId();\n\n // Render React component if provided\n if (options.component) {\n try {\n options.html = await renderReactMail(options.component);\n } catch (error) {\n const mailError = new MailError(\n `Failed to render React component: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"RENDER_ERROR\",\n error instanceof Error ? error : undefined,\n );\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n\n throw mailError;\n }\n }\n\n // Normalize mail\n const normalized = normalizeMail(options);\n const driver = normalized.config.driver || \"smtp\";\n\n // Run beforeSending event (per-mail, global, and mail-specific)\n const beforeResult = await runMailEvent(options.beforeSending, options);\n const globalBeforeResults = await triggerEvents(mailId, \"beforeSending\", options);\n\n // If any returns false, cancel sending\n if (beforeResult === false || globalBeforeResults.some((r) => r === false)) {\n log.info(\n `mail.${driver}`,\n \"cancelled\",\n \"Mail sending cancelled by beforeSending event\",\n );\n\n const result: MailResult = {\n success: false,\n accepted: [],\n rejected: normalized.to,\n response: \"Cancelled by beforeSending event\",\n };\n\n return result;\n }\n\n // Test mode - capture without sending\n if (isTestMode()) {\n log.info(\n `mail.${driver}`,\n \"test\",\n `[TEST MODE] Captured mail to: ${normalized.to.join(\", \")}`,\n );\n\n const result: MailResult = {\n success: true,\n messageId: `test-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Test mode - mail captured\",\n };\n\n const captured: CapturedMail = {\n options,\n normalized,\n timestamp: new Date(),\n result,\n };\n\n captureMail(captured);\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Development mode - log without sending\n if (isDevelopmentMode()) {\n log.info(\n `mail.${driver}`,\n \"dev\",\n `[DEV MODE] Would send mail to: ${normalized.to.join(\", \")}`,\n );\n log.info(`mail.${driver}`, \"dev\", `Subject: ${normalized.subject}`);\n\n if (normalized.html) {\n log.info(\n `mail.${driver}`,\n \"dev\",\n `HTML length: ${normalized.html.length} chars`,\n );\n }\n\n const result: MailResult = {\n success: true,\n messageId: `dev-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Development mode - mail logged\",\n };\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Production mode - actually send\n try {\n const config = resolveMailConfig(options);\n const mailer = await getMailer(config);\n const nodemailerOptions = await buildNodemailerOptions(normalized);\n\n log.info(\n `mail.${driver}`,\n \"send\",\n `Sending mail to: ${normalized.to.join(\", \")}`,\n );\n\n const output = await mailer.sendMail(nodemailerOptions);\n\n const accepted = output.accepted || (output.messageId ? normalized.to : []);\n const rejected = output.rejected || [];\n\n const result: MailResult = {\n success: accepted.length > 0,\n messageId: output.messageId,\n accepted: accepted as string[],\n rejected: rejected as string[],\n response: output.response,\n envelope: output.envelope,\n };\n\n if (result.success) {\n log.success(\n `mail.${driver}`,\n \"sent\",\n `Mail sent successfully (ID: ${result.messageId})`,\n );\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n } else {\n log.warn(\n `mail.${driver}`,\n \"partial\",\n `Mail partially rejected: ${rejected.join(\", \")}`,\n );\n }\n\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n let code: MailError[\"code\"] = \"UNKNOWN\";\n\n // Detect error type\n if (errorMessage.includes(\"ECONNREFUSED\") || errorMessage.includes(\"ENOTFOUND\")) {\n code = \"CONNECTION_ERROR\";\n } else if (errorMessage.includes(\"authentication\") || errorMessage.includes(\"auth\")) {\n code = \"AUTH_ERROR\";\n } else if (errorMessage.includes(\"timeout\") || errorMessage.includes(\"ETIMEDOUT\")) {\n code = \"TIMEOUT\";\n } else if (errorMessage.includes(\"rate\") || errorMessage.includes(\"limit\")) {\n code = \"RATE_LIMIT\";\n }\n\n const mailError = new MailError(\n `Failed to send mail: ${errorMessage}`,\n code,\n error instanceof Error ? error : undefined,\n );\n\n log.error(`mail.${driver}`, \"error\", mailError.message);\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n await runMailEvent(options.onSent, options, null, mailError);\n await triggerEvents(mailId, \"sent\", options, null, mailError);\n\n throw mailError;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAS,gBAAgB,SAA8B;CACrD,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,OAAO,IAAI,QAAQ,KAAK,KAAK,QAAQ,QAAQ;AAC/C;;;;AAKA,SAAS,oBAAoB,YAAqD;CAChF,IAAI,CAAC,YACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AAC7D;;;;AAKA,SAAS,YAAY,UAAmD;CACtE,OAAO;AACT;;;;AAKA,SAAS,cAAc,SAAsC;CAC3D,MAAM,SAAS,kBAAkB,OAAO;CAExC,OAAO;EACL,IAAI,oBAAoB,QAAQ,EAAE;EAClC,IAAI,oBAAoB,QAAQ,EAAE;EAClC,KAAK,oBAAoB,QAAQ,GAAG;EACpC,SAAS,QAAQ;EACjB,MAAM,QAAQ,QAAQ,OAAO,QAAQ;GAAE,MAAM;GAAY,SAAS;EAAoB;EACtF,SAAS,QAAQ;EACjB,MAAM,QAAQ;EACd,MAAM,QAAQ;EACd,aAAa,QAAQ,eAAe,CAAC;EACrC,UAAU,QAAQ,YAAY;EAC9B,SAAS,QAAQ,WAAW,CAAC;EAC7B,MAAM,QAAQ,QAAQ,CAAC;EACvB,eAAe,QAAQ;EACvB;CACF;AAC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;EACvD,MAAM,aAAa,QAAQ,QAAQ,SAAS,MAAM,SAAS;EAC3D,MAAM,cAAc,QAAQ,QAAQ,SAAS,MAAM,SAAS;EAE5D,MAAM;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"send-mail.mjs","names":[],"sources":["../../../../../../../core/src/mail/send-mail.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport { readFile } from \"node:fs/promises\";\nimport type { Options as NodemailerOptions } from \"nodemailer/lib/mailer\";\nimport { isDevelopmentMode, isTestMode, resolveMailConfig } from \"./config\";\nimport { MAIL_EVENTS, generateMailId, mailEvents } from \"./events\";\nimport { getMailer } from \"./mailer-pool\";\nimport { renderReactMail } from \"./react-mail\";\nimport { captureMail } from \"./test-mailbox\";\nimport {\n MailError,\n type CapturedMail,\n type MailAddress,\n type MailAttachment,\n type MailOptions,\n type MailPriority,\n type MailResult,\n type NormalizedMail,\n} from \"./types\";\n\n/**\n * Normalize email address to string\n */\nfunction addressToString(address: MailAddress): string {\n if (typeof address === \"string\") {\n return address;\n }\n\n return `\"${address.name}\" <${address.address}>`;\n}\n\n/**\n * Normalize recipients to array\n */\nfunction normalizeRecipients(recipients: string | string[] | undefined): string[] {\n if (!recipients) {\n return [];\n }\n\n return Array.isArray(recipients) ? recipients : [recipients];\n}\n\n/**\n * Map priority to nodemailer format\n */\nfunction mapPriority(priority: MailPriority): \"high\" | \"normal\" | \"low\" {\n return priority;\n}\n\n/**\n * Normalize mail options to internal format\n */\nfunction normalizeMail(options: MailOptions): NormalizedMail {\n const config = resolveMailConfig(options);\n\n return {\n to: normalizeRecipients(options.to),\n cc: normalizeRecipients(options.cc),\n bcc: normalizeRecipients(options.bcc),\n replyTo: options.replyTo,\n from: options.from || config.from || { name: \"No Reply\", address: \"noreply@localhost\" },\n subject: options.subject,\n html: options.html,\n text: options.text,\n attachments: options.attachments || [],\n priority: options.priority || \"normal\",\n headers: options.headers || {},\n tags: options.tags || [],\n correlationId: options.correlationId,\n config,\n };\n}\n\n/**\n * Resolve attachment - read file if path is provided\n */\nasync function resolveAttachment(attachment: MailAttachment): Promise<{\n filename: string;\n content: Buffer | string;\n contentType?: string;\n encoding?: string;\n cid?: string;\n}> {\n // If path is provided, read the file\n if (attachment.path) {\n try {\n const content = await readFile(attachment.path);\n return {\n filename: attachment.filename,\n content,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n } catch (error) {\n throw new MailError(\n `Failed to read attachment file \"${attachment.path}\": ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"CONFIG_ERROR\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n // Already has content\n return {\n filename: attachment.filename,\n content: attachment.content!,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n}\n\n/**\n * Build nodemailer options from normalized mail\n */\nasync function buildNodemailerOptions(normalized: NormalizedMail): Promise<NodemailerOptions> {\n const options: NodemailerOptions = {\n to: normalized.to,\n from: addressToString(normalized.from),\n subject: normalized.subject,\n priority: mapPriority(normalized.priority),\n };\n\n if (normalized.cc.length > 0) {\n options.cc = normalized.cc;\n }\n\n if (normalized.bcc.length > 0) {\n options.bcc = normalized.bcc;\n }\n\n if (normalized.replyTo) {\n options.replyTo = normalized.replyTo;\n }\n\n if (normalized.html) {\n options.html = normalized.html;\n }\n\n if (normalized.text) {\n options.text = normalized.text;\n }\n\n if (normalized.attachments.length > 0) {\n // Resolve all attachments (read files if needed)\n const resolvedAttachments = await Promise.all(\n normalized.attachments.map((att) => resolveAttachment(att as MailAttachment)),\n );\n\n options.attachments = resolvedAttachments.map((att) => ({\n filename: att.filename,\n content: att.content,\n contentType: att.contentType,\n encoding: att.encoding,\n cid: att.cid,\n }));\n }\n\n if (Object.keys(normalized.headers).length > 0) {\n options.headers = normalized.headers;\n }\n\n return options;\n}\n\n/**\n * Run per-mail event handler\n */\nasync function runMailEvent<T extends (...args: any[]) => any>(\n handler: T | undefined,\n ...args: Parameters<T>\n): Promise<ReturnType<T> | undefined> {\n if (!handler) {\n return undefined;\n }\n\n try {\n return await handler(...args);\n } catch (error) {\n log.error(\"mail\", \"event\", `Per-mail event handler error: ${error}`);\n return undefined;\n }\n}\n\n/**\n * Trigger both global and mail-specific events\n */\nasync function triggerEvents(\n mailId: string,\n event: \"beforeSending\" | \"sent\" | \"success\" | \"error\",\n ...args: any[]\n): Promise<any[]> {\n try {\n // Trigger global event (e.g., mail.success)\n const globalEventName =\n event === \"beforeSending\"\n ? \"BEFORE_SENDING\"\n : event === \"sent\"\n ? \"SENT\"\n : event === \"success\"\n ? \"SUCCESS\"\n : \"ERROR\";\n\n const globalResults = await mailEvents.trigger(\n globalEventName as keyof typeof MAIL_EVENTS,\n ...args,\n );\n\n // Trigger mail-specific event (e.g., mail.$id.success)\n const specificResults = await mailEvents.triggerForMail(mailId, event, ...args);\n\n return [...(globalResults || []), ...(specificResults || [])];\n } catch (error) {\n log.error(\"mail\", \"event\", `Event handler error: ${error}`);\n return [];\n }\n}\n\n/**\n * Send an email\n *\n * @param options Mail options including recipients, content, and configuration\n * @returns Result containing success status, message ID, and accepted/rejected recipients\n *\n * @example\n * ```typescript\n * // Basic usage\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n *\n * // With React component\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * component: <WelcomeEmail name=\"John\" />,\n * });\n *\n * // Track specific mail with events\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => {\n * console.log(\"This specific mail was sent!\");\n * });\n * await sendMail({ id: mailId, to: \"...\", subject: \"...\", html: \"...\" });\n * ```\n */\nexport async function sendMail(options: MailOptions): Promise<MailResult> {\n // Generate or use provided mail ID\n const mailId = options.id || generateMailId();\n\n // Render React component if provided\n if (options.component) {\n try {\n options.html = await renderReactMail(options.component);\n } catch (error) {\n const mailError = new MailError(\n `Failed to render React component: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"RENDER_ERROR\",\n error instanceof Error ? error : undefined,\n );\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n\n throw mailError;\n }\n }\n\n // Normalize mail\n const normalized = normalizeMail(options);\n const driver = normalized.config.driver || \"smtp\";\n\n // Run beforeSending event (per-mail, global, and mail-specific)\n const beforeResult = await runMailEvent(options.beforeSending, options);\n const globalBeforeResults = await triggerEvents(mailId, \"beforeSending\", options);\n\n // If any returns false, cancel sending\n if (beforeResult === false || globalBeforeResults.some((r) => r === false)) {\n log.info(\n `mail.${driver}`,\n \"cancelled\",\n \"Mail sending cancelled by beforeSending event\",\n );\n\n const result: MailResult = {\n success: false,\n accepted: [],\n rejected: normalized.to,\n response: \"Cancelled by beforeSending event\",\n };\n\n return result;\n }\n\n // Test mode - capture without sending\n if (isTestMode()) {\n log.info(\n `mail.${driver}`,\n \"test\",\n `[TEST MODE] Captured mail to: ${normalized.to.join(\", \")}`,\n );\n\n const result: MailResult = {\n success: true,\n messageId: `test-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Test mode - mail captured\",\n };\n\n const captured: CapturedMail = {\n options,\n normalized,\n timestamp: new Date(),\n result,\n };\n\n captureMail(captured);\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Development mode - log without sending\n if (isDevelopmentMode()) {\n log.info(\n `mail.${driver}`,\n \"dev\",\n `[DEV MODE] Would send mail to: ${normalized.to.join(\", \")}`,\n );\n log.info(`mail.${driver}`, \"dev\", `Subject: ${normalized.subject}`);\n\n if (normalized.html) {\n log.info(\n `mail.${driver}`,\n \"dev\",\n `HTML length: ${normalized.html.length} chars`,\n );\n }\n\n const result: MailResult = {\n success: true,\n messageId: `dev-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Development mode - mail logged\",\n };\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Production mode - actually send\n try {\n const config = resolveMailConfig(options);\n const mailer = await getMailer(config);\n const nodemailerOptions = await buildNodemailerOptions(normalized);\n\n log.info(\n `mail.${driver}`,\n \"send\",\n `Sending mail to: ${normalized.to.join(\", \")}`,\n );\n\n const output = await mailer.sendMail(nodemailerOptions);\n\n const accepted = output.accepted || (output.messageId ? normalized.to : []);\n const rejected = output.rejected || [];\n\n const result: MailResult = {\n success: accepted.length > 0,\n messageId: output.messageId,\n accepted: accepted as string[],\n rejected: rejected as string[],\n response: output.response,\n envelope: output.envelope,\n };\n\n if (result.success) {\n log.success(\n `mail.${driver}`,\n \"sent\",\n `Mail sent successfully (ID: ${result.messageId})`,\n );\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n } else {\n log.warn(\n `mail.${driver}`,\n \"partial\",\n `Mail partially rejected: ${rejected.join(\", \")}`,\n );\n }\n\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n let code: MailError[\"code\"] = \"UNKNOWN\";\n\n // Detect error type\n if (errorMessage.includes(\"ECONNREFUSED\") || errorMessage.includes(\"ENOTFOUND\")) {\n code = \"CONNECTION_ERROR\";\n } else if (errorMessage.includes(\"authentication\") || errorMessage.includes(\"auth\")) {\n code = \"AUTH_ERROR\";\n } else if (errorMessage.includes(\"timeout\") || errorMessage.includes(\"ETIMEDOUT\")) {\n code = \"TIMEOUT\";\n } else if (errorMessage.includes(\"rate\") || errorMessage.includes(\"limit\")) {\n code = \"RATE_LIMIT\";\n }\n\n const mailError = new MailError(\n `Failed to send mail: ${errorMessage}`,\n code,\n error instanceof Error ? error : undefined,\n );\n\n log.error(`mail.${driver}`, \"error\", mailError.message);\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n await runMailEvent(options.onSent, options, null, mailError);\n await triggerEvents(mailId, \"sent\", options, null, mailError);\n\n throw mailError;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAS,gBAAgB,SAA8B;CACrD,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,OAAO,IAAI,QAAQ,KAAK,KAAK,QAAQ,QAAQ;AAC/C;;;;AAKA,SAAS,oBAAoB,YAAqD;CAChF,IAAI,CAAC,YACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AAC7D;;;;AAKA,SAAS,YAAY,UAAmD;CACtE,OAAO;AACT;;;;AAKA,SAAS,cAAc,SAAsC;CAC3D,MAAM,SAAS,kBAAkB,OAAO;CAExC,OAAO;EACL,IAAI,oBAAoB,QAAQ,EAAE;EAClC,IAAI,oBAAoB,QAAQ,EAAE;EAClC,KAAK,oBAAoB,QAAQ,GAAG;EACpC,SAAS,QAAQ;EACjB,MAAM,QAAQ,QAAQ,OAAO,QAAQ;GAAE,MAAM;GAAY,SAAS;EAAoB;EACtF,SAAS,QAAQ;EACjB,MAAM,QAAQ;EACd,MAAM,QAAQ;EACd,aAAa,QAAQ,eAAe,CAAC;EACrC,UAAU,QAAQ,YAAY;EAC9B,SAAS,QAAQ,WAAW,CAAC;EAC7B,MAAM,QAAQ,QAAQ,CAAC;EACvB,eAAe,QAAQ;EACvB;CACF;AACF;;;;AAKA,eAAe,kBAAkB,YAM9B;CAED,IAAI,WAAW,MACb,IAAI;EACF,MAAM,UAAU,MAAM,SAAS,WAAW,IAAI;EAC9C,OAAO;GACL,UAAU,WAAW;GACrB;GACA,aAAa,WAAW;GACxB,UAAU,WAAW;GACrB,KAAK,WAAW;EAClB;CACF,SAAS,OAAO;EACd,MAAM,IAAI,UACR,mCAAmC,WAAW,KAAK,KAAK,iBAAiB,QAAQ,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AAkB,EAAZ,YAAY;;;;iBAO9B,cAAA,
|
|
1
|
+
{"version":3,"file":"test-mailbox.d.mts","names":[],"sources":["../../../../../../../core/src/mail/test-mailbox.ts"],"mappings":";;;;;;iBA2EgB,WAAA,CAAY,IAAkB,EAAZ,YAAY;;;;iBAO9B,cAAA,IAAkB,YAAY;;;;iBAO9B,WAAA,IAAe,YAAY;;;;iBAO3B,WAAA,CAAY,KAAA,WAAgB,YAAY;;;;iBAUxC,kBAAA,CAAmB,OAAA,WAAkB,YAAY;;;;iBAOjD,aAAA,CAAc,KAAa;;;;iBAO3B,sBAAA,CAAuB,OAAe;;;;iBAOtC,cAAA;;;;iBAOA,gBAAA;;;;iBAOA,cAAA,CAAe,SAAA,GAAY,IAAA,EAAM,YAAA,eAA2B,YAAY;;;;iBAaxE,eAAA,CAAgB,KAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-mailbox.mjs","names":[],"sources":["../../../../../../../core/src/mail/test-mailbox.ts"],"sourcesContent":["/**\n * Test Mailbox for Mail v2\n *\n * Provides utilities for capturing and asserting sent emails in test mode.\n *\n * ## Setup\n *\n * ```typescript\n * import { setMailMode, clearTestMailbox } from \"@warlock.js/core/mail/v2\";\n *\n * beforeEach(() => {\n * setMailMode(\"test\");\n * clearTestMailbox();\n * });\n * ```\n *\n * ## Usage\n *\n * ```typescript\n * import { sendMail, getTestMailbox, findMailsTo } from \"@warlock.js/core/mail/v2\";\n *\n * // Send email in test mode\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * html: \"<p>Hello</p>\",\n * });\n *\n * // Get all captured mails\n * const mails = getTestMailbox();\n * expect(mails).toHaveLength(1);\n * expect(mails[0].options.subject).toBe(\"Welcome!\");\n *\n * // Find specific mails\n * const userMails = findMailsTo(\"user@example.com\");\n * expect(userMails).toHaveLength(1);\n *\n * // Check if mail was sent\n * expect(wasMailSentTo(\"user@example.com\")).toBe(true);\n * expect(wasMailSentWithSubject(\"Welcome!\")).toBe(true);\n * ```\n *\n * ## Assertion Helpers\n *\n * ```typescript\n * // Assert a mail matching a predicate was sent\n * const mail = assertMailSent(m => m.options.to === \"user@example.com\");\n * expect(mail.options.subject).toBe(\"Welcome!\");\n *\n * // Assert exact count\n * assertMailCount(2); // throws if count doesn't match\n * ```\n *\n * ## Captured Mail Structure\n *\n * Each captured mail contains:\n * - `options` - Original MailOptions passed to sendMail\n * - `normalized` - Normalized mail data (arrays, addresses resolved)\n * - `timestamp` - When the mail was captured\n * - `result` - MailResult (in test mode, always success)\n * - `error` - MailError if sending failed (null in test mode)\n *\n * @module test-mailbox\n */\n\nimport type { CapturedMail } from \"./types\";\n\n/**\n * Test mailbox for capturing sent emails in test mode\n */\nlet testMailbox: CapturedMail[] = [];\n\n/**\n * Add a mail to the test mailbox\n */\nexport function captureMail(mail: CapturedMail): void {\n testMailbox.push(mail);\n}\n\n/**\n * Get all captured mails\n */\nexport function getTestMailbox(): CapturedMail[] {\n return [...testMailbox];\n}\n\n/**\n * Get the last captured mail\n */\nexport function getLastMail(): CapturedMail | undefined {\n return testMailbox[testMailbox.length - 1];\n}\n\n/**\n * Find mails by recipient\n */\nexport function findMailsTo(email: string): CapturedMail[] {\n return testMailbox.filter((mail) => {\n const to = Array.isArray(mail.options.to) ? mail.options.to : [mail.options.to];\n return to.includes(email);\n });\n}\n\n/**\n * Find mails by subject (partial match)\n */\nexport function findMailsBySubject(subject: string): CapturedMail[] {\n return testMailbox.filter((mail) => mail.options.subject.includes(subject));\n}\n\n/**\n * Check if a mail was sent to a specific recipient\n */\nexport function wasMailSentTo(email: string): boolean {\n return findMailsTo(email).length > 0;\n}\n\n/**\n * Check if a mail with specific subject was sent\n */\nexport function wasMailSentWithSubject(subject: string): boolean {\n return testMailbox.some((mail) => mail.options.subject === subject);\n}\n\n/**\n * Get mailbox size\n */\nexport function getMailboxSize(): number {\n return testMailbox.length;\n}\n\n/**\n * Clear the test mailbox\n */\nexport function clearTestMailbox(): void {\n testMailbox = [];\n}\n\n/**\n * Assert helper for testing\n */\nexport function assertMailSent(predicate: (mail: CapturedMail) => boolean): CapturedMail {\n const mail = testMailbox.find(predicate);\n\n if (!mail) {\n throw new Error(\"No mail matching the predicate was found in the test mailbox\");\n }\n\n return mail;\n}\n\n/**\n * Assert that a specific number of mails were sent\n */\nexport function assertMailCount(count: number): void {\n if (testMailbox.length !== count) {\n throw new Error(`Expected ${count} mails to be sent, but found ${testMailbox.length}`);\n }\n}\n"],"mappings":";;;;AAsEA,IAAI,cAA8B,CAAC;;;;AAKnC,SAAgB,YAAY,MAA0B;CACpD,YAAY,KAAK,IAAI;AACvB;;;;AAKA,SAAgB,iBAAiC;CAC/C,OAAO,CAAC,GAAG,WAAW;AACxB;;;;AAKA,SAAgB,cAAwC;CACtD,OAAO,YAAY,YAAY,SAAS;AAC1C;;;;AAKA,SAAgB,YAAY,OAA+B;CACzD,OAAO,YAAY,QAAQ,SAAS;EAElC,QADW,MAAM,QAAQ,KAAK,QAAQ,EAAE,IAAI,KAAK,QAAQ,KAAK,CAAC,KAAK,QAAQ,EAAE,
|
|
1
|
+
{"version":3,"file":"test-mailbox.mjs","names":[],"sources":["../../../../../../../core/src/mail/test-mailbox.ts"],"sourcesContent":["/**\n * Test Mailbox for Mail v2\n *\n * Provides utilities for capturing and asserting sent emails in test mode.\n *\n * ## Setup\n *\n * ```typescript\n * import { setMailMode, clearTestMailbox } from \"@warlock.js/core/mail/v2\";\n *\n * beforeEach(() => {\n * setMailMode(\"test\");\n * clearTestMailbox();\n * });\n * ```\n *\n * ## Usage\n *\n * ```typescript\n * import { sendMail, getTestMailbox, findMailsTo } from \"@warlock.js/core/mail/v2\";\n *\n * // Send email in test mode\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * html: \"<p>Hello</p>\",\n * });\n *\n * // Get all captured mails\n * const mails = getTestMailbox();\n * expect(mails).toHaveLength(1);\n * expect(mails[0].options.subject).toBe(\"Welcome!\");\n *\n * // Find specific mails\n * const userMails = findMailsTo(\"user@example.com\");\n * expect(userMails).toHaveLength(1);\n *\n * // Check if mail was sent\n * expect(wasMailSentTo(\"user@example.com\")).toBe(true);\n * expect(wasMailSentWithSubject(\"Welcome!\")).toBe(true);\n * ```\n *\n * ## Assertion Helpers\n *\n * ```typescript\n * // Assert a mail matching a predicate was sent\n * const mail = assertMailSent(m => m.options.to === \"user@example.com\");\n * expect(mail.options.subject).toBe(\"Welcome!\");\n *\n * // Assert exact count\n * assertMailCount(2); // throws if count doesn't match\n * ```\n *\n * ## Captured Mail Structure\n *\n * Each captured mail contains:\n * - `options` - Original MailOptions passed to sendMail\n * - `normalized` - Normalized mail data (arrays, addresses resolved)\n * - `timestamp` - When the mail was captured\n * - `result` - MailResult (in test mode, always success)\n * - `error` - MailError if sending failed (null in test mode)\n *\n * @module test-mailbox\n */\n\nimport type { CapturedMail } from \"./types\";\n\n/**\n * Test mailbox for capturing sent emails in test mode\n */\nlet testMailbox: CapturedMail[] = [];\n\n/**\n * Add a mail to the test mailbox\n */\nexport function captureMail(mail: CapturedMail): void {\n testMailbox.push(mail);\n}\n\n/**\n * Get all captured mails\n */\nexport function getTestMailbox(): CapturedMail[] {\n return [...testMailbox];\n}\n\n/**\n * Get the last captured mail\n */\nexport function getLastMail(): CapturedMail | undefined {\n return testMailbox[testMailbox.length - 1];\n}\n\n/**\n * Find mails by recipient\n */\nexport function findMailsTo(email: string): CapturedMail[] {\n return testMailbox.filter((mail) => {\n const to = Array.isArray(mail.options.to) ? mail.options.to : [mail.options.to];\n return to.includes(email);\n });\n}\n\n/**\n * Find mails by subject (partial match)\n */\nexport function findMailsBySubject(subject: string): CapturedMail[] {\n return testMailbox.filter((mail) => mail.options.subject.includes(subject));\n}\n\n/**\n * Check if a mail was sent to a specific recipient\n */\nexport function wasMailSentTo(email: string): boolean {\n return findMailsTo(email).length > 0;\n}\n\n/**\n * Check if a mail with specific subject was sent\n */\nexport function wasMailSentWithSubject(subject: string): boolean {\n return testMailbox.some((mail) => mail.options.subject === subject);\n}\n\n/**\n * Get mailbox size\n */\nexport function getMailboxSize(): number {\n return testMailbox.length;\n}\n\n/**\n * Clear the test mailbox\n */\nexport function clearTestMailbox(): void {\n testMailbox = [];\n}\n\n/**\n * Assert helper for testing\n */\nexport function assertMailSent(predicate: (mail: CapturedMail) => boolean): CapturedMail {\n const mail = testMailbox.find(predicate);\n\n if (!mail) {\n throw new Error(\"No mail matching the predicate was found in the test mailbox\");\n }\n\n return mail;\n}\n\n/**\n * Assert that a specific number of mails were sent\n */\nexport function assertMailCount(count: number): void {\n if (testMailbox.length !== count) {\n throw new Error(`Expected ${count} mails to be sent, but found ${testMailbox.length}`);\n }\n}\n"],"mappings":";;;;AAsEA,IAAI,cAA8B,CAAC;;;;AAKnC,SAAgB,YAAY,MAA0B;CACpD,YAAY,KAAK,IAAI;AACvB;;;;AAKA,SAAgB,iBAAiC;CAC/C,OAAO,CAAC,GAAG,WAAW;AACxB;;;;AAKA,SAAgB,cAAwC;CACtD,OAAO,YAAY,YAAY,SAAS;AAC1C;;;;AAKA,SAAgB,YAAY,OAA+B;CACzD,OAAO,YAAY,QAAQ,SAAS;EAElC,QADW,MAAM,QAAQ,KAAK,QAAQ,EAAE,IAAI,KAAK,QAAQ,KAAK,CAAC,KAAK,QAAQ,EAAE,EACrE,CAAC,SAAS,KAAK;CAC1B,CAAC;AACH;;;;AAKA,SAAgB,mBAAmB,SAAiC;CAClE,OAAO,YAAY,QAAQ,SAAS,KAAK,QAAQ,QAAQ,SAAS,OAAO,CAAC;AAC5E;;;;AAKA,SAAgB,cAAc,OAAwB;CACpD,OAAO,YAAY,KAAK,CAAC,CAAC,SAAS;AACrC;;;;AAKA,SAAgB,uBAAuB,SAA0B;CAC/D,OAAO,YAAY,MAAM,SAAS,KAAK,QAAQ,YAAY,OAAO;AACpE;;;;AAKA,SAAgB,iBAAyB;CACvC,OAAO,YAAY;AACrB;;;;AAKA,SAAgB,mBAAyB;CACvC,cAAc,CAAC;AACjB;;;;AAKA,SAAgB,eAAe,WAA0D;CACvF,MAAM,OAAO,YAAY,KAAK,SAAS;CAEvC,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,8DAA8D;CAGhF,OAAO;AACT;;;;AAKA,SAAgB,gBAAgB,OAAqB;CACnD,IAAI,YAAY,WAAW,OACzB,MAAM,IAAI,MAAM,YAAY,MAAM,+BAA+B,YAAY,QAAQ;AAEzF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assert-generated-imports.mjs","names":[],"sources":["../../../../../../../core/src/production/assert-generated-imports.ts"],"sourcesContent":["import { builtinModules } from \"node:module\";\n\n/**\n * A specifier the builder wrote into generated code that the consuming app does\n * not declare.\n */\nexport type UndeclaredImport = {\n /** File the import was written into, relative to the generation directory. */\n file: string;\n /** The specifier exactly as emitted. */\n specifier: string;\n /** The package the specifier resolves to — `@scope/name` for a deep import. */\n packageName: string;\n};\n\nexport type GeneratedFile = {\n file: string;\n content: string;\n};\n\n/**\n * Raised when generated code would ship an import the app cannot resolve.\n *\n * Carries every violation rather than the first, so a build reports the whole\n * problem in one pass instead of one specifier per re-run.\n */\nexport class UndeclaredGeneratedImportError extends Error {\n public constructor(public readonly violations: UndeclaredImport[]) {\n super(\n [\n `Generated code imports ${violations.length} package(s) the application does not declare:`,\n \"\",\n ...violations.map(\n ({ file, specifier, packageName }) =>\n ` ${file} → \"${specifier}\" (requires \"${packageName}\" in the app's dependencies)`,\n ),\n \"\",\n \"Generated code may only import packages the app itself declares. A framework-internal\",\n \"dependency must be reached through a re-export from @warlock.js/core — a bare specifier\",\n \"resolves by accident under npm/yarn hoisting and fails under pnpm's strict layout.\",\n ].join(\"\\n\"),\n );\n\n this.name = \"UndeclaredGeneratedImportError\";\n }\n}\n\n// The clause between `import` and `from` excludes `;` and both quote\n// characters so the lazy match cannot run past the end of its own statement.\n// Allowing it to would let a side-effect import (`import \"./bootstrap\";`) bind\n// to the `from` of the NEXT statement and disappear from the results.\nconst IMPORT_PATTERN =\n /(?:import|export)\\s+(?:[^\"';]*?\\sfrom\\s*)?[\"']([^\"']+)[\"']|import\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g;\n\n/**\n * Every module specifier a source file references — static, side-effect,\n * re-export and dynamic `import()` forms alike.\n *\n * Regex is sufficient and deliberate here: the input is code this builder wrote\n * itself, so it has no comments, no strings that look like imports, and no\n * syntax the pattern could misread. Parsing it with a full AST would buy\n * nothing and cost a dependency in the build path.\n */\nexport function extractSpecifiers(content: string): string[] {\n const specifiers: string[] = [];\n\n for (const match of content.matchAll(IMPORT_PATTERN)) {\n const specifier = match[1] ?? match[2];\n\n if (specifier) {\n specifiers.push(specifier);\n }\n }\n\n return specifiers;\n}\n\n/**\n * The package a specifier resolves to — `@scope/name` or `name`, ignoring any\n * deep path after it. Returns undefined for anything that is not a package:\n * relative paths, absolute paths, URLs, and Node builtins.\n */\nexport function resolvePackageName(specifier: string): string | undefined {\n if (\n specifier.startsWith(\".\") ||\n specifier.startsWith(\"/\") ||\n specifier.startsWith(\"node:\") ||\n specifier.includes(\"://\")\n ) {\n return undefined;\n }\n\n const segments = specifier.split(\"/\");\n const packageName = specifier.startsWith(\"@\") ? segments.slice(0, 2).join(\"/\") : segments[0];\n\n if (builtinModules.includes(packageName)) {\n return undefined;\n }\n\n return packageName;\n}\n\n/**\n * Find every import in generated code that the app does not declare.\n *\n * `dependencies` only, deliberately: the artifact this checks is a production\n * bundle, so a package the app lists as a dev dependency is not guaranteed to\n * be installed where it runs.\n */\nexport function findUndeclaredImports(\n files: GeneratedFile[],\n declaredDependencies: string[],\n): UndeclaredImport[] {\n const declared = new Set(declaredDependencies);\n const violations: UndeclaredImport[] = [];\n\n for (const { file, content } of files) {\n for (const specifier of extractSpecifiers(content)) {\n const packageName = resolvePackageName(specifier);\n\n if (!packageName || declared.has(packageName)) {\n continue;\n }\n\n violations.push({ file, specifier, packageName });\n }\n }\n\n return violations;\n}\n\n/**\n * Fail the build when generated code would import something the app cannot\n * resolve.\n *\n * This is the part that stops the defect class from returning. Rewriting the\n * one bad specifier fixes today's bundle; only the assertion stops the next\n * change to the generator from reintroducing it — under npm or yarn the mistake\n * is invisible, because hoisting resolves it by accident.\n *\n * @throws {UndeclaredGeneratedImportError} listing every violation found.\n */\nexport function assertGeneratedImportsAreDeclared(\n files: GeneratedFile[],\n declaredDependencies: string[],\n): void {\n const violations = findUndeclaredImports(files, declaredDependencies);\n\n if (violations.length > 0) {\n throw new UndeclaredGeneratedImportError(violations);\n }\n}\n"],"mappings":";;;;;;;;;AA0BA,IAAa,iCAAb,cAAoD,MAAM;CACxD,AAAO,YAAY,AAAgB,YAAgC;EACjE,MACE;GACE,0BAA0B,WAAW,OAAO;GAC5C;GACA,GAAG,WAAW,KACX,EAAE,MAAM,WAAW,kBAClB,KAAK,KAAK,MAAM,UAAU,eAAe,YAAY,6BACzD;GACA;GACA;GACA;GACA;EACF,
|
|
1
|
+
{"version":3,"file":"assert-generated-imports.mjs","names":[],"sources":["../../../../../../../core/src/production/assert-generated-imports.ts"],"sourcesContent":["import { builtinModules } from \"node:module\";\n\n/**\n * A specifier the builder wrote into generated code that the consuming app does\n * not declare.\n */\nexport type UndeclaredImport = {\n /** File the import was written into, relative to the generation directory. */\n file: string;\n /** The specifier exactly as emitted. */\n specifier: string;\n /** The package the specifier resolves to — `@scope/name` for a deep import. */\n packageName: string;\n};\n\nexport type GeneratedFile = {\n file: string;\n content: string;\n};\n\n/**\n * Raised when generated code would ship an import the app cannot resolve.\n *\n * Carries every violation rather than the first, so a build reports the whole\n * problem in one pass instead of one specifier per re-run.\n */\nexport class UndeclaredGeneratedImportError extends Error {\n public constructor(public readonly violations: UndeclaredImport[]) {\n super(\n [\n `Generated code imports ${violations.length} package(s) the application does not declare:`,\n \"\",\n ...violations.map(\n ({ file, specifier, packageName }) =>\n ` ${file} → \"${specifier}\" (requires \"${packageName}\" in the app's dependencies)`,\n ),\n \"\",\n \"Generated code may only import packages the app itself declares. A framework-internal\",\n \"dependency must be reached through a re-export from @warlock.js/core — a bare specifier\",\n \"resolves by accident under npm/yarn hoisting and fails under pnpm's strict layout.\",\n ].join(\"\\n\"),\n );\n\n this.name = \"UndeclaredGeneratedImportError\";\n }\n}\n\n// The clause between `import` and `from` excludes `;` and both quote\n// characters so the lazy match cannot run past the end of its own statement.\n// Allowing it to would let a side-effect import (`import \"./bootstrap\";`) bind\n// to the `from` of the NEXT statement and disappear from the results.\nconst IMPORT_PATTERN =\n /(?:import|export)\\s+(?:[^\"';]*?\\sfrom\\s*)?[\"']([^\"']+)[\"']|import\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g;\n\n/**\n * Every module specifier a source file references — static, side-effect,\n * re-export and dynamic `import()` forms alike.\n *\n * Regex is sufficient and deliberate here: the input is code this builder wrote\n * itself, so it has no comments, no strings that look like imports, and no\n * syntax the pattern could misread. Parsing it with a full AST would buy\n * nothing and cost a dependency in the build path.\n */\nexport function extractSpecifiers(content: string): string[] {\n const specifiers: string[] = [];\n\n for (const match of content.matchAll(IMPORT_PATTERN)) {\n const specifier = match[1] ?? match[2];\n\n if (specifier) {\n specifiers.push(specifier);\n }\n }\n\n return specifiers;\n}\n\n/**\n * The package a specifier resolves to — `@scope/name` or `name`, ignoring any\n * deep path after it. Returns undefined for anything that is not a package:\n * relative paths, absolute paths, URLs, and Node builtins.\n */\nexport function resolvePackageName(specifier: string): string | undefined {\n if (\n specifier.startsWith(\".\") ||\n specifier.startsWith(\"/\") ||\n specifier.startsWith(\"node:\") ||\n specifier.includes(\"://\")\n ) {\n return undefined;\n }\n\n const segments = specifier.split(\"/\");\n const packageName = specifier.startsWith(\"@\") ? segments.slice(0, 2).join(\"/\") : segments[0];\n\n if (builtinModules.includes(packageName)) {\n return undefined;\n }\n\n return packageName;\n}\n\n/**\n * Find every import in generated code that the app does not declare.\n *\n * `dependencies` only, deliberately: the artifact this checks is a production\n * bundle, so a package the app lists as a dev dependency is not guaranteed to\n * be installed where it runs.\n */\nexport function findUndeclaredImports(\n files: GeneratedFile[],\n declaredDependencies: string[],\n): UndeclaredImport[] {\n const declared = new Set(declaredDependencies);\n const violations: UndeclaredImport[] = [];\n\n for (const { file, content } of files) {\n for (const specifier of extractSpecifiers(content)) {\n const packageName = resolvePackageName(specifier);\n\n if (!packageName || declared.has(packageName)) {\n continue;\n }\n\n violations.push({ file, specifier, packageName });\n }\n }\n\n return violations;\n}\n\n/**\n * Fail the build when generated code would import something the app cannot\n * resolve.\n *\n * This is the part that stops the defect class from returning. Rewriting the\n * one bad specifier fixes today's bundle; only the assertion stops the next\n * change to the generator from reintroducing it — under npm or yarn the mistake\n * is invisible, because hoisting resolves it by accident.\n *\n * @throws {UndeclaredGeneratedImportError} listing every violation found.\n */\nexport function assertGeneratedImportsAreDeclared(\n files: GeneratedFile[],\n declaredDependencies: string[],\n): void {\n const violations = findUndeclaredImports(files, declaredDependencies);\n\n if (violations.length > 0) {\n throw new UndeclaredGeneratedImportError(violations);\n }\n}\n"],"mappings":";;;;;;;;;AA0BA,IAAa,iCAAb,cAAoD,MAAM;CACxD,AAAO,YAAY,AAAgB,YAAgC;EACjE,MACE;GACE,0BAA0B,WAAW,OAAO;GAC5C;GACA,GAAG,WAAW,KACX,EAAE,MAAM,WAAW,kBAClB,KAAK,KAAK,MAAM,UAAU,eAAe,YAAY,6BACzD;GACA;GACA;GACA;GACA;EACF,CAAC,CAAC,KAAK,IAAI,CACb;EAdiC;EAgBjC,KAAK,OAAO;CACd;AACF;AAMA,MAAM,iBACJ;;;;;;;;;;AAWF,SAAgB,kBAAkB,SAA2B;CAC3D,MAAM,aAAuB,CAAC;CAE9B,KAAK,MAAM,SAAS,QAAQ,SAAS,cAAc,GAAG;EACpD,MAAM,YAAY,MAAM,MAAM,MAAM;EAEpC,IAAI,WACF,WAAW,KAAK,SAAS;CAE7B;CAEA,OAAO;AACT;;;;;;AAOA,SAAgB,mBAAmB,WAAuC;CACxE,IACE,UAAU,WAAW,GAAG,KACxB,UAAU,WAAW,GAAG,KACxB,UAAU,WAAW,OAAO,KAC5B,UAAU,SAAS,KAAK,GAExB;CAGF,MAAM,WAAW,UAAU,MAAM,GAAG;CACpC,MAAM,cAAc,UAAU,WAAW,GAAG,IAAI,SAAS,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,SAAS;CAE1F,IAAI,eAAe,SAAS,WAAW,GACrC;CAGF,OAAO;AACT;;;;;;;;AASA,SAAgB,sBACd,OACA,sBACoB;CACpB,MAAM,WAAW,IAAI,IAAI,oBAAoB;CAC7C,MAAM,aAAiC,CAAC;CAExC,KAAK,MAAM,EAAE,MAAM,aAAa,OAC9B,KAAK,MAAM,aAAa,kBAAkB,OAAO,GAAG;EAClD,MAAM,cAAc,mBAAmB,SAAS;EAEhD,IAAI,CAAC,eAAe,SAAS,IAAI,WAAW,GAC1C;EAGF,WAAW,KAAK;GAAE;GAAM;GAAW;EAAY,CAAC;CAClD;CAGF,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,kCACd,OACA,sBACM;CACN,MAAM,aAAa,sBAAsB,OAAO,oBAAoB;CAEpE,IAAI,WAAW,SAAS,GACtB,MAAM,IAAI,+BAA+B,UAAU;AAEvD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-app-production.mjs","names":[],"sources":["../../../../../../../core/src/production/build-app-production.ts"],"sourcesContent":["import { ProductionBuilder } from \"./production-builder\";\n\n/**\n * Build the application for production\n * Options are loaded from warlock.config.ts\n */\nexport async function buildAppProduction() {\n const builder = new ProductionBuilder();\n await builder.build();\n}\n"],"mappings":";;;;;;;AAMA,eAAsB,qBAAqB;CAEzC,MAAM,IADc,kBACR,
|
|
1
|
+
{"version":3,"file":"build-app-production.mjs","names":[],"sources":["../../../../../../../core/src/production/build-app-production.ts"],"sourcesContent":["import { ProductionBuilder } from \"./production-builder\";\n\n/**\n * Build the application for production\n * Options are loaded from warlock.config.ts\n */\nexport async function buildAppProduction() {\n const builder = new ProductionBuilder();\n await builder.build();\n}\n"],"mappings":";;;;;;;AAMA,eAAsB,qBAAqB;CAEzC,MAAM,IADc,kBACR,CAAC,CAAC,MAAM;AACtB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dist-build-manifest.mjs","names":[],"sources":["../../../../../../../core/src/production/dist-build-manifest.ts"],"sourcesContent":["import { getJsonFileAsync, putJsonFileAsync } from \"@warlock.js/fs\";\nimport path from \"path\";\n\n/**\n * Name of the marker file `warlock build` writes into the output directory\n * as the last step before promoting it to `dist`, and the only thing\n * `warlock start` trusts to tell a genuine build from stale or\n * hand-assembled output.\n *\n * Hidden (leading dot) so it never collides with a route, a static asset, or\n * anything an app might legitimately name `manifest.json`.\n */\nexport const DIST_BUILD_MANIFEST_FILE_NAME = \".warlock-build.json\";\n\n/**\n * Recorded once, at the end of a build that reached the promote step. Its\n * presence — with `status: \"success\"` — is the whole contract `warlock\n * start` checks. Not any particular output file, which a future build shape\n * could rename or drop.\n */\nexport type DistBuildManifest = {\n status: \"success\";\n builtAt: string;\n};\n\n/**\n * Write the build-success marker into an output directory (the temp\n * directory a build assembled, before it is promoted to `dist`).\n */\nexport async function writeDistBuildManifestAsync(directory: string): Promise<void> {\n const manifest: DistBuildManifest = {\n status: \"success\",\n builtAt: new Date().toISOString(),\n };\n\n await putJsonFileAsync(path.join(directory, DIST_BUILD_MANIFEST_FILE_NAME), manifest);\n}\n\n/**\n * Read the build-success marker out of `dist`.\n *\n * Returns `undefined` for every way the marker can fail to back a real\n * build: missing, unreadable, malformed JSON, or present without\n * `status: \"success\"`. \"Never built\", \"build failed before promoting\", and\n * \"someone hand-edited dist\" all collapse to the same outcome, because\n * `warlock start` treats them identically — refuse, and say why.\n */\nexport async function readDistBuildManifestAsync(\n directory: string,\n): Promise<DistBuildManifest | undefined> {\n try {\n const manifest = await getJsonFileAsync<DistBuildManifest>(\n path.join(directory, DIST_BUILD_MANIFEST_FILE_NAME),\n );\n\n if (manifest?.status !== \"success\") {\n return undefined;\n }\n\n return manifest;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,gCAAgC;;;;;AAiB7C,eAAsB,4BAA4B,WAAkC;CAClF,MAAM,WAA8B;EAClC,QAAQ;EACR,0BAAS,IAAI,KAAK,
|
|
1
|
+
{"version":3,"file":"dist-build-manifest.mjs","names":[],"sources":["../../../../../../../core/src/production/dist-build-manifest.ts"],"sourcesContent":["import { getJsonFileAsync, putJsonFileAsync } from \"@warlock.js/fs\";\nimport path from \"path\";\n\n/**\n * Name of the marker file `warlock build` writes into the output directory\n * as the last step before promoting it to `dist`, and the only thing\n * `warlock start` trusts to tell a genuine build from stale or\n * hand-assembled output.\n *\n * Hidden (leading dot) so it never collides with a route, a static asset, or\n * anything an app might legitimately name `manifest.json`.\n */\nexport const DIST_BUILD_MANIFEST_FILE_NAME = \".warlock-build.json\";\n\n/**\n * Recorded once, at the end of a build that reached the promote step. Its\n * presence — with `status: \"success\"` — is the whole contract `warlock\n * start` checks. Not any particular output file, which a future build shape\n * could rename or drop.\n */\nexport type DistBuildManifest = {\n status: \"success\";\n builtAt: string;\n};\n\n/**\n * Write the build-success marker into an output directory (the temp\n * directory a build assembled, before it is promoted to `dist`).\n */\nexport async function writeDistBuildManifestAsync(directory: string): Promise<void> {\n const manifest: DistBuildManifest = {\n status: \"success\",\n builtAt: new Date().toISOString(),\n };\n\n await putJsonFileAsync(path.join(directory, DIST_BUILD_MANIFEST_FILE_NAME), manifest);\n}\n\n/**\n * Read the build-success marker out of `dist`.\n *\n * Returns `undefined` for every way the marker can fail to back a real\n * build: missing, unreadable, malformed JSON, or present without\n * `status: \"success\"`. \"Never built\", \"build failed before promoting\", and\n * \"someone hand-edited dist\" all collapse to the same outcome, because\n * `warlock start` treats them identically — refuse, and say why.\n */\nexport async function readDistBuildManifestAsync(\n directory: string,\n): Promise<DistBuildManifest | undefined> {\n try {\n const manifest = await getJsonFileAsync<DistBuildManifest>(\n path.join(directory, DIST_BUILD_MANIFEST_FILE_NAME),\n );\n\n if (manifest?.status !== \"success\") {\n return undefined;\n }\n\n return manifest;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,gCAAgC;;;;;AAiB7C,eAAsB,4BAA4B,WAAkC;CAClF,MAAM,WAA8B;EAClC,QAAQ;EACR,0BAAS,IAAI,KAAK,EAAC,CAAC,YAAY;CAClC;CAEA,MAAM,iBAAiB,KAAK,KAAK,WAAW,6BAA6B,GAAG,QAAQ;AACtF;;;;;;;;;;AAWA,eAAsB,2BACpB,WACwC;CACxC,IAAI;EACF,MAAM,WAAW,MAAM,iBACrB,KAAK,KAAK,WAAW,6BAA6B,CACpD;EAEA,IAAI,UAAU,WAAW,WACvB;EAGF,OAAO;CACT,QAAQ;EACN;CACF;AACF"}
|