@warlock.js/core 5.24.0 → 5.26.0
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 +64 -1
- package/bin/warlock.js +0 -0
- package/esm/application/application.d.mts +21 -0
- package/esm/application/application.d.mts.map +1 -1
- package/esm/application/application.mjs +29 -1
- package/esm/application/application.mjs.map +1 -1
- package/esm/application/boot-signal.d.mts +2 -1
- package/esm/application/boot-signal.d.mts.map +1 -1
- package/esm/application/boot-signal.mjs.map +1 -1
- package/esm/application/index.d.mts +1 -0
- package/esm/application/index.mjs +1 -0
- package/esm/application/roles.d.mts +72 -0
- package/esm/application/roles.d.mts.map +1 -0
- package/esm/application/roles.mjs +124 -0
- package/esm/application/roles.mjs.map +1 -0
- package/esm/cli/commands/add.command.mjs.map +1 -1
- package/esm/cli/commands/create-database.command.mjs.map +1 -1
- package/esm/cli/commands/dev-server.command.mjs.map +1 -1
- package/esm/cli/commands/doctor/boot-for-diagnostics.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/index.mjs +2 -0
- package/esm/cli/commands/doctor/checks/index.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/locales-ts-deprecated.check.mjs +170 -0
- package/esm/cli/commands/doctor/checks/locales-ts-deprecated.check.mjs.map +1 -0
- package/esm/cli/commands/doctor/doctor-command.action.mjs +7 -2
- package/esm/cli/commands/doctor/doctor-command.action.mjs.map +1 -1
- package/esm/cli/commands/doctor.command.mjs +5 -0
- package/esm/cli/commands/doctor.command.mjs.map +1 -1
- package/esm/cli/commands/drop-tables.command.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/module.generator.mjs +1 -12
- package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/utils/path-resolver.mjs.map +1 -1
- package/esm/cli/commands/migrate.command.mjs.map +1 -1
- package/esm/cli/commands/routes.command.mjs.map +1 -1
- package/esm/cli/commands/seed.command.mjs.map +1 -1
- package/esm/cli/commands/start-production.command.mjs +54 -5
- package/esm/cli/commands/start-production.command.mjs.map +1 -1
- package/esm/cli/commands/storage-put.action.mjs.map +1 -1
- package/esm/cli/commands/storage-put.command.mjs.map +1 -1
- package/esm/cli/commands/typings-generator.command.mjs +20 -1
- package/esm/cli/commands/typings-generator.command.mjs.map +1 -1
- package/esm/cli/commands/update.command.mjs.map +1 -1
- package/esm/cli/commands-loader.mjs.map +1 -1
- package/esm/config/config-loader.d.mts.map +1 -1
- package/esm/config/config-loader.mjs +3 -1
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/connectors/connectors-manager.mjs.map +1 -1
- package/esm/connectors/database-connector.mjs.map +1 -1
- package/esm/connectors/herald-connector.mjs.map +1 -1
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs +7 -0
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/connectors/logger-connector.mjs.map +1 -1
- package/esm/connectors/mail-connector.mjs.map +1 -1
- package/esm/connectors/types.d.mts +8 -0
- package/esm/connectors/types.d.mts.map +1 -1
- package/esm/connectors/types.mjs.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 +4 -3
- package/esm/database/migrate-action.mjs.map +1 -1
- package/esm/database/models/database-log/database-log.mjs.map +1 -1
- package/esm/database/seed-command-action.mjs +2 -1
- package/esm/database/seed-command-action.mjs.map +1 -1
- package/esm/dev-server/dependency-graph.mjs.map +1 -1
- package/esm/dev-server/development-server.mjs +2 -0
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/layer-executor.mjs.map +1 -1
- package/esm/dev-server/legacy-locales-warning.mjs +16 -0
- package/esm/dev-server/legacy-locales-warning.mjs.map +1 -0
- package/esm/dev-server/manifest-manager.mjs.map +1 -1
- package/esm/dev-server/module-loader.mjs +26 -5
- package/esm/dev-server/module-loader.mjs.map +1 -1
- package/esm/dev-server/register-installed-devtools.mjs +47 -0
- package/esm/dev-server/register-installed-devtools.mjs.map +1 -0
- package/esm/dev-server/run-connector-typings.mjs +28 -0
- package/esm/dev-server/run-connector-typings.mjs.map +1 -0
- package/esm/dev-server/special-file-patterns.mjs +5 -3
- package/esm/dev-server/special-file-patterns.mjs.map +1 -1
- package/esm/dev-server/special-files-collector.d.mts +2 -2
- package/esm/dev-server/special-files-collector.d.mts.map +1 -1
- package/esm/dev-server/special-files-collector.mjs +7 -4
- package/esm/dev-server/special-files-collector.mjs.map +1 -1
- package/esm/dev-server/translation-keys-sources.mjs +7 -3
- package/esm/dev-server/translation-keys-sources.mjs.map +1 -1
- package/esm/dev-server/type-generator.mjs +27 -4
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/encryption/password.mjs.map +1 -1
- package/esm/generations/add-command.action.mjs +3 -1
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/features/access.feature.mjs +38 -18
- package/esm/generations/features/access.feature.mjs.map +1 -1
- package/esm/generations/features/ai-anthropic.feature.mjs.map +1 -1
- package/esm/generations/features/ai-bedrock.feature.mjs.map +1 -1
- package/esm/generations/features/ai-google.feature.mjs.map +1 -1
- package/esm/generations/features/ai-ollama.feature.mjs.map +1 -1
- package/esm/generations/features/ai-openai.feature.mjs.map +1 -1
- package/esm/generations/features/ai-panoptic.feature.mjs.map +1 -1
- package/esm/generations/features/ai-tools.feature.mjs.map +1 -1
- package/esm/generations/features/ai-workspace.feature.mjs.map +1 -1
- package/esm/generations/features/ai.feature.mjs.map +1 -1
- package/esm/generations/features/bull-board.feature.mjs +2 -2
- package/esm/generations/features/bull-board.feature.mjs.map +1 -1
- package/esm/generations/features/devtools.feature.mjs +23 -0
- package/esm/generations/features/devtools.feature.mjs.map +1 -0
- package/esm/generations/features/herald.feature.mjs.map +1 -1
- package/esm/generations/features/image.feature.mjs.map +1 -1
- package/esm/generations/features/index.mjs +2 -0
- package/esm/generations/features/index.mjs.map +1 -1
- package/esm/generations/features/mail.feature.mjs.map +1 -1
- package/esm/generations/features/mongodb.feature.mjs.map +1 -1
- package/esm/generations/features/notifications.feature.mjs.map +1 -1
- package/esm/generations/features/postgres.feature.mjs.map +1 -1
- package/esm/generations/features/react-email.feature.mjs.map +1 -1
- package/esm/generations/features/react.feature.mjs.map +1 -1
- package/esm/generations/features/redis.feature.mjs.map +1 -1
- package/esm/generations/features/s3.feature.mjs.map +1 -1
- package/esm/generations/features/scheduler.feature.mjs.map +1 -1
- package/esm/generations/features/ses.feature.mjs.map +1 -1
- package/esm/generations/features/socket.feature.mjs.map +1 -1
- package/esm/generations/features/test.feature.mjs +6 -2
- package/esm/generations/features/test.feature.mjs.map +1 -1
- package/esm/generations/features/types.mjs.map +1 -1
- package/esm/generations/features/web.feature.mjs.map +1 -1
- package/esm/http/build-rate-limit-options.d.mts +8 -2
- package/esm/http/build-rate-limit-options.d.mts.map +1 -1
- package/esm/http/build-rate-limit-options.mjs +1 -0
- package/esm/http/build-rate-limit-options.mjs.map +1 -1
- package/esm/http/database/RequestLog.mjs.map +1 -1
- package/esm/http/errors/errors.d.mts +1 -17
- package/esm/http/errors/errors.d.mts.map +1 -1
- package/esm/http/errors/errors.mjs +1 -20
- package/esm/http/errors/errors.mjs.map +1 -1
- package/esm/http/index.d.mts +4 -3
- package/esm/http/index.mjs +3 -2
- package/esm/http/middleware/inject-request-context.d.mts +1 -1
- package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs +9 -1
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/middleware/rate-limit.middleware.d.mts.map +1 -1
- package/esm/http/middleware/rate-limit.middleware.mjs +5 -1
- package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
- package/esm/http/request.d.mts +7 -24
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +1 -22
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.d.mts +5 -5
- package/esm/http/response.d.mts.map +1 -1
- package/esm/http/response.mjs +4 -2
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/server-rebuilt.d.mts +20 -0
- package/esm/http/server-rebuilt.d.mts.map +1 -0
- package/esm/http/server-rebuilt.mjs +21 -0
- package/esm/http/server-rebuilt.mjs.map +1 -0
- package/esm/http/tracing/index.mjs +1 -1
- package/esm/http/tracing/tracing-dispatcher.d.mts +13 -6
- package/esm/http/tracing/tracing-dispatcher.d.mts.map +1 -1
- package/esm/http/tracing/tracing-dispatcher.mjs +46 -14
- package/esm/http/tracing/tracing-dispatcher.mjs.map +1 -1
- package/esm/http/tracing/tracing.type.d.mts +2 -1
- package/esm/http/tracing/tracing.type.d.mts.map +1 -1
- package/esm/http/types.d.mts +9 -0
- package/esm/http/types.d.mts.map +1 -1
- package/esm/image/image.mjs.map +1 -1
- package/esm/index.d.mts +8 -4
- package/esm/index.mjs +8 -3
- package/esm/loader/app-module-importer.d.mts +17 -0
- package/esm/loader/app-module-importer.d.mts.map +1 -0
- package/esm/loader/app-module-importer.mjs +20 -0
- package/esm/loader/app-module-importer.mjs.map +1 -0
- package/esm/localization/index.mjs +4 -0
- package/esm/localization/parse-locale-dictionary.d.mts +23 -0
- package/esm/localization/parse-locale-dictionary.d.mts.map +1 -0
- package/esm/localization/parse-locale-dictionary.mjs +215 -0
- package/esm/localization/parse-locale-dictionary.mjs.map +1 -0
- package/esm/localization/register-locale-dictionary.d.mts +12 -0
- package/esm/localization/register-locale-dictionary.d.mts.map +1 -0
- package/esm/localization/register-locale-dictionary.mjs +58 -0
- package/esm/localization/register-locale-dictionary.mjs.map +1 -0
- package/esm/logger/logger.mjs.map +1 -1
- package/esm/mail/events.d.mts +7 -0
- package/esm/mail/events.d.mts.map +1 -1
- package/esm/mail/events.mjs +7 -0
- package/esm/mail/events.mjs.map +1 -1
- package/esm/mail/send-mail.d.mts.map +1 -1
- package/esm/mail/send-mail.mjs +23 -2
- package/esm/mail/send-mail.mjs.map +1 -1
- package/esm/mail/types.d.mts +5 -1
- package/esm/mail/types.d.mts.map +1 -1
- package/esm/mail/types.mjs.map +1 -1
- package/esm/manifest/manifest-manager.mjs.map +1 -1
- package/esm/production/build-contributions.mjs +19 -3
- package/esm/production/build-contributions.mjs.map +1 -1
- package/esm/production/production-builder.mjs +39 -10
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/production-supervisor.mjs +6 -0
- package/esm/production/production-supervisor.mjs.map +1 -1
- package/esm/production/resolve-build-config.d.mts +1 -1
- package/esm/production/resolve-build-config.mjs +15 -0
- package/esm/production/resolve-build-config.mjs.map +1 -1
- package/esm/production/route-registration-child.mjs +14 -2
- package/esm/production/route-registration-child.mjs.map +1 -1
- package/esm/production/route-registration-snapshot.mjs +9 -2
- package/esm/production/route-registration-snapshot.mjs.map +1 -1
- package/esm/resource/resource-field-builder.mjs +1 -1
- package/esm/resource/resource-field-builder.mjs.map +1 -1
- package/esm/resource/resource.d.mts +5 -0
- package/esm/resource/resource.d.mts.map +1 -1
- package/esm/resource/resource.mjs +17 -6
- package/esm/resource/resource.mjs.map +1 -1
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +1 -0
- package/esm/router/router.mjs.map +1 -1
- package/esm/router/types.d.mts +10 -1
- package/esm/router/types.d.mts.map +1 -1
- package/esm/tests/index.d.mts +3 -2
- package/esm/tests/index.mjs +3 -2
- package/esm/tests/start-http-development-server.d.mts +10 -0
- package/esm/tests/start-http-development-server.d.mts.map +1 -1
- package/esm/tests/start-http-development-server.mjs +16 -2
- package/esm/tests/start-http-development-server.mjs.map +1 -1
- package/esm/tests/vitest-setup.d.mts +16 -1
- package/esm/tests/vitest-setup.d.mts.map +1 -1
- package/esm/tests/vitest-setup.mjs +20 -2
- package/esm/tests/vitest-setup.mjs.map +1 -1
- package/esm/use-cases/use-case-events.mjs.map +1 -1
- package/esm/utils/is-test-file.mjs +15 -0
- package/esm/utils/is-test-file.mjs.map +1 -0
- package/esm/utils/normalized-path.d.mts +3 -1
- package/esm/utils/normalized-path.d.mts.map +1 -1
- package/esm/utils/normalized-path.mjs +4 -2
- package/esm/utils/normalized-path.mjs.map +1 -1
- package/esm/utils/paths.mjs.map +1 -1
- package/esm/validation/plugins/database-plugin.mjs.map +1 -1
- package/esm/validation/validateAll.mjs +57 -4
- package/esm/validation/validateAll.mjs.map +1 -1
- package/esm/warlock-config/default-configurations.mjs +1 -0
- package/esm/warlock-config/default-configurations.mjs.map +1 -1
- package/esm/warlock-config/types.d.mts +7 -0
- package/esm/warlock-config/types.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
- package/llms-full.txt +382 -214
- package/llms.txt +1 -1
- package/package.json +23 -19
- package/skills/README.md +1 -1
- package/skills/configure-app/SKILL.md +2 -0
- package/skills/create-controller/SKILL.md +4 -0
- package/skills/define-resource/SKILL.md +4 -0
- package/skills/request-tracing/SKILL.md +38 -15
- package/skills/run-app/SKILL.md +71 -34
- package/skills/send-mail/SKILL.md +55 -25
- package/skills/test-http/SKILL.md +28 -9
- package/skills/test-service/SKILL.md +61 -40
- package/skills/use-localization/SKILL.md +39 -26
- package/skills/warlock-conventions/SKILL.md +26 -18
- package/skills/write-cli-command/SKILL.md +50 -45
package/esm/mail/types.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../core/src/mail/types.ts"],"sourcesContent":["import type SMTPTransport from \"nodemailer/lib/smtp-transport\";\nimport type React from \"react\";\n\n/**\n * AWS SES mail configuration\n */\nexport type SESConfigurations = {\n driver: \"ses\";\n accessKeyId: string;\n secretAccessKey: string;\n region: string;\n from?: MailAddress;\n};\n\n/**\n * Any mail configuration (SMTP or SES)\n */\nexport type MailConfigurations = SMTPConfigurations | SESConfigurations;\n\n/**\n * Mail mode determines how emails are handled\n */\nexport type MailMode = \"production\" | \"development\" | \"test\";\n\n/**\n * Mail priority levels\n */\nexport type MailPriority = \"high\" | \"normal\" | \"low\";\n\n/**\n * Email address with optional name\n */\nexport type MailAddress =\n | string\n | {\n name: string;\n address: string;\n };\n\n/**\n * Mail attachment\n * Supports both buffer/string content and file paths\n */\nexport type MailAttachment = {\n filename: string;\n contentType?: string;\n encoding?: \"base64\" | \"binary\" | \"hex\";\n cid?: string; // Content-ID for inline attachments\n} & (\n | {\n content: Buffer | string;\n path?: never;\n }\n | {\n content?: never;\n path: string; // File path - will be read automatically\n }\n);\n\n/**\n * Mail configuration for SMTP transport\n *\n * ## Basic Configuration\n *\n * ```typescript\n * setMailConfigurations({\n * host: \"smtp.gmail.com\",\n * port: 587,\n * secure: false, // true for 465, false for other ports\n * tls: true, // Use STARTTLS\n * username: \"user@gmail.com\",\n * password: \"app-password\",\n * from: { name: \"My App\", address: \"noreply@myapp.com\" },\n * });\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `host` | `string` | - | SMTP server hostname (e.g., \"smtp.gmail.com\") |\n * | `port` | `number` | 587 | SMTP port. Common: 25, 465 (SSL), 587 (TLS) |\n * | `secure` | `boolean` | false | Use SSL/TLS. Set `true` for port 465 |\n * | `tls` | `boolean` | true | Enable STARTTLS upgrade. For port 587 |\n * | `requireTLS` | `boolean` | - | Fail if STARTTLS upgrade fails |\n * | `username` | `string` | - | SMTP auth username (convenience alias) |\n * | `password` | `string` | - | SMTP auth password (convenience alias) |\n * | `auth` | `object` | - | Full auth object: `{ user, pass, type }` |\n * | `from` | `MailAddress` | - | Default sender for all emails |\n *\n * ## Provider Examples\n *\n * ### Gmail\n * ```typescript\n * { host: \"smtp.gmail.com\", port: 587, tls: true, username: \"...\", password: \"...\" }\n * ```\n *\n * ### SendGrid\n * ```typescript\n * { host: \"smtp.sendgrid.net\", port: 587, username: \"apikey\", password: \"SG.xxx\" }\n * ```\n *\n * ### AWS SES\n * ```typescript\n * { host: \"email-smtp.us-east-1.amazonaws.com\", port: 587, username: \"...\", password: \"...\" }\n * ```\n *\n * ### Mailgun\n * ```typescript\n * { host: \"smtp.mailgun.org\", port: 587, username: \"postmaster@...\", password: \"...\" }\n * ```\n *\n * ## Multi-tenant Usage\n *\n * For multi-tenant apps, pass config per-mail instead of globally:\n * ```typescript\n * await sendMail({\n * config: tenant.mailSettings, // Tenant-specific config\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n * ```\n */\nexport type SMTPConfigurations = SMTPTransport.Options & {\n /**\n * Transport driver type\n */\n driver?: \"smtp\";\n /**\n * Enable STARTTLS upgrade (alias for requireTLS)\n * Set to `true` for port 587\n */\n tls?: boolean;\n /**\n * SMTP authentication username\n * Convenience alias - can also use `auth.user`\n */\n username?: string;\n /**\n * SMTP authentication password\n * Convenience alias - can also use `auth.pass`\n */\n password?: string;\n /**\n * Default sender for all emails\n * Can be string (\"noreply@app.com\") or object ({ name, address })\n */\n from?: MailAddress;\n};\n\n/**\n * Named mailers configuration\n */\nexport type MailersConfig = {\n /**\n * Default mailer configuration\n */\n default?: MailConfigurations;\n /**\n * Named mailer configurations\n */\n mailers?: Record<string, MailConfigurations>;\n};\n\n/**\n * Mail result after sending\n */\nexport type MailResult = {\n success: boolean;\n messageId?: string;\n accepted: string[];\n rejected: string[];\n response?: string;\n envelope?: {\n from: string;\n to: string[];\n };\n};\n\n/**\n * Error codes for mail operations\n */\nexport type MailErrorCode =\n | \"CONNECTION_ERROR\"\n | \"AUTH_ERROR\"\n | \"RATE_LIMIT\"\n | \"INVALID_ADDRESS\"\n | \"REJECTED\"\n | \"TIMEOUT\"\n | \"RENDER_ERROR\"\n | \"CONFIG_ERROR\"\n | \"UNKNOWN\";\n\n/**\n * Mail event callbacks (per-mail)\n * For global events, use mailEvents.on() from events.ts\n */\nexport type MailEvents = {\n /**\n * Called before sending the email\n * Can be used to modify the mail or cancel sending\n */\n beforeSending?: (mail: MailOptions) => void | Promise<void> | false | Promise<false>;\n /**\n * Called after send attempt (success or failure)\n */\n onSent?: (\n mail: MailOptions,\n result: MailResult | null,\n error: MailError | null,\n ) => void | Promise<void>;\n /**\n * Called only on successful send\n */\n onSuccess?: (mail: MailOptions, result: MailResult) => void | Promise<void>;\n /**\n * Called only on error\n */\n onError?: (mail: MailOptions, error: MailError) => void | Promise<void>;\n};\n\n/**\n * Mail options for sending\n */\nexport type MailOptions = {\n /**\n * Unique mail ID for event namespacing\n * If not provided, one will be auto-generated\n *\n * Use this to subscribe to events for a specific mail:\n * ```typescript\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => { ... });\n * await sendMail({ id: mailId, to: \"...\", subject: \"...\", html: \"...\" });\n * ```\n */\n id?: string;\n\n // Recipients\n to: string | string[];\n cc?: string | string[];\n bcc?: string | string[];\n replyTo?: string;\n\n // Content\n subject: string;\n html?: string;\n text?: string;\n component?: React.ReactElement;\n\n // Configuration\n config?: MailConfigurations;\n mailer?: string;\n from?: MailAddress;\n\n // Attachments\n attachments?: MailAttachment[];\n\n // Options\n priority?: MailPriority;\n headers?: Record<string, string>;\n tags?: string[];\n\n // Meta\n correlationId?: string;\n} & MailEvents;\n\n/**\n * Internal normalized mail data\n */\nexport type NormalizedMail = {\n to: string[];\n cc: string[];\n bcc: string[];\n replyTo?: string;\n from: MailAddress;\n subject: string;\n html?: string;\n text?: string;\n attachments: MailAttachment[];\n priority: MailPriority;\n headers: Record<string, string>;\n tags: string[];\n correlationId?: string;\n config: MailConfigurations;\n};\n\n/**\n * Captured mail for test
|
|
1
|
+
{"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../core/src/mail/types.ts"],"sourcesContent":["import type SMTPTransport from \"nodemailer/lib/smtp-transport\";\nimport type React from \"react\";\n\n/**\n * AWS SES mail configuration\n */\nexport type SESConfigurations = {\n driver: \"ses\";\n accessKeyId: string;\n secretAccessKey: string;\n region: string;\n from?: MailAddress;\n};\n\n/**\n * Any mail configuration (SMTP or SES)\n */\nexport type MailConfigurations = SMTPConfigurations | SESConfigurations;\n\n/**\n * Mail mode determines how emails are handled\n */\nexport type MailMode = \"production\" | \"development\" | \"test\";\n\n/**\n * Mail priority levels\n */\nexport type MailPriority = \"high\" | \"normal\" | \"low\";\n\n/**\n * Email address with optional name\n */\nexport type MailAddress =\n | string\n | {\n name: string;\n address: string;\n };\n\n/**\n * Mail attachment\n * Supports both buffer/string content and file paths\n */\nexport type MailAttachment = {\n filename: string;\n contentType?: string;\n encoding?: \"base64\" | \"binary\" | \"hex\";\n cid?: string; // Content-ID for inline attachments\n} & (\n | {\n content: Buffer | string;\n path?: never;\n }\n | {\n content?: never;\n path: string; // File path - will be read automatically\n }\n);\n\n/**\n * Mail configuration for SMTP transport\n *\n * ## Basic Configuration\n *\n * ```typescript\n * setMailConfigurations({\n * host: \"smtp.gmail.com\",\n * port: 587,\n * secure: false, // true for 465, false for other ports\n * tls: true, // Use STARTTLS\n * username: \"user@gmail.com\",\n * password: \"app-password\",\n * from: { name: \"My App\", address: \"noreply@myapp.com\" },\n * });\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `host` | `string` | - | SMTP server hostname (e.g., \"smtp.gmail.com\") |\n * | `port` | `number` | 587 | SMTP port. Common: 25, 465 (SSL), 587 (TLS) |\n * | `secure` | `boolean` | false | Use SSL/TLS. Set `true` for port 465 |\n * | `tls` | `boolean` | true | Enable STARTTLS upgrade. For port 587 |\n * | `requireTLS` | `boolean` | - | Fail if STARTTLS upgrade fails |\n * | `username` | `string` | - | SMTP auth username (convenience alias) |\n * | `password` | `string` | - | SMTP auth password (convenience alias) |\n * | `auth` | `object` | - | Full auth object: `{ user, pass, type }` |\n * | `from` | `MailAddress` | - | Default sender for all emails |\n *\n * ## Provider Examples\n *\n * ### Gmail\n * ```typescript\n * { host: \"smtp.gmail.com\", port: 587, tls: true, username: \"...\", password: \"...\" }\n * ```\n *\n * ### SendGrid\n * ```typescript\n * { host: \"smtp.sendgrid.net\", port: 587, username: \"apikey\", password: \"SG.xxx\" }\n * ```\n *\n * ### AWS SES\n * ```typescript\n * { host: \"email-smtp.us-east-1.amazonaws.com\", port: 587, username: \"...\", password: \"...\" }\n * ```\n *\n * ### Mailgun\n * ```typescript\n * { host: \"smtp.mailgun.org\", port: 587, username: \"postmaster@...\", password: \"...\" }\n * ```\n *\n * ## Multi-tenant Usage\n *\n * For multi-tenant apps, pass config per-mail instead of globally:\n * ```typescript\n * await sendMail({\n * config: tenant.mailSettings, // Tenant-specific config\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n * ```\n */\nexport type SMTPConfigurations = SMTPTransport.Options & {\n /**\n * Transport driver type\n */\n driver?: \"smtp\";\n /**\n * Enable STARTTLS upgrade (alias for requireTLS)\n * Set to `true` for port 587\n */\n tls?: boolean;\n /**\n * SMTP authentication username\n * Convenience alias - can also use `auth.user`\n */\n username?: string;\n /**\n * SMTP authentication password\n * Convenience alias - can also use `auth.pass`\n */\n password?: string;\n /**\n * Default sender for all emails\n * Can be string (\"noreply@app.com\") or object ({ name, address })\n */\n from?: MailAddress;\n};\n\n/**\n * Named mailers configuration\n */\nexport type MailersConfig = {\n /**\n * Default mailer configuration\n */\n default?: MailConfigurations;\n /**\n * Named mailer configurations\n */\n mailers?: Record<string, MailConfigurations>;\n};\n\n/**\n * Mail result after sending\n */\nexport type MailResult = {\n success: boolean;\n messageId?: string;\n accepted: string[];\n rejected: string[];\n response?: string;\n envelope?: {\n from: string;\n to: string[];\n };\n};\n\n/**\n * Error codes for mail operations\n */\nexport type MailErrorCode =\n | \"CONNECTION_ERROR\"\n | \"AUTH_ERROR\"\n | \"RATE_LIMIT\"\n | \"INVALID_ADDRESS\"\n | \"REJECTED\"\n | \"TIMEOUT\"\n | \"RENDER_ERROR\"\n | \"CONFIG_ERROR\"\n | \"UNKNOWN\";\n\n/**\n * Mail event callbacks (per-mail)\n * For global events, use mailEvents.on() from events.ts\n */\nexport type MailEvents = {\n /**\n * Called before sending the email\n * Can be used to modify the mail or cancel sending\n */\n beforeSending?: (mail: MailOptions) => void | Promise<void> | false | Promise<false>;\n /**\n * Called after send attempt (success or failure)\n */\n onSent?: (\n mail: MailOptions,\n result: MailResult | null,\n error: MailError | null,\n ) => void | Promise<void>;\n /**\n * Called only on successful send\n */\n onSuccess?: (mail: MailOptions, result: MailResult) => void | Promise<void>;\n /**\n * Called only on error\n */\n onError?: (mail: MailOptions, error: MailError) => void | Promise<void>;\n};\n\n/**\n * Mail options for sending\n */\nexport type MailOptions = {\n /**\n * Unique mail ID for event namespacing\n * If not provided, one will be auto-generated\n *\n * Use this to subscribe to events for a specific mail:\n * ```typescript\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => { ... });\n * await sendMail({ id: mailId, to: \"...\", subject: \"...\", html: \"...\" });\n * ```\n */\n id?: string;\n\n // Recipients\n to: string | string[];\n cc?: string | string[];\n bcc?: string | string[];\n replyTo?: string;\n\n // Content\n subject: string;\n html?: string;\n text?: string;\n component?: React.ReactElement;\n\n // Configuration\n config?: MailConfigurations;\n mailer?: string;\n from?: MailAddress;\n\n // Attachments\n attachments?: MailAttachment[];\n\n // Options\n priority?: MailPriority;\n headers?: Record<string, string>;\n tags?: string[];\n\n // Meta\n correlationId?: string;\n} & MailEvents;\n\n/**\n * Internal normalized mail data\n */\nexport type NormalizedMail = {\n to: string[];\n cc: string[];\n bcc: string[];\n replyTo?: string;\n from: MailAddress;\n subject: string;\n html?: string;\n text?: string;\n attachments: MailAttachment[];\n priority: MailPriority;\n headers: Record<string, string>;\n tags: string[];\n correlationId?: string;\n config: MailConfigurations;\n};\n\n/**\n * Captured mail for development and test modes.\n *\n * Attachments retain their normalized contents so test assertions can inspect\n * the exact mail that would be sent.\n */\nexport type CapturedMail = {\n /** The mail ID used for event namespacing and result correlation. */\n id: string;\n options: MailOptions;\n normalized: NormalizedMail;\n timestamp: Date;\n result?: MailResult;\n error?: MailError;\n};\n\n/**\n * Mail error class\n */\nexport class MailError extends Error {\n public readonly code: MailErrorCode;\n public readonly originalError?: Error;\n\n public constructor(message: string, code: MailErrorCode, originalError?: Error) {\n super(message);\n this.name = \"MailError\";\n this.code = code;\n this.originalError = originalError;\n }\n}\n"],"mappings":";;;;AAmTA,IAAa,YAAb,cAA+B,MAAM;CAInC,AAAO,YAAY,SAAiB,MAAqB,eAAuB;EAC9E,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,gBAAgB;CACvB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest-manager.mjs","names":[],"sources":["../../../../../../../core/src/manifest/manifest-manager.ts"],"sourcesContent":["import { getJsonFileAsync, putJsonFileAsync, unlinkAsync } from \"@warlock.js/fs\";\
|
|
1
|
+
{"version":3,"file":"manifest-manager.mjs","names":[],"sources":["../../../../../../../core/src/manifest/manifest-manager.ts"],"sourcesContent":["import { getJsonFileAsync, putJsonFileAsync, unlinkAsync } from \"@warlock.js/fs\";\nimport { warlockPath } from \"../utils\";\n\n/**\n * Stored option metadata in manifest\n */\nexport type ManifestCommandOption = {\n name: string;\n text: string;\n alias?: string;\n description?: string;\n type?: \"string\" | \"boolean\" | \"number\";\n required?: boolean;\n defaultValue?: string | boolean | number;\n};\n\n/**\n * Command metadata stored in commands.json\n */\nexport type ManifestCommandData = {\n relativePath?: string;\n source: \"framework\" | \"plugin\" | \"project\";\n description?: string;\n alias?: string;\n options?: ManifestCommandOption[];\n};\n\ntype ManifestCommandsJson = {\n commands: Record<string, ManifestCommandData>;\n};\n\nexport class ManifestManager {\n /**\n * commands json\n */\n protected _commandsJson?: ManifestCommandsJson;\n\n /**\n * Check if commands json is changed\n */\n protected _hasChanges = false;\n\n /**\n * Whether commands json is loaded\n */\n protected _isLoaded = false;\n\n /**\n * Get if commands json has changes\n */\n public get hasChanges() {\n return this._hasChanges;\n }\n\n /**\n * Check if commands json is loaded\n */\n public get isCommandLoaded() {\n return this._isLoaded;\n }\n\n /**\n * Load commands.json file\n */\n public async loadCommands(): Promise<ManifestCommandsJson | undefined> {\n // now try to locate it in .warlock folder\n if (this._isLoaded) return this._commandsJson;\n\n try {\n this._commandsJson = await getJsonFileAsync(warlockPath(\"commands.json\"));\n\n this._isLoaded = true;\n\n return this._commandsJson;\n } catch {\n return;\n }\n }\n\n /**\n * Get commands json content\n */\n public get commandsJson() {\n return this._commandsJson;\n }\n\n /**\n * Save commands in commands.json file\n */\n public async saveCommands() {\n await putJsonFileAsync(warlockPath(\"commands.json\"), this._commandsJson);\n\n this._isLoaded = true;\n this._hasChanges = false;\n }\n\n /**\n * Add command info to commands list (But do not save commands)\n */\n public addCommandToList(name: string, command: ManifestCommandsJson[\"commands\"][string]) {\n if (!this._commandsJson) {\n this._commandsJson = {\n commands: {},\n };\n }\n\n this._commandsJson.commands[name] = command;\n\n this._hasChanges = true;\n }\n\n /**\n * Clear commands cache\n */\n public clearCommandsCache() {\n this._commandsJson = undefined;\n this._hasChanges = false;\n this._isLoaded = false;\n }\n\n /**\n * Remove commands.json file\n */\n public async removeCommandsFile() {\n try {\n await unlinkAsync(warlockPath(\"commands.json\"));\n } catch {\n // do nothing\n }\n }\n}\n\nexport const manifestManager = new ManifestManager();\n"],"mappings":";;;;;AA+BA,IAAa,kBAAb,MAA6B;;qBASH;mBAKF;;;;;CAKtB,IAAW,aAAa;EACtB,OAAO,KAAK;CACd;;;;CAKA,IAAW,kBAAkB;EAC3B,OAAO,KAAK;CACd;;;;CAKA,MAAa,eAA0D;EAErE,IAAI,KAAK,WAAW,OAAO,KAAK;EAEhC,IAAI;GACF,KAAK,gBAAgB,MAAM,iBAAiB,YAAY,eAAe,CAAC;GAExE,KAAK,YAAY;GAEjB,OAAO,KAAK;EACd,QAAQ;GACN;EACF;CACF;;;;CAKA,IAAW,eAAe;EACxB,OAAO,KAAK;CACd;;;;CAKA,MAAa,eAAe;EAC1B,MAAM,iBAAiB,YAAY,eAAe,GAAG,KAAK,aAAa;EAEvE,KAAK,YAAY;EACjB,KAAK,cAAc;CACrB;;;;CAKA,AAAO,iBAAiB,MAAc,SAAmD;EACvF,IAAI,CAAC,KAAK,eACR,KAAK,gBAAgB,EACnB,UAAU,CAAC,EACb;EAGF,KAAK,cAAc,SAAS,QAAQ;EAEpC,KAAK,cAAc;CACrB;;;;CAKA,AAAO,qBAAqB;EAC1B,KAAK,gBAAgB;EACrB,KAAK,cAAc;EACnB,KAAK,YAAY;CACnB;;;;CAKA,MAAa,qBAAqB;EAChC,IAAI;GACF,MAAM,YAAY,YAAY,eAAe,CAAC;EAChD,QAAQ,CAER;CACF;AACF;AAEA,MAAa,kBAAkB,IAAI,gBAAgB"}
|
|
@@ -10,7 +10,11 @@ const ErrorWithCause = Error;
|
|
|
10
10
|
* posture as the `tsconfig` guard in `resolve-build-config`: dropping the key
|
|
11
11
|
* quietly would leave the author believing their plugin ran.
|
|
12
12
|
*/
|
|
13
|
-
const ALLOWED_CONTRIBUTION_KEYS = [
|
|
13
|
+
const ALLOWED_CONTRIBUTION_KEYS = [
|
|
14
|
+
"generate",
|
|
15
|
+
"emit",
|
|
16
|
+
"typings"
|
|
17
|
+
];
|
|
14
18
|
/**
|
|
15
19
|
* Reject a contribution object carrying anything but the two hooks.
|
|
16
20
|
*
|
|
@@ -21,7 +25,7 @@ function assertClosedContribution(connector) {
|
|
|
21
25
|
if (!contribution) return;
|
|
22
26
|
for (const key of Object.keys(contribution)) {
|
|
23
27
|
if (ALLOWED_CONTRIBUTION_KEYS.includes(key)) continue;
|
|
24
|
-
throw new Error(`Connector "${connector.name}" declares an unsupported build contribution key "${key}". A build contribution carries exactly
|
|
28
|
+
throw new Error(`Connector "${connector.name}" declares an unsupported build contribution key "${key}". A build contribution carries exactly these optional hooks — ${ALLOWED_CONTRIBUTION_KEYS.join(", ")} — and no data. Anything a hook needs (plugins, pipelines, aliases) must be constructed inside that hook, so it never lands in the connector's static import graph.`);
|
|
25
29
|
}
|
|
26
30
|
}
|
|
27
31
|
/**
|
|
@@ -66,6 +70,18 @@ async function runEmitContributions(connectors, context) {
|
|
|
66
70
|
}
|
|
67
71
|
}
|
|
68
72
|
/**
|
|
73
|
+
* Drain every connector's `typings` hook, in array order, sequentially.
|
|
74
|
+
* Connectors without one — every API-only app — are skipped without error.
|
|
75
|
+
*/
|
|
76
|
+
async function runTypingsContributions(connectors, context) {
|
|
77
|
+
for (const connector of connectors) {
|
|
78
|
+
assertClosedContribution(connector);
|
|
79
|
+
const typings = connector.build?.typings;
|
|
80
|
+
if (!typings) continue;
|
|
81
|
+
await runHook(connector, "typings", () => typings(context));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
69
85
|
* Merge two contributor patches. Later wins, except:
|
|
70
86
|
*
|
|
71
87
|
* - `define` merges per key — two contributors defining different
|
|
@@ -114,5 +130,5 @@ async function runHook(connector, hook, run) {
|
|
|
114
130
|
}
|
|
115
131
|
|
|
116
132
|
//#endregion
|
|
117
|
-
export { dedupe, runEmitContributions, runGenerateContributions };
|
|
133
|
+
export { dedupe, runEmitContributions, runGenerateContributions, runTypingsContributions };
|
|
118
134
|
//# sourceMappingURL=build-contributions.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-contributions.mjs","names":[],"sources":["../../../../../../../core/src/production/build-contributions.ts"],"sourcesContent":["import type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\n\n/**\n * `Error` with the `cause` option typed. Same shim as\n * `application.ts` — lib.es2022 declares `cause` on `ErrorOptions`, but the\n * package still compiles against an older lib in some consumers.\n */\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\n\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\n\n/**\n * The only keys a `build` contribution may carry.\n *\n * The runtime half of the closed-contribution constraint: the\n * type already makes `build: { plugins: [...] }` unrepresentable, but a\n * plain `warlock.config.js`, an `as any`, or a connector compiled against an\n * older core all slip past the type. Rejected rather than ignored — the same\n * posture as the `tsconfig` guard in `resolve-build-config`: dropping the key\n * quietly would leave the author believing their plugin ran.\n */\nconst ALLOWED_CONTRIBUTION_KEYS = [\"generate\", \"emit\"] as const;\n\n/**\n * What the generate pass produced, merged across every contributor.\n */\nexport type GenerateContributionsResult = {\n /** Entry lines in contributor order, appended after `./routes` */\n entryImports: string[];\n /** The contributors' esbuild patches, merged into one */\n esbuild: ConnectorEsbuildPatch;\n};\n\n/**\n * Reject a contribution object carrying anything but the two hooks.\n *\n * @throws Error naming the connector and the offending key\n */\nexport function assertClosedContribution(connector: Connector): void {\n const contribution = connector.build;\n\n if (!contribution) return;\n\n for (const key of Object.keys(contribution)) {\n if ((ALLOWED_CONTRIBUTION_KEYS as readonly string[]).includes(key)) continue;\n\n throw new Error(\n `Connector \"${connector.name}\" declares an unsupported build contribution key \"${key}\". ` +\n `A build contribution carries exactly
|
|
1
|
+
{"version":3,"file":"build-contributions.mjs","names":[],"sources":["../../../../../../../core/src/production/build-contributions.ts"],"sourcesContent":["import type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\n\n/**\n * `Error` with the `cause` option typed. Same shim as\n * `application.ts` — lib.es2022 declares `cause` on `ErrorOptions`, but the\n * package still compiles against an older lib in some consumers.\n */\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\n\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\n\n/**\n * The only keys a `build` contribution may carry.\n *\n * The runtime half of the closed-contribution constraint: the\n * type already makes `build: { plugins: [...] }` unrepresentable, but a\n * plain `warlock.config.js`, an `as any`, or a connector compiled against an\n * older core all slip past the type. Rejected rather than ignored — the same\n * posture as the `tsconfig` guard in `resolve-build-config`: dropping the key\n * quietly would leave the author believing their plugin ran.\n */\nconst ALLOWED_CONTRIBUTION_KEYS = [\"generate\", \"emit\", \"typings\"] as const;\n\n/**\n * What the generate pass produced, merged across every contributor.\n */\nexport type GenerateContributionsResult = {\n /** Entry lines in contributor order, appended after `./routes` */\n entryImports: string[];\n /** The contributors' esbuild patches, merged into one */\n esbuild: ConnectorEsbuildPatch;\n};\n\n/**\n * Reject a contribution object carrying anything but the two hooks.\n *\n * @throws Error naming the connector and the offending key\n */\nexport function assertClosedContribution(connector: Connector): void {\n const contribution = connector.build;\n\n if (!contribution) return;\n\n for (const key of Object.keys(contribution)) {\n if ((ALLOWED_CONTRIBUTION_KEYS as readonly string[]).includes(key)) continue;\n\n throw new Error(\n `Connector \"${connector.name}\" declares an unsupported build contribution key \"${key}\". ` +\n `A build contribution carries exactly these optional hooks — ` +\n `${ALLOWED_CONTRIBUTION_KEYS.join(\", \")} — and no data. ` +\n `Anything a hook needs (plugins, pipelines, aliases) must be constructed inside ` +\n `that hook, so it never lands in the connector's static import graph.`,\n );\n }\n}\n\n/**\n * Drain every connector's `generate` hook, in array order, sequentially.\n *\n * Semantics are copied from `Application.runStartupValidators`\n * (`application.ts:304-329`) on purpose: ordered, awaited one at a time, and\n * a throw is rethrown wrapped in an error NAMING the contributor. A\n * contributor failure IS the build failing — that is what makes\n * \"green build, no client bundle\" unrepresentable rather than merely\n * unlikely.\n */\nexport async function runGenerateContributions(\n connectors: readonly Connector[],\n context: ConnectorBuildContext,\n): Promise<GenerateContributionsResult> {\n const entryImports: string[] = [];\n let esbuild: ConnectorEsbuildPatch = {};\n\n for (const connector of connectors) {\n assertClosedContribution(connector);\n\n const generate = connector.build?.generate;\n\n if (!generate) continue;\n\n const result = await runHook(connector, \"generate\", () => generate(context));\n\n if (!result) continue;\n\n if (result.entryImports) {\n entryImports.push(...result.entryImports);\n }\n\n if (result.esbuild) {\n esbuild = mergeEsbuildPatches(esbuild, result.esbuild);\n }\n }\n\n return { entryImports, esbuild };\n}\n\n/**\n * Drain every connector's `emit` hook, in array order, sequentially.\n *\n * Runs after esbuild and before `.warlock/production` is removed, so a hook\n * may still read what `generate` wrote there.\n */\nexport async function runEmitContributions(\n connectors: readonly Connector[],\n context: ConnectorBuildContext,\n): Promise<void> {\n for (const connector of connectors) {\n assertClosedContribution(connector);\n\n const emit = connector.build?.emit;\n\n if (!emit) continue;\n\n await runHook(connector, \"emit\", () => emit(context));\n }\n}\n\n/**\n * Drain every connector's `typings` hook, in array order, sequentially.\n * Connectors without one — every API-only app — are skipped without error.\n */\nexport async function runTypingsContributions(\n connectors: readonly Connector[],\n context: ConnectorBuildContext,\n): Promise<void> {\n for (const connector of connectors) {\n assertClosedContribution(connector);\n\n const typings = connector.build?.typings;\n\n if (!typings) continue;\n\n await runHook(connector, \"typings\", () => typings(context));\n }\n}\n\n/**\n * Merge two contributor patches. Later wins, except:\n *\n * - `define` merges per key — two contributors defining different\n * `import.meta.env.*` entries must both survive; a wholesale replace would\n * drop one silently.\n * - `external` concatenates and dedupes — it is a set of package names, and\n * under `singleBundle` each contributor adds its own optional peers.\n * - `loader` merges per extension, for the same reason as `define`.\n * - `plugins` concatenate in contribution order. They are constructed inside\n * a hook, so this does not reopen the closed-contribution constraint.\n */\nexport function mergeEsbuildPatches(\n base: ConnectorEsbuildPatch,\n patch: ConnectorEsbuildPatch,\n): ConnectorEsbuildPatch {\n const merged: ConnectorEsbuildPatch = { ...base, ...patch };\n\n if (base.define || patch.define) {\n merged.define = { ...base.define, ...patch.define };\n }\n\n if (base.external || patch.external) {\n merged.external = dedupe([...(base.external ?? []), ...(patch.external ?? [])]);\n }\n\n if (base.loader || patch.loader) {\n merged.loader = { ...base.loader, ...patch.loader };\n }\n\n if (base.plugins || patch.plugins) {\n merged.plugins = [...(base.plugins ?? []), ...(patch.plugins ?? [])];\n }\n\n return merged;\n}\n\n/**\n * Concatenation order preserved — esbuild does not care, but a stable order\n * keeps build output diffable.\n */\nexport function dedupe(values: string[]): string[] {\n return [...new Set(values)];\n}\n\n/**\n * Run one hook and rename its failure after the connector that owns it.\n */\nasync function runHook<Result>(\n connector: Connector,\n hook: \"generate\" | \"emit\" | \"typings\",\n run: () => Result | Promise<Result>,\n): Promise<Result> {\n try {\n return await run();\n } catch (error) {\n const cause = error instanceof Error ? error.message : String(error);\n\n throw new ErrorWithCause(\n `Build contribution \"${connector.name}\" failed during ${hook}: ${cause}. ` +\n `The build cannot continue — an artifact this connector was responsible for ` +\n `is missing, and shipping the bundle without it would fail at runtime instead.`,\n { cause: error },\n );\n }\n}\n"],"mappings":";AASA,MAAM,iBAAiB;;;;;;;;;;;AAYvB,MAAM,4BAA4B;CAAC;CAAY;CAAQ;AAAS;;;;;;AAiBhE,SAAgB,yBAAyB,WAA4B;CACnE,MAAM,eAAe,UAAU;CAE/B,IAAI,CAAC,cAAc;CAEnB,KAAK,MAAM,OAAO,OAAO,KAAK,YAAY,GAAG;EAC3C,IAAK,0BAAgD,SAAS,GAAG,GAAG;EAEpE,MAAM,IAAI,MACR,cAAc,UAAU,KAAK,oDAAoD,IAAI,iEAEhF,0BAA0B,KAAK,IAAI,EAAE,oKAG5C;CACF;AACF;;;;;;;;;;;AAYA,eAAsB,yBACpB,YACA,SACsC;CACtC,MAAM,eAAyB,CAAC;CAChC,IAAI,UAAiC,CAAC;CAEtC,KAAK,MAAM,aAAa,YAAY;EAClC,yBAAyB,SAAS;EAElC,MAAM,WAAW,UAAU,OAAO;EAElC,IAAI,CAAC,UAAU;EAEf,MAAM,SAAS,MAAM,QAAQ,WAAW,kBAAkB,SAAS,OAAO,CAAC;EAE3E,IAAI,CAAC,QAAQ;EAEb,IAAI,OAAO,cACT,aAAa,KAAK,GAAG,OAAO,YAAY;EAG1C,IAAI,OAAO,SACT,UAAU,oBAAoB,SAAS,OAAO,OAAO;CAEzD;CAEA,OAAO;EAAE;EAAc;CAAQ;AACjC;;;;;;;AAQA,eAAsB,qBACpB,YACA,SACe;CACf,KAAK,MAAM,aAAa,YAAY;EAClC,yBAAyB,SAAS;EAElC,MAAM,OAAO,UAAU,OAAO;EAE9B,IAAI,CAAC,MAAM;EAEX,MAAM,QAAQ,WAAW,cAAc,KAAK,OAAO,CAAC;CACtD;AACF;;;;;AAMA,eAAsB,wBACpB,YACA,SACe;CACf,KAAK,MAAM,aAAa,YAAY;EAClC,yBAAyB,SAAS;EAElC,MAAM,UAAU,UAAU,OAAO;EAEjC,IAAI,CAAC,SAAS;EAEd,MAAM,QAAQ,WAAW,iBAAiB,QAAQ,OAAO,CAAC;CAC5D;AACF;;;;;;;;;;;;;AAcA,SAAgB,oBACd,MACA,OACuB;CACvB,MAAM,SAAgC;EAAE,GAAG;EAAM,GAAG;CAAM;CAE1D,IAAI,KAAK,UAAU,MAAM,QACvB,OAAO,SAAS;EAAE,GAAG,KAAK;EAAQ,GAAG,MAAM;CAAO;CAGpD,IAAI,KAAK,YAAY,MAAM,UACzB,OAAO,WAAW,OAAO,CAAC,GAAI,KAAK,YAAY,CAAC,GAAI,GAAI,MAAM,YAAY,CAAC,CAAE,CAAC;CAGhF,IAAI,KAAK,UAAU,MAAM,QACvB,OAAO,SAAS;EAAE,GAAG,KAAK;EAAQ,GAAG,MAAM;CAAO;CAGpD,IAAI,KAAK,WAAW,MAAM,SACxB,OAAO,UAAU,CAAC,GAAI,KAAK,WAAW,CAAC,GAAI,GAAI,MAAM,WAAW,CAAC,CAAE;CAGrE,OAAO;AACT;;;;;AAMA,SAAgB,OAAO,QAA4B;CACjD,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC5B;;;;AAKA,eAAe,QACb,WACA,MACA,KACiB;CACjB,IAAI;EACF,OAAO,MAAM,IAAI;CACnB,SAAS,OAAO;EACd,MAAM,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAEnE,MAAM,IAAI,eACR,uBAAuB,UAAU,KAAK,kBAAkB,KAAK,IAAI,MAAM,6JAGvE,EAAE,OAAO,MAAM,CACjB;CACF;AACF"}
|
|
@@ -4,7 +4,7 @@ import { assertNoReservedConnectorNames } from "../connectors/assert-no-reserved
|
|
|
4
4
|
import { assertUniqueConnectorNames } from "../connectors/assert-unique-connector-names.mjs";
|
|
5
5
|
import { warlockConfigManager } from "../warlock-config/warlock-config.manager.mjs";
|
|
6
6
|
import { tsconfigManager } from "../dev-server/tsconfig-manager.mjs";
|
|
7
|
-
import { isConfigFile, isEventFile, isLocaleFile, isMainFile, isRouteFile } from "../dev-server/special-file-patterns.mjs";
|
|
7
|
+
import { isConfigFile, isEventFile, isLocaleFile, isMainFile, isRouteFile, isWorkerFile } from "../dev-server/special-file-patterns.mjs";
|
|
8
8
|
import { configKeyFromPath } from "../config/config-key-from-path.mjs";
|
|
9
9
|
import { assertGeneratedImportsAreDeclared } from "./assert-generated-imports.mjs";
|
|
10
10
|
import { bundleFrameworkDependencies } from "./bundle-framework-dependencies.mjs";
|
|
@@ -86,7 +86,8 @@ var ProductionBuilder = class {
|
|
|
86
86
|
locales: false,
|
|
87
87
|
events: false,
|
|
88
88
|
main: false,
|
|
89
|
-
routes: false
|
|
89
|
+
routes: false,
|
|
90
|
+
workers: false
|
|
90
91
|
};
|
|
91
92
|
}
|
|
92
93
|
/**
|
|
@@ -177,7 +178,10 @@ var ProductionBuilder = class {
|
|
|
177
178
|
await clearOwnedRouteTypes(rootPath());
|
|
178
179
|
return;
|
|
179
180
|
}
|
|
180
|
-
this.namedApiRoutes = (await collectRouteRegistrationSnapshot({
|
|
181
|
+
this.namedApiRoutes = (await collectRouteRegistrationSnapshot({
|
|
182
|
+
cwd: rootPath(),
|
|
183
|
+
timeoutMs: this.options.routeRegistrationTimeoutMs
|
|
184
|
+
})).routes;
|
|
181
185
|
}
|
|
182
186
|
/**
|
|
183
187
|
* Drain the `generate` hooks and fold what they returned back into the
|
|
@@ -213,17 +217,19 @@ var ProductionBuilder = class {
|
|
|
213
217
|
console.log(colors.yellow(" Generating production files..."));
|
|
214
218
|
await this.generateBootstrap();
|
|
215
219
|
await this.generateConfigLoader();
|
|
216
|
-
const [locales, events, main, routes] = await Promise.all([
|
|
220
|
+
const [locales, events, main, routes, workers] = await Promise.all([
|
|
217
221
|
this.generateLocales(),
|
|
218
222
|
this.generateEvents(),
|
|
219
223
|
this.generateMain(),
|
|
220
|
-
this.generateRoutes()
|
|
224
|
+
this.generateRoutes(),
|
|
225
|
+
this.generateWorkers()
|
|
221
226
|
]);
|
|
222
227
|
this.generatedFiles = {
|
|
223
228
|
locales,
|
|
224
229
|
events,
|
|
225
230
|
main,
|
|
226
|
-
routes
|
|
231
|
+
routes,
|
|
232
|
+
workers
|
|
227
233
|
};
|
|
228
234
|
}
|
|
229
235
|
/**
|
|
@@ -272,7 +278,7 @@ bootstrap();
|
|
|
272
278
|
* Returns relative paths from .warlock/production/ to src/app/
|
|
273
279
|
*/
|
|
274
280
|
async globModule(matches) {
|
|
275
|
-
return (await glob("**/*.{ts,tsx}", {
|
|
281
|
+
return (await glob("**/*.{ts,tsx,json}", {
|
|
276
282
|
cwd: appPath(),
|
|
277
283
|
absolute: false
|
|
278
284
|
})).filter((file) => matches("src/app/" + file)).sort().map((file) => "../../src/app/" + file.replace(/\.(ts|tsx)$/, ""));
|
|
@@ -321,7 +327,16 @@ bootstrap();
|
|
|
321
327
|
async generateLocales() {
|
|
322
328
|
const files = await this.globModule(isLocaleFile);
|
|
323
329
|
if (files.length === 0) return false;
|
|
324
|
-
|
|
330
|
+
const content = files.map((file, index) => {
|
|
331
|
+
if (!file.endsWith(".json")) return `import "${file}";`;
|
|
332
|
+
const moduleFolder = file.split("/").at(-3);
|
|
333
|
+
return [
|
|
334
|
+
`import dictionary${index} from "${file}";`,
|
|
335
|
+
"import { registerLocaleDictionary } from \"@warlock.js/core\";",
|
|
336
|
+
`registerLocaleDictionary({ sourceFile: ${JSON.stringify(file)}, source: JSON.stringify(dictionary${index}), defaultNamespace: ${JSON.stringify(moduleFolder)} });`
|
|
337
|
+
].join("\n");
|
|
338
|
+
}).join("\n");
|
|
339
|
+
await putFileAsync(path.join(this.productionDir, "locales.ts"), content + "\n");
|
|
325
340
|
return true;
|
|
326
341
|
}
|
|
327
342
|
/**
|
|
@@ -355,6 +370,16 @@ bootstrap();
|
|
|
355
370
|
return true;
|
|
356
371
|
}
|
|
357
372
|
/**
|
|
373
|
+
* Generate workers.ts (only if there are worker files)
|
|
374
|
+
* @returns true if file was generated with content
|
|
375
|
+
*/
|
|
376
|
+
async generateWorkers() {
|
|
377
|
+
const files = await this.globModule(isWorkerFile);
|
|
378
|
+
if (files.length === 0) return false;
|
|
379
|
+
await this.generateImportsFile(files, "workers.ts");
|
|
380
|
+
return true;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
358
383
|
* Generate a file with imports from all given files
|
|
359
384
|
*/
|
|
360
385
|
async generateImportsFile(importPaths, outputFile) {
|
|
@@ -397,7 +422,9 @@ bootstrap();
|
|
|
397
422
|
"// a bind-and-release on a socket that is never served, and it reports",
|
|
398
423
|
"// on stderr because no log channel is configured this early.",
|
|
399
424
|
"import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";",
|
|
400
|
-
"
|
|
425
|
+
"if (Application.hasRole(\"api\") || Application.hasRole(\"web\")) {",
|
|
426
|
+
" await preflightConfiguredHttpPort();",
|
|
427
|
+
"}",
|
|
401
428
|
"",
|
|
402
429
|
"// 3. Start early-phase connectors (database, cache, logger, ...)",
|
|
403
430
|
"// so data sources, cache, etc. are ready before app code runs",
|
|
@@ -407,7 +434,8 @@ bootstrap();
|
|
|
407
434
|
if (this.generatedFiles.events) imports.push("await import(\"./events\");");
|
|
408
435
|
if (this.generatedFiles.locales) imports.push("await import(\"./locales\");");
|
|
409
436
|
if (this.generatedFiles.main) imports.push("await import(\"./main\");");
|
|
410
|
-
if (this.generatedFiles.routes) imports.push("await import(\"./routes\");");
|
|
437
|
+
if (this.generatedFiles.routes) imports.push("if (Application.hasRole(\"api\")) {", " await import(\"./routes\");", "}");
|
|
438
|
+
if (this.generatedFiles.workers) imports.push("if (Application.hasRole(\"worker\")) {", " await import(\"./workers\");", "}");
|
|
411
439
|
imports.push(...contributedImports);
|
|
412
440
|
imports.push("", "// 5. Run startup validators registered via Application.onValidateBoot(...)", "await Application.runStartupValidators();");
|
|
413
441
|
imports.push("", "// 6. Start late-phase connectors (http, socket) — routes and", "// listeners registered by app code are now ready to bind", "await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);", "", "// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire", "Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });", "connectorsManager.shutdownOnProcessKill();");
|
|
@@ -438,6 +466,7 @@ bootstrap();
|
|
|
438
466
|
delete esbuildOptions.singleBundle;
|
|
439
467
|
delete esbuildOptions.esmShim;
|
|
440
468
|
delete esbuildOptions.banner;
|
|
469
|
+
delete esbuildOptions.routeRegistrationTimeoutMs;
|
|
441
470
|
await ensureDirectoryAsync(writeOutDir);
|
|
442
471
|
const alias = this.buildAliasMapFromTsconfig();
|
|
443
472
|
const perEdgeExternals = !singleBundle && esbuildOptions.packages === void 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport {\n ensureDirectoryAsync,\n fileExistsAsync,\n getFileAsync,\n getJsonFileAsync,\n putFileAsync,\n removeDirectoryAsync,\n} from \"@warlock.js/fs\";\nimport esbuild from \"esbuild\";\nimport glob from \"fast-glob\";\nimport path from \"path\";\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\nimport { configKeyFromPath } from \"../config/config-key-from-path\";\nimport { isConfigFile, isEventFile, isLocaleFile, isMainFile, isRouteFile } from \"../dev-server/special-file-patterns\";\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\nimport { appPath, rootPath, warlockPath } from \"../utils\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\nimport { bundleFrameworkDependencies } from \"./bundle-framework-dependencies\";\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\nimport { assertEsbuildBinaryIsLinked } from \"./esbuild-preflight\";\nimport { collectRouteRegistrationSnapshot } from \"./route-registration-snapshot\";\nimport { clearOwnedRouteTypes } from \"../dev-server/route-types-publisher\";\nimport {\n commitDistAsync,\n createTempOutputDir,\n rollbackDistAsync,\n stageDistAsync,\n type StagedDist,\n} from \"./promote-dist\";\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\nimport { tsconfigPathAliases } from \"./tsconfig-path-aliases\";\nimport { toKebabCase } from \"@mongez/reinforcements\";\n\n/**\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\n *\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\n * esbuild substitutes a stub that throws — **after the build has reported\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\n * firing, and it is the defect this shim removes.\n *\n * `__dirname` matters as much as `require`: without it a dependency resolving\n * an asset path silently gets `undefined` and fails later, further from the\n * cause.\n *\n * Written as one line because esbuild inserts a banner verbatim above the\n * bundle and a multi-line string here would shift every mapped line.\n */\nconst ESM_INTEROP_SHIM =\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\n \"import{dirname as __wlDirname}from'node:path';\" +\n \"const require=__wlCreateRequire(import.meta.url);\" +\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\n \"const __dirname=__wlDirname(__filename);\";\n\n/**\n * Combine the framework's banner with the user's, keeping both.\n *\n * esbuild's `banner` is an object keyed by output type, and every merge in the\n * path to it — the config merge and the options spread — REPLACES that object\n * rather than merging it. So whichever is applied second silently deletes the\n * other. This is the only place the two can coexist.\n *\n * The shim goes first: it defines `require`, which a user banner may use.\n *\n * @param userBanner banner from `warlock.config.ts`, if any\n * @param shim the interop shim, or undefined when it does not apply\n */\nfunction mergeBanner(\n userBanner: Record<string, string> | undefined,\n shim: string | undefined,\n): Record<string, string> | undefined {\n if (!shim) return userBanner;\n\n const userJs = userBanner?.js;\n\n return {\n ...userBanner,\n js: userJs ? `${shim}${userJs}` : shim,\n };\n}\n\n/**\n * Prefix every generated file uses to reach the app root.\n *\n * Generated sources are written into `.warlock/production/`, two levels below\n * the app root, so `../../` lands back on it — the same hop already spelled\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\n * config-loader generators emit. Named once so a generator that needs a new\n * app-root file (`warlock.config`) cannot pick a different depth.\n */\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\n\n/**\n * Production Builder\n * Generates production-ready files and bundles them for deployment\n * Build options are loaded from warlock.config.ts\n */\nexport class ProductionBuilder {\n private options!: ResolvedBuildConfig;\n private readonly productionDir = warlockPath(\"production\");\n\n /**\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\n * never calls `boot()`/`start()` on them; it only\n * drains their `build` contributions.\n */\n private connectors: readonly Connector[] = [];\n\n /**\n * The contributors' merged esbuild patch, produced by the `generate` pass\n * and consumed by {@link bundle}.\n */\n private contributedEsbuild: ConnectorEsbuildPatch = {};\n\n /** Browser-safe API metadata captured in a fresh registration-only child. */\n private namedApiRoutes?: readonly import(\"../router/types\").NamedApiRoute[];\n\n /**\n * Main build entry point\n *\n * The esbuild bundle is written into a TEMP directory next to the real\n * output directory, never into it, and that directory is renamed over\n * `outdir` as one filesystem operation — so `outdir` is never observed as\n * a mix of the old build and the new one, and a build that fails before\n * that rename never touches `outdir` at all.\n *\n * `this.options.outdir` is NOT repointed at the temp directory while that\n * happens, and must never be. It is not merely a write target: consumers\n * BAKE it into runtime output — `web`'s build contribution derives the\n * `clientDir` recorded in its pages manifest from it\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\n * produces an artifact whose browser paths point at a directory promotion\n * has since renamed away. The temp path is passed explicitly, as a\n * parameter, to the one operation that writes into it ({@link bundle});\n * everything else, `buildContext()` included, keeps reading the final\n * destination.\n *\n * That is also why promotion is STAGED rather than done at the very end.\n * Connector `emit` hooks write real artifacts (the web client bundle) and\n * see the final `outdir`, so they must run when `outdir` genuinely holds\n * this build — after the rename, not before it, or promotion would replace\n * the directory they just wrote into. The previous build is kept parked\n * aside until they finish: `emit` throwing rolls the whole promotion back,\n * and the build-success marker `warlock start` checks is written last of\n * all, so a failure at any point leaves no `dist` that start will boot.\n */\n public async build(): Promise<void> {\n console.log(colors.cyan(\"Building for production...\\n\"));\n\n // Step 0: Fail fast when esbuild's native binary never got linked (the\n // state pnpm leaves a project in when its build-script approval gate\n // blocked esbuild's postinstall) rather than let bundling die on esbuild's\n // own cryptic \"package could not be found\" error several steps from now.\n assertEsbuildBinaryIsLinked();\n\n // Step 1: Initialize options from config\n await this.initializeOptions();\n\n const finalOutDir = this.options.outdir!;\n const tempOutDir = createTempOutputDir(finalOutDir);\n\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\n // presence is what tells the catch below whether a failure has a\n // promotion to undo or only a temp directory to discard.\n let staged: StagedDist | undefined;\n\n try {\n // Step 2: Generate combined files\n await this.generateCombinedFiles();\n\n // Step 3: Generate entry point\n await this.generateEntryPoint();\n\n // Step 4: Refuse to bundle code the app could not resolve at runtime\n await this.assertGeneratedImports();\n\n // Step 4.5: Drain the connectors' `generate` contributions\n await this.captureNamedApiRoutesForWeb();\n const contributed = await this.runGenerateContributions();\n\n // Step 4.6: Re-assert over what the contributors just wrote.\n //\n // Step 4 only saw core's own generated files; a contributor writes its\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\n // specifier in it reaches the bundle unchecked. Under\n // `packages: \"external\"` that specifier survives verbatim into the\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\n // and re-reading the production dir is pure cost in the common case.\n if (contributed) {\n await this.assertGeneratedImports();\n }\n\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\n // operation handed that path — it is a write target, not config.\n await this.bundle(tempOutDir);\n\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\n // build parked aside. `outdir` now holds exactly this build, so the\n // steps below write into — and record — the real destination.\n staged = await stageDistAsync(tempOutDir, finalOutDir);\n\n // Step 5.6: Drain the connectors' `emit` contributions — after the\n // bundle is in place (so what they write survives promotion and the\n // paths they bake in resolve), and BEFORE step 6 deletes the\n // production directory they may still read.\n await runEmitContributions(this.connectors, this.buildContext());\n\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\n // `warlock start` trusts. Written LAST on purpose: every earlier step\n // can still fail, and until this file exists nothing will boot what\n // they left behind.\n await writeDistBuildManifestAsync(finalOutDir);\n\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\n await commitDistAsync(staged);\n } catch (error) {\n if (staged) {\n // The promotion already happened; put the previous build back and\n // take this half-finished one out of `outdir`.\n await rollbackDistAsync(staged);\n } else {\n // Nothing this build produced ever reached `outdir` — discard the\n // temp directory and leave `outdir` exactly as it was.\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\n }\n\n throw error;\n }\n\n // Step 6: Remove production folder\n await removeDirectoryAsync(this.productionDir);\n\n console.log(colors.green(\"Build complete!\"));\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\n }\n\n /**\n * Initialize options from warlock.config.ts\n */\n private async initializeOptions(): Promise<void> {\n this.options = resolveBuildConfig();\n // Same config object `resolveBuildConfig` just read — `warlock build`\n // preloads warlock.config.ts, so no additional load happens here.\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\n\n // Checked here, where the array is first read, so nothing downstream has\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\n // a name listed twice would write its files and merge its esbuild options\n // twice into an artifact the runtime then boots that name only once from.\n // A build that half-applied a connector and reported success is worse than\n // one that never started.\n assertUniqueConnectorNames([...connectors]);\n\n // And here rather than only at boot, for the same reason: a name a built-in\n // already owns is skipped by the runtime, so an artifact built from it\n // carries the custom connector's generated files and esbuild patches while\n // the server boots the built-in instead. Refusing it at boot alone would\n // mean the build had already emitted that artifact — the failure has to\n // land on the developer running `warlock build`, not on whoever starts the\n // server. Same assertion the registration half calls, over the same names.\n assertNoReservedConnectorNames([...connectors]);\n\n this.connectors = connectors;\n\n // Ensure production directory exists\n await ensureDirectoryAsync(this.productionDir);\n }\n\n /**\n * The context handed to every build contribution.\n */\n private buildContext(): ConnectorBuildContext {\n return {\n productionDir: this.productionDir,\n appRoot: rootPath(),\n options: this.options,\n namedApiRoutes: this.namedApiRoutes,\n };\n }\n\n /**\n * Web route declarations need application API registration, which cannot be\n * inferred from generated files. Capture it once in a disposable child before\n * contributors write build artifacts; no connector lifecycle runs there.\n */\n private async captureNamedApiRoutesForWeb(): Promise<void> {\n if (!this.connectors.some((connector) => connector.name === \"web\")) {\n await clearOwnedRouteTypes(rootPath());\n return;\n }\n\n this.namedApiRoutes = (await collectRouteRegistrationSnapshot({ cwd: rootPath() })).routes;\n }\n\n /**\n * Drain the `generate` hooks and fold what they returned back into the\n * build.\n *\n * The entry point is REGENERATED here rather than generated later. The\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\n * bundles that the app could not resolve) and before `bundle` — while\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\n * generated code the assertion has to see; moving it past the assertion\n * would silently drop the entry from that check. Rewriting one small file\n * is cheaper than losing either guarantee, and the write is pure\n * (`generatedFiles` + these imports), so doing it twice is not a\n * correctness risk.\n *\n * @returns whether any connector ran a `generate` hook — the caller uses it\n * to decide if the import assertion is worth a second pass. Keyed on the\n * hook EXISTING, not on what it returned: a hook that returns nothing may\n * still have written files into `productionDir`, and those are exactly the\n * files the second pass is there to read.\n */\n private async runGenerateContributions(): Promise<boolean> {\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\n\n const { entryImports, esbuild } = await runGenerateContributions(\n this.connectors,\n this.buildContext(),\n );\n\n this.contributedEsbuild = esbuild;\n\n if (entryImports.length > 0) {\n await this.generateEntryPoint(entryImports);\n }\n\n return contributed;\n }\n\n /**\n * Track which special files were generated\n */\n private generatedFiles = {\n locales: false,\n events: false,\n main: false,\n routes: false,\n };\n\n /**\n * Generate all combined files\n */\n private async generateCombinedFiles(): Promise<void> {\n console.log(colors.yellow(\" Generating production files...\"));\n\n // Generate bootstrap.ts file\n await this.generateBootstrap();\n\n // Generate config loader\n await this.generateConfigLoader();\n\n // Generate special files and track which ones have content\n const [locales, events, main, routes] = await Promise.all([\n this.generateLocales(),\n this.generateEvents(),\n this.generateMain(),\n this.generateRoutes(),\n ]);\n\n this.generatedFiles = { locales, events, main, routes };\n }\n\n /**\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\n */\n private async generateBootstrap(): Promise<void> {\n // ESM hoists imports, so the app bootstrap must be the first import to run first\n const appBootstrapImport = (await fileExistsAsync(appPath(\"bootstrap.ts\")))\n ? \"import './../../src/app/bootstrap';\\n\"\n : \"\";\n\n const content = `${appBootstrapImport}import { bootstrap, Application } from \"@warlock.js/core\";\n\n// Production runtime; NODE_ENV is only defaulted so an explicit value (e.g. staging) wins\nApplication.setRuntimeStrategy(\"production\");\nif (!process.env.NODE_ENV) {\n Application.setEnvironment(\"production\");\n}\n\n// Bootstrap the application\nbootstrap();\n`;\n\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\n }\n\n /**\n * Fail the build when generated code imports a package the app does not\n * declare.\n *\n * The bundler is configured `packages: \"external\"`, so every bare specifier\n * written above survives verbatim into an artifact that resolves against the\n * **consuming app's** node_modules. A framework-internal dependency imported\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\n * which is how a production app shipped that could not boot. Rewriting the\n * offending import fixes today's bundle; this check is what stops the next\n * change to the generator from quietly reintroducing it.\n */\n private async assertGeneratedImports(): Promise<void> {\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\n cwd: this.productionDir,\n absolute: false,\n });\n\n const [files, appPackage] = await Promise.all([\n Promise.all(\n generatedPaths.map(async (file) => ({\n file,\n content: await getFileAsync(path.join(this.productionDir, file)),\n })),\n ),\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\n ]);\n\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\n }\n\n /**\n * Glob `src/app` and keep the files the shared dev-server predicate accepts,\n * so production discovers exactly what the dev collector does.\n * Returns relative paths from .warlock/production/ to src/app/\n */\n private async globModule(matches: (relativePath: string) => boolean): Promise<string[]> {\n const files = await glob(\"**/*.{ts,tsx}\", {\n cwd: appPath(),\n absolute: false,\n });\n\n // e.g., \"users/main.ts\" -> \"../../src/app/users/main\"\n return files\n .filter((file) => matches(\"src/app/\" + file))\n .sort()\n .map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\n }\n\n /**\n * Generate config-loader.ts\n */\n private async generateConfigLoader(): Promise<void> {\n const configDirectory = path.join(process.cwd(), \"src/config\");\n\n const files = await glob(\"**/*.{ts,tsx}\", {\n cwd: configDirectory,\n absolute: false,\n });\n\n // Same key rule as the dev config loader: the raw path, never camel-cased\n const configNames = files\n .filter((f) => isConfigFile(\"src/config/\" + f))\n .map((f) => ({\n path: f.replace(/\\.(ts|tsx)$/, \"\"),\n key: configKeyFromPath(\"src/config/\" + f),\n }))\n .filter((entry): entry is { path: string; key: string } => entry.key !== undefined)\n .sort((a, b) => a.path.localeCompare(b.path));\n\n // Only `@warlock.js/core` — the one package the app itself declares. See\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\n // dependency, so a bare import of it resolved by luck under npm/yarn\n // hoisting and died under pnpm's strict layout.\n const imports: string[] = [\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\n ];\n const configImports: string[] = [];\n const configSetCalls: string[] = [];\n const executors: string[] = [];\n\n configNames.forEach(({ path: configPath, key }, index) => {\n // Index-based identifier: keys like \"rate-limit\" or \"mail/smtp\" are not valid names\n const varName = `config${index}`;\n configImports.push(`import ${varName} from \"../../src/config/${configPath}\";`);\n configSetCalls.push(`setConfig(${JSON.stringify(key)}, ${varName});`);\n executors.push(`await configSpecialHandlers.execute(${JSON.stringify(key)}, ${varName});`);\n });\n\n // ESM hoists imports, so prestart must be the first import to run first\n const prestartImports = (await fileExistsAsync(appPath(\"prestart.ts\")))\n ? [\"import './../../src/app/prestart';\"]\n : [];\n\n const content = [\n ...prestartImports,\n ...imports,\n \"\",\n \"// Config imports\",\n ...configImports,\n \"\",\n \"// Register configs\",\n ...configSetCalls,\n \"\",\n \"// Special handlers\",\n ...executors,\n \"\",\n ].join(\"\\n\");\n\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\n }\n\n /**\n * Generate locales.ts (only if there are locale files)\n * @returns true if file was generated with content\n */\n private async generateLocales(): Promise<boolean> {\n const files = await this.globModule(isLocaleFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"locales.ts\");\n return true;\n }\n\n /**\n * Generate events.ts (only if there are event files)\n * @returns true if file was generated with content\n */\n private async generateEvents(): Promise<boolean> {\n const files = await this.globModule(isEventFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"events.ts\");\n return true;\n }\n\n /**\n * Generate main.ts (only if there are main files)\n * @returns true if file was generated with content\n */\n private async generateMain(): Promise<boolean> {\n const files = await this.globModule(isMainFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"main.ts\");\n return true;\n }\n\n /**\n * Generate routes.ts (only if there are route files)\n * @returns true if file was generated with content\n */\n private async generateRoutes(): Promise<boolean> {\n const files = await this.globModule(isRouteFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"routes.ts\");\n return true;\n }\n\n /**\n * Generate a file with imports from all given files\n */\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, outputFile), content);\n }\n\n /**\n * Generate the main entry point (app.ts)\n *\n * @param contributedImports lines from connector `generate` hooks, appended\n * to section 4 after `./routes`\n */\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\n console.log(colors.yellow(\" Generating entry point...\"));\n\n // The names this build resolved, baked in as a literal. The entry imports\n // the config source, and that source is re-evaluated at startup — an\n // env-conditional `connectors` array can hand the boot a different list\n // than the one drained here. A literal is the only part of the array that\n // survives into the artifact unchanged, so it is what the boot compares\n // against.\n const expectedNames = this.connectors\n .map((connector) => JSON.stringify(connector.name))\n .join(\", \");\n\n // Build imports based on which files were generated\n const imports: string[] = [\n \"// 1. Bootstrap (loads .env, initializes framework)\",\n 'import \"./bootstrap\";',\n \"\",\n \"// 2. Load configs\",\n 'import \"./config-loader\";',\n \"\",\n // Registration has to sit between the config being available and the\n // first phase starting: the connectors listed in `connectors` are the\n // same ones this build drained contributions from, so the bundle boots\n // exactly what it was built for. Register any later and an early-phase\n // connector would miss its own start.\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\n \"// build read its contributions from, so built-for and boots-with match).\",\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\n \"// and the array is handed over explicitly — an artifact has no\",\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\n \"// that quietly found nothing to register is the exact drift this\",\n \"// section exists to prevent.\",\n \"// `expectedNames` is the list this build resolved, in order — boot\",\n \"// refuses to start when the config hands over a different set or order.\",\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\n \"\",\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\n \"// own preflight is not reached until the database and cache have\",\n \"// connected and every app module has been imported — seconds of work\",\n \"// thrown away before anyone learns the port was taken. This probe is\",\n \"// a bind-and-release on a socket that is never served, and it reports\",\n \"// on stderr because no log channel is configured this early.\",\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\n \"await preflightConfiguredHttpPort();\",\n \"\",\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\n \"// so data sources, cache, etc. are ready before app code runs\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\n ];\n\n // App code uses dynamic `await import(...)` so each module's side\n // effects fire at THIS point in execution. Static imports would be\n // hoisted to module-instantiation time (before the early-phase await\n // resolves), which is exactly the bug this split is meant to fix.\n //\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\n // it at the await, not at instantiation. It does NOT come from\n // `splitting: true`, which only decides one-file-vs-chunks. This\n // previously said splitting was required; it is not, and `singleBundle`\n // (splitting: false) preserves the ordering.\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\n\n if (this.generatedFiles.events) {\n imports.push('await import(\"./events\");');\n }\n if (this.generatedFiles.locales) {\n imports.push('await import(\"./locales\");');\n }\n if (this.generatedFiles.main) {\n imports.push('await import(\"./main\");');\n }\n if (this.generatedFiles.routes) {\n imports.push('await import(\"./routes\");');\n }\n\n // Contributor imports come AFTER `./routes`, never before: a connector\n // that registers pages needs the routes app code already collected —\n // the same ordering dev uses (routes first, then the connector installs\n // on top of them). Emitted verbatim; the contributor writes the whole\n // statement (e.g. `await import(\"./pages\");`).\n imports.push(...contributedImports);\n\n // A rejecting validator (Application.onValidateBoot) must abort boot\n // before late-phase connectors bind a port.\n imports.push(\n \"\",\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\n \"await Application.runStartupValidators();\",\n );\n\n // Start late-phase connectors after app code registers routes/listeners\n imports.push(\n \"\",\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\n \"// listeners registered by app code are now ready to bind\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\n \"\",\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\n \"connectorsManager.shutdownOnProcessKill();\",\n );\n\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\n }\n\n /**\n * Bundle with esbuild\n *\n * @param writeOutDir the directory esbuild writes into — the build's\n * private temp directory, NOT `options.outdir`. Taken as a parameter\n * rather than read off `this.options` because the two are different paths\n * with different meanings: `options.outdir` is the final destination every\n * consumer bakes into the artifact, and this is only where bytes land\n * before promotion moves them there.\n */\n private async bundle(writeOutDir: string): Promise<void> {\n console.log(colors.magenta(\" Bundling with esbuild...\"));\n\n const entryPoint = path.join(this.productionDir, \"app.ts\");\n const outFileName = this.options.outFile!;\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\n const entryName = path.basename(outFileName, path.extname(outFileName));\n\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\n // unknown keys, and the user options are spread into its call verbatim.\n const singleBundle = this.options.singleBundle === true;\n const esmShim = this.options.esmShim !== false;\n // Read before deleting: the merged banner is applied AFTER the user\n // spread, so a user banner must not be lost to it or clobber the shim.\n const userBanner = this.options.banner;\n\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\n // resolve-build-config.ts documents that widening them pushed a lie downstream\n // into start-production.command.ts, which then could not trust its own config.\n // This is the one place they must be absent - the object is spread into esbuild's\n // call verbatim and esbuild throws on unknown keys.\n //\n // Stripped off a LOCAL COPY of `this.options`, never off `this.options`\n // itself: `buildContext()` hands `this.options` to every `generate`/`emit`\n // contribution hook, including the `emit` pass that runs AFTER this method\n // returns (`build()` step 5.6). Deleting these keys from the shared object\n // used to leave those hooks reading `undefined` for `outFile`, `entryPath`,\n // `singleBundle`, `esmShim` and `banner` even though `ConnectorBuildContext`\n // types them as present. A shallow copy is enough — every field this method\n // reads off it is either scalar or already re-merged below (`define`,\n // `external`, `loader`, `banner`), so nothing here needs a deep clone.\n const esbuildOptions: Partial<ResolvedBuildConfig> = { ...this.options };\n\n delete esbuildOptions.outFile;\n delete esbuildOptions.entryPath;\n delete esbuildOptions.singleBundle;\n delete esbuildOptions.esmShim;\n delete esbuildOptions.banner;\n\n await ensureDirectoryAsync(writeOutDir);\n\n const alias = this.buildAliasMapFromTsconfig();\n\n // Whether this build decides externality per import EDGE\n // (`bundle-framework-dependencies.ts`, which explains the rule at\n // length) or keeps the blunt `packages: \"external\"`.\n //\n // Not in `singleBundle` mode: that bundles everything by definition, and\n // a plugin that can only ever ADD an external would silently narrow it.\n // Not when the user set `packages` themselves: their value has always\n // won over the default below, and it must keep winning — the plugin is\n // the default's implementation, not a new policy layered on top.\n const perEdgeExternals = !singleBundle && (esbuildOptions as any).packages === undefined;\n\n // The user can override `format`, so gate the shim on the EFFECTIVE\n // format rather than on the default below. A CJS build already has\n // `require` and friends; injecting them there would be a redefinition.\n const isEsm = (esbuildOptions.format ?? \"esm\") === \"esm\";\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\n\n // Contributor patch, split into the part that can ride the spread order\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\n // BEFORE the user spread below, which gives the ruled precedence for\n // free: builder defaults < contributor < user config.\n //\n // `define`, `external` and `loader` are pulled out because a spread\n // REPLACES them wholesale — the same trap `banner` documents. Two\n // contributors' env defines, a contributor's optional peers plus the\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\n // must both survive, so they are merged by key/by set and re-applied\n // after the spread with the user still winning per key.\n const {\n define: contributedDefine,\n external: contributedExternal,\n loader: contributedLoader,\n plugins: contributedPlugins,\n ...contributedOptions\n } = this.contributedEsbuild;\n\n const userDefine: Record<string, string> | undefined = esbuildOptions.define;\n const userExternal: string[] | undefined = esbuildOptions.external;\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = esbuildOptions.loader;\n\n const define =\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\n\n const loader =\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\n\n const external =\n contributedExternal || userExternal\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\n : undefined;\n\n if (singleBundle) {\n console.log(\n colors.magenta(\n \" Single-bundle mode — one JS file\" +\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\n \". Native .node addons are still emitted alongside it.\",\n ),\n );\n }\n\n try {\n await esbuild.build({\n platform: \"node\",\n entryPoints: [entryPoint],\n bundle: true,\n // Both are DEFAULTS the user can override — they sit before the\n // `...esbuildOptions` spread deliberately. `singleBundle` moves them,\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\n //\n // Phase ordering does not depend on `splitting`: it comes from the\n // generated app.ts using dynamic `await import(...)` (see\n // generateAppEntry above), which esbuild defers to the call site in\n // either mode. Splitting only decides one file vs chunks.\n splitting: !singleBundle,\n // `\"bundle\"` under `perEdgeExternals` is not \"bundle everything\":\n // the plugin below returns `external: true` for every bare specifier\n // this build must not bundle, which is all of them bar the framework's\n // own declared dependencies. Saying `\"external\"` here instead would\n // externalise them before the plugin could rule.\n packages: singleBundle || perEdgeExternals ? \"bundle\" : \"external\",\n minify: esbuildOptions.minify,\n sourcemap: esbuildOptions.sourcemap === true ? \"linked\" : esbuildOptions.sourcemap,\n format: \"esm\",\n // Targeting a concrete Node version (not \"esnext\") so esbuild\n // transpiles TC39 stage 3 decorators into helpers — Node does not\n // implement them natively yet.\n target: [\"node22\"],\n entryNames: entryName,\n alias,\n plugins: [\n nativeNodeModulesPlugin,\n // BEFORE the framework-dependency plugin, and the order is\n // load-bearing: the first `onResolve` callback to answer wins, and\n // `app/users/...` is a bare specifier the other one would rule\n // external.\n tsconfigPathAliases(this.tsconfigPathAliasConfig()),\n ...(perEdgeExternals\n ? [bundleFrameworkDependencies({ appRoot: rootPath(), aliasKeys: Object.keys(alias) })]\n : []),\n // Contributor plugins run last: they load their own file types and\n // must not shadow the resolvers above.\n ...(contributedPlugins ?? []),\n ],\n // Between the defaults and the user spread — the ruled precedence.\n ...contributedOptions,\n ...(esbuildOptions as any),\n // AFTER the spread, and NOT overridable: `esbuildOptions.outdir` rides\n // that spread carrying the FINAL destination, which is exactly where\n // this build must not write yet. The final path is the user's setting\n // and stays authoritative for everyone reading the config — it is only\n // this one esbuild call that is redirected, and only until promotion\n // moves the result onto that very path.\n outdir: writeOutDir,\n // AFTER the spread for the same reason `banner` is: a spread replaces\n // these objects instead of merging them, so the merged values are\n // re-applied here. The user still wins — they were merged in last.\n ...(define ? { define } : {}),\n ...(external ? { external } : {}),\n ...(loader ? { loader } : {}),\n // AFTER the spread, and intentionally so: `banner` is an object, and\n // both the config merge and this spread REPLACE it wholesale rather\n // than merging. Left as a default above, any user banner would delete\n // the shim; left to the spread, the shim would delete theirs. The\n // merge is the only form that keeps both.\n ...(banner ? { banner } : {}),\n });\n } catch (e) {\n console.log(e);\n throw e;\n }\n }\n\n /**\n * The WILDCARD half of the same tsconfig `paths` map that\n * {@link ProductionBuilder.buildAliasMapFromTsconfig} reads the exact half\n * of. `tsconfig-path-aliases.ts` explains why the two halves need different\n * mechanisms — in short, esbuild's `alias` option cannot express a wildcard,\n * so the entries it skips have to be resolved by a plugin instead of being\n * left to no one.\n */\n private tsconfigPathAliasConfig(): { baseUrl: string; paths: Record<string, string[]> } {\n tsconfigManager.init();\n\n return {\n baseUrl: path.resolve(process.cwd(), tsconfigManager.baseUrl),\n paths: tsconfigManager.aliases as Record<string, string[]>,\n };\n }\n\n /**\n * Build an alias map from tsconfig `paths` so esbuild resolves local\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\n * folders during bundling. Without this, `packages: \"external\"` would\n * leave those bare specifiers as raw imports and Node would fail to\n * resolve them at runtime (they aren't installed in node_modules).\n *\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\n * option doesn't support glob-style mappings. The wildcard half is not\n * dropped, it is handled elsewhere: see\n * {@link ProductionBuilder.tsconfigPathAliasConfig}.\n */\n private buildAliasMapFromTsconfig(): Record<string, string> {\n tsconfigManager.init();\n\n const alias: Record<string, string> = {};\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\n\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\n continue;\n }\n\n const target = to[0];\n\n if (target === undefined) {\n continue;\n }\n\n alias[from] = path.resolve(baseUrl, target);\n }\n\n return alias;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,mBACJ;;;;;;;;;;;;;;AAoBF,SAAS,YACP,YACA,MACoC;CACpC,IAAI,CAAC,MAAM,OAAO;CAElB,MAAM,SAAS,YAAY;CAE3B,OAAO;EACL,GAAG;EACH,IAAI,SAAS,GAAG,OAAO,WAAW;CACpC;AACF;;;;;;;;;;AAWA,MAAM,+BAA+B;;;;;;AAOrC,IAAa,oBAAb,MAA+B;;uBAEI,YAAY,YAAY;oBAOd,CAAC;4BAMQ,CAAC;wBA+N5B;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;EACV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAlMA,MAAa,QAAuB;EAClC,QAAQ,IAAI,OAAO,KAAK,8BAA8B,CAAC;EAMvD,4BAA4B;EAG5B,MAAM,KAAK,kBAAkB;EAE7B,MAAM,cAAc,KAAK,QAAQ;EACjC,MAAM,aAAa,oBAAoB,WAAW;EAKlD,IAAI;EAEJ,IAAI;GAEF,MAAM,KAAK,sBAAsB;GAGjC,MAAM,KAAK,mBAAmB;GAG9B,MAAM,KAAK,uBAAuB;GAGlC,MAAM,KAAK,4BAA4B;GAYvC,IAAI,MAXsB,KAAK,yBAAyB,GAYtD,MAAM,KAAK,uBAAuB;GAKpC,MAAM,KAAK,OAAO,UAAU;GAK5B,SAAS,MAAM,eAAe,YAAY,WAAW;GAMrD,MAAM,qBAAqB,KAAK,YAAY,KAAK,aAAa,CAAC;GAM/D,MAAM,4BAA4B,WAAW;GAG7C,MAAM,gBA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BAAgB,OAAO,GAAG;GAChE,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG,WAAW,GAC7D;GAGF,MAAM,SAAS,GAAG;GAElB,IAAI,WAAW,QACb;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,MAAM;EAC5C;EAEA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport {\n ensureDirectoryAsync,\n fileExistsAsync,\n getFileAsync,\n getJsonFileAsync,\n putFileAsync,\n removeDirectoryAsync,\n} from \"@warlock.js/fs\";\nimport esbuild from \"esbuild\";\nimport glob from \"fast-glob\";\nimport path from \"path\";\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\nimport { configKeyFromPath } from \"../config/config-key-from-path\";\nimport {\n isConfigFile,\n isEventFile,\n isLocaleFile,\n isMainFile,\n isRouteFile,\n isWorkerFile,\n} from \"../dev-server/special-file-patterns\";\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\nimport { appPath, rootPath, warlockPath } from \"../utils\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\nimport { bundleFrameworkDependencies } from \"./bundle-framework-dependencies\";\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\nimport { assertEsbuildBinaryIsLinked } from \"./esbuild-preflight\";\nimport { collectRouteRegistrationSnapshot } from \"./route-registration-snapshot\";\nimport { clearOwnedRouteTypes } from \"../dev-server/route-types-publisher\";\nimport {\n commitDistAsync,\n createTempOutputDir,\n rollbackDistAsync,\n stageDistAsync,\n type StagedDist,\n} from \"./promote-dist\";\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\nimport { tsconfigPathAliases } from \"./tsconfig-path-aliases\";\nimport { toKebabCase } from \"@mongez/reinforcements\";\n\n/**\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\n *\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\n * esbuild substitutes a stub that throws — **after the build has reported\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\n * firing, and it is the defect this shim removes.\n *\n * `__dirname` matters as much as `require`: without it a dependency resolving\n * an asset path silently gets `undefined` and fails later, further from the\n * cause.\n *\n * Written as one line because esbuild inserts a banner verbatim above the\n * bundle and a multi-line string here would shift every mapped line.\n */\nconst ESM_INTEROP_SHIM =\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\n \"import{dirname as __wlDirname}from'node:path';\" +\n \"const require=__wlCreateRequire(import.meta.url);\" +\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\n \"const __dirname=__wlDirname(__filename);\";\n\n/**\n * Combine the framework's banner with the user's, keeping both.\n *\n * esbuild's `banner` is an object keyed by output type, and every merge in the\n * path to it — the config merge and the options spread — REPLACES that object\n * rather than merging it. So whichever is applied second silently deletes the\n * other. This is the only place the two can coexist.\n *\n * The shim goes first: it defines `require`, which a user banner may use.\n *\n * @param userBanner banner from `warlock.config.ts`, if any\n * @param shim the interop shim, or undefined when it does not apply\n */\nfunction mergeBanner(\n userBanner: Record<string, string> | undefined,\n shim: string | undefined,\n): Record<string, string> | undefined {\n if (!shim) return userBanner;\n\n const userJs = userBanner?.js;\n\n return {\n ...userBanner,\n js: userJs ? `${shim}${userJs}` : shim,\n };\n}\n\n/**\n * Prefix every generated file uses to reach the app root.\n *\n * Generated sources are written into `.warlock/production/`, two levels below\n * the app root, so `../../` lands back on it — the same hop already spelled\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\n * config-loader generators emit. Named once so a generator that needs a new\n * app-root file (`warlock.config`) cannot pick a different depth.\n */\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\n\n/**\n * Production Builder\n * Generates production-ready files and bundles them for deployment\n * Build options are loaded from warlock.config.ts\n */\nexport class ProductionBuilder {\n private options!: ResolvedBuildConfig;\n private readonly productionDir = warlockPath(\"production\");\n\n /**\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\n * never calls `boot()`/`start()` on them; it only\n * drains their `build` contributions.\n */\n private connectors: readonly Connector[] = [];\n\n /**\n * The contributors' merged esbuild patch, produced by the `generate` pass\n * and consumed by {@link bundle}.\n */\n private contributedEsbuild: ConnectorEsbuildPatch = {};\n\n /** Browser-safe API metadata captured in a fresh registration-only child. */\n private namedApiRoutes?: readonly import(\"../router/types\").NamedApiRoute[];\n\n /**\n * Main build entry point\n *\n * The esbuild bundle is written into a TEMP directory next to the real\n * output directory, never into it, and that directory is renamed over\n * `outdir` as one filesystem operation — so `outdir` is never observed as\n * a mix of the old build and the new one, and a build that fails before\n * that rename never touches `outdir` at all.\n *\n * `this.options.outdir` is NOT repointed at the temp directory while that\n * happens, and must never be. It is not merely a write target: consumers\n * BAKE it into runtime output — `web`'s build contribution derives the\n * `clientDir` recorded in its pages manifest from it\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\n * produces an artifact whose browser paths point at a directory promotion\n * has since renamed away. The temp path is passed explicitly, as a\n * parameter, to the one operation that writes into it ({@link bundle});\n * everything else, `buildContext()` included, keeps reading the final\n * destination.\n *\n * That is also why promotion is STAGED rather than done at the very end.\n * Connector `emit` hooks write real artifacts (the web client bundle) and\n * see the final `outdir`, so they must run when `outdir` genuinely holds\n * this build — after the rename, not before it, or promotion would replace\n * the directory they just wrote into. The previous build is kept parked\n * aside until they finish: `emit` throwing rolls the whole promotion back,\n * and the build-success marker `warlock start` checks is written last of\n * all, so a failure at any point leaves no `dist` that start will boot.\n */\n public async build(): Promise<void> {\n console.log(colors.cyan(\"Building for production...\\n\"));\n\n // Step 0: Fail fast when esbuild's native binary never got linked (the\n // state pnpm leaves a project in when its build-script approval gate\n // blocked esbuild's postinstall) rather than let bundling die on esbuild's\n // own cryptic \"package could not be found\" error several steps from now.\n assertEsbuildBinaryIsLinked();\n\n // Step 1: Initialize options from config\n await this.initializeOptions();\n\n const finalOutDir = this.options.outdir!;\n const tempOutDir = createTempOutputDir(finalOutDir);\n\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\n // presence is what tells the catch below whether a failure has a\n // promotion to undo or only a temp directory to discard.\n let staged: StagedDist | undefined;\n\n try {\n // Step 2: Generate combined files\n await this.generateCombinedFiles();\n\n // Step 3: Generate entry point\n await this.generateEntryPoint();\n\n // Step 4: Refuse to bundle code the app could not resolve at runtime\n await this.assertGeneratedImports();\n\n // Step 4.5: Drain the connectors' `generate` contributions\n await this.captureNamedApiRoutesForWeb();\n const contributed = await this.runGenerateContributions();\n\n // Step 4.6: Re-assert over what the contributors just wrote.\n //\n // Step 4 only saw core's own generated files; a contributor writes its\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\n // specifier in it reaches the bundle unchecked. Under\n // `packages: \"external\"` that specifier survives verbatim into the\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\n // and re-reading the production dir is pure cost in the common case.\n if (contributed) {\n await this.assertGeneratedImports();\n }\n\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\n // operation handed that path — it is a write target, not config.\n await this.bundle(tempOutDir);\n\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\n // build parked aside. `outdir` now holds exactly this build, so the\n // steps below write into — and record — the real destination.\n staged = await stageDistAsync(tempOutDir, finalOutDir);\n\n // Step 5.6: Drain the connectors' `emit` contributions — after the\n // bundle is in place (so what they write survives promotion and the\n // paths they bake in resolve), and BEFORE step 6 deletes the\n // production directory they may still read.\n await runEmitContributions(this.connectors, this.buildContext());\n\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\n // `warlock start` trusts. Written LAST on purpose: every earlier step\n // can still fail, and until this file exists nothing will boot what\n // they left behind.\n await writeDistBuildManifestAsync(finalOutDir);\n\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\n await commitDistAsync(staged);\n } catch (error) {\n if (staged) {\n // The promotion already happened; put the previous build back and\n // take this half-finished one out of `outdir`.\n await rollbackDistAsync(staged);\n } else {\n // Nothing this build produced ever reached `outdir` — discard the\n // temp directory and leave `outdir` exactly as it was.\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\n }\n\n throw error;\n }\n\n // Step 6: Remove production folder\n await removeDirectoryAsync(this.productionDir);\n\n console.log(colors.green(\"Build complete!\"));\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\n }\n\n /**\n * Initialize options from warlock.config.ts\n */\n private async initializeOptions(): Promise<void> {\n this.options = resolveBuildConfig();\n // Same config object `resolveBuildConfig` just read — `warlock build`\n // preloads warlock.config.ts, so no additional load happens here.\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\n\n // Checked here, where the array is first read, so nothing downstream has\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\n // a name listed twice would write its files and merge its esbuild options\n // twice into an artifact the runtime then boots that name only once from.\n // A build that half-applied a connector and reported success is worse than\n // one that never started.\n assertUniqueConnectorNames([...connectors]);\n\n // And here rather than only at boot, for the same reason: a name a built-in\n // already owns is skipped by the runtime, so an artifact built from it\n // carries the custom connector's generated files and esbuild patches while\n // the server boots the built-in instead. Refusing it at boot alone would\n // mean the build had already emitted that artifact — the failure has to\n // land on the developer running `warlock build`, not on whoever starts the\n // server. Same assertion the registration half calls, over the same names.\n assertNoReservedConnectorNames([...connectors]);\n\n this.connectors = connectors;\n\n // Ensure production directory exists\n await ensureDirectoryAsync(this.productionDir);\n }\n\n /**\n * The context handed to every build contribution.\n */\n private buildContext(): ConnectorBuildContext {\n return {\n productionDir: this.productionDir,\n appRoot: rootPath(),\n options: this.options,\n namedApiRoutes: this.namedApiRoutes,\n };\n }\n\n /**\n * Web route declarations need application API registration, which cannot be\n * inferred from generated files. Capture it once in a disposable child before\n * contributors write build artifacts; no connector lifecycle runs there.\n */\n private async captureNamedApiRoutesForWeb(): Promise<void> {\n if (!this.connectors.some((connector) => connector.name === \"web\")) {\n await clearOwnedRouteTypes(rootPath());\n return;\n }\n\n this.namedApiRoutes = (\n await collectRouteRegistrationSnapshot({\n cwd: rootPath(),\n timeoutMs: this.options.routeRegistrationTimeoutMs,\n })\n ).routes;\n }\n\n /**\n * Drain the `generate` hooks and fold what they returned back into the\n * build.\n *\n * The entry point is REGENERATED here rather than generated later. The\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\n * bundles that the app could not resolve) and before `bundle` — while\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\n * generated code the assertion has to see; moving it past the assertion\n * would silently drop the entry from that check. Rewriting one small file\n * is cheaper than losing either guarantee, and the write is pure\n * (`generatedFiles` + these imports), so doing it twice is not a\n * correctness risk.\n *\n * @returns whether any connector ran a `generate` hook — the caller uses it\n * to decide if the import assertion is worth a second pass. Keyed on the\n * hook EXISTING, not on what it returned: a hook that returns nothing may\n * still have written files into `productionDir`, and those are exactly the\n * files the second pass is there to read.\n */\n private async runGenerateContributions(): Promise<boolean> {\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\n\n const { entryImports, esbuild } = await runGenerateContributions(\n this.connectors,\n this.buildContext(),\n );\n\n this.contributedEsbuild = esbuild;\n\n if (entryImports.length > 0) {\n await this.generateEntryPoint(entryImports);\n }\n\n return contributed;\n }\n\n /**\n * Track which special files were generated\n */\n private generatedFiles = {\n locales: false,\n events: false,\n main: false,\n routes: false,\n workers: false,\n };\n\n /**\n * Generate all combined files\n */\n private async generateCombinedFiles(): Promise<void> {\n console.log(colors.yellow(\" Generating production files...\"));\n\n // Generate bootstrap.ts file\n await this.generateBootstrap();\n\n // Generate config loader\n await this.generateConfigLoader();\n\n // Generate special files and track which ones have content\n const [locales, events, main, routes, workers] = await Promise.all([\n this.generateLocales(),\n this.generateEvents(),\n this.generateMain(),\n this.generateRoutes(),\n this.generateWorkers(),\n ]);\n\n this.generatedFiles = { locales, events, main, routes, workers };\n }\n\n /**\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\n */\n private async generateBootstrap(): Promise<void> {\n // ESM hoists imports, so the app bootstrap must be the first import to run first\n const appBootstrapImport = (await fileExistsAsync(appPath(\"bootstrap.ts\")))\n ? \"import './../../src/app/bootstrap';\\n\"\n : \"\";\n\n const content = `${appBootstrapImport}import { bootstrap, Application } from \"@warlock.js/core\";\n\n// Production runtime; NODE_ENV is only defaulted so an explicit value (e.g. staging) wins\nApplication.setRuntimeStrategy(\"production\");\nif (!process.env.NODE_ENV) {\n Application.setEnvironment(\"production\");\n}\n\n// Bootstrap the application\nbootstrap();\n`;\n\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\n }\n\n /**\n * Fail the build when generated code imports a package the app does not\n * declare.\n *\n * The bundler is configured `packages: \"external\"`, so every bare specifier\n * written above survives verbatim into an artifact that resolves against the\n * **consuming app's** node_modules. A framework-internal dependency imported\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\n * which is how a production app shipped that could not boot. Rewriting the\n * offending import fixes today's bundle; this check is what stops the next\n * change to the generator from quietly reintroducing it.\n */\n private async assertGeneratedImports(): Promise<void> {\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\n cwd: this.productionDir,\n absolute: false,\n });\n\n const [files, appPackage] = await Promise.all([\n Promise.all(\n generatedPaths.map(async (file) => ({\n file,\n content: await getFileAsync(path.join(this.productionDir, file)),\n })),\n ),\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\n ]);\n\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\n }\n\n /**\n * Glob `src/app` and keep the files the shared dev-server predicate accepts,\n * so production discovers exactly what the dev collector does.\n * Returns relative paths from .warlock/production/ to src/app/\n */\n private async globModule(matches: (relativePath: string) => boolean): Promise<string[]> {\n const files = await glob(\"**/*.{ts,tsx,json}\", {\n cwd: appPath(),\n absolute: false,\n });\n\n // e.g., \"users/main.ts\" -> \"../../src/app/users/main\"\n return files\n .filter((file) => matches(\"src/app/\" + file))\n .sort()\n .map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\n }\n\n /**\n * Generate config-loader.ts\n */\n private async generateConfigLoader(): Promise<void> {\n const configDirectory = path.join(process.cwd(), \"src/config\");\n\n const files = await glob(\"**/*.{ts,tsx}\", {\n cwd: configDirectory,\n absolute: false,\n });\n\n // Same key rule as the dev config loader: the raw path, never camel-cased\n const configNames = files\n .filter((f) => isConfigFile(\"src/config/\" + f))\n .map((f) => ({\n path: f.replace(/\\.(ts|tsx)$/, \"\"),\n key: configKeyFromPath(\"src/config/\" + f),\n }))\n .filter((entry): entry is { path: string; key: string } => entry.key !== undefined)\n .sort((a, b) => a.path.localeCompare(b.path));\n\n // Only `@warlock.js/core` — the one package the app itself declares. See\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\n // dependency, so a bare import of it resolved by luck under npm/yarn\n // hoisting and died under pnpm's strict layout.\n const imports: string[] = [\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\n ];\n const configImports: string[] = [];\n const configSetCalls: string[] = [];\n const executors: string[] = [];\n\n configNames.forEach(({ path: configPath, key }, index) => {\n // Index-based identifier: keys like \"rate-limit\" or \"mail/smtp\" are not valid names\n const varName = `config${index}`;\n configImports.push(`import ${varName} from \"../../src/config/${configPath}\";`);\n configSetCalls.push(`setConfig(${JSON.stringify(key)}, ${varName});`);\n executors.push(`await configSpecialHandlers.execute(${JSON.stringify(key)}, ${varName});`);\n });\n\n // ESM hoists imports, so prestart must be the first import to run first\n const prestartImports = (await fileExistsAsync(appPath(\"prestart.ts\")))\n ? [\"import './../../src/app/prestart';\"]\n : [];\n\n const content = [\n ...prestartImports,\n ...imports,\n \"\",\n \"// Config imports\",\n ...configImports,\n \"\",\n \"// Register configs\",\n ...configSetCalls,\n \"\",\n \"// Special handlers\",\n ...executors,\n \"\",\n ].join(\"\\n\");\n\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\n }\n\n /**\n * Generate locales.ts (only if there are locale files)\n * @returns true if file was generated with content\n */\n private async generateLocales(): Promise<boolean> {\n const files = await this.globModule(isLocaleFile);\n if (files.length === 0) return false;\n const content = files\n .map((file, index) => {\n if (!file.endsWith(\".json\")) return `import \"${file}\";`;\n const moduleFolder = file.split(\"/\").at(-3)!;\n return [\n `import dictionary${index} from \"${file}\";`,\n 'import { registerLocaleDictionary } from \"@warlock.js/core\";',\n `registerLocaleDictionary({ sourceFile: ${JSON.stringify(file)}, source: JSON.stringify(dictionary${index}), defaultNamespace: ${JSON.stringify(moduleFolder)} });`,\n ].join(\"\\n\");\n })\n .join(\"\\n\");\n await putFileAsync(path.join(this.productionDir, \"locales.ts\"), content + \"\\n\");\n return true;\n }\n\n /**\n * Generate events.ts (only if there are event files)\n * @returns true if file was generated with content\n */\n private async generateEvents(): Promise<boolean> {\n const files = await this.globModule(isEventFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"events.ts\");\n return true;\n }\n\n /**\n * Generate main.ts (only if there are main files)\n * @returns true if file was generated with content\n */\n private async generateMain(): Promise<boolean> {\n const files = await this.globModule(isMainFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"main.ts\");\n return true;\n }\n\n /**\n * Generate routes.ts (only if there are route files)\n * @returns true if file was generated with content\n */\n private async generateRoutes(): Promise<boolean> {\n const files = await this.globModule(isRouteFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"routes.ts\");\n return true;\n }\n\n /**\n * Generate workers.ts (only if there are worker files)\n * @returns true if file was generated with content\n */\n private async generateWorkers(): Promise<boolean> {\n const files = await this.globModule(isWorkerFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"workers.ts\");\n return true;\n }\n\n /**\n * Generate a file with imports from all given files\n */\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, outputFile), content);\n }\n\n /**\n * Generate the main entry point (app.ts)\n *\n * @param contributedImports lines from connector `generate` hooks, appended\n * to section 4 after `./routes`\n */\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\n console.log(colors.yellow(\" Generating entry point...\"));\n\n // The names this build resolved, baked in as a literal. The entry imports\n // the config source, and that source is re-evaluated at startup — an\n // env-conditional `connectors` array can hand the boot a different list\n // than the one drained here. A literal is the only part of the array that\n // survives into the artifact unchanged, so it is what the boot compares\n // against.\n const expectedNames = this.connectors\n .map((connector) => JSON.stringify(connector.name))\n .join(\", \");\n\n // Build imports based on which files were generated\n const imports: string[] = [\n \"// 1. Bootstrap (loads .env, initializes framework)\",\n 'import \"./bootstrap\";',\n \"\",\n \"// 2. Load configs\",\n 'import \"./config-loader\";',\n \"\",\n // Registration has to sit between the config being available and the\n // first phase starting: the connectors listed in `connectors` are the\n // same ones this build drained contributions from, so the bundle boots\n // exactly what it was built for. Register any later and an early-phase\n // connector would miss its own start.\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\n \"// build read its contributions from, so built-for and boots-with match).\",\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\n \"// and the array is handed over explicitly — an artifact has no\",\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\n \"// that quietly found nothing to register is the exact drift this\",\n \"// section exists to prevent.\",\n \"// `expectedNames` is the list this build resolved, in order — boot\",\n \"// refuses to start when the config hands over a different set or order.\",\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\n \"\",\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\n \"// own preflight is not reached until the database and cache have\",\n \"// connected and every app module has been imported — seconds of work\",\n \"// thrown away before anyone learns the port was taken. This probe is\",\n \"// a bind-and-release on a socket that is never served, and it reports\",\n \"// on stderr because no log channel is configured this early.\",\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\n 'if (Application.hasRole(\"api\") || Application.hasRole(\"web\")) {',\n \" await preflightConfiguredHttpPort();\",\n \"}\",\n \"\",\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\n \"// so data sources, cache, etc. are ready before app code runs\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\n ];\n\n // App code uses dynamic `await import(...)` so each module's side\n // effects fire at THIS point in execution. Static imports would be\n // hoisted to module-instantiation time (before the early-phase await\n // resolves), which is exactly the bug this split is meant to fix.\n //\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\n // it at the await, not at instantiation. It does NOT come from\n // `splitting: true`, which only decides one-file-vs-chunks. This\n // previously said splitting was required; it is not, and `singleBundle`\n // (splitting: false) preserves the ordering.\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\n\n if (this.generatedFiles.events) {\n imports.push('await import(\"./events\");');\n }\n if (this.generatedFiles.locales) {\n imports.push('await import(\"./locales\");');\n }\n if (this.generatedFiles.main) {\n imports.push('await import(\"./main\");');\n }\n if (this.generatedFiles.routes) {\n imports.push('if (Application.hasRole(\"api\")) {', ' await import(\"./routes\");', \"}\");\n }\n if (this.generatedFiles.workers) {\n imports.push('if (Application.hasRole(\"worker\")) {', ' await import(\"./workers\");', \"}\");\n }\n\n // Contributor imports come AFTER `./routes`, never before: a connector\n // that registers pages needs the routes app code already collected —\n // the same ordering dev uses (routes first, then the connector installs\n // on top of them). Emitted verbatim; the contributor writes the whole\n // statement (e.g. `await import(\"./pages\");`).\n imports.push(...contributedImports);\n\n // A rejecting validator (Application.onValidateBoot) must abort boot\n // before late-phase connectors bind a port.\n imports.push(\n \"\",\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\n \"await Application.runStartupValidators();\",\n );\n\n // Start late-phase connectors after app code registers routes/listeners\n imports.push(\n \"\",\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\n \"// listeners registered by app code are now ready to bind\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\n \"\",\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\n \"connectorsManager.shutdownOnProcessKill();\",\n );\n\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\n }\n\n /**\n * Bundle with esbuild\n *\n * @param writeOutDir the directory esbuild writes into — the build's\n * private temp directory, NOT `options.outdir`. Taken as a parameter\n * rather than read off `this.options` because the two are different paths\n * with different meanings: `options.outdir` is the final destination every\n * consumer bakes into the artifact, and this is only where bytes land\n * before promotion moves them there.\n */\n private async bundle(writeOutDir: string): Promise<void> {\n console.log(colors.magenta(\" Bundling with esbuild...\"));\n\n const entryPoint = path.join(this.productionDir, \"app.ts\");\n const outFileName = this.options.outFile!;\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\n const entryName = path.basename(outFileName, path.extname(outFileName));\n\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\n // unknown keys, and the user options are spread into its call verbatim.\n const singleBundle = this.options.singleBundle === true;\n const esmShim = this.options.esmShim !== false;\n // Read before deleting: the merged banner is applied AFTER the user\n // spread, so a user banner must not be lost to it or clobber the shim.\n const userBanner = this.options.banner;\n\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\n // resolve-build-config.ts documents that widening them pushed a lie downstream\n // into start-production.command.ts, which then could not trust its own config.\n // This is the one place they must be absent - the object is spread into esbuild's\n // call verbatim and esbuild throws on unknown keys.\n //\n // Stripped off a LOCAL COPY of `this.options`, never off `this.options`\n // itself: `buildContext()` hands `this.options` to every `generate`/`emit`\n // contribution hook, including the `emit` pass that runs AFTER this method\n // returns (`build()` step 5.6). Deleting these keys from the shared object\n // used to leave those hooks reading `undefined` for `outFile`, `entryPath`,\n // `singleBundle`, `esmShim` and `banner` even though `ConnectorBuildContext`\n // types them as present. A shallow copy is enough — every field this method\n // reads off it is either scalar or already re-merged below (`define`,\n // `external`, `loader`, `banner`), so nothing here needs a deep clone.\n const esbuildOptions: Partial<ResolvedBuildConfig> = { ...this.options };\n\n delete esbuildOptions.outFile;\n delete esbuildOptions.entryPath;\n delete esbuildOptions.singleBundle;\n delete esbuildOptions.esmShim;\n delete esbuildOptions.banner;\n delete esbuildOptions.routeRegistrationTimeoutMs;\n\n await ensureDirectoryAsync(writeOutDir);\n\n const alias = this.buildAliasMapFromTsconfig();\n\n // Whether this build decides externality per import EDGE\n // (`bundle-framework-dependencies.ts`, which explains the rule at\n // length) or keeps the blunt `packages: \"external\"`.\n //\n // Not in `singleBundle` mode: that bundles everything by definition, and\n // a plugin that can only ever ADD an external would silently narrow it.\n // Not when the user set `packages` themselves: their value has always\n // won over the default below, and it must keep winning — the plugin is\n // the default's implementation, not a new policy layered on top.\n const perEdgeExternals = !singleBundle && (esbuildOptions as any).packages === undefined;\n\n // The user can override `format`, so gate the shim on the EFFECTIVE\n // format rather than on the default below. A CJS build already has\n // `require` and friends; injecting them there would be a redefinition.\n const isEsm = (esbuildOptions.format ?? \"esm\") === \"esm\";\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\n\n // Contributor patch, split into the part that can ride the spread order\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\n // BEFORE the user spread below, which gives the ruled precedence for\n // free: builder defaults < contributor < user config.\n //\n // `define`, `external` and `loader` are pulled out because a spread\n // REPLACES them wholesale — the same trap `banner` documents. Two\n // contributors' env defines, a contributor's optional peers plus the\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\n // must both survive, so they are merged by key/by set and re-applied\n // after the spread with the user still winning per key.\n const {\n define: contributedDefine,\n external: contributedExternal,\n loader: contributedLoader,\n plugins: contributedPlugins,\n ...contributedOptions\n } = this.contributedEsbuild;\n\n const userDefine: Record<string, string> | undefined = esbuildOptions.define;\n const userExternal: string[] | undefined = esbuildOptions.external;\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = esbuildOptions.loader;\n\n const define =\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\n\n const loader =\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\n\n const external =\n contributedExternal || userExternal\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\n : undefined;\n\n if (singleBundle) {\n console.log(\n colors.magenta(\n \" Single-bundle mode — one JS file\" +\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\n \". Native .node addons are still emitted alongside it.\",\n ),\n );\n }\n\n try {\n await esbuild.build({\n platform: \"node\",\n entryPoints: [entryPoint],\n bundle: true,\n // Both are DEFAULTS the user can override — they sit before the\n // `...esbuildOptions` spread deliberately. `singleBundle` moves them,\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\n //\n // Phase ordering does not depend on `splitting`: it comes from the\n // generated app.ts using dynamic `await import(...)` (see\n // generateAppEntry above), which esbuild defers to the call site in\n // either mode. Splitting only decides one file vs chunks.\n splitting: !singleBundle,\n // `\"bundle\"` under `perEdgeExternals` is not \"bundle everything\":\n // the plugin below returns `external: true` for every bare specifier\n // this build must not bundle, which is all of them bar the framework's\n // own declared dependencies. Saying `\"external\"` here instead would\n // externalise them before the plugin could rule.\n packages: singleBundle || perEdgeExternals ? \"bundle\" : \"external\",\n minify: esbuildOptions.minify,\n sourcemap: esbuildOptions.sourcemap === true ? \"linked\" : esbuildOptions.sourcemap,\n format: \"esm\",\n // Targeting a concrete Node version (not \"esnext\") so esbuild\n // transpiles TC39 stage 3 decorators into helpers — Node does not\n // implement them natively yet.\n target: [\"node22\"],\n entryNames: entryName,\n alias,\n plugins: [\n nativeNodeModulesPlugin,\n // BEFORE the framework-dependency plugin, and the order is\n // load-bearing: the first `onResolve` callback to answer wins, and\n // `app/users/...` is a bare specifier the other one would rule\n // external.\n tsconfigPathAliases(this.tsconfigPathAliasConfig()),\n ...(perEdgeExternals\n ? [bundleFrameworkDependencies({ appRoot: rootPath(), aliasKeys: Object.keys(alias) })]\n : []),\n // Contributor plugins run last: they load their own file types and\n // must not shadow the resolvers above.\n ...(contributedPlugins ?? []),\n ],\n // Between the defaults and the user spread — the ruled precedence.\n ...contributedOptions,\n ...(esbuildOptions as any),\n // AFTER the spread, and NOT overridable: `esbuildOptions.outdir` rides\n // that spread carrying the FINAL destination, which is exactly where\n // this build must not write yet. The final path is the user's setting\n // and stays authoritative for everyone reading the config — it is only\n // this one esbuild call that is redirected, and only until promotion\n // moves the result onto that very path.\n outdir: writeOutDir,\n // AFTER the spread for the same reason `banner` is: a spread replaces\n // these objects instead of merging them, so the merged values are\n // re-applied here. The user still wins — they were merged in last.\n ...(define ? { define } : {}),\n ...(external ? { external } : {}),\n ...(loader ? { loader } : {}),\n // AFTER the spread, and intentionally so: `banner` is an object, and\n // both the config merge and this spread REPLACE it wholesale rather\n // than merging. Left as a default above, any user banner would delete\n // the shim; left to the spread, the shim would delete theirs. The\n // merge is the only form that keeps both.\n ...(banner ? { banner } : {}),\n });\n } catch (e) {\n console.log(e);\n throw e;\n }\n }\n\n /**\n * The WILDCARD half of the same tsconfig `paths` map that\n * {@link ProductionBuilder.buildAliasMapFromTsconfig} reads the exact half\n * of. `tsconfig-path-aliases.ts` explains why the two halves need different\n * mechanisms — in short, esbuild's `alias` option cannot express a wildcard,\n * so the entries it skips have to be resolved by a plugin instead of being\n * left to no one.\n */\n private tsconfigPathAliasConfig(): { baseUrl: string; paths: Record<string, string[]> } {\n tsconfigManager.init();\n\n return {\n baseUrl: path.resolve(process.cwd(), tsconfigManager.baseUrl),\n paths: tsconfigManager.aliases as Record<string, string[]>,\n };\n }\n\n /**\n * Build an alias map from tsconfig `paths` so esbuild resolves local\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\n * folders during bundling. Without this, `packages: \"external\"` would\n * leave those bare specifiers as raw imports and Node would fail to\n * resolve them at runtime (they aren't installed in node_modules).\n *\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\n * option doesn't support glob-style mappings. The wildcard half is not\n * dropped, it is handled elsewhere: see\n * {@link ProductionBuilder.tsconfigPathAliasConfig}.\n */\n private buildAliasMapFromTsconfig(): Record<string, string> {\n tsconfigManager.init();\n\n const alias: Record<string, string> = {};\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\n\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\n continue;\n }\n\n const target = to[0];\n\n if (target === undefined) {\n continue;\n }\n\n alias[from] = path.resolve(baseUrl, target);\n }\n\n return alias;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,mBACJ;;;;;;;;;;;;;;AAoBF,SAAS,YACP,YACA,MACoC;CACpC,IAAI,CAAC,MAAM,OAAO;CAElB,MAAM,SAAS,YAAY;CAE3B,OAAO;EACL,GAAG;EACH,IAAI,SAAS,GAAG,OAAO,WAAW;CACpC;AACF;;;;;;;;;;AAWA,MAAM,+BAA+B;;;;;;AAOrC,IAAa,oBAAb,MAA+B;;uBAEI,YAAY,YAAY;oBAOd,CAAC;4BAMQ,CAAC;wBAoO5B;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;GACR,SAAS;EACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAxMA,MAAa,QAAuB;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Q,gBAAgB,OAAO,GAAG;GAChE,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG,WAAW,GAC7D;GAGF,MAAM,SAAS,GAAG;GAElB,IAAI,WAAW,QACb;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,MAAM;EAC5C;EAEA,OAAO;CACT;AACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { BOOT_SIGNAL_ENV_KEY, isBootSignal } from "../application/boot-signal.mjs";
|
|
2
2
|
import { displayMissingReadinessNotice, displayProductionReadyBanner, displayProductionStartFailure } from "../cli/cli-commands.utils.mjs";
|
|
3
|
+
import { colors } from "@mongez/copper";
|
|
3
4
|
import { spawn } from "child_process";
|
|
4
5
|
|
|
5
6
|
//#region ../core/src/production/production-supervisor.ts
|
|
@@ -80,6 +81,11 @@ function superviseProductionProcess({ nodeArgs, cwd = process.cwd(), env = proce
|
|
|
80
81
|
displayProductionReadyBanner({ bootDurationMs: message.bootDurationMs }).catch((error) => {
|
|
81
82
|
console.error(error);
|
|
82
83
|
});
|
|
84
|
+
const roles = message.roles ?? [];
|
|
85
|
+
if (roles.length > 0) {
|
|
86
|
+
const summary = roles.includes("api") || roles.includes("web") ? `roles: ${roles.join(", ")}` : `worker ready — roles: ${roles.join(", ")}`;
|
|
87
|
+
console.log(` ${colors.dim(summary)}`);
|
|
88
|
+
}
|
|
83
89
|
});
|
|
84
90
|
child.on("error", (error) => {
|
|
85
91
|
console.error(error);
|