@warlock.js/core 5.33.0 → 5.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/CHANGELOG.md +36 -46
  2. package/esm/cli/commands/check/check-command.action.mjs +2 -1
  3. package/esm/cli/commands/check/check-command.action.mjs.map +1 -1
  4. package/esm/cli/commands/check.command.mjs +2 -2
  5. package/esm/cli/commands/check.command.mjs.map +1 -1
  6. package/esm/cli/commands/e2e.command.mjs +63 -0
  7. package/esm/cli/commands/e2e.command.mjs.map +1 -0
  8. package/esm/cli/commands/load-e2e-spec.mjs +47 -0
  9. package/esm/cli/commands/load-e2e-spec.mjs.map +1 -0
  10. package/esm/cli/framework-cli-commands.mjs +2 -0
  11. package/esm/cli/framework-cli-commands.mjs.map +1 -1
  12. package/esm/dev-server/health-checker/checkers/oxlint-health-checker.mjs +1 -1
  13. package/esm/dev-server/health-checker/default-health-checkers.mjs +1 -6
  14. package/esm/dev-server/health-checker/default-health-checkers.mjs.map +1 -1
  15. package/esm/dev-server/health-checker/file-health-checker.contract.d.mts +0 -2
  16. package/esm/dev-server/health-checker/file-health-checker.contract.d.mts.map +1 -1
  17. package/esm/dev-server/health-checker/file-health-result.d.mts +1 -1
  18. package/esm/dev-server/health-checker/file-health-result.mjs.map +1 -1
  19. package/esm/e2e/browser.d.mts +4 -0
  20. package/esm/e2e/browser.d.mts.map +1 -0
  21. package/esm/e2e/browser.mjs +88 -0
  22. package/esm/e2e/browser.mjs.map +1 -0
  23. package/esm/e2e/cdp.d.mts +152 -0
  24. package/esm/e2e/cdp.d.mts.map +1 -0
  25. package/esm/e2e/cdp.mjs +106 -0
  26. package/esm/e2e/cdp.mjs.map +1 -0
  27. package/esm/e2e/fixture.mjs +195 -0
  28. package/esm/e2e/fixture.mjs.map +1 -0
  29. package/esm/e2e/index.d.mts +5 -0
  30. package/esm/e2e/index.mjs +6 -0
  31. package/esm/e2e/owned-process.mjs +193 -0
  32. package/esm/e2e/owned-process.mjs.map +1 -0
  33. package/esm/e2e/page.d.mts +64 -0
  34. package/esm/e2e/page.d.mts.map +1 -0
  35. package/esm/e2e/page.mjs +376 -0
  36. package/esm/e2e/page.mjs.map +1 -0
  37. package/esm/e2e/run-e2e.d.mts +17 -0
  38. package/esm/e2e/run-e2e.d.mts.map +1 -0
  39. package/esm/e2e/run-e2e.mjs +143 -0
  40. package/esm/e2e/run-e2e.mjs.map +1 -0
  41. package/esm/e2e/types.d.mts +123 -0
  42. package/esm/e2e/types.d.mts.map +1 -0
  43. package/esm/e2e/types.mjs +24 -0
  44. package/esm/e2e/types.mjs.map +1 -0
  45. package/esm/generations/features/web.feature.mjs +7 -4
  46. package/esm/generations/features/web.feature.mjs.map +1 -1
  47. package/esm/generations/stubs.mjs +18 -35
  48. package/esm/generations/stubs.mjs.map +1 -1
  49. package/esm/index.d.mts +2 -2
  50. package/esm/secrets/errors.d.mts +1 -1
  51. package/esm/secrets/errors.d.mts.map +1 -1
  52. package/esm/secrets/errors.mjs +2 -0
  53. package/esm/secrets/errors.mjs.map +1 -1
  54. package/esm/secrets/file-backend.mjs +1 -0
  55. package/esm/secrets/file-backend.mjs.map +1 -1
  56. package/esm/secrets/index.d.mts +2 -2
  57. package/esm/secrets/keyring-backend.mjs +1 -0
  58. package/esm/secrets/keyring-backend.mjs.map +1 -1
  59. package/esm/secrets/memory-backend.d.mts +1 -0
  60. package/esm/secrets/memory-backend.d.mts.map +1 -1
  61. package/esm/secrets/memory-backend.mjs +1 -0
  62. package/esm/secrets/memory-backend.mjs.map +1 -1
  63. package/esm/secrets/resolve-driver.mjs +14 -0
  64. package/esm/secrets/resolve-driver.mjs.map +1 -0
  65. package/esm/secrets/secret-store.d.mts +4 -2
  66. package/esm/secrets/secret-store.d.mts.map +1 -1
  67. package/esm/secrets/secret-store.mjs +22 -8
  68. package/esm/secrets/secret-store.mjs.map +1 -1
  69. package/esm/secrets/secrets.d.mts +2 -0
  70. package/esm/secrets/secrets.d.mts.map +1 -1
  71. package/esm/secrets/secrets.mjs +13 -1
  72. package/esm/secrets/secrets.mjs.map +1 -1
  73. package/esm/secrets/types.d.mts +8 -0
  74. package/esm/secrets/types.d.mts.map +1 -1
  75. package/esm/tooling/check/lint-step.d.mts +3 -3
  76. package/esm/tooling/check/lint-step.d.mts.map +1 -1
  77. package/esm/tooling/check/lint-step.mjs +3 -47
  78. package/esm/tooling/check/lint-step.mjs.map +1 -1
  79. package/esm/tooling/check/run-check.d.mts +2 -2
  80. package/esm/tooling/check/run-check.mjs +4 -2
  81. package/esm/tooling/check/run-check.mjs.map +1 -1
  82. package/esm/tooling/problem.d.mts +1 -1
  83. package/esm/tooling/problem.d.mts.map +1 -1
  84. package/esm/tooling/problem.mjs.map +1 -1
  85. package/esm/updater/package-manager.mjs +5 -1
  86. package/esm/updater/package-manager.mjs.map +1 -1
  87. package/esm/upgrade/codemods/index.mjs +2 -1
  88. package/esm/upgrade/codemods/index.mjs.map +1 -1
  89. package/esm/upgrade/codemods/oxc-toolchain.mjs +59 -10
  90. package/esm/upgrade/codemods/oxc-toolchain.mjs.map +1 -1
  91. package/esm/upgrade/codemods/oxlint-rule-schemas.mjs +6 -0
  92. package/esm/upgrade/codemods/oxlint-rule-schemas.mjs.map +1 -0
  93. package/esm/upgrade/codemods/port-eslint-rules.mjs +343 -0
  94. package/esm/upgrade/codemods/port-eslint-rules.mjs.map +1 -0
  95. package/esm/upgrade/codemods/toolchain-templates.mjs +1 -1
  96. package/esm/upgrade/codemods/toolchain-templates.mjs.map +1 -1
  97. package/esm/upgrade/codemods/validate-oxlint-rule.mjs +60 -0
  98. package/esm/upgrade/codemods/validate-oxlint-rule.mjs.map +1 -0
  99. package/esm/upgrade/notes.mjs +14 -7
  100. package/esm/upgrade/notes.mjs.map +1 -1
  101. package/esm/warlock-config/types.d.mts +0 -1
  102. package/esm/warlock-config/types.d.mts.map +1 -1
  103. package/llms-full.txt +269 -44
  104. package/llms.txt +4 -3
  105. package/package.json +19 -20
  106. package/skills/create-module/SKILL.md +2 -2
  107. package/skills/run-app/SKILL.md +3 -3
  108. package/skills/store-secrets/SKILL.md +60 -2
  109. package/skills/test-browser/SKILL.md +119 -0
  110. package/skills/upgrade-from-5-29/SKILL.md +70 -29
  111. package/skills/warlock-check/SKILL.md +3 -3
  112. package/skills/warlock-doctor/SKILL.md +2 -3
  113. package/skills/write-cli-command/SKILL.md +6 -2
  114. package/esm/dev-server/health-checker/checkers/eslint-health-checker.mjs +0 -152
  115. package/esm/dev-server/health-checker/checkers/eslint-health-checker.mjs.map +0 -1
  116. package/esm/dev-server/health-checker/eslint-support.mjs +0 -27
  117. package/esm/dev-server/health-checker/eslint-support.mjs.map +0 -1
  118. package/esm/dev-server/health-checker/workers/eslint-health.worker.d.mts +0 -1
  119. package/esm/dev-server/health-checker/workers/eslint-health.worker.mjs +0 -183
  120. package/esm/dev-server/health-checker/workers/eslint-health.worker.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"stubs.mjs","names":[],"sources":["../../../../../../../../packages/core/src/generations/stubs.ts"],"sourcesContent":["export const accessConfigStub = `import { type AccessConfigurations } from \"@warlock.js/access\";\nimport { DatabaseAccessResolver } from \"app/access/services/access-resolver\";\n\n/**\n * Authorization configuration — read by @warlock.js/access on boot.\n *\n * The resolver is the one required piece: it tells the engine how to read a\n * user's roles + permissions. The ejected DatabaseAccessResolver reads roles\n * from the user_roles table and maps them through the roles catalog table (so\n * roles + their permissions are managed at runtime, in the DB).\n *\n * For a fixed, code-defined catalog with no tables, swap in DefaultAccessResolver:\n * import { DefaultAccessResolver } from \"@warlock.js/access\";\n * resolver: new DefaultAccessResolver({ admin: [\"*\"], editor: [\"orders.*\"] }),\n *\n * Multi-tenant? Add a \\`resolveTenant()\\` to the resolver to read the active\n * tenant from the request; checks then scope to it automatically.\n */\nconst access: AccessConfigurations = {\n resolver: new DatabaseAccessResolver(),\n\n // Cache resolved permission sets (default \"10m\").\n // cache: { ttl: \"10m\" },\n};\n\nexport default access;\n`;\n\nexport const aiConfigStub = `import type { AIConfig } from \"@warlock.js/ai\";\n\n// >>> warlock:ai-packages (auto-managed) >>>\n// Satellite packages augment the \"ai\" object on import — e.g. ai.workspace,\n// ai.tools / ai.mcp, and panoptic's ai.config({ panoptic }) wiring. The command\n// \"warlock add ai-workspace | ai-tools | ai-panoptic\" adds the matching\n// side-effect import below; keep them so the augmentation + runtime registration\n// load before the ai connector applies this config.\n// <<< warlock:ai-packages <<<\n\n/**\n * AI configuration — applied on boot by the ai connector, which calls\n * ai.config(...) with the object below. Cross-cutting defaults live here\n * (shared cache / snapshot stores, observability); per-call options always win.\n *\n * Wire a default model from a provider you installed, e.g.:\n * import { OpenAISDK } from \"@warlock.js/ai-openai\";\n * const openai = OpenAISDK({ apiKey: env(\"OPENAI_API_KEY\") });\n * // then pass openai.model({ name: \"gpt-4o-mini\" }) into your agents.\n */\nconst ai: Partial<AIConfig> = {\n // Default cache driver for cache-backed AI features (semantic cache, rag / memory vector stores).\n // defaultStore: cache.driver(\"redis\", { client }),\n\n // Observability — requires \"warlock add ai-panoptic\". Exporters + the local dashboard.\n // panoptic: { exporters: [], dashboard: false, observeAll: false },\n};\n\nexport default ai;\n`;\n\nexport const accessRoleModelStub = `import { Model, RegisterModel } from \"@warlock.js/cascade\";\nimport { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Validation schema for the roles catalog — mirrors the migration columns\n * (snake_case). Each row is a role name plus the permission strings it grants;\n * wildcards work (\"orders.*\", \"*\"). The DatabaseAccessResolver maps a user's\n * assigned role names through this table to their effective permissions.\n */\nexport const roleSchema = v.object({\n name: v.string(),\n permissions: v.array(v.string()).default([]),\n});\n\nexport type RoleSchema = Infer<typeof roleSchema>;\n\n/**\n * The roles catalog — role name → the permissions it grants. Managed at runtime\n * (admins add roles + edit their permissions), unlike a fixed code map. Read by\n * DatabaseAccessResolver.resolvePermissions to expand a user's roles to permissions.\n */\n@RegisterModel()\nexport class Role extends Model<RoleSchema> {\n public static table = \"roles\";\n\n public static schema = roleSchema;\n\n /** The permission strings this role grants. */\n public get permissions(): string[] {\n return this.get<string[]>(\"permissions\", []);\n }\n}\n`;\n\nexport const accessRoleModelIndexStub = `export * from \"./role.model\";\n`;\n\nexport const accessRoleMigrationStub = `import { arrayText, Migration, text } from \"@warlock.js/cascade\";\nimport { Role } from \"../role.model\";\n\n/**\n * Roles catalog table. \\`name\\` is unique (one row per role); \\`permissions\\` is a\n * text array of the permission strings the role grants.\n */\nexport default Migration.create(Role, {\n name: text().notNullable().unique(),\n permissions: arrayText().nullable(),\n});\n`;\n\nexport const accessUserRoleModelStub = `import { access } from \"@warlock.js/access\";\nimport type { Auth } from \"@warlock.js/auth\";\nimport { Model, RegisterModel } from \"@warlock.js/cascade\";\nimport { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Validation schema for a role assignment — mirrors the migration columns\n * (snake_case). \\`tenant\\` is nullable: a null tenant is a GLOBAL assignment.\n */\nexport const userRoleSchema = v.object({\n user_id: v.string(),\n user_type: v.string(),\n role: v.string(),\n tenant: v.string().optional(),\n});\n\nexport type UserRoleSchema = Infer<typeof userRoleSchema>;\n\n/**\n * The role-assignment table — which roles a user holds, optionally per tenant.\n * Read by DatabaseAccessResolver.resolveRoles; mutated via the statics below.\n * \\`assign\\` / \\`revoke\\` flush the cached permission set automatically, so callers\n * never need to call \\`access.flush(user, tenant)\\` themselves.\n */\n@RegisterModel()\nexport class UserRole extends Model<UserRoleSchema> {\n public static table = \"user_roles\";\n\n public static schema = userRoleSchema;\n\n /**\n * Role names assigned to the user in the given tenant.\n *\n * An unresolved tenant (\\`undefined\\`) scopes to GLOBAL roles only — the rows\n * stored with no tenant (\\`null\\`) — never the union across every tenant. The\n * union would be a privilege-escalation: a user who is \\`owner\\` in one tenant\n * must not be treated as \\`owner\\` everywhere just because a check didn't carry\n * a tenant. This mirrors how \\`assign(user, role)\\` stores a global row.\n */\n public static async rolesFor(user: Auth, tenant?: string): Promise<string[]> {\n const rows = await this.query()\n .where({\n user_id: user.id,\n user_type: user.userType,\n tenant: tenant ?? null,\n })\n .get();\n\n // De-dupe so a duplicate row (a concurrent assign that slipped past the\n // existence check) can't distort the resolved set.\n return [...new Set(rows.map((row) => row.get(\"role\") as string))];\n }\n\n /**\n * Assign a role to the user. No-op if the assignment already exists.\n * Flushes the user's cached permission set automatically.\n */\n public static async assign(user: Auth, role: string, tenant?: string): Promise<void> {\n const existing = await this.first({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant: tenant ?? null,\n });\n\n if (existing) return;\n\n await this.create({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant,\n });\n\n await access.flush(user, tenant);\n }\n\n /**\n * Remove a role assignment from the user.\n * Flushes the user's cached permission set automatically.\n */\n public static async revoke(user: Auth, role: string, tenant?: string): Promise<void> {\n await this.delete({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant: tenant ?? null,\n });\n\n await access.flush(user, tenant);\n }\n}\n`;\n\nexport const accessUserRoleModelIndexStub = `export * from \"./user-role.model\";\n`;\n\nexport const accessUserRoleMigrationStub = `import { Migration, text, uuid } from \"@warlock.js/cascade\";\nimport { UserRole } from \"../user-role.model\";\n\n/**\n * Role-assignment table. \\`user_id\\` is a UUID — override this migration if your\n * user ids are integers. The composite index powers the per-user (per-tenant)\n * lookup the resolver runs on every check.\n */\nexport default Migration.create(\n UserRole,\n {\n user_id: uuid().notNullable().index(),\n user_type: text().notNullable(),\n role: text().notNullable().index(),\n tenant: text().nullable().index(),\n },\n {\n index: [{ columns: [\"user_id\", \"user_type\", \"tenant\"] }],\n },\n);\n`;\n\nexport const accessResolverStub = `import type { AccessResolver } from \"@warlock.js/access\";\nimport type { Auth } from \"@warlock.js/auth\";\nimport { Role } from \"app/access/models/role\";\nimport { UserRole } from \"app/access/models/user-role\";\n\n/**\n * The app's access adapter — connects @warlock.js/access to the ejected role\n * tables. Roles come from the user_roles assignment table; permissions are\n * expanded by mapping those role names through the roles catalog table. Both\n * are managed at runtime (in the DB), so admins can add roles + edit their\n * permissions without a deploy.\n *\n * The engine owns the hard parts (wildcard matching, caching, fail-closed); this\n * resolver only fetches — keep it dumb, never cache inside it.\n */\nexport class DatabaseAccessResolver implements AccessResolver {\n /** The role names this user holds (powers \\`hasRole\\` / \\`hasAnyRole\\`). */\n public async resolveRoles(user: Auth, tenant?: string): Promise<string[]> {\n return UserRole.rolesFor(user, tenant);\n }\n\n /** The effective permission strings this user has (powers \\`can\\` / \\`authorize\\`). */\n public async resolvePermissions(user: Auth, tenant?: string): Promise<string[]> {\n const names = await this.resolveRoles(user, tenant);\n\n if (names.length === 0) return [];\n\n const roles = await Role.query().whereIn(\"name\", names).get();\n\n // Flatten + de-dupe so two roles granting the same permission yield one entry.\n return [...new Set(roles.flatMap((role) => role.permissions))];\n }\n\n /**\n * Optional. Resolve the ambient tenant when a check doesn't pass one\n * explicitly — derive it from the authenticated user (safer than reading\n * client request input, which a caller could spoof). Uncomment + adapt for a\n * multi-tenant app (single-tenant apps leave this off and return undefined).\n */\n // public resolveTenant(user: Auth): string | undefined {\n // return user.get(\"organization_id\");\n // }\n}\n`;\n\nexport const socketConfigStub = `import type { SocketOptions } from \"@warlock.js/core\";\n\n/**\n * Socket.IO configuration — read by the framework's socket connector\n * on boot. When the HTTP server is running the socket server attaches\n * to it; otherwise it listens on its own configured port.\n *\n * Remove this file to disable the socket server entirely.\n */\nexport default {\n options: {\n cors: {\n origin: \"*\",\n },\n },\n} as SocketOptions;\n`;\n\nexport const communicatorsConfigStub = `import { env } from \"@warlock.js/core\";\nimport type { BrokerConfigurations, RabbitMQClientOptions } from \"@warlock.js/herald\";\n\nconst heraldConfigurations: BrokerConfigurations<RabbitMQClientOptions> = {\n driver: \"rabbitmq\",\n name: \"default\",\n isDefault: true,\n\n // ============================================================================\n // Connection Settings\n // ============================================================================\n\n host: env(\"RABBITMQ_HOST\", \"localhost\"),\n port: env(\"RABBITMQ_PORT\", 5672),\n username: env(\"RABBITMQ_USERNAME\", \"guest\"),\n password: env(\"RABBITMQ_PASSWORD\", \"guest\"),\n vhost: env(\"RABBITMQ_VHOST\", \"/\"),\n\n // Or use connection URI (takes precedence over host/port)\n // uri: env(\"RABBITMQ_URL\"),\n\n // ============================================================================\n // Connection Options\n // ============================================================================\n\n /** Heartbeat interval in seconds */\n heartbeat: 60,\n\n /** Connection timeout in milliseconds */\n connectionTimeout: 10000,\n\n /** Enable automatic reconnection on disconnect */\n reconnect: true,\n\n /** Delay between reconnection attempts in milliseconds */\n reconnectDelay: 5_000,\n\n // ============================================================================\n // Consumer Options\n // ============================================================================\n\n /** Default prefetch count (number of unacknowledged messages per consumer) */\n prefetch: 10,\n\n // ============================================================================\n // Client Options (Native amqplib options)\n // ============================================================================\n // These options are passed directly to amqplib.connect()\n // for low-level configuration like frame size, TLS, socket options, etc.\n // ============================================================================\n clientOptions: {\n // Frame max size in bytes (0 = no limit)\n // frameMax: 0,\n\n // Channel max (0 = unlimited)\n // channelMax: 0,\n\n // Socket options\n socket: {\n // Enable TCP keep-alive\n keepAlive: true,\n\n // Disable Nagle's algorithm for lower latency\n noDelay: true,\n\n // Socket timeout (in addition to heartbeat)\n // timeout: 30000,\n },\n\n // TLS/SSL options (uncomment for secure connections)\n // socket: {\n // ca: fs.readFileSync('/path/to/ca.pem'),\n // cert: fs.readFileSync('/path/to/cert.pem'),\n // key: fs.readFileSync('/path/to/key.pem'),\n // rejectUnauthorized: true,\n // },\n },\n};\n\nexport default heraldConfigurations;\n`;\n\nexport const notificationsConfigStub = `import { type NotificationConfig, inApp, mailChannel } from \"@warlock.js/notifications\";\nimport { Notification } from \"app/notifications/models/notification/notification.model\";\n\n/**\n * Notifications configuration. Auto-loaded from src/config on boot — the\n * framework's notifications connector reads this default export and hands it to\n * setNotificationConfig, so this file stays declarative (no side-effect call).\n *\n * Each channel is payload-typed, so notify.mail(...) / notify.database(...)\n * and defineNotification are type-checked against the registry.\n *\n * Channels enabled here:\n * - mail wraps @warlock.js/core sendMail; route is notifiable.email.\n * The \"from\" address defaults to config/mail.ts; override per\n * channel with mailChannel({ from: \"no-reply@yourapp.com\" }).\n * - database in-app store backed by the Notification model. The \"inApp\"\n * facade exposes the recipient-scoped read API: listUnread,\n * countUnread, markAsRead, dismiss, ...\n *\n * Async delivery (.queue()) is OPTIONAL: run \"npx warlock add herald\",\n * import { heraldQueue } from \"@warlock.js/notifications\", and uncomment the\n * queue line below.\n */\nconst config: NotificationConfig = {\n channels: {\n mail: mailChannel(),\n database: inApp.configure({ model: Notification }),\n },\n\n // Async queue — requires @warlock.js/herald (npx warlock add herald):\n // queue: heraldQueue(),\n};\n\nexport default config;\n`;\n\n/** `src/app/notifications/models/notification/notification.model.ts`. */\nexport const notificationModelStub = `import { RegisterModel } from \"@warlock.js/cascade\";\nimport { DatabaseNotification, type NotificationColumnMap } from \"@warlock.js/notifications\";\nimport { v } from \"@warlock.js/seal\";\nimport { NotificationResource } from \"../../resources/notification.resource\";\n\n/**\n * Validation schema for the notifications table — mirrors the migration\n * columns (snake_case). Cascade validates + casts every write against it:\n * nullable columns use .nullish() (may be absent or null), and payload is\n * free-form JSON. Keep this in sync with the migration + columnMap when you\n * add or rename columns.\n *\n * user_id accepts a string or an integer so it matches whichever id type your\n * users use (and the idType you pass to notificationColumns in the migration).\n * Narrow it to that one type.\n */\nconst notificationSchema = v.object({\n user_id: v.union([v.string(), v.int()]),\n type: v.string(),\n title: v.string(),\n body: v.string().nullish(),\n payload: v.record(v.any()).nullish(),\n read_at: v.date().nullish(),\n idempotency_key: v.string().nullish(),\n});\n\n/**\n * In-app notification model.\n *\n * Extends the package's DatabaseNotification base, which provides the stable\n * accessors (recipientId, tenantId, isRead, readAt, markRead) — all derived\n * from the columnMap below. The read/write API lives on the inApp facade\n * (configured in config/notifications.ts); you rarely touch this class directly.\n */\n@RegisterModel()\nexport class Notification extends DatabaseNotification {\n public static table = \"notifications\";\n public static schema = notificationSchema;\n\n /** Every response that returns a notification is shaped by this resource. */\n public static resource = NotificationResource;\n\n /**\n * Maps the in-app store's roles to your columns. This default is\n * single-tenant + read_at-only. Add tenant: \"organization_id\" for\n * multi-tenant; use isRead: \"is_read\" (instead of, or alongside, readAt) to\n * track a boolean read flag. The migration, the accessors and the resource\n * all follow this map.\n */\n public static columnMap: NotificationColumnMap = { readAt: \"read_at\" };\n}\n`;\n\n/** The notifications migration, under `models/notification/migrations/`. */\nexport const notificationMigrationStub = `import { Migration } from \"@warlock.js/cascade\";\nimport { notificationColumns } from \"@warlock.js/notifications\";\nimport { Notification } from \"../notification.model\";\n\n/**\n * Notifications table.\n *\n * Columns come from notificationColumns(Notification) — the recipient / tenant\n * / read-state names follow the model's columnMap; type / title / body /\n * payload / idempotency_key are fixed. The recipient column is a UUID unless\n * you pass { idType: \"integer\" } (or \"bigint\" / \"string\") to match your users.\n * Spread it to add your own columns (and mirror them in the model schema):\n *\n * import { uuid } from \"@warlock.js/cascade\";\n *\n * export default Migration.create(Notification, {\n * ...notificationColumns(Notification, { idType: \"integer\" }),\n * // category_id: uuid().index().nullable(),\n * });\n */\nexport default Migration.create(Notification, notificationColumns(Notification));\n`;\n\n/** `src/app/notifications/resources/notification.resource.ts` — the output shape. */\nexport const notificationResourceStub = `import { defineResource } from \"@warlock.js/core\";\n\n/**\n * What every notification endpoint returns, whatever columns the model holds.\n * readAt reads the default read_at column; change it if you change the model's\n * columnMap.\n */\nexport const NotificationResource = defineResource({\n schema: {\n // Passed through as stored: a UUID string or an integer, per the migration.\n id: (id: string | number) => id,\n type: \"string\",\n title: \"string\",\n body: \"string?\",\n payload: \"object?\",\n readAt: [\"read_at\", \"date?\"],\n createdAt: \"date?\",\n },\n});\n`;\n\n/** `src/app/notifications/schema/list-notifications.schema.ts` — the validated list query. */\nexport const listNotificationsSchemaStub = `import { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Query for GET /notifications. Only these keys reach the store (others, such\n * as a cache-busting \\`_\\`, are dropped rather than rejected), and limit is\n * capped so one request cannot read every row. Query values arrive as strings,\n * so the numbers and the flag are coerced.\n */\nexport const listNotificationsSchema = v.object({\n page: v.int().coerce().min(1).optional(),\n limit: v.int().coerce().min(1).max(50).optional(),\n type: v.string().optional(),\n unread: v.boolean().coerce().optional(),\n}).stripUnknown();\n\nexport type ListNotificationsSchema = Infer<typeof listNotificationsSchema>;\n`;\n\n/** `src/app/notifications/types/notifications-request.type.ts` — the guarded request. */\nexport const notificationsRequestTypeStub = `import type { Request, RequestHandler, RequestLocals } from \"@warlock.js/core\";\nimport type { Id } from \"@warlock.js/notifications\";\n\n/**\n * A request that passed authMiddleware, so locals.user is always set. Only the\n * user's id is declared because that is all the inApp store needs. If your\n * app has its own guarded request type, use it instead.\n */\nexport type NotificationsRequest<Payload = unknown> = Request<Payload> & {\n locals: RequestLocals & { user: { id: Id } };\n};\n\nexport type NotificationsRequestHandler<Payload = unknown> = RequestHandler<\n NotificationsRequest<Payload>\n>;\n`;\n\n/** `src/app/notifications/services/mark-notification-read.service.ts`. */\nexport const markNotificationReadServiceStub = `import { ResourceNotFoundError, t } from \"@warlock.js/core\";\nimport { type Id, inApp } from \"@warlock.js/notifications\";\n\n/**\n * Mark one of the user's notifications read and return it. inApp is scoped to\n * the recipient, so another user's id changes nothing and answers 404 here.\n */\nexport async function markNotificationReadService(userId: Id, notificationId: Id) {\n await inApp.markAsRead(userId, notificationId);\n\n const notification = await inApp.find(userId, notificationId);\n\n if (!notification) {\n throw new ResourceNotFoundError(t(\"notifications.notFound\"));\n }\n\n return notification;\n}\n`;\n\n/** `src/app/notifications/controllers/list-notifications.controller.ts`. */\nexport const listNotificationsControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport {\n type ListNotificationsSchema,\n listNotificationsSchema,\n} from \"../schema/list-notifications.schema\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** GET /notifications — the user's notifications, most recent first. */\nexport const listNotificationsController: NotificationsRequestHandler<\n ListNotificationsSchema\n> = async ({ request, response }) => {\n const { data, pagination } = await inApp.list(request.locals.user.id, request.validated());\n\n return response.success({ notifications: data, pagination });\n};\n\nlistNotificationsController.description = \"List notifications\";\n\nlistNotificationsController.validation = {\n schema: listNotificationsSchema,\n validating: [\"query\"],\n};\n`;\n\n/** `src/app/notifications/controllers/unread-notifications-count.controller.ts`. */\nexport const unreadNotificationsCountControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** GET /notifications/unread-count — drives the bell badge. */\nexport const unreadNotificationsCountController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n const count = await inApp.countUnread(request.locals.user.id);\n\n return response.success({ count });\n};\n\nunreadNotificationsCountController.description = \"Unread notifications count\";\n`;\n\n/** `src/app/notifications/controllers/mark-notification-read.controller.ts`. */\nexport const markNotificationReadControllerStub = `import { markNotificationReadService } from \"../services/mark-notification-read.service\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** PATCH /notifications/:id/read — mark one read and return it. */\nexport const markNotificationReadController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n // Route params are strings. A numeric id is an integer id (the default\n // MongoDB stack); anything else, such as a UUID, stays a string.\n const rawId = request.string(\"id\");\n const id = /^\\\\d+$/.test(rawId) ? Number(rawId) : rawId;\n\n const notification = await markNotificationReadService(request.locals.user.id, id);\n\n return response.success({ notification });\n};\n\nmarkNotificationReadController.description = \"Mark notification read\";\n`;\n\n/** `src/app/notifications/controllers/mark-all-notifications-read.controller.ts`. */\nexport const markAllNotificationsReadControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** PATCH /notifications/read-all — mark every unread one read. */\nexport const markAllNotificationsReadController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n const count = await inApp.markAsRead(request.locals.user.id);\n\n return response.success({ count });\n};\n\nmarkAllNotificationsReadController.description = \"Mark all notifications read\";\n`;\n\n/** `src/app/notifications/routes.ts` — the four read endpoints behind `authMiddleware`. */\nexport const notificationRoutesStub = `import { authMiddleware } from \"@warlock.js/auth\";\nimport { router } from \"@warlock.js/core\";\nimport { listNotificationsController } from \"./controllers/list-notifications.controller\";\nimport { markAllNotificationsReadController } from \"./controllers/mark-all-notifications-read.controller\";\nimport { markNotificationReadController } from \"./controllers/mark-notification-read.controller\";\nimport { unreadNotificationsCountController } from \"./controllers/unread-notifications-count.controller\";\n\n/**\n * The signed-in user's own notifications.\n *\n * Notifications come from domain events, so there is no create. Dismissing is\n * left out on purpose; add it when the product needs it (inApp.dismiss).\n *\n * authMiddleware([]) admits any signed-in user. To limit who may read\n * notifications, add a permission gate to the group:\n *\n * import { gate } from \"@warlock.js/access\";\n *\n * router.group({ middleware: [authMiddleware([]), gate(\"notifications.read\")] }, ...);\n */\nrouter.group({ middleware: [authMiddleware([])] }, () => {\n const notifications = router.route(\"/notifications\");\n\n notifications.list(listNotificationsController);\n notifications.nest(\"/unread-count\").get(unreadNotificationsCountController);\n notifications.nest(\"/read-all\").patch(markAllNotificationsReadController);\n notifications.nest(\"/:id/read\").patch(markNotificationReadController);\n});\n`;\n\n/** `src/app/notifications/utils/locales.json` — the module's translations. */\nexport const notificationLocalesStub = `{\n \"notFound\": { \"en\": \"Notification not found\" }\n}\n`;\n\n/** Shared fixtures for the generated signed-in notification controller specs. */\nexport const notificationTestFixtureStub = `import type { Auth } from \"@warlock.js/auth\";\nimport type { ChildModel } from \"@warlock.js/cascade\";\nimport { config } from \"@warlock.js/core\";\nimport { actingAs, type AuthenticatedTestClient } from \"@warlock.js/core/tests\";\nimport { randomUUID } from \"node:crypto\";\nimport { Notification } from \"../models/notification/notification.model\";\n\n/** Isolated recipients and rows; adjust user fields if your auth model requires more. */\nexport async function createNotificationTestFixture() {\n const User = config.key<ChildModel<Auth>>(\"auth.userType.user\");\n if (!User) throw new Error(\"Notification specs need the configured auth.userType.user model.\");\n const users: Auth[] = [];\n const clients: AuthenticatedTestClient[] = [];\n const rows: Notification[] = [];\n\n async function cleanup() {\n const credentials = await Promise.allSettled(\n clients.splice(0).map((client) => client.dispose()),\n );\n const notifications = await Promise.allSettled(\n rows.splice(0).map((row) => row.destroy({ strategy: \"permanent\" })),\n );\n const recipients = await Promise.allSettled(\n users.splice(0).map((user) => user.destroy({ strategy: \"permanent\" })),\n );\n const errors = [...credentials, ...notifications, ...recipients]\n .filter((result): result is PromiseRejectedResult => result.status === \"rejected\")\n .map((result) => result.reason);\n if (errors.length) throw new AggregateError(errors, \"Notification fixture cleanup failed.\");\n }\n\n const createUser = async () => {\n const user = await User.create({\n name: \"Notification test user\",\n email: \"notifications-\" + randomUUID() + \"@example.test\",\n password: \"test-password\",\n });\n users.push(user);\n return user;\n };\n const signIn = async (user: Auth) => {\n const client = await actingAs(user);\n clients.push(client);\n return client;\n };\n const createNotification = async (recipientId: string | number, title: string, readAt?: Date) => {\n const row = await Notification.create({\n user_id: recipientId,\n type: \"test\",\n title,\n read_at: readAt,\n });\n rows.push(row);\n return row;\n };\n\n try {\n const user = await createUser();\n const otherUser = await createUser();\n const client = await signIn(user);\n const otherClient = await signIn(otherUser);\n const own = await createNotification(user.id, \"Own unread notification\");\n const alreadyRead = await createNotification(user.id, \"Own read notification\", new Date());\n const foreign = await createNotification(otherUser.id, \"Other user's notification\");\n await createNotification(otherUser.id, \"Other user's second notification\");\n return { user, otherUser, client, otherClient, own, alreadyRead, foreign, cleanup };\n } catch (error) {\n // Preserve the setup failure after attempting every owned resource's cleanup.\n await cleanup().catch(() => undefined);\n throw error;\n }\n}\n`;\n\n/** A spec for each generated controller, including authenticated recipient isolation. */\nexport function notificationControllerSpecStub(method: \"GET\" | \"PATCH\", path: string): string {\n const helper = method === \"GET\" ? \"testGet\" : \"testPatch\";\n let signedInCases: string;\n if (path === \"/notifications\") {\n signedInCases = ` it(\"lists only the signed-in recipient's rows, ignoring a forged recipient query\", async () => {\n const response = await fixture.client.get(\n \"/notifications?recipientId=\" + fixture.otherUser.id,\n );\n const body = await expectJson<{ notifications: { id: string | number }[] }>(response);\n expect(body.notifications.map((row) => row.id)).toEqual(\n expect.arrayContaining([fixture.own.id, fixture.alreadyRead.id]),\n );\n expect(body.notifications).toHaveLength(2);\n });\n\n it(\"applies unread and paging query filters\", async () => {\n const response = await fixture.client.get(\"/notifications?unread=true&limit=1\");\n const body = await expectJson<{ notifications: { id: string | number }[] }>(response);\n expect(body.notifications.map((row) => row.id)).toEqual([fixture.own.id]);\n });\n\n it(\"rejects a list limit above the schema's cap\", async () => {\n expect((await fixture.client.get(\"/notifications?limit=999\")).status).toBe(422);\n });`;\n } else if (path === \"/notifications/unread-count\") {\n signedInCases = ` it(\"counts only this recipient's unread notifications\", async () => {\n const own = await expectJson<{ count: number }>(\n await fixture.client.get(\"/notifications/unread-count\"),\n );\n const other = await expectJson<{ count: number }>(\n await fixture.otherClient.get(\"/notifications/unread-count\"),\n );\n expect(own.count).toBe(1);\n expect(other.count).toBe(2);\n });`;\n } else if (path === \"/notifications/read-all\") {\n signedInCases = ` it(\"marks only this recipient's unread rows and leaves another recipient unchanged\", async () => {\n const body = await expectJson<{ count: number }>(\n await fixture.client.patch(\"/notifications/read-all\"),\n );\n expect(body.count).toBe(1);\n expect((await Notification.find(fixture.own.id))?.isRead).toBe(true);\n expect((await Notification.find(fixture.foreign.id))?.isRead).toBe(false);\n const other = await expectJson<{ count: number }>(\n await fixture.otherClient.get(\"/notifications/unread-count\"),\n );\n expect(other.count).toBe(2);\n const again = await expectJson<{ count: number }>(\n await fixture.client.patch(\"/notifications/read-all\"),\n );\n expect(again.count).toBe(0);\n });`;\n } else {\n signedInCases = ` it(\"marks its own notification read and returns it\", async () => {\n const response = await fixture.client.patch(\"/notifications/\" + fixture.own.id + \"/read\");\n const body = await expectJson<{\n notification: { id: string | number; readAt?: string | null };\n }>(response);\n expect(body.notification.id).toBe(fixture.own.id);\n expect(body.notification.readAt).toBeTruthy();\n expect((await Notification.find(fixture.own.id))?.isRead).toBe(true);\n });\n\n it(\"answers 404 for another recipient's notification without changing it\", async () => {\n const response = await fixture.client.patch(\"/notifications/\" + fixture.foreign.id + \"/read\");\n expect(response.status).toBe(404);\n expect((await Notification.find(fixture.foreign.id))?.isRead).toBe(false);\n });`;\n }\n const modelImport =\n method === \"PATCH\"\n ? 'import { Notification } from \"../models/notification/notification.model\";\\n'\n : \"\";\n return `import { expectJson, ${helper} } from \"@warlock.js/core/tests\";\nimport { afterEach, beforeEach, describe, expect, it } from \"vitest\";\n${modelImport}import { createNotificationTestFixture } from \"../tests/notifications.fixture\";\n\ndescribe(\"${method} ${path}\", () => {\n it(\"answers 401 without a signed-in user\", async () => {\n const response = await ${helper}(\"${path}\");\n expect(response.status).toBe(401);\n });\n\n describe(\"signed in\", () => {\n let fixture: Awaited<ReturnType<typeof createNotificationTestFixture>> | undefined;\n beforeEach(async () => {\n fixture = await createNotificationTestFixture();\n });\n afterEach(async () => {\n const current = fixture;\n fixture = undefined;\n await current?.cleanup();\n });\n\n${signedInCases.replaceAll(\"fixture.\", \"fixture!.\")}\n });\n});\n`;\n}\n\n/**\n * `src/web/root.tsx` — the application root for the SSR page layer.\n *\n * Deliberately minimal. The framework ships a default root, so this exists to\n * give you a place to start rather than because anything requires it. The\n * reference app (`v5/app/src/web/root.tsx`) is where to look for the fuller\n * shape: middleware, an app-level loader, locales, an ErrorBoundary.\n */\nexport const webRootStub = `import type { AppProps } from \"@warlock.js/web\";\nimport { Head, Scripts } from \"@warlock.js/web\";\n\n/**\n * The application root.\n *\n * NOT async, and it receives no request/response: it renders on the server and\n * again in the browser during hydration, where neither exists.\n */\nexport default function App({ children }: AppProps) {\n return (\n <html lang=\"en\">\n <head>\n {/*\n <Head /> also renders the viewport tag (width=device-width,\n initial-scale=1). Change it with \\`metadata.viewport\\`,\n or set it to false to leave it out; do not add a second one here.\n */}\n {/*\n Placement only. The framework injects the page's \\`metadata\\`, the\n stylesheet and preload tags for this route, and the canonical links\n into <head> by default — <Head /> just says WHERE they land.\n\n Do not add a <title> here: the page's \\`metadata\\` owns it, and a root\n that emits one too produces two.\n */}\n <Head />\n <link rel=\"icon\" href=\"data:,\" />\n </head>\n <body>\n {/*\n REQUIRED — this is the hydration mount point, not a styling wrapper.\n\n The browser runtime looks up \\`#vessel\\` and hydrates that element only.\n Remove this div, or rename the id, and the page still renders from the\n server but never becomes interactive: the runtime throws in the console\n and nothing on screen changes.\n\n Wrap it in your own markup freely, and put anything that must live\n outside the hydrated tree (a static footer, a portal target) outside\n it — just keep an element with \\`id=\"vessel\"\\` around {children}.\n */}\n <div id=\"vessel\">{children}</div>\n {/*\n The hydration payload and module tags. Written explicitly because\n placement occasionally matters — a CSP nonce, or ordering against\n your own scripts.\n */}\n <Scripts />\n </body>\n </html>\n );\n}\n`;\n\n/**\n * `src/app/contact/controllers/contact.controller.ts` — a real API endpoint\n * for the Web starter's contact form. It intentionally has no persistence\n * dependency: replace the acknowledgement with a mail/job/database action.\n */\nexport const webContactControllerStub = `import { type Request, type RequestHandler } from \"@warlock.js/core\";\nimport { v, type Infer } from \"@warlock.js/seal\";\n\nexport const contactSchema = v.object({\n name: v.string().min(2),\n email: v.email(),\n message: v.string().min(10),\n});\n\nexport type ContactSchema = Infer.Output<typeof contactSchema>;\n\n/** POST /api/contact — validates the starter contact form. */\nexport const contactController: RequestHandler<Request<ContactSchema>> = async ({\n request,\n response,\n}) => {\n const contact = request.validated();\n\n // Replace this with delivery/persistence for your app. Keeping the accepted\n // payload visible makes the endpoint useful while remaining side-effect free.\n return response.success({\n message: \"Thanks, \" + contact.name + \". Your message has been received.\",\n });\n};\n\ncontactController.validation = { schema: contactSchema };\n`;\n\n/** `src/app/contact/routes.ts` — discovered by the standard app route loader. */\nexport const webContactRoutesStub = `import { router } from \"@warlock.js/core\";\nimport { contactController } from \"./controllers/contact.controller\";\n\nrouter.post(\"/api/contact\", contactController, { public: true });\n`;\n\n/**\n * `src/web/index.register.ts` — universal static setup for the starter page.\n *\n * The page re-exports this stable binding so Warlock's `register()` lifecycle\n * still sees it in both realms without making React Fast Refresh treat every\n * JSX edit as an incompatible function-export replacement.\n */\nexport const webHomeRegisterStub = `import { extend } from \"@mongez/localization\";\n\nexport function register() {\n extend(\"en\", {\n starter: {\n title: \"Your Warlock app is running.\",\n introduction: \"This page is rendered on the server and hydrated in the browser.\",\n language: \"العربية\",\n contact: \"Send a message\",\n name: \"Name\",\n email: \"Email\",\n message: \"Message\",\n submit: \"Send message\",\n sent: \"Thanks — your message has been received.\",\n },\n });\n extend(\"ar\", {\n starter: {\n title: \"تطبيق Warlock يعمل الآن.\",\n introduction: \"تُعرض هذه الصفحة على الخادم ثم تُفعَّل في المتصفح.\",\n language: \"English\",\n contact: \"أرسل رسالة\",\n name: \"الاسم\",\n email: \"البريد الإلكتروني\",\n message: \"الرسالة\",\n submit: \"إرسال الرسالة\",\n sent: \"شكرًا — تم استلام رسالتك.\",\n },\n });\n}\n`;\n\n/**\n * `src/web/index.page.tsx` — one page, so \\`warlock dev\\` has something to serve\n * the moment this finishes.\n */\nexport const webHomePageStub = `import { http } from \"@mongez/http\";\nimport { setCurrentLocaleCode } from \"@mongez/localization\";\nimport { Form, useFormControl, type FormControlProps } from \"@mongez/react-form\";\nimport { transX } from \"@mongez/react-localization\";\nimport { v } from \"@warlock.js/seal\";\nimport { Link, type PageConfig, type PageProps } from \"@warlock.js/web\";\nimport { useState } from \"react\";\n\nexport { register } from \"./index.register\";\n\n/**\n * A page route is an ordinary Warlock route whose handler renders React\n * instead of returning JSON.\n *\n * The URL and stable hydration name are the ones this file DECLARES below.\n * This page answers \\`GET \"/\"\\` because \\`config.route.path = \"/\"\\`, not because of\n * where the file lives. A page file with\n * no \\`config.route\\` declaration derives its URL from the filesystem.\n */\nexport const config: PageConfig = {\n route: { path: \"/\", name: \"index\" },\n metadata: { title: \"Home\" },\n};\n\nconst contactSchema = v.object({\n name: v.string().min(2),\n email: v.email(),\n message: v.string().min(10),\n});\n\nfunction TextInput({ label, ...controlProps }: FormControlProps & { label: string }) {\n const { error, getErrorProps, getInputProps } = useFormControl(controlProps);\n\n return (\n <div className=\"wk-field\">\n <label htmlFor={controlProps.name}>{label}</label>\n <input {...getInputProps()} />\n {error && <p {...getErrorProps()}>{error}</p>}\n </div>\n );\n}\n\n/**\n * Add a \\`loader\\` export to fetch data on the server, and it arrives here as\n * \\`data\\`, typed:\n *\n * export const loader = (async () => ({ items: await itemsRepository.all() }));\n * export default function HomePage({ data }: PageProps<typeof loader>) { ... }\n */\nexport default function HomePage(_props: PageProps) {\n // Live state. If the button below does nothing, the page rendered on the\n // server but never hydrated — the runtime never mounted at \\`#vessel\\`. This is\n // deliberately here so that failure is impossible to miss.\n const [count, setCount] = useState(0);\n const [locale, setLocale] = useState<\"en\" | \"ar\">(\"en\");\n const [submitted, setSubmitted] = useState(false);\n const [submitError, setSubmitError] = useState<string | null>(null);\n\n const toggleLocale = () => {\n const nextLocale = locale === \"en\" ? \"ar\" : \"en\";\n setCurrentLocaleCode(nextLocale);\n setLocale(nextLocale);\n };\n\n return (\n <>\n {/*\n Self-contained, dependency-free styling: plain CSS, system fonts, and\n CSS custom properties, scoped to this page. No CSS framework, no utility\n classes, no external stylesheet — this page looks the same whether or\n not \\`warlock add tailwind\\` has ever been run.\n */}\n <style>{\\`\n .wk-home {\n --wk-fg: #0f172a;\n --wk-muted: #64748b;\n --wk-accent: #4f46e5;\n --wk-border: #e2e8f0;\n font-family: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n color: var(--wk-fg);\n max-width: 42rem;\n margin: 4rem auto;\n padding: 0 1.5rem;\n line-height: 1.6;\n }\n .wk-home h1 { font-size: 2.25rem; margin: 0 0 0.5rem; }\n .wk-home p { color: var(--wk-muted); margin: 0 0 1.5rem; }\n .wk-home code {\n font-family: ui-monospace, \"SFMono-Regular\", Menlo, monospace;\n background: #f1f5f9;\n padding: 0.1rem 0.35rem;\n border-radius: 0.25rem;\n }\n .wk-check {\n border: 1px solid var(--wk-border);\n border-radius: 0.75rem;\n padding: 1.25rem 1.5rem;\n margin: 2rem 0;\n }\n .wk-check strong { display: block; font-size: 1.5rem; }\n .wk-check button {\n font: inherit;\n cursor: pointer;\n background: var(--wk-accent);\n color: #fff;\n border: 0;\n border-radius: 0.5rem;\n padding: 0.5rem 1rem;\n margin-top: 0.75rem;\n }\n .wk-links { display: flex; gap: 1.25rem; font-size: 0.95rem; }\n .wk-links a { color: var(--wk-accent); text-decoration: none; }\n .wk-links a:hover { text-decoration: underline; }\n .wk-language { margin-left: auto; }\n .wk-contact { margin-top: 2rem; }\n .wk-field { display: grid; gap: 0.35rem; margin: 0.8rem 0; }\n .wk-field input, .wk-field textarea { font: inherit; padding: 0.55rem; }\n .wk-field p, .wk-submit-error { color: #b91c1c; margin: 0; }\n .wk-success { color: #047857; }\n \\`}</style>\n\n <main className=\"wk-home\" dir={locale === \"ar\" ? \"rtl\" : \"ltr\"}>\n <nav className=\"wk-links\" aria-label=\"Starter links\">\n <a href=\"https://warlock.js.org\" target=\"_blank\" rel=\"noreferrer\">\n Docs\n </a>\n <Link href=\"/\" aria-current=\"page\">\n Home\n </Link>\n <button\n className=\"wk-language\"\n type=\"button\"\n aria-pressed={locale === \"ar\"}\n onClick={toggleLocale}\n >\n {transX(\"starter.language\")}\n </button>\n </nav>\n\n <h1>{transX(\"starter.title\")}</h1>\n <p>{transX(\"starter.introduction\")}</p>\n\n <section className=\"wk-check\">\n <label>If this number goes up when you click, React is hydrated:</label>\n <strong>{count}</strong>\n <button type=\"button\" onClick={() => setCount((c) => c + 1)}>\n Count up\n </button>\n </section>\n\n <section className=\"wk-contact\" aria-labelledby=\"contact-heading\">\n <h2 id=\"contact-heading\">{transX(\"starter.contact\")}</h2>\n <Form<typeof contactSchema>\n id=\"contact-form\"\n schema={contactSchema}\n onSubmit={async ({ form, values }) => {\n setSubmitted(false);\n setSubmitError(null);\n const result = await http.post<{ message: string }>(\"/api/contact\", values);\n\n if (result.error) {\n if (result.error.isValidationError) {\n const body = result.error.body as {\n errors?: Array<{ input: string; error: string }>;\n message?: string;\n };\n form.setErrors(\n Object.fromEntries(\n (body.errors ?? []).map(({ input, error }) => [input, error]),\n ),\n );\n setSubmitError(body.message ?? \"Please correct the highlighted fields.\");\n } else {\n setSubmitError(\"Your message could not be sent. Please try again.\");\n }\n return;\n }\n\n setSubmitted(true);\n form.reset();\n }}\n >\n <TextInput name=\"name\" label={transX(\"starter.name\")} autoComplete=\"name\" />\n <TextInput\n name=\"email\"\n label={transX(\"starter.email\")}\n type=\"email\"\n autoComplete=\"email\"\n />\n <ContactMessage />\n <button type=\"submit\">{transX(\"starter.submit\")}</button>\n {submitError && (\n <p className=\"wk-submit-error\" role=\"alert\">\n {submitError}\n </p>\n )}\n {submitted && (\n <p className=\"wk-success\" role=\"status\">\n {transX(\"starter.sent\")}\n </p>\n )}\n </Form>\n </section>\n </main>\n </>\n );\n}\n\nfunction ContactMessage() {\n const { error, getErrorProps, getInputProps } = useFormControl({ name: \"message\" });\n\n return (\n <div className=\"wk-field\">\n <label htmlFor=\"message\">{transX(\"starter.message\")}</label>\n <textarea {...getInputProps()} rows={5} />\n {error && <p {...getErrorProps()}>{error}</p>}\n </div>\n );\n}\n`;\n"],"mappings":";AAAA,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BhC,MAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+B5B,MAAa,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCnC,MAAa,2BAA2B;;AAGxC,MAAa,0BAA0B;;;;;;;;;;;;AAavC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FvC,MAAa,+BAA+B;;AAG5C,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;;AAsB3C,MAAa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ClC,MAAa,mBAAmB;;;;;;;;;;;;;;;;;AAkBhC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFvC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCvC,MAAa,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDrC,MAAa,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;AAwBzC,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;AAsBxC,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;AAmB3C,MAAa,+BAA+B;;;;;;;;;;;;;;;;;AAkB5C,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;;;AAqB/C,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;AAyB/C,MAAa,yCAAyC;;;;;;;;;;;;;;;;AAiBtD,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;;;;AAsBlD,MAAa,yCAAyC;;;;;;;;;;;;;;;;AAiBtD,MAAa,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BtC,MAAa,0BAA0B;;;;;AAMvC,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2E3C,SAAgB,+BAA+B,QAAyB,MAAsB;CAC5F,MAAM,SAAS,WAAW,QAAQ,YAAY;CAC9C,IAAI;CACJ,IAAI,SAAS,kBACX,gBAAgB;;;;;;;;;;;;;;;;;;;;MAoBX,IAAI,SAAS,+BAClB,gBAAgB;;;;;;;;;;MAUX,IAAI,SAAS,2BAClB,gBAAgB;;;;;;;;;;;;;;;;MAiBhB,gBAAgB;;;;;;;;;;;;;;;CAoBlB,OAAO,wBAAwB,OAAO;;EAHpC,WAAW,UACP,kFACA,GAGM;;YAEF,OAAO,GAAG,KAAK;;6BAEE,OAAO,IAAI,KAAK;;;;;;;;;;;;;;;EAe3C,cAAc,WAAW,YAAY,WAAW,EAAE;;;;AAIpD;;;;;;;;;AAUA,MAAa,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4D3B,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BxC,MAAa,uBAAuB;;;;;;;;;;;;AAapC,MAAa,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCnC,MAAa,kBAAkB"}
1
+ {"version":3,"file":"stubs.mjs","names":[],"sources":["../../../../../../../../packages/core/src/generations/stubs.ts"],"sourcesContent":["export const accessConfigStub = `import { type AccessConfigurations } from \"@warlock.js/access\";\nimport { DatabaseAccessResolver } from \"app/access/services/access-resolver\";\n\n/**\n * Authorization configuration — read by @warlock.js/access on boot.\n *\n * The resolver is the one required piece: it tells the engine how to read a\n * user's roles + permissions. The ejected DatabaseAccessResolver reads roles\n * from the user_roles table and maps them through the roles catalog table (so\n * roles + their permissions are managed at runtime, in the DB).\n *\n * For a fixed, code-defined catalog with no tables, swap in DefaultAccessResolver:\n * import { DefaultAccessResolver } from \"@warlock.js/access\";\n * resolver: new DefaultAccessResolver({ admin: [\"*\"], editor: [\"orders.*\"] }),\n *\n * Multi-tenant? Add a \\`resolveTenant()\\` to the resolver to read the active\n * tenant from the request; checks then scope to it automatically.\n */\nconst access: AccessConfigurations = {\n resolver: new DatabaseAccessResolver(),\n\n // Cache resolved permission sets (default \"10m\").\n // cache: { ttl: \"10m\" },\n};\n\nexport default access;\n`;\n\nexport const aiConfigStub = `import type { AIConfig } from \"@warlock.js/ai\";\n\n// >>> warlock:ai-packages (auto-managed) >>>\n// Satellite packages augment the \"ai\" object on import — e.g. ai.workspace,\n// ai.tools / ai.mcp, and panoptic's ai.config({ panoptic }) wiring. The command\n// \"warlock add ai-workspace | ai-tools | ai-panoptic\" adds the matching\n// side-effect import below; keep them so the augmentation + runtime registration\n// load before the ai connector applies this config.\n// <<< warlock:ai-packages <<<\n\n/**\n * AI configuration — applied on boot by the ai connector, which calls\n * ai.config(...) with the object below. Cross-cutting defaults live here\n * (shared cache / snapshot stores, observability); per-call options always win.\n *\n * Wire a default model from a provider you installed, e.g.:\n * import { OpenAISDK } from \"@warlock.js/ai-openai\";\n * const openai = OpenAISDK({ apiKey: env(\"OPENAI_API_KEY\") });\n * // then pass openai.model({ name: \"gpt-4o-mini\" }) into your agents.\n */\nconst ai: Partial<AIConfig> = {\n // Default cache driver for cache-backed AI features (semantic cache, rag / memory vector stores).\n // defaultStore: cache.driver(\"redis\", { client }),\n\n // Observability — requires \"warlock add ai-panoptic\". Exporters + the local dashboard.\n // panoptic: { exporters: [], dashboard: false, observeAll: false },\n};\n\nexport default ai;\n`;\n\nexport const accessRoleModelStub = `import { Model, RegisterModel } from \"@warlock.js/cascade\";\nimport { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Validation schema for the roles catalog — mirrors the migration columns\n * (snake_case). Each row is a role name plus the permission strings it grants;\n * wildcards work (\"orders.*\", \"*\"). The DatabaseAccessResolver maps a user's\n * assigned role names through this table to their effective permissions.\n */\nexport const roleSchema = v.object({\n name: v.string(),\n permissions: v.array(v.string()).default([]),\n});\n\nexport type RoleSchema = Infer<typeof roleSchema>;\n\n/**\n * The roles catalog — role name → the permissions it grants. Managed at runtime\n * (admins add roles + edit their permissions), unlike a fixed code map. Read by\n * DatabaseAccessResolver.resolvePermissions to expand a user's roles to permissions.\n */\n@RegisterModel()\nexport class Role extends Model<RoleSchema> {\n public static table = \"roles\";\n\n public static schema = roleSchema;\n\n /** The permission strings this role grants. */\n public get permissions(): string[] {\n return this.get<string[]>(\"permissions\", []);\n }\n}\n`;\n\nexport const accessRoleModelIndexStub = `export * from \"./role.model\";\n`;\n\nexport const accessRoleMigrationStub = `import { arrayText, Migration, text } from \"@warlock.js/cascade\";\nimport { Role } from \"../role.model\";\n\n/**\n * Roles catalog table. \\`name\\` is unique (one row per role); \\`permissions\\` is a\n * text array of the permission strings the role grants.\n */\nexport default Migration.create(Role, {\n name: text().notNullable().unique(),\n permissions: arrayText().nullable(),\n});\n`;\n\nexport const accessUserRoleModelStub = `import { access } from \"@warlock.js/access\";\nimport type { Auth } from \"@warlock.js/auth\";\nimport { Model, RegisterModel } from \"@warlock.js/cascade\";\nimport { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Validation schema for a role assignment — mirrors the migration columns\n * (snake_case). \\`tenant\\` is nullable: a null tenant is a GLOBAL assignment.\n */\nexport const userRoleSchema = v.object({\n user_id: v.string(),\n user_type: v.string(),\n role: v.string(),\n tenant: v.string().optional(),\n});\n\nexport type UserRoleSchema = Infer<typeof userRoleSchema>;\n\n/**\n * The role-assignment table — which roles a user holds, optionally per tenant.\n * Read by DatabaseAccessResolver.resolveRoles; mutated via the statics below.\n * \\`assign\\` / \\`revoke\\` flush the cached permission set automatically, so callers\n * never need to call \\`access.flush(user, tenant)\\` themselves.\n */\n@RegisterModel()\nexport class UserRole extends Model<UserRoleSchema> {\n public static table = \"user_roles\";\n\n public static schema = userRoleSchema;\n\n /**\n * Role names assigned to the user in the given tenant.\n *\n * An unresolved tenant (\\`undefined\\`) scopes to GLOBAL roles only — the rows\n * stored with no tenant (\\`null\\`) — never the union across every tenant. The\n * union would be a privilege-escalation: a user who is \\`owner\\` in one tenant\n * must not be treated as \\`owner\\` everywhere just because a check didn't carry\n * a tenant. This mirrors how \\`assign(user, role)\\` stores a global row.\n */\n public static async rolesFor(user: Auth, tenant?: string): Promise<string[]> {\n const rows = await this.query()\n .where({\n user_id: user.id,\n user_type: user.userType,\n tenant: tenant ?? null,\n })\n .get();\n\n // De-dupe so a duplicate row (a concurrent assign that slipped past the\n // existence check) can't distort the resolved set.\n return [...new Set(rows.map((row) => row.get(\"role\") as string))];\n }\n\n /**\n * Assign a role to the user. No-op if the assignment already exists.\n * Flushes the user's cached permission set automatically.\n */\n public static async assign(user: Auth, role: string, tenant?: string): Promise<void> {\n const existing = await this.first({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant: tenant ?? null,\n });\n\n if (existing) return;\n\n await this.create({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant,\n });\n\n await access.flush(user, tenant);\n }\n\n /**\n * Remove a role assignment from the user.\n * Flushes the user's cached permission set automatically.\n */\n public static async revoke(user: Auth, role: string, tenant?: string): Promise<void> {\n await this.delete({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant: tenant ?? null,\n });\n\n await access.flush(user, tenant);\n }\n}\n`;\n\nexport const accessUserRoleModelIndexStub = `export * from \"./user-role.model\";\n`;\n\nexport const accessUserRoleMigrationStub = `import { Migration, text, uuid } from \"@warlock.js/cascade\";\nimport { UserRole } from \"../user-role.model\";\n\n/**\n * Role-assignment table. \\`user_id\\` is a UUID — override this migration if your\n * user ids are integers. The composite index powers the per-user (per-tenant)\n * lookup the resolver runs on every check.\n */\nexport default Migration.create(\n UserRole,\n {\n user_id: uuid().notNullable().index(),\n user_type: text().notNullable(),\n role: text().notNullable().index(),\n tenant: text().nullable().index(),\n },\n {\n index: [{ columns: [\"user_id\", \"user_type\", \"tenant\"] }],\n },\n);\n`;\n\nexport const accessResolverStub = `import type { AccessResolver } from \"@warlock.js/access\";\nimport type { Auth } from \"@warlock.js/auth\";\nimport { Role } from \"app/access/models/role\";\nimport { UserRole } from \"app/access/models/user-role\";\n\n/**\n * The app's access adapter — connects @warlock.js/access to the ejected role\n * tables. Roles come from the user_roles assignment table; permissions are\n * expanded by mapping those role names through the roles catalog table. Both\n * are managed at runtime (in the DB), so admins can add roles + edit their\n * permissions without a deploy.\n *\n * The engine owns the hard parts (wildcard matching, caching, fail-closed); this\n * resolver only fetches — keep it dumb, never cache inside it.\n */\nexport class DatabaseAccessResolver implements AccessResolver {\n /** The role names this user holds (powers \\`hasRole\\` / \\`hasAnyRole\\`). */\n public async resolveRoles(user: Auth, tenant?: string): Promise<string[]> {\n return UserRole.rolesFor(user, tenant);\n }\n\n /** The effective permission strings this user has (powers \\`can\\` / \\`authorize\\`). */\n public async resolvePermissions(user: Auth, tenant?: string): Promise<string[]> {\n const names = await this.resolveRoles(user, tenant);\n\n if (names.length === 0) return [];\n\n const roles = await Role.query().whereIn(\"name\", names).get();\n\n // Flatten + de-dupe so two roles granting the same permission yield one entry.\n return [...new Set(roles.flatMap((role) => role.permissions))];\n }\n\n /**\n * Optional. Resolve the ambient tenant when a check doesn't pass one\n * explicitly — derive it from the authenticated user (safer than reading\n * client request input, which a caller could spoof). Uncomment + adapt for a\n * multi-tenant app (single-tenant apps leave this off and return undefined).\n */\n // public resolveTenant(user: Auth): string | undefined {\n // return user.get(\"organization_id\");\n // }\n}\n`;\n\nexport const socketConfigStub = `import type { SocketOptions } from \"@warlock.js/core\";\n\n/**\n * Socket.IO configuration — read by the framework's socket connector\n * on boot. When the HTTP server is running the socket server attaches\n * to it; otherwise it listens on its own configured port.\n *\n * Remove this file to disable the socket server entirely.\n */\nexport default {\n options: {\n cors: {\n origin: \"*\",\n },\n },\n} as SocketOptions;\n`;\n\nexport const communicatorsConfigStub = `import { env } from \"@warlock.js/core\";\nimport type { BrokerConfigurations, RabbitMQClientOptions } from \"@warlock.js/herald\";\n\nconst heraldConfigurations: BrokerConfigurations<RabbitMQClientOptions> = {\n driver: \"rabbitmq\",\n name: \"default\",\n isDefault: true,\n\n // ============================================================================\n // Connection Settings\n // ============================================================================\n\n host: env(\"RABBITMQ_HOST\", \"localhost\"),\n port: env(\"RABBITMQ_PORT\", 5672),\n username: env(\"RABBITMQ_USERNAME\", \"guest\"),\n password: env(\"RABBITMQ_PASSWORD\", \"guest\"),\n vhost: env(\"RABBITMQ_VHOST\", \"/\"),\n\n // Or use connection URI (takes precedence over host/port)\n // uri: env(\"RABBITMQ_URL\"),\n\n // ============================================================================\n // Connection Options\n // ============================================================================\n\n /** Heartbeat interval in seconds */\n heartbeat: 60,\n\n /** Connection timeout in milliseconds */\n connectionTimeout: 10000,\n\n /** Enable automatic reconnection on disconnect */\n reconnect: true,\n\n /** Delay between reconnection attempts in milliseconds */\n reconnectDelay: 5_000,\n\n // ============================================================================\n // Consumer Options\n // ============================================================================\n\n /** Default prefetch count (number of unacknowledged messages per consumer) */\n prefetch: 10,\n\n // ============================================================================\n // Client Options (Native amqplib options)\n // ============================================================================\n // These options are passed directly to amqplib.connect()\n // for low-level configuration like frame size, TLS, socket options, etc.\n // ============================================================================\n clientOptions: {\n // Frame max size in bytes (0 = no limit)\n // frameMax: 0,\n\n // Channel max (0 = unlimited)\n // channelMax: 0,\n\n // Socket options\n socket: {\n // Enable TCP keep-alive\n keepAlive: true,\n\n // Disable Nagle's algorithm for lower latency\n noDelay: true,\n\n // Socket timeout (in addition to heartbeat)\n // timeout: 30000,\n },\n\n // TLS/SSL options (uncomment for secure connections)\n // socket: {\n // ca: fs.readFileSync('/path/to/ca.pem'),\n // cert: fs.readFileSync('/path/to/cert.pem'),\n // key: fs.readFileSync('/path/to/key.pem'),\n // rejectUnauthorized: true,\n // },\n },\n};\n\nexport default heraldConfigurations;\n`;\n\nexport const notificationsConfigStub = `import { type NotificationConfig, inApp, mailChannel } from \"@warlock.js/notifications\";\nimport { Notification } from \"app/notifications/models/notification/notification.model\";\n\n/**\n * Notifications configuration. Auto-loaded from src/config on boot — the\n * framework's notifications connector reads this default export and hands it to\n * setNotificationConfig, so this file stays declarative (no side-effect call).\n *\n * Each channel is payload-typed, so notify.mail(...) / notify.database(...)\n * and defineNotification are type-checked against the registry.\n *\n * Channels enabled here:\n * - mail wraps @warlock.js/core sendMail; route is notifiable.email.\n * The \"from\" address defaults to config/mail.ts; override per\n * channel with mailChannel({ from: \"no-reply@yourapp.com\" }).\n * - database in-app store backed by the Notification model. The \"inApp\"\n * facade exposes the recipient-scoped read API: listUnread,\n * countUnread, markAsRead, dismiss, ...\n *\n * Async delivery (.queue()) is OPTIONAL: run \"npx warlock add herald\",\n * import { heraldQueue } from \"@warlock.js/notifications\", and uncomment the\n * queue line below.\n */\nconst config: NotificationConfig = {\n channels: {\n mail: mailChannel(),\n database: inApp.configure({ model: Notification }),\n },\n\n // Async queue — requires @warlock.js/herald (npx warlock add herald):\n // queue: heraldQueue(),\n};\n\nexport default config;\n`;\n\n/** `src/app/notifications/models/notification/notification.model.ts`. */\nexport const notificationModelStub = `import { RegisterModel } from \"@warlock.js/cascade\";\nimport { DatabaseNotification, type NotificationColumnMap } from \"@warlock.js/notifications\";\nimport { v } from \"@warlock.js/seal\";\nimport { NotificationResource } from \"../../resources/notification.resource\";\n\n/**\n * Validation schema for the notifications table — mirrors the migration\n * columns (snake_case). Cascade validates + casts every write against it:\n * nullable columns use .nullish() (may be absent or null), and payload is\n * free-form JSON. Keep this in sync with the migration + columnMap when you\n * add or rename columns.\n *\n * user_id accepts a string or an integer so it matches whichever id type your\n * users use (and the idType you pass to notificationColumns in the migration).\n * Narrow it to that one type.\n */\nconst notificationSchema = v.object({\n user_id: v.union([v.string(), v.int()]),\n type: v.string(),\n title: v.string(),\n body: v.string().nullish(),\n payload: v.record(v.any()).nullish(),\n read_at: v.date().nullish(),\n idempotency_key: v.string().nullish(),\n});\n\n/**\n * In-app notification model.\n *\n * Extends the package's DatabaseNotification base, which provides the stable\n * accessors (recipientId, tenantId, isRead, readAt, markRead) — all derived\n * from the columnMap below. The read/write API lives on the inApp facade\n * (configured in config/notifications.ts); you rarely touch this class directly.\n */\n@RegisterModel()\nexport class Notification extends DatabaseNotification {\n public static table = \"notifications\";\n public static schema = notificationSchema;\n\n /** Every response that returns a notification is shaped by this resource. */\n public static resource = NotificationResource;\n\n /**\n * Maps the in-app store's roles to your columns. This default is\n * single-tenant + read_at-only. Add tenant: \"organization_id\" for\n * multi-tenant; use isRead: \"is_read\" (instead of, or alongside, readAt) to\n * track a boolean read flag. The migration, the accessors and the resource\n * all follow this map.\n */\n public static columnMap: NotificationColumnMap = { readAt: \"read_at\" };\n}\n`;\n\n/** The notifications migration, under `models/notification/migrations/`. */\nexport const notificationMigrationStub = `import { Migration } from \"@warlock.js/cascade\";\nimport { notificationColumns } from \"@warlock.js/notifications\";\nimport { Notification } from \"../notification.model\";\n\n/**\n * Notifications table.\n *\n * Columns come from notificationColumns(Notification) — the recipient / tenant\n * / read-state names follow the model's columnMap; type / title / body /\n * payload / idempotency_key are fixed. The recipient column is a UUID unless\n * you pass { idType: \"integer\" } (or \"bigint\" / \"string\") to match your users.\n * Spread it to add your own columns (and mirror them in the model schema):\n *\n * import { uuid } from \"@warlock.js/cascade\";\n *\n * export default Migration.create(Notification, {\n * ...notificationColumns(Notification, { idType: \"integer\" }),\n * // category_id: uuid().index().nullable(),\n * });\n */\nexport default Migration.create(Notification, notificationColumns(Notification));\n`;\n\n/** `src/app/notifications/resources/notification.resource.ts` — the output shape. */\nexport const notificationResourceStub = `import { defineResource } from \"@warlock.js/core\";\n\n/**\n * What every notification endpoint returns, whatever columns the model holds.\n * readAt reads the default read_at column; change it if you change the model's\n * columnMap.\n */\nexport const NotificationResource = defineResource({\n schema: {\n // Passed through as stored: a UUID string or an integer, per the migration.\n id: (id: string | number) => id,\n type: \"string\",\n title: \"string\",\n body: \"string?\",\n payload: \"object?\",\n readAt: [\"read_at\", \"date?\"],\n createdAt: \"date?\",\n },\n});\n`;\n\n/** `src/app/notifications/schema/list-notifications.schema.ts` — the validated list query. */\nexport const listNotificationsSchemaStub = `import { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Query for GET /notifications. Only these keys reach the store (others, such\n * as a cache-busting \\`_\\`, are dropped rather than rejected), and limit is\n * capped so one request cannot read every row. Query values arrive as strings,\n * so the numbers and the flag are coerced.\n */\nexport const listNotificationsSchema = v.object({\n page: v.int().coerce().min(1).optional(),\n limit: v.int().coerce().min(1).max(50).optional(),\n type: v.string().optional(),\n unread: v.boolean().coerce().optional(),\n}).stripUnknown();\n\nexport type ListNotificationsSchema = Infer<typeof listNotificationsSchema>;\n`;\n\n/** `src/app/notifications/types/notifications-request.type.ts` — the guarded request. */\nexport const notificationsRequestTypeStub = `import type { Request, RequestHandler, RequestLocals } from \"@warlock.js/core\";\nimport type { Id } from \"@warlock.js/notifications\";\n\n/**\n * A request that passed authMiddleware, so locals.user is always set. Only the\n * user's id is declared because that is all the inApp store needs. If your\n * app has its own guarded request type, use it instead.\n */\nexport type NotificationsRequest<Payload = unknown> = Request<Payload> & {\n locals: RequestLocals & { user: { id: Id } };\n};\n\nexport type NotificationsRequestHandler<Payload = unknown> = RequestHandler<\n NotificationsRequest<Payload>\n>;\n`;\n\n/** `src/app/notifications/services/mark-notification-read.service.ts`. */\nexport const markNotificationReadServiceStub = `import { ResourceNotFoundError, t } from \"@warlock.js/core\";\nimport { type Id, inApp } from \"@warlock.js/notifications\";\n\n/**\n * Mark one of the user's notifications read and return it. inApp is scoped to\n * the recipient, so another user's id changes nothing and answers 404 here.\n */\nexport async function markNotificationReadService(userId: Id, notificationId: Id) {\n await inApp.markAsRead(userId, notificationId);\n\n const notification = await inApp.find(userId, notificationId);\n\n if (!notification) {\n throw new ResourceNotFoundError(t(\"notifications.notFound\"));\n }\n\n return notification;\n}\n`;\n\n/** `src/app/notifications/controllers/list-notifications.controller.ts`. */\nexport const listNotificationsControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport {\n type ListNotificationsSchema,\n listNotificationsSchema,\n} from \"../schema/list-notifications.schema\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** GET /notifications — the user's notifications, most recent first. */\nexport const listNotificationsController: NotificationsRequestHandler<\n ListNotificationsSchema\n> = async ({ request, response }) => {\n const { data, pagination } = await inApp.list(request.locals.user.id, request.validated());\n\n return response.success({ notifications: data, pagination });\n};\n\nlistNotificationsController.description = \"List notifications\";\n\nlistNotificationsController.validation = {\n schema: listNotificationsSchema,\n validating: [\"query\"],\n};\n`;\n\n/** `src/app/notifications/controllers/unread-notifications-count.controller.ts`. */\nexport const unreadNotificationsCountControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** GET /notifications/unread-count — drives the bell badge. */\nexport const unreadNotificationsCountController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n const count = await inApp.countUnread(request.locals.user.id);\n\n return response.success({ count });\n};\n\nunreadNotificationsCountController.description = \"Unread notifications count\";\n`;\n\n/** `src/app/notifications/controllers/mark-notification-read.controller.ts`. */\nexport const markNotificationReadControllerStub = `import { markNotificationReadService } from \"../services/mark-notification-read.service\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** PATCH /notifications/:id/read — mark one read and return it. */\nexport const markNotificationReadController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n // Route params are strings. A numeric id is an integer id (the default\n // MongoDB stack); anything else, such as a UUID, stays a string.\n const rawId = request.string(\"id\");\n const id = /^\\\\d+$/.test(rawId) ? Number(rawId) : rawId;\n\n const notification = await markNotificationReadService(request.locals.user.id, id);\n\n return response.success({ notification });\n};\n\nmarkNotificationReadController.description = \"Mark notification read\";\n`;\n\n/** `src/app/notifications/controllers/mark-all-notifications-read.controller.ts`. */\nexport const markAllNotificationsReadControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** PATCH /notifications/read-all — mark every unread one read. */\nexport const markAllNotificationsReadController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n const count = await inApp.markAsRead(request.locals.user.id);\n\n return response.success({ count });\n};\n\nmarkAllNotificationsReadController.description = \"Mark all notifications read\";\n`;\n\n/** `src/app/notifications/routes.ts` — the four read endpoints behind `authMiddleware`. */\nexport const notificationRoutesStub = `import { authMiddleware } from \"@warlock.js/auth\";\nimport { router } from \"@warlock.js/core\";\nimport { listNotificationsController } from \"./controllers/list-notifications.controller\";\nimport { markAllNotificationsReadController } from \"./controllers/mark-all-notifications-read.controller\";\nimport { markNotificationReadController } from \"./controllers/mark-notification-read.controller\";\nimport { unreadNotificationsCountController } from \"./controllers/unread-notifications-count.controller\";\n\n/**\n * The signed-in user's own notifications.\n *\n * Notifications come from domain events, so there is no create. Dismissing is\n * left out on purpose; add it when the product needs it (inApp.dismiss).\n *\n * authMiddleware([]) admits any signed-in user. To limit who may read\n * notifications, add a permission gate to the group:\n *\n * import { gate } from \"@warlock.js/access\";\n *\n * router.group({ middleware: [authMiddleware([]), gate(\"notifications.read\")] }, ...);\n */\nrouter.group({ middleware: [authMiddleware([])] }, () => {\n const notifications = router.route(\"/notifications\");\n\n notifications.list(listNotificationsController);\n notifications.nest(\"/unread-count\").get(unreadNotificationsCountController);\n notifications.nest(\"/read-all\").patch(markAllNotificationsReadController);\n notifications.nest(\"/:id/read\").patch(markNotificationReadController);\n});\n`;\n\n/** `src/app/notifications/utils/locales.json` — the module's translations. */\nexport const notificationLocalesStub = `{\n \"notFound\": { \"en\": \"Notification not found\" }\n}\n`;\n\n/** Shared fixtures for the generated signed-in notification controller specs. */\nexport const notificationTestFixtureStub = `import type { Auth } from \"@warlock.js/auth\";\nimport type { ChildModel } from \"@warlock.js/cascade\";\nimport { config } from \"@warlock.js/core\";\nimport { actingAs, type AuthenticatedTestClient } from \"@warlock.js/core/tests\";\nimport { randomUUID } from \"node:crypto\";\nimport { Notification } from \"../models/notification/notification.model\";\n\n/** Isolated recipients and rows; adjust user fields if your auth model requires more. */\nexport async function createNotificationTestFixture() {\n const User = config.key<ChildModel<Auth>>(\"auth.userType.user\");\n if (!User) throw new Error(\"Notification specs need the configured auth.userType.user model.\");\n const users: Auth[] = [];\n const clients: AuthenticatedTestClient[] = [];\n const rows: Notification[] = [];\n\n async function cleanup() {\n const credentials = await Promise.allSettled(\n clients.splice(0).map((client) => client.dispose()),\n );\n const notifications = await Promise.allSettled(\n rows.splice(0).map((row) => row.destroy({ strategy: \"permanent\" })),\n );\n const recipients = await Promise.allSettled(\n users.splice(0).map((user) => user.destroy({ strategy: \"permanent\" })),\n );\n const errors = [...credentials, ...notifications, ...recipients]\n .filter((result): result is PromiseRejectedResult => result.status === \"rejected\")\n .map((result) => result.reason);\n if (errors.length) throw new AggregateError(errors, \"Notification fixture cleanup failed.\");\n }\n\n const createUser = async () => {\n const user = await User.create({\n name: \"Notification test user\",\n email: \"notifications-\" + randomUUID() + \"@example.test\",\n password: \"test-password\",\n });\n users.push(user);\n return user;\n };\n const signIn = async (user: Auth) => {\n const client = await actingAs(user);\n clients.push(client);\n return client;\n };\n const createNotification = async (recipientId: string | number, title: string, readAt?: Date) => {\n const row = await Notification.create({\n user_id: recipientId,\n type: \"test\",\n title,\n read_at: readAt,\n });\n rows.push(row);\n return row;\n };\n\n try {\n const user = await createUser();\n const otherUser = await createUser();\n const client = await signIn(user);\n const otherClient = await signIn(otherUser);\n const own = await createNotification(user.id, \"Own unread notification\");\n const alreadyRead = await createNotification(user.id, \"Own read notification\", new Date());\n const foreign = await createNotification(otherUser.id, \"Other user's notification\");\n await createNotification(otherUser.id, \"Other user's second notification\");\n return { user, otherUser, client, otherClient, own, alreadyRead, foreign, cleanup };\n } catch (error) {\n // Preserve the setup failure after attempting every owned resource's cleanup.\n await cleanup().catch(() => undefined);\n throw error;\n }\n}\n`;\n\n/** A spec for each generated controller, including authenticated recipient isolation. */\nexport function notificationControllerSpecStub(method: \"GET\" | \"PATCH\", path: string): string {\n const helper = method === \"GET\" ? \"testGet\" : \"testPatch\";\n let signedInCases: string;\n if (path === \"/notifications\") {\n signedInCases = ` it(\"lists only the signed-in recipient's rows, ignoring a forged recipient query\", async () => {\n const response = await fixture.client.get(\n \"/notifications?recipientId=\" + fixture.otherUser.id,\n );\n const body = await expectJson<{ notifications: { id: string | number }[] }>(response);\n expect(body.notifications.map((row) => row.id)).toEqual(\n expect.arrayContaining([fixture.own.id, fixture.alreadyRead.id]),\n );\n expect(body.notifications).toHaveLength(2);\n });\n\n it(\"applies unread and paging query filters\", async () => {\n const response = await fixture.client.get(\"/notifications?unread=true&limit=1\");\n const body = await expectJson<{ notifications: { id: string | number }[] }>(response);\n expect(body.notifications.map((row) => row.id)).toEqual([fixture.own.id]);\n });\n\n it(\"rejects a list limit above the schema's cap\", async () => {\n expect((await fixture.client.get(\"/notifications?limit=999\")).status).toBe(422);\n });`;\n } else if (path === \"/notifications/unread-count\") {\n signedInCases = ` it(\"counts only this recipient's unread notifications\", async () => {\n const own = await expectJson<{ count: number }>(\n await fixture.client.get(\"/notifications/unread-count\"),\n );\n const other = await expectJson<{ count: number }>(\n await fixture.otherClient.get(\"/notifications/unread-count\"),\n );\n expect(own.count).toBe(1);\n expect(other.count).toBe(2);\n });`;\n } else if (path === \"/notifications/read-all\") {\n signedInCases = ` it(\"marks only this recipient's unread rows and leaves another recipient unchanged\", async () => {\n const body = await expectJson<{ count: number }>(\n await fixture.client.patch(\"/notifications/read-all\"),\n );\n expect(body.count).toBe(1);\n expect((await Notification.find(fixture.own.id))?.isRead).toBe(true);\n expect((await Notification.find(fixture.foreign.id))?.isRead).toBe(false);\n const other = await expectJson<{ count: number }>(\n await fixture.otherClient.get(\"/notifications/unread-count\"),\n );\n expect(other.count).toBe(2);\n const again = await expectJson<{ count: number }>(\n await fixture.client.patch(\"/notifications/read-all\"),\n );\n expect(again.count).toBe(0);\n });`;\n } else {\n signedInCases = ` it(\"marks its own notification read and returns it\", async () => {\n const response = await fixture.client.patch(\"/notifications/\" + fixture.own.id + \"/read\");\n const body = await expectJson<{\n notification: { id: string | number; readAt?: string | null };\n }>(response);\n expect(body.notification.id).toBe(fixture.own.id);\n expect(body.notification.readAt).toBeTruthy();\n expect((await Notification.find(fixture.own.id))?.isRead).toBe(true);\n });\n\n it(\"answers 404 for another recipient's notification without changing it\", async () => {\n const response = await fixture.client.patch(\"/notifications/\" + fixture.foreign.id + \"/read\");\n expect(response.status).toBe(404);\n expect((await Notification.find(fixture.foreign.id))?.isRead).toBe(false);\n });`;\n }\n const modelImport =\n method === \"PATCH\"\n ? 'import { Notification } from \"../models/notification/notification.model\";\\n'\n : \"\";\n return `import { expectJson, ${helper} } from \"@warlock.js/core/tests\";\nimport { afterEach, beforeEach, describe, expect, it } from \"vitest\";\n${modelImport}import { createNotificationTestFixture } from \"../tests/notifications.fixture\";\n\ndescribe(\"${method} ${path}\", () => {\n it(\"answers 401 without a signed-in user\", async () => {\n const response = await ${helper}(\"${path}\");\n expect(response.status).toBe(401);\n });\n\n describe(\"signed in\", () => {\n let fixture: Awaited<ReturnType<typeof createNotificationTestFixture>> | undefined;\n beforeEach(async () => {\n fixture = await createNotificationTestFixture();\n });\n afterEach(async () => {\n const current = fixture;\n fixture = undefined;\n await current?.cleanup();\n });\n\n${signedInCases.replaceAll(\"fixture.\", \"fixture!.\")}\n });\n});\n`;\n}\n\n/** `src/web/root.setup.ts` — document policy. */\nexport const webRootSetupStub = `import type { RootConfig } from \"@warlock.js/web\";\n\nexport const config: RootConfig = { strictMode: true };\n`;\n\n/**\n * `src/web/root.tsx` — the application root for the SSR page layer.\n *\n * Deliberately minimal. The framework ships a default root, so this exists to\n * give you a place to start rather than because anything requires it. The\n * document component stays here; request policy and an app-level loader\n * belong in `root.setup.ts`. Named ErrorBoundary components stay in the UI.\n */\nexport const webRootStub = `import type { AppProps } from \"@warlock.js/web\";\nimport { Head, Scripts } from \"@warlock.js/web\";\n\n/**\n * The application root.\n *\n * NOT async, and it receives no request/response: it renders on the server and\n * again in the browser during hydration, where neither exists.\n */\nexport default function App({ children }: AppProps) {\n return (\n <html lang=\"en\">\n <head>\n {/*\n <Head /> also renders the viewport tag (width=device-width,\n initial-scale=1). Change it with \\`metadata.viewport\\`,\n or set it to false to leave it out; do not add a second one here.\n */}\n {/*\n Placement only. The framework injects the page's \\`metadata\\`, the\n stylesheet and preload tags for this route, and the canonical links\n into <head> by default — <Head /> just says WHERE they land.\n\n Do not add a <title> here: the page's \\`metadata\\` owns it, and a root\n that emits one too produces two.\n */}\n <Head />\n <link rel=\"icon\" href=\"data:,\" />\n </head>\n <body>\n {/*\n REQUIRED — this is the hydration mount point, not a styling wrapper.\n\n The browser runtime looks up \\`#vessel\\` and hydrates that element only.\n Remove this div, or rename the id, and the page still renders from the\n server but never becomes interactive: the runtime throws in the console\n and nothing on screen changes.\n\n Wrap it in your own markup freely, and put anything that must live\n outside the hydrated tree (a static footer, a portal target) outside\n it — just keep an element with \\`id=\"vessel\"\\` around {children}.\n */}\n <div id=\"vessel\">{children}</div>\n {/*\n The hydration payload and module tags. Written explicitly because\n placement occasionally matters — a CSP nonce, or ordering against\n your own scripts.\n */}\n <Scripts />\n </body>\n </html>\n );\n}\n`;\n\n/**\n * `src/app/contact/controllers/contact.controller.ts` — a real API endpoint\n * for the Web starter's contact form. It intentionally has no persistence\n * dependency: replace the acknowledgement with a mail/job/database action.\n */\nexport const webContactControllerStub = `import { type Request, type RequestHandler } from \"@warlock.js/core\";\nimport { v, type Infer } from \"@warlock.js/seal\";\n\nexport const contactSchema = v.object({\n name: v.string().min(2),\n email: v.email(),\n message: v.string().min(10),\n});\n\nexport type ContactSchema = Infer.Output<typeof contactSchema>;\n\n/** POST /api/contact — validates the starter contact form. */\nexport const contactController: RequestHandler<Request<ContactSchema>> = async ({\n request,\n response,\n}) => {\n const contact = request.validated();\n\n // Replace this with delivery/persistence for your app. Keeping the accepted\n // payload visible makes the endpoint useful while remaining side-effect free.\n return response.success({\n message: \"Thanks, \" + contact.name + \". Your message has been received.\",\n });\n};\n\ncontactController.validation = { schema: contactSchema };\n`;\n\n/** `src/app/contact/routes.ts` — discovered by the standard app route loader. */\nexport const webContactRoutesStub = `import { router } from \"@warlock.js/core\";\nimport { contactController } from \"./controllers/contact.controller\";\n\nrouter.post(\"/api/contact\", contactController, { public: true });\n`;\n\n/** `src/web/index.setup.ts` — page policy and universal registration. */\nexport const webHomeSetupStub = `import { extend } from \"@mongez/localization\";\nimport type { PageConfig } from \"@warlock.js/web\";\n\nexport const config: PageConfig = {\n route: { path: \"/\", name: \"index\" },\n metadata: { title: \"Home\" },\n};\n\nexport function register() {\n extend(\"en\", {\n starter: {\n title: \"Your Warlock app is running.\",\n introduction: \"This page is rendered on the server and hydrated in the browser.\",\n language: \"العربية\",\n contact: \"Send a message\",\n name: \"Name\",\n email: \"Email\",\n message: \"Message\",\n submit: \"Send message\",\n sent: \"Thanks — your message has been received.\",\n },\n });\n extend(\"ar\", {\n starter: {\n title: \"تطبيق Warlock يعمل الآن.\",\n introduction: \"تُعرض هذه الصفحة على الخادم ثم تُفعَّل في المتصفح.\",\n language: \"English\",\n contact: \"أرسل رسالة\",\n name: \"الاسم\",\n email: \"البريد الإلكتروني\",\n message: \"الرسالة\",\n submit: \"إرسال الرسالة\",\n sent: \"شكرًا — تم استلام رسالتك.\",\n },\n });\n}\n`;\n\n/**\n * `src/web/index.page.tsx` — one page, so \\`warlock dev\\` has something to serve\n * the moment this finishes.\n */\nexport const webHomePageStub = `import { http } from \"@mongez/http\";\nimport { setCurrentLocaleCode } from \"@mongez/localization\";\nimport { Form, useFormControl, type FormControlProps } from \"@mongez/react-form\";\nimport { transX } from \"@mongez/react-localization\";\nimport { v } from \"@warlock.js/seal\";\nimport { Link, type PageProps } from \"@warlock.js/web\";\nimport { useState } from \"react\";\n\nconst contactSchema = v.object({\n name: v.string().min(2),\n email: v.email(),\n message: v.string().min(10),\n});\n\nfunction TextInput({ label, ...controlProps }: FormControlProps & { label: string }) {\n const { error, getErrorProps, getInputProps } = useFormControl(controlProps);\n\n return (\n <div className=\"wk-field\">\n <label htmlFor={controlProps.name}>{label}</label>\n <input {...getInputProps()} />\n {error && <p {...getErrorProps()}>{error}</p>}\n </div>\n );\n}\n\n/** Fetch data in index.setup.ts; use a type-only loader import for PageProps. */\nexport default function HomePage(_props: PageProps) {\n // Live state. If the button below does nothing, the page rendered on the\n // server but never hydrated — the runtime never mounted at \\`#vessel\\`. This is\n // deliberately here so that failure is impossible to miss.\n const [count, setCount] = useState(0);\n const [locale, setLocale] = useState<\"en\" | \"ar\">(\"en\");\n const [submitted, setSubmitted] = useState(false);\n const [submitError, setSubmitError] = useState<string | null>(null);\n\n const toggleLocale = () => {\n const nextLocale = locale === \"en\" ? \"ar\" : \"en\";\n setCurrentLocaleCode(nextLocale);\n setLocale(nextLocale);\n };\n\n return (\n <>\n {/*\n Self-contained, dependency-free styling: plain CSS, system fonts, and\n CSS custom properties, scoped to this page. No CSS framework, no utility\n classes, no external stylesheet — this page looks the same whether or\n not \\`warlock add tailwind\\` has ever been run.\n */}\n <style>{\\`\n .wk-home {\n --wk-fg: #0f172a;\n --wk-muted: #64748b;\n --wk-accent: #4f46e5;\n --wk-border: #e2e8f0;\n font-family: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n color: var(--wk-fg);\n max-width: 42rem;\n margin: 4rem auto;\n padding: 0 1.5rem;\n line-height: 1.6;\n }\n .wk-home h1 { font-size: 2.25rem; margin: 0 0 0.5rem; }\n .wk-home p { color: var(--wk-muted); margin: 0 0 1.5rem; }\n .wk-home code {\n font-family: ui-monospace, \"SFMono-Regular\", Menlo, monospace;\n background: #f1f5f9;\n padding: 0.1rem 0.35rem;\n border-radius: 0.25rem;\n }\n .wk-check {\n border: 1px solid var(--wk-border);\n border-radius: 0.75rem;\n padding: 1.25rem 1.5rem;\n margin: 2rem 0;\n }\n .wk-check strong { display: block; font-size: 1.5rem; }\n .wk-check button {\n font: inherit;\n cursor: pointer;\n background: var(--wk-accent);\n color: #fff;\n border: 0;\n border-radius: 0.5rem;\n padding: 0.5rem 1rem;\n margin-top: 0.75rem;\n }\n .wk-links { display: flex; gap: 1.25rem; font-size: 0.95rem; }\n .wk-links a { color: var(--wk-accent); text-decoration: none; }\n .wk-links a:hover { text-decoration: underline; }\n .wk-language { margin-left: auto; }\n .wk-contact { margin-top: 2rem; }\n .wk-field { display: grid; gap: 0.35rem; margin: 0.8rem 0; }\n .wk-field input, .wk-field textarea { font: inherit; padding: 0.55rem; }\n .wk-field p, .wk-submit-error { color: #b91c1c; margin: 0; }\n .wk-success { color: #047857; }\n \\`}</style>\n\n <main className=\"wk-home\" dir={locale === \"ar\" ? \"rtl\" : \"ltr\"}>\n <nav className=\"wk-links\" aria-label=\"Starter links\">\n <a href=\"https://warlock.js.org\" target=\"_blank\" rel=\"noreferrer\">\n Docs\n </a>\n <Link href=\"/\" aria-current=\"page\">\n Home\n </Link>\n <button\n className=\"wk-language\"\n type=\"button\"\n aria-pressed={locale === \"ar\"}\n onClick={toggleLocale}\n >\n {transX(\"starter.language\")}\n </button>\n </nav>\n\n <h1>{transX(\"starter.title\")}</h1>\n <p>{transX(\"starter.introduction\")}</p>\n\n <section className=\"wk-check\">\n <label>If this number goes up when you click, React is hydrated:</label>\n <strong>{count}</strong>\n <button type=\"button\" onClick={() => setCount((c) => c + 1)}>\n Count up\n </button>\n </section>\n\n <section className=\"wk-contact\" aria-labelledby=\"contact-heading\">\n <h2 id=\"contact-heading\">{transX(\"starter.contact\")}</h2>\n <Form<typeof contactSchema>\n id=\"contact-form\"\n schema={contactSchema}\n onSubmit={async ({ form, values }) => {\n setSubmitted(false);\n setSubmitError(null);\n const result = await http.post<{ message: string }>(\"/api/contact\", values);\n\n if (result.error) {\n if (result.error.isValidationError) {\n const body = result.error.body as {\n errors?: Array<{ input: string; error: string }>;\n message?: string;\n };\n form.setErrors(\n Object.fromEntries(\n (body.errors ?? []).map(({ input, error }) => [input, error]),\n ),\n );\n setSubmitError(body.message ?? \"Please correct the highlighted fields.\");\n } else {\n setSubmitError(\"Your message could not be sent. Please try again.\");\n }\n return;\n }\n\n setSubmitted(true);\n form.reset();\n }}\n >\n <TextInput name=\"name\" label={transX(\"starter.name\")} autoComplete=\"name\" />\n <TextInput\n name=\"email\"\n label={transX(\"starter.email\")}\n type=\"email\"\n autoComplete=\"email\"\n />\n <ContactMessage />\n <button type=\"submit\">{transX(\"starter.submit\")}</button>\n {submitError && (\n <p className=\"wk-submit-error\" role=\"alert\">\n {submitError}\n </p>\n )}\n {submitted && (\n <p className=\"wk-success\" role=\"status\">\n {transX(\"starter.sent\")}\n </p>\n )}\n </Form>\n </section>\n </main>\n </>\n );\n}\n\nfunction ContactMessage() {\n const { error, getErrorProps, getInputProps } = useFormControl({ name: \"message\" });\n\n return (\n <div className=\"wk-field\">\n <label htmlFor=\"message\">{transX(\"starter.message\")}</label>\n <textarea {...getInputProps()} rows={5} />\n {error && <p {...getErrorProps()}>{error}</p>}\n </div>\n );\n}\n`;\n"],"mappings":";AAAA,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BhC,MAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+B5B,MAAa,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCnC,MAAa,2BAA2B;;AAGxC,MAAa,0BAA0B;;;;;;;;;;;;AAavC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FvC,MAAa,+BAA+B;;AAG5C,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;;AAsB3C,MAAa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ClC,MAAa,mBAAmB;;;;;;;;;;;;;;;;;AAkBhC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFvC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCvC,MAAa,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDrC,MAAa,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;AAwBzC,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;AAsBxC,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;AAmB3C,MAAa,+BAA+B;;;;;;;;;;;;;;;;;AAkB5C,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;;;AAqB/C,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;AAyB/C,MAAa,yCAAyC;;;;;;;;;;;;;;;;AAiBtD,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;;;;AAsBlD,MAAa,yCAAyC;;;;;;;;;;;;;;;;AAiBtD,MAAa,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BtC,MAAa,0BAA0B;;;;;AAMvC,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2E3C,SAAgB,+BAA+B,QAAyB,MAAsB;CAC5F,MAAM,SAAS,WAAW,QAAQ,YAAY;CAC9C,IAAI;CACJ,IAAI,SAAS,kBACX,gBAAgB;;;;;;;;;;;;;;;;;;;;MAoBX,IAAI,SAAS,+BAClB,gBAAgB;;;;;;;;;;MAUX,IAAI,SAAS,2BAClB,gBAAgB;;;;;;;;;;;;;;;;MAiBhB,gBAAgB;;;;;;;;;;;;;;;CAoBlB,OAAO,wBAAwB,OAAO;;EAHpC,WAAW,UACP,kFACA,GAGM;;YAEF,OAAO,GAAG,KAAK;;6BAEE,OAAO,IAAI,KAAK;;;;;;;;;;;;;;;EAe3C,cAAc,WAAW,YAAY,WAAW,EAAE;;;;AAIpD;;AAGA,MAAa,mBAAmB;;;;;;;;;;;;AAahC,MAAa,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4D3B,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BxC,MAAa,uBAAuB;;;;;;AAOpC,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0ChC,MAAa,kBAAkB"}
package/esm/index.d.mts CHANGED
@@ -151,7 +151,7 @@ import { hmacHash } from "./encryption/hash.mjs";
151
151
  import { hashPassword, verifyPassword } from "./encryption/password.mjs";
152
152
  import { EncryptionConfigurations, EncryptionPasswordConfigurations } from "./encryption/types.mjs";
153
153
  import { SecretStoreError, SecretStoreErrorCode } from "./secrets/errors.mjs";
154
- import { SecretBackend, SecretStoreOptions, SecretsConfigurations } from "./secrets/types.mjs";
154
+ import { SecretBackend, SecretBackendType, SecretStoreOptions, SecretsConfigurations } from "./secrets/types.mjs";
155
155
  import { MemorySecretBackend } from "./secrets/memory-backend.mjs";
156
156
  import { SecretStore } from "./secrets/secret-store.mjs";
157
157
  import { secrets } from "./secrets/secrets.mjs";
@@ -232,7 +232,7 @@ import "./warlock-config/index.mjs";
232
232
  import { env } from "@mongez/dotenv";
233
233
  import { colors } from "@mongez/copper";
234
234
  export * from "@mongez/localization";
235
- export { $registerUseCase, $unregisterUseCase, APP_ROLES, AUTH_GUARD_MARKER, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, AppRole, Application, AuthDescriptor, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseCastOutput, BaseConnector, type BenchmarkChannel, type BenchmarkConfigurations, type BenchmarkErrorResult, type BenchmarkOptions, BenchmarkProfiler, type BenchmarkProfilerOptions, type BenchmarkResult, BenchmarkSnapshots, type BenchmarkSnapshotsOptions, type BenchmarkStats, type BenchmarkSuccessResult, BootContext, BootListener, BootSignal, BootSignalType, BootValidator, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, CastOutput, ChunkCallback, ClockSource, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConditionalRequestInput, ConditionalRequestOutcome, ConfigIssue, ConfigKey, ConfigKeyRegistry, ConfigModuleEntry, ConfigName, ConfigOf, ConfigRegistry, ConfigSchema, ConfigSchemaOptions, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, DetectedImageFormat, type DevelopmentAppModuleEntry, type DevelopmentAppModules, type DevelopmentModelModuleEntry, type DevelopmentModelModuleState, type DevelopmentModelModules, DevelopmentPostmanResult, ERROR_CODES, ERROR_CODES_DOCS_URL, EncryptionConfigurations, EncryptionPasswordConfigurations, EntityTag, Environment, ErrorCodeArea, ErrorCodeCategory, ErrorCodeDefinition, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FieldOutput, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, type HttpErrorMapper, type HttpErrorMapping, HttpLoggingConfig, HttpReadyReport, HttpServerOptions, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, IdsSource, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidConfigError, InvalidCspDirectiveError, type IpFilterOptions, JavaScriptRuntime, JavaScriptRuntimeName, ListOptions, LocalDriver, LocalStorageDriverOptions, LocaleDictionaryEntries, LocaleDictionaryError, LocalizedObject, LogConfigurations, LoggerConnector, MAIL_EVENTS, Mail, type MailAddress, type MailAttachment, type MailConfigurations, MailError, type MailErrorCode, type MailEvents, type MailMode, type MailOptions, type MailPriority, type MailResult, MailerConnector, type MailersConfig, type MaintenanceOptions, MemorySecretBackend, Middleware, MiddlewareResponse, MimeTypes, ModelResourceRegistry, NULLABLE_RESOURCE, NamedApiRoute, NamedApiRoutesOptions, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, NullableResource, NullableResourceTarget, OPENAPI_JSON_SCHEMA_DIALECT, OpenApiBuildResult, OpenApiComponents, OpenApiContext, OpenApiDocument, OpenApiOperation, OpenApiParameter, OpenApiRequestBody, OpenApiResponse, OpenApiRouteInput, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSecurityScheme, OpenApiValidationResponseConfig, POSTMAN_COLLECTION_SCHEMA, PaginationMode, PaginationResult, ParsedLocaleDictionary, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PostmanAuth, PostmanAuthEntry, PostmanBody, PostmanCollection, PostmanCollectionOptions, PostmanFolder, PostmanFormParam, PostmanHeader, PostmanItem, PostmanOriginalRequest, PostmanQueryParam, PostmanRequest, PostmanRequestItem, PostmanResponse, PostmanUrl, PostmanVariable, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PrivateRequestLoggingRule, PurgeImageVariantsOptions, PutDirectoryOptions, PutDirectoryResult, PutFromUrlOptions, PutOptions, QueryBuilderContract, Queue, R2Driver, R2StorageDriverOptions, type RateLimitOptions, RegisterConfiguredConnectorsOptions, RegisterResource, RegisteredUseCase, RepositoryAdapterContract, RepositoryConfigurations, RepositoryEvent, RepositoryManager, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, Request, RequestContextStore, RequestController, RequestControllerContract, RequestEvent, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestLocals, RequestLog, RequestLogSnapshot, RequestLogSource, RequestLoggingOptions, RequestMethod, RequestTranslator, ResolveImageVariantInput, type ResolvedCLICommandOption, ResolvedImageVariant, ResolvedImageVariantsConfig, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutput, ResourceOutputOf, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyOutput, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSSEMessageOptions, ResponseSSEOptions, ResponseSchema, ResponseSchemaOutput, ResponseStatus, ResponseStreamController, ResponseStreamOptions, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteNameTakenError, RouteOptions, RouteRateLimitOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SUPPORTED_RUNTIMES_DOCS_URL, SafeFetchOptions, SafeFetchResult, SafeRedirectOptions, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, type SecretBackend, SecretStore, SecretStoreError, SecretStoreErrorCode, type SecretStoreOptions, type SecretsConfigurations, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, Serialized, SerializedWire, ServerError, ShutdownListener, SocketAdapterFactory, SocketConnector, SocketOptions, StaticMountOptions, Storage, StorageCapabilityError, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StorageNotInitializedError, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileControllerOptions, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, ValidationFailureContext, ValidationFailureHandler, ValidationFailureResponse, ValidationResponseConfiguration, VariantOutputFormat, VariantSourceFormat, WarlockConfig, WarlockConfigManager, WarlockError, WarlockErrorCode, WarningSink, WatermarkConfig, WhereOperator, XMLable, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertNodeOnlyCommand, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assertValidConfigModules, assetsUrl, beginHttpDrain, bootstrap, broadcastSocketEvent, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildRequestLogSnapshot, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, clock, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, createUploadedFileController, decrypt, defaultHttpConfigurations, defineConfig, defineConfigSchema, defineResource, deriveTraceId, describeJavaScriptRuntime, describePositionalHandlerSuspect, detectJavaScriptRuntime, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, errorCodeDocsUrl, errorCodeOf, escapeHeaderValue, evaluateConditionalRequest, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, explainErrorCode, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, formatConfigIssues, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getExplicitMailMode, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, ids, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isAuthGuardMiddleware, isBootSignal, isConfigSchema, isDevelopmentMode, isNewerVersion, isNullableResource, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isSafeRedirect, isTestMode, isTracingEnabled, isUnguardedMutatingRoute, isUnknownTsExtensionError, isUnresolvedConfigImportError, isUnsupportedTypeStrippingError, isValidIdempotencyKey, isWarlockErrorCode, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, markAuthGuard, matchesDerivedRouteName, matchesIfMatch, matchesIfNoneMatch, measure, mergeCspDirectives, middleware, nodeOnlyCommandError, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, nullable, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetMailMode, resetRolesCacheForTests, resetTracingConfigForTests, resetUnguardedRouteReports, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolveMailConfig, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, safeRedirect, sanitizePath, secrets, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setClockSource, setConfig, setEnvironment, setHttpReadyReport, setIdsSource, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, strongEntityTagMatch, t, tempPath, toJson, toSingleLineSseField, trackConnectionsForDrain, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, unverifiedBuildRuntimeNotice, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateConfigValue, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, weakEntityTagMatch, wrapResponseInDataKey };
235
+ export { $registerUseCase, $unregisterUseCase, APP_ROLES, AUTH_GUARD_MARKER, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, AppRole, Application, AuthDescriptor, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseCastOutput, BaseConnector, type BenchmarkChannel, type BenchmarkConfigurations, type BenchmarkErrorResult, type BenchmarkOptions, BenchmarkProfiler, type BenchmarkProfilerOptions, type BenchmarkResult, BenchmarkSnapshots, type BenchmarkSnapshotsOptions, type BenchmarkStats, type BenchmarkSuccessResult, BootContext, BootListener, BootSignal, BootSignalType, BootValidator, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, CastOutput, ChunkCallback, ClockSource, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConditionalRequestInput, ConditionalRequestOutcome, ConfigIssue, ConfigKey, ConfigKeyRegistry, ConfigModuleEntry, ConfigName, ConfigOf, ConfigRegistry, ConfigSchema, ConfigSchemaOptions, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, DetectedImageFormat, type DevelopmentAppModuleEntry, type DevelopmentAppModules, type DevelopmentModelModuleEntry, type DevelopmentModelModuleState, type DevelopmentModelModules, DevelopmentPostmanResult, ERROR_CODES, ERROR_CODES_DOCS_URL, EncryptionConfigurations, EncryptionPasswordConfigurations, EntityTag, Environment, ErrorCodeArea, ErrorCodeCategory, ErrorCodeDefinition, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FieldOutput, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, type HttpErrorMapper, type HttpErrorMapping, HttpLoggingConfig, HttpReadyReport, HttpServerOptions, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, IdsSource, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidConfigError, InvalidCspDirectiveError, type IpFilterOptions, JavaScriptRuntime, JavaScriptRuntimeName, ListOptions, LocalDriver, LocalStorageDriverOptions, LocaleDictionaryEntries, LocaleDictionaryError, LocalizedObject, LogConfigurations, LoggerConnector, MAIL_EVENTS, Mail, type MailAddress, type MailAttachment, type MailConfigurations, MailError, type MailErrorCode, type MailEvents, type MailMode, type MailOptions, type MailPriority, type MailResult, MailerConnector, type MailersConfig, type MaintenanceOptions, MemorySecretBackend, Middleware, MiddlewareResponse, MimeTypes, ModelResourceRegistry, NULLABLE_RESOURCE, NamedApiRoute, NamedApiRoutesOptions, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, NullableResource, NullableResourceTarget, OPENAPI_JSON_SCHEMA_DIALECT, OpenApiBuildResult, OpenApiComponents, OpenApiContext, OpenApiDocument, OpenApiOperation, OpenApiParameter, OpenApiRequestBody, OpenApiResponse, OpenApiRouteInput, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSecurityScheme, OpenApiValidationResponseConfig, POSTMAN_COLLECTION_SCHEMA, PaginationMode, PaginationResult, ParsedLocaleDictionary, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PostmanAuth, PostmanAuthEntry, PostmanBody, PostmanCollection, PostmanCollectionOptions, PostmanFolder, PostmanFormParam, PostmanHeader, PostmanItem, PostmanOriginalRequest, PostmanQueryParam, PostmanRequest, PostmanRequestItem, PostmanResponse, PostmanUrl, PostmanVariable, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PrivateRequestLoggingRule, PurgeImageVariantsOptions, PutDirectoryOptions, PutDirectoryResult, PutFromUrlOptions, PutOptions, QueryBuilderContract, Queue, R2Driver, R2StorageDriverOptions, type RateLimitOptions, RegisterConfiguredConnectorsOptions, RegisterResource, RegisteredUseCase, RepositoryAdapterContract, RepositoryConfigurations, RepositoryEvent, RepositoryManager, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, Request, RequestContextStore, RequestController, RequestControllerContract, RequestEvent, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestLocals, RequestLog, RequestLogSnapshot, RequestLogSource, RequestLoggingOptions, RequestMethod, RequestTranslator, ResolveImageVariantInput, type ResolvedCLICommandOption, ResolvedImageVariant, ResolvedImageVariantsConfig, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutput, ResourceOutputOf, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyOutput, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSSEMessageOptions, ResponseSSEOptions, ResponseSchema, ResponseSchemaOutput, ResponseStatus, ResponseStreamController, ResponseStreamOptions, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteNameTakenError, RouteOptions, RouteRateLimitOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SUPPORTED_RUNTIMES_DOCS_URL, SafeFetchOptions, SafeFetchResult, SafeRedirectOptions, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, type SecretBackend, type SecretBackendType, SecretStore, SecretStoreError, SecretStoreErrorCode, type SecretStoreOptions, type SecretsConfigurations, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, Serialized, SerializedWire, ServerError, ShutdownListener, SocketAdapterFactory, SocketConnector, SocketOptions, StaticMountOptions, Storage, StorageCapabilityError, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StorageNotInitializedError, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileControllerOptions, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, ValidationFailureContext, ValidationFailureHandler, ValidationFailureResponse, ValidationResponseConfiguration, VariantOutputFormat, VariantSourceFormat, WarlockConfig, WarlockConfigManager, WarlockError, WarlockErrorCode, WarningSink, WatermarkConfig, WhereOperator, XMLable, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertNodeOnlyCommand, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assertValidConfigModules, assetsUrl, beginHttpDrain, bootstrap, broadcastSocketEvent, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildRequestLogSnapshot, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, clock, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, createUploadedFileController, decrypt, defaultHttpConfigurations, defineConfig, defineConfigSchema, defineResource, deriveTraceId, describeJavaScriptRuntime, describePositionalHandlerSuspect, detectJavaScriptRuntime, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, errorCodeDocsUrl, errorCodeOf, escapeHeaderValue, evaluateConditionalRequest, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, explainErrorCode, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, formatConfigIssues, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getExplicitMailMode, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, ids, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isAuthGuardMiddleware, isBootSignal, isConfigSchema, isDevelopmentMode, isNewerVersion, isNullableResource, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isSafeRedirect, isTestMode, isTracingEnabled, isUnguardedMutatingRoute, isUnknownTsExtensionError, isUnresolvedConfigImportError, isUnsupportedTypeStrippingError, isValidIdempotencyKey, isWarlockErrorCode, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, markAuthGuard, matchesDerivedRouteName, matchesIfMatch, matchesIfNoneMatch, measure, mergeCspDirectives, middleware, nodeOnlyCommandError, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, nullable, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetMailMode, resetRolesCacheForTests, resetTracingConfigForTests, resetUnguardedRouteReports, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolveMailConfig, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, safeRedirect, sanitizePath, secrets, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setClockSource, setConfig, setEnvironment, setHttpReadyReport, setIdsSource, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, strongEntityTagMatch, t, tempPath, toJson, toSingleLineSseField, trackConnectionsForDrain, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, unverifiedBuildRuntimeNotice, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateConfigValue, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, weakEntityTagMatch, wrapResponseInDataKey };
236
236
  import "./config/types.mjs";
237
237
  import "./http/request.mjs";
238
238
  import "./http/serialized.mjs";
@@ -1,5 +1,5 @@
1
1
  //#region ../../packages/core/src/secrets/errors.d.ts
2
- export type SecretStoreErrorCode = "INVALID_NAME" | "INVALID_VALUE" | "INVALID_NAMESPACE" | "READ_ONLY" | "KEY_REQUIRED" | "UNAVAILABLE" | "UNSAFE_FILE" | "CORRUPT_FILE";
2
+ export type SecretStoreErrorCode = "INVALID_DRIVER" | "MEMORY_IN_PRODUCTION" | "INVALID_NAME" | "INVALID_VALUE" | "INVALID_NAMESPACE" | "READ_ONLY" | "KEY_REQUIRED" | "UNAVAILABLE" | "UNSAFE_FILE" | "CORRUPT_FILE";
3
3
  /** Safe to log: never carries names, values, paths, or vendor error causes. */
4
4
  export declare class SecretStoreError extends Error {
5
5
  readonly code: SecretStoreErrorCode;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/secrets/errors.ts"],"mappings":";YAAY;;qBAWC,yBAAyB;WACD,MAAM;EAAzC,YAAmC,MAAM"}
1
+ {"version":3,"file":"errors.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/secrets/errors.ts"],"mappings":";YAAY;;qBAaC,yBAAyB;WACD,MAAM;EAAzC,YAAmC,MAAM"}
@@ -3,6 +3,8 @@
3
3
  var SecretStoreError = class extends Error {
4
4
  constructor(code) {
5
5
  super({
6
+ INVALID_DRIVER: "secrets.driver / SECRETS_DRIVER must be auto or memory.",
7
+ MEMORY_IN_PRODUCTION: "The memory secrets driver requires secrets.allowMemoryInProduction: true when NODE_ENV=production.",
6
8
  INVALID_NAME: "Secret names must be valid Unicode strings of 1 to 256 UTF-16 code units.",
7
9
  INVALID_VALUE: "Secret values must be strings.",
8
10
  INVALID_NAMESPACE: "A nonempty secret store namespace is required.",
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","names":[],"sources":["../../../../../../../../packages/core/src/secrets/errors.ts"],"sourcesContent":["export type SecretStoreErrorCode =\n | \"INVALID_NAME\"\n | \"INVALID_VALUE\"\n | \"INVALID_NAMESPACE\"\n | \"READ_ONLY\"\n | \"KEY_REQUIRED\"\n | \"UNAVAILABLE\"\n | \"UNSAFE_FILE\"\n | \"CORRUPT_FILE\";\n\n/** Safe to log: never carries names, values, paths, or vendor error causes. */\nexport class SecretStoreError extends Error {\n public constructor(public readonly code: SecretStoreErrorCode) {\n super(\n {\n INVALID_NAME: \"Secret names must be valid Unicode strings of 1 to 256 UTF-16 code units.\",\n INVALID_VALUE: \"Secret values must be strings.\",\n INVALID_NAMESPACE: \"A nonempty secret store namespace is required.\",\n READ_ONLY: \"This secret is supplied by a read-only environment variable.\",\n KEY_REQUIRED: \"File secrets require encryption.key: exactly 64 hexadecimal characters.\",\n UNAVAILABLE: \"The selected secret backend is unavailable. No unsafe write was attempted.\",\n UNSAFE_FILE: \"Secret storage must use an owned, private directory and regular files.\",\n CORRUPT_FILE:\n \"A secret file could not be authenticated. Check the app key and restore a backup.\",\n }[code],\n );\n this.name = \"SecretStoreError\";\n }\n}\n"],"mappings":";;AAWA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,AAAO,YAAY,AAAgB,MAA4B;EAC7D,MACE;GACE,cAAc;GACd,eAAe;GACf,mBAAmB;GACnB,WAAW;GACX,cAAc;GACd,aAAa;GACb,aAAa;GACb,cACE;EACJ,EAAE,KACJ;EAbiC;EAcjC,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"errors.mjs","names":[],"sources":["../../../../../../../../packages/core/src/secrets/errors.ts"],"sourcesContent":["export type SecretStoreErrorCode =\n | \"INVALID_DRIVER\"\n | \"MEMORY_IN_PRODUCTION\"\n | \"INVALID_NAME\"\n | \"INVALID_VALUE\"\n | \"INVALID_NAMESPACE\"\n | \"READ_ONLY\"\n | \"KEY_REQUIRED\"\n | \"UNAVAILABLE\"\n | \"UNSAFE_FILE\"\n | \"CORRUPT_FILE\";\n\n/** Safe to log: never carries names, values, paths, or vendor error causes. */\nexport class SecretStoreError extends Error {\n public constructor(public readonly code: SecretStoreErrorCode) {\n super(\n {\n INVALID_DRIVER: \"secrets.driver / SECRETS_DRIVER must be auto or memory.\",\n MEMORY_IN_PRODUCTION:\n \"The memory secrets driver requires secrets.allowMemoryInProduction: true when NODE_ENV=production.\",\n INVALID_NAME: \"Secret names must be valid Unicode strings of 1 to 256 UTF-16 code units.\",\n INVALID_VALUE: \"Secret values must be strings.\",\n INVALID_NAMESPACE: \"A nonempty secret store namespace is required.\",\n READ_ONLY: \"This secret is supplied by a read-only environment variable.\",\n KEY_REQUIRED: \"File secrets require encryption.key: exactly 64 hexadecimal characters.\",\n UNAVAILABLE: \"The selected secret backend is unavailable. No unsafe write was attempted.\",\n UNSAFE_FILE: \"Secret storage must use an owned, private directory and regular files.\",\n CORRUPT_FILE:\n \"A secret file could not be authenticated. Check the app key and restore a backup.\",\n }[code],\n );\n this.name = \"SecretStoreError\";\n }\n}\n"],"mappings":";;AAaA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,AAAO,YAAY,AAAgB,MAA4B;EAC7D,MACE;GACE,gBAAgB;GAChB,sBACE;GACF,cAAc;GACd,eAAe;GACf,mBAAmB;GACnB,WAAW;GACX,cAAc;GACd,aAAa;GACb,aAAa;GACb,cACE;EACJ,EAAE,KACJ;EAhBiC;EAiBjC,KAAK,OAAO;CACd;AACF"}
@@ -17,6 +17,7 @@ var FileSecretBackend = class {
17
17
  constructor(directory, encryptionKey) {
18
18
  this.directory = directory;
19
19
  this.encryptionKey = encryptionKey;
20
+ this.type = "file";
20
21
  }
21
22
  key(namespace) {
22
23
  const secret = this.encryptionKey();
@@ -1 +1 @@
1
- {"version":3,"file":"file-backend.mjs","names":[],"sources":["../../../../../../../../packages/core/src/secrets/file-backend.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from \"node:crypto\";\nimport { registerLogSecret } from \"@warlock.js/logger\";\nimport { constants, type Stats } from \"node:fs\";\nimport { lstat, mkdir, open, rename, unlink, type FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { SecretStoreError } from \"./errors\";\nimport type { SecretBackend } from \"./types\";\n\nfunction digest(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction isMissing(error: unknown): boolean {\n return error instanceof Error && \"code\" in error && error.code === \"ENOENT\";\n}\n\n/** One authenticated file per secret: concurrent writes to different keys cannot clobber each other. */\nexport class FileSecretBackend implements SecretBackend {\n public constructor(\n private readonly directory: string,\n private readonly encryptionKey: () => string | undefined,\n ) {}\n\n private key(namespace: string): Buffer {\n const secret = this.encryptionKey();\n if (typeof secret !== \"string\" || !/^[a-f\\d]{64}$/i.test(secret)) {\n throw new SecretStoreError(\"KEY_REQUIRED\");\n }\n registerLogSecret(secret, [\"encryptionKey\"]);\n // Core's encrypt/decrypt helpers use global config directly. Derive a\n // separate AES-256-GCM key without changing that global config.\n // https://nodejs.org/docs/latest-v22.x/api/crypto.html#cryptohkdfsyncdigest-ikm-salt-info-keylen\n return Buffer.from(\n hkdfSync(\"sha256\", Buffer.from(secret, \"hex\"), namespace, \"warlock:secrets:v1\", 32),\n );\n }\n\n private validateOwner(stats: Stats, directory: boolean): void {\n if (\n (directory ? !stats.isDirectory() : !stats.isFile() || stats.nlink !== 1) ||\n (process.getuid && stats.uid !== process.getuid())\n ) {\n throw new SecretStoreError(\"UNSAFE_FILE\");\n }\n }\n\n private async folder(namespace: string, create: boolean): Promise<string | undefined> {\n // Node's Windows modes cannot enforce owner-only ACLs. Fail closed there.\n // https://nodejs.org/docs/latest-v22.x/api/fs.html#file-modes\n const root = path.resolve(this.directory);\n const folder = path.join(root, digest(namespace));\n for (const directory of [root, folder]) {\n if (!create) {\n try {\n await lstat(directory);\n } catch (error) {\n if (isMissing(error)) return undefined;\n throw error;\n }\n }\n if (process.platform === \"win32\") throw new SecretStoreError(\"UNSAFE_FILE\");\n if (create) await mkdir(directory, { recursive: true, mode: 0o700 });\n this.validateOwner(await lstat(directory), true);\n const handle = await open(directory, constants.O_RDONLY | constants.O_NOFOLLOW);\n try {\n this.validateOwner(await handle.stat(), true);\n await handle.chmod(0o700);\n if (((await handle.stat()).mode & 0o777) !== 0o700) {\n throw new SecretStoreError(\"UNSAFE_FILE\");\n }\n } finally {\n await handle.close();\n }\n }\n return folder;\n }\n\n private async location(\n namespace: string,\n name: string,\n create: boolean,\n ): Promise<string | undefined> {\n const folder = await this.folder(namespace, create);\n return folder ? path.join(folder, `${digest(name)}.secret`) : undefined;\n }\n\n private aad(namespace: string, name: string): Buffer {\n return Buffer.from(JSON.stringify([\"warlock:secrets:v1\", namespace, name]));\n }\n\n private async safe<T>(operation: () => Promise<T>): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (error instanceof SecretStoreError) throw error;\n if (error instanceof Error && \"code\" in error && error.code === \"ELOOP\") {\n throw new SecretStoreError(\"UNSAFE_FILE\");\n }\n throw new SecretStoreError(\"UNAVAILABLE\");\n }\n }\n\n public async get(namespace: string, name: string): Promise<string | undefined> {\n return this.safe(async () => {\n const file = await this.location(namespace, name, false);\n if (!file) return undefined;\n let handle: FileHandle;\n try {\n handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n } catch (error) {\n if (isMissing(error)) return undefined;\n throw error;\n }\n let payload: Buffer;\n try {\n this.validateOwner(await handle.stat(), false);\n await handle.chmod(0o600);\n if (((await handle.stat()).mode & 0o777) !== 0o600) {\n throw new SecretStoreError(\"UNSAFE_FILE\");\n }\n payload = await handle.readFile();\n } finally {\n await handle.close();\n }\n const key = this.key(namespace);\n try {\n // v1 (one byte), 12-byte IV, 16-byte tag, then ciphertext (possibly empty).\n if (payload.length < 29 || payload[0] !== 1) throw new Error();\n const decipher = createDecipheriv(\"aes-256-gcm\", key, payload.subarray(1, 13));\n decipher.setAAD(this.aad(namespace, name));\n decipher.setAuthTag(payload.subarray(13, 29));\n return Buffer.concat([decipher.update(payload.subarray(29)), decipher.final()]).toString(\n \"utf8\",\n );\n } catch {\n throw new SecretStoreError(\"CORRUPT_FILE\");\n }\n });\n }\n\n public async set(namespace: string, name: string, value: string): Promise<void> {\n return this.safe(async () => {\n const key = this.key(namespace);\n const file = await this.location(namespace, name, true);\n if (!file) throw new SecretStoreError(\"UNAVAILABLE\");\n try {\n this.validateOwner(await lstat(file), false);\n } catch (error) {\n if (!isMissing(error)) throw error;\n }\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n cipher.setAAD(this.aad(namespace, name));\n const encrypted = Buffer.concat([cipher.update(value, \"utf8\"), cipher.final()]);\n const payload = Buffer.concat([Buffer.from([1]), iv, cipher.getAuthTag(), encrypted]);\n const temporary = `${file}.${randomBytes(16).toString(\"hex\")}.tmp`;\n const handle = await open(temporary, \"wx\", 0o600);\n try {\n try {\n await handle.chmod(0o600);\n this.validateOwner(await handle.stat(), false);\n if (((await handle.stat()).mode & 0o777) !== 0o600) {\n throw new SecretStoreError(\"UNSAFE_FILE\");\n }\n await handle.writeFile(payload);\n await handle.sync();\n } finally {\n await handle.close();\n }\n await rename(temporary, file);\n } finally {\n await unlink(temporary).catch((error: unknown) => {\n if (!isMissing(error)) throw error;\n });\n }\n });\n }\n\n public async remove(namespace: string, name: string): Promise<boolean> {\n return this.safe(async () => {\n const file = await this.location(namespace, name, false);\n if (!file) return false;\n try {\n this.validateOwner(await lstat(file), false);\n await unlink(file);\n return true;\n } catch (error) {\n if (isMissing(error)) return false;\n throw error;\n }\n });\n }\n}\n"],"mappings":";;;;;;;;AAQA,SAAS,OAAO,OAAuB;CACrC,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,SAAS,UAAU,OAAyB;CAC1C,OAAO,iBAAiB,SAAS,UAAU,SAAS,MAAM,SAAS;AACrE;;AAGA,IAAa,oBAAb,MAAwD;CACtD,AAAO,YACL,AAAiB,WACjB,AAAiB,eACjB;EAFiB;EACA;CAChB;CAEH,AAAQ,IAAI,WAA2B;EACrC,MAAM,SAAS,KAAK,cAAc;EAClC,IAAI,OAAO,WAAW,YAAY,CAAC,iBAAiB,KAAK,MAAM,GAC7D,MAAM,IAAI,iBAAiB,cAAc;EAE3C,kBAAkB,QAAQ,CAAC,eAAe,CAAC;EAI3C,OAAO,OAAO,KACZ,SAAS,UAAU,OAAO,KAAK,QAAQ,KAAK,GAAG,WAAW,sBAAsB,EAAE,CACpF;CACF;CAEA,AAAQ,cAAc,OAAc,WAA0B;EAC5D,KACG,YAAY,CAAC,MAAM,YAAY,IAAI,CAAC,MAAM,OAAO,KAAK,MAAM,UAAU,MACtE,QAAQ,UAAU,MAAM,QAAQ,QAAQ,OAAO,GAEhD,MAAM,IAAI,iBAAiB,aAAa;CAE5C;CAEA,MAAc,OAAO,WAAmB,QAA8C;EAGpF,MAAM,OAAO,KAAK,QAAQ,KAAK,SAAS;EACxC,MAAM,SAAS,KAAK,KAAK,MAAM,OAAO,SAAS,CAAC;EAChD,KAAK,MAAM,aAAa,CAAC,MAAM,MAAM,GAAG;GACtC,IAAI,CAAC,QACH,IAAI;IACF,MAAM,MAAM,SAAS;GACvB,SAAS,OAAO;IACd,IAAI,UAAU,KAAK,GAAG,OAAO;IAC7B,MAAM;GACR;GAEF,IAAI,QAAQ,aAAa,SAAS,MAAM,IAAI,iBAAiB,aAAa;GAC1E,IAAI,QAAQ,MAAM,MAAM,WAAW;IAAE,WAAW;IAAM,MAAM;GAAM,CAAC;GACnE,KAAK,cAAc,MAAM,MAAM,SAAS,GAAG,IAAI;GAC/C,MAAM,SAAS,MAAM,KAAK,WAAW,UAAU,WAAW,UAAU,UAAU;GAC9E,IAAI;IACF,KAAK,cAAc,MAAM,OAAO,KAAK,GAAG,IAAI;IAC5C,MAAM,OAAO,MAAM,GAAK;IACxB,MAAM,MAAM,OAAO,KAAK,EAAC,CAAE,OAAO,SAAW,KAC3C,MAAM,IAAI,iBAAiB,aAAa;GAE5C,UAAU;IACR,MAAM,OAAO,MAAM;GACrB;EACF;EACA,OAAO;CACT;CAEA,MAAc,SACZ,WACA,MACA,QAC6B;EAC7B,MAAM,SAAS,MAAM,KAAK,OAAO,WAAW,MAAM;EAClD,OAAO,SAAS,KAAK,KAAK,QAAQ,GAAG,OAAO,IAAI,EAAE,QAAQ,IAAI;CAChE;CAEA,AAAQ,IAAI,WAAmB,MAAsB;EACnD,OAAO,OAAO,KAAK,KAAK,UAAU;GAAC;GAAsB;GAAW;EAAI,CAAC,CAAC;CAC5E;CAEA,MAAc,KAAQ,WAAyC;EAC7D,IAAI;GACF,OAAO,MAAM,UAAU;EACzB,SAAS,OAAO;GACd,IAAI,iBAAiB,kBAAkB,MAAM;GAC7C,IAAI,iBAAiB,SAAS,UAAU,SAAS,MAAM,SAAS,SAC9D,MAAM,IAAI,iBAAiB,aAAa;GAE1C,MAAM,IAAI,iBAAiB,aAAa;EAC1C;CACF;CAEA,MAAa,IAAI,WAAmB,MAA2C;EAC7E,OAAO,KAAK,KAAK,YAAY;GAC3B,MAAM,OAAO,MAAM,KAAK,SAAS,WAAW,MAAM,KAAK;GACvD,IAAI,CAAC,MAAM,OAAO;GAClB,IAAI;GACJ,IAAI;IACF,SAAS,MAAM,KAAK,MAAM,UAAU,WAAW,UAAU,aAAa,UAAU,UAAU;GAC5F,SAAS,OAAO;IACd,IAAI,UAAU,KAAK,GAAG,OAAO;IAC7B,MAAM;GACR;GACA,IAAI;GACJ,IAAI;IACF,KAAK,cAAc,MAAM,OAAO,KAAK,GAAG,KAAK;IAC7C,MAAM,OAAO,MAAM,GAAK;IACxB,MAAM,MAAM,OAAO,KAAK,EAAC,CAAE,OAAO,SAAW,KAC3C,MAAM,IAAI,iBAAiB,aAAa;IAE1C,UAAU,MAAM,OAAO,SAAS;GAClC,UAAU;IACR,MAAM,OAAO,MAAM;GACrB;GACA,MAAM,MAAM,KAAK,IAAI,SAAS;GAC9B,IAAI;IAEF,IAAI,QAAQ,SAAS,MAAM,QAAQ,OAAO,GAAG,MAAM,IAAI,MAAM;IAC7D,MAAM,WAAW,iBAAiB,eAAe,KAAK,QAAQ,SAAS,GAAG,EAAE,CAAC;IAC7E,SAAS,OAAO,KAAK,IAAI,WAAW,IAAI,CAAC;IACzC,SAAS,WAAW,QAAQ,SAAS,IAAI,EAAE,CAAC;IAC5C,OAAO,OAAO,OAAO,CAAC,SAAS,OAAO,QAAQ,SAAS,EAAE,CAAC,GAAG,SAAS,MAAM,CAAC,CAAC,CAAC,CAAC,SAC9E,MACF;GACF,QAAQ;IACN,MAAM,IAAI,iBAAiB,cAAc;GAC3C;EACF,CAAC;CACH;CAEA,MAAa,IAAI,WAAmB,MAAc,OAA8B;EAC9E,OAAO,KAAK,KAAK,YAAY;GAC3B,MAAM,MAAM,KAAK,IAAI,SAAS;GAC9B,MAAM,OAAO,MAAM,KAAK,SAAS,WAAW,MAAM,IAAI;GACtD,IAAI,CAAC,MAAM,MAAM,IAAI,iBAAiB,aAAa;GACnD,IAAI;IACF,KAAK,cAAc,MAAM,MAAM,IAAI,GAAG,KAAK;GAC7C,SAAS,OAAO;IACd,IAAI,CAAC,UAAU,KAAK,GAAG,MAAM;GAC/B;GACA,MAAM,KAAK,YAAY,EAAE;GACzB,MAAM,SAAS,eAAe,eAAe,KAAK,EAAE;GACpD,OAAO,OAAO,KAAK,IAAI,WAAW,IAAI,CAAC;GACvC,MAAM,YAAY,OAAO,OAAO,CAAC,OAAO,OAAO,OAAO,MAAM,GAAG,OAAO,MAAM,CAAC,CAAC;GAC9E,MAAM,UAAU,OAAO,OAAO;IAAC,OAAO,KAAK,CAAC,CAAC,CAAC;IAAG;IAAI,OAAO,WAAW;IAAG;GAAS,CAAC;GACpF,MAAM,YAAY,GAAG,KAAK,GAAG,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK,EAAE;GAC7D,MAAM,SAAS,MAAM,KAAK,WAAW,MAAM,GAAK;GAChD,IAAI;IACF,IAAI;KACF,MAAM,OAAO,MAAM,GAAK;KACxB,KAAK,cAAc,MAAM,OAAO,KAAK,GAAG,KAAK;KAC7C,MAAM,MAAM,OAAO,KAAK,EAAC,CAAE,OAAO,SAAW,KAC3C,MAAM,IAAI,iBAAiB,aAAa;KAE1C,MAAM,OAAO,UAAU,OAAO;KAC9B,MAAM,OAAO,KAAK;IACpB,UAAU;KACR,MAAM,OAAO,MAAM;IACrB;IACA,MAAM,OAAO,WAAW,IAAI;GAC9B,UAAU;IACR,MAAM,OAAO,SAAS,CAAC,CAAC,OAAO,UAAmB;KAChD,IAAI,CAAC,UAAU,KAAK,GAAG,MAAM;IAC/B,CAAC;GACH;EACF,CAAC;CACH;CAEA,MAAa,OAAO,WAAmB,MAAgC;EACrE,OAAO,KAAK,KAAK,YAAY;GAC3B,MAAM,OAAO,MAAM,KAAK,SAAS,WAAW,MAAM,KAAK;GACvD,IAAI,CAAC,MAAM,OAAO;GAClB,IAAI;IACF,KAAK,cAAc,MAAM,MAAM,IAAI,GAAG,KAAK;IAC3C,MAAM,OAAO,IAAI;IACjB,OAAO;GACT,SAAS,OAAO;IACd,IAAI,UAAU,KAAK,GAAG,OAAO;IAC7B,MAAM;GACR;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"file-backend.mjs","names":[],"sources":["../../../../../../../../packages/core/src/secrets/file-backend.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from \"node:crypto\";\nimport { registerLogSecret } from \"@warlock.js/logger\";\nimport { constants, type Stats } from \"node:fs\";\nimport { lstat, mkdir, open, rename, unlink, type FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { SecretStoreError } from \"./errors\";\nimport type { SecretBackend } from \"./types\";\n\nfunction digest(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction isMissing(error: unknown): boolean {\n return error instanceof Error && \"code\" in error && error.code === \"ENOENT\";\n}\n\n/** One authenticated file per secret: concurrent writes to different keys cannot clobber each other. */\nexport class FileSecretBackend implements SecretBackend {\n public readonly type = \"file\";\n public constructor(\n private readonly directory: string,\n private readonly encryptionKey: () => string | undefined,\n ) {}\n\n private key(namespace: string): Buffer {\n const secret = this.encryptionKey();\n if (typeof secret !== \"string\" || !/^[a-f\\d]{64}$/i.test(secret)) {\n throw new SecretStoreError(\"KEY_REQUIRED\");\n }\n registerLogSecret(secret, [\"encryptionKey\"]);\n // Core's encrypt/decrypt helpers use global config directly. Derive a\n // separate AES-256-GCM key without changing that global config.\n // https://nodejs.org/docs/latest-v22.x/api/crypto.html#cryptohkdfsyncdigest-ikm-salt-info-keylen\n return Buffer.from(\n hkdfSync(\"sha256\", Buffer.from(secret, \"hex\"), namespace, \"warlock:secrets:v1\", 32),\n );\n }\n\n private validateOwner(stats: Stats, directory: boolean): void {\n if (\n (directory ? !stats.isDirectory() : !stats.isFile() || stats.nlink !== 1) ||\n (process.getuid && stats.uid !== process.getuid())\n ) {\n throw new SecretStoreError(\"UNSAFE_FILE\");\n }\n }\n\n private async folder(namespace: string, create: boolean): Promise<string | undefined> {\n // Node's Windows modes cannot enforce owner-only ACLs. Fail closed there.\n // https://nodejs.org/docs/latest-v22.x/api/fs.html#file-modes\n const root = path.resolve(this.directory);\n const folder = path.join(root, digest(namespace));\n for (const directory of [root, folder]) {\n if (!create) {\n try {\n await lstat(directory);\n } catch (error) {\n if (isMissing(error)) return undefined;\n throw error;\n }\n }\n if (process.platform === \"win32\") throw new SecretStoreError(\"UNSAFE_FILE\");\n if (create) await mkdir(directory, { recursive: true, mode: 0o700 });\n this.validateOwner(await lstat(directory), true);\n const handle = await open(directory, constants.O_RDONLY | constants.O_NOFOLLOW);\n try {\n this.validateOwner(await handle.stat(), true);\n await handle.chmod(0o700);\n if (((await handle.stat()).mode & 0o777) !== 0o700) {\n throw new SecretStoreError(\"UNSAFE_FILE\");\n }\n } finally {\n await handle.close();\n }\n }\n return folder;\n }\n\n private async location(\n namespace: string,\n name: string,\n create: boolean,\n ): Promise<string | undefined> {\n const folder = await this.folder(namespace, create);\n return folder ? path.join(folder, `${digest(name)}.secret`) : undefined;\n }\n\n private aad(namespace: string, name: string): Buffer {\n return Buffer.from(JSON.stringify([\"warlock:secrets:v1\", namespace, name]));\n }\n\n private async safe<T>(operation: () => Promise<T>): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (error instanceof SecretStoreError) throw error;\n if (error instanceof Error && \"code\" in error && error.code === \"ELOOP\") {\n throw new SecretStoreError(\"UNSAFE_FILE\");\n }\n throw new SecretStoreError(\"UNAVAILABLE\");\n }\n }\n\n public async get(namespace: string, name: string): Promise<string | undefined> {\n return this.safe(async () => {\n const file = await this.location(namespace, name, false);\n if (!file) return undefined;\n let handle: FileHandle;\n try {\n handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n } catch (error) {\n if (isMissing(error)) return undefined;\n throw error;\n }\n let payload: Buffer;\n try {\n this.validateOwner(await handle.stat(), false);\n await handle.chmod(0o600);\n if (((await handle.stat()).mode & 0o777) !== 0o600) {\n throw new SecretStoreError(\"UNSAFE_FILE\");\n }\n payload = await handle.readFile();\n } finally {\n await handle.close();\n }\n const key = this.key(namespace);\n try {\n // v1 (one byte), 12-byte IV, 16-byte tag, then ciphertext (possibly empty).\n if (payload.length < 29 || payload[0] !== 1) throw new Error();\n const decipher = createDecipheriv(\"aes-256-gcm\", key, payload.subarray(1, 13));\n decipher.setAAD(this.aad(namespace, name));\n decipher.setAuthTag(payload.subarray(13, 29));\n return Buffer.concat([decipher.update(payload.subarray(29)), decipher.final()]).toString(\n \"utf8\",\n );\n } catch {\n throw new SecretStoreError(\"CORRUPT_FILE\");\n }\n });\n }\n\n public async set(namespace: string, name: string, value: string): Promise<void> {\n return this.safe(async () => {\n const key = this.key(namespace);\n const file = await this.location(namespace, name, true);\n if (!file) throw new SecretStoreError(\"UNAVAILABLE\");\n try {\n this.validateOwner(await lstat(file), false);\n } catch (error) {\n if (!isMissing(error)) throw error;\n }\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n cipher.setAAD(this.aad(namespace, name));\n const encrypted = Buffer.concat([cipher.update(value, \"utf8\"), cipher.final()]);\n const payload = Buffer.concat([Buffer.from([1]), iv, cipher.getAuthTag(), encrypted]);\n const temporary = `${file}.${randomBytes(16).toString(\"hex\")}.tmp`;\n const handle = await open(temporary, \"wx\", 0o600);\n try {\n try {\n await handle.chmod(0o600);\n this.validateOwner(await handle.stat(), false);\n if (((await handle.stat()).mode & 0o777) !== 0o600) {\n throw new SecretStoreError(\"UNSAFE_FILE\");\n }\n await handle.writeFile(payload);\n await handle.sync();\n } finally {\n await handle.close();\n }\n await rename(temporary, file);\n } finally {\n await unlink(temporary).catch((error: unknown) => {\n if (!isMissing(error)) throw error;\n });\n }\n });\n }\n\n public async remove(namespace: string, name: string): Promise<boolean> {\n return this.safe(async () => {\n const file = await this.location(namespace, name, false);\n if (!file) return false;\n try {\n this.validateOwner(await lstat(file), false);\n await unlink(file);\n return true;\n } catch (error) {\n if (isMissing(error)) return false;\n throw error;\n }\n });\n }\n}\n"],"mappings":"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"}
@@ -1,6 +1,6 @@
1
1
  import { SecretStoreError, SecretStoreErrorCode } from "./errors.mjs";
2
- import { SecretBackend, SecretStoreOptions, SecretsConfigurations } from "./types.mjs";
2
+ import { SecretBackend, SecretBackendType, SecretStoreOptions, SecretsConfigurations } from "./types.mjs";
3
3
  import { MemorySecretBackend } from "./memory-backend.mjs";
4
4
  import { SecretStore } from "./secret-store.mjs";
5
5
  import { secrets } from "./secrets.mjs";
6
- export { MemorySecretBackend, type SecretBackend, SecretStore, SecretStoreError, SecretStoreErrorCode, type SecretStoreOptions, type SecretsConfigurations, secrets };
6
+ export { MemorySecretBackend, type SecretBackend, type SecretBackendType, SecretStore, SecretStoreError, SecretStoreErrorCode, type SecretStoreOptions, type SecretsConfigurations, secrets };
@@ -4,6 +4,7 @@ import { SecretStoreError } from "./errors.mjs";
4
4
  var KeyringSecretBackend = class KeyringSecretBackend {
5
5
  constructor(keyring) {
6
6
  this.keyring = keyring;
7
+ this.type = "keychain";
7
8
  }
8
9
  /** Read-only availability probe; never writes a setup credential. */
9
10
  static async load(namespace, importer = importKeyring) {
@@ -1 +1 @@
1
- {"version":3,"file":"keyring-backend.mjs","names":[],"sources":["../../../../../../../../packages/core/src/secrets/keyring-backend.ts"],"sourcesContent":["import { SecretStoreError } from \"./errors\";\nimport type { SecretBackend } from \"./types\";\n\n// Verified against @napi-rs/keyring 2.1.1's published index.d.ts and README:\n// https://github.com/Brooooooklyn/keyring-node (2026-10-19).\n// Structural types keep the optional peer unnecessary for TypeScript consumers.\ninterface KeyringEntry {\n getPassword(): Promise<string | null>;\n setPassword(value: string): Promise<void>;\n deletePassword(): Promise<boolean>;\n}\n\ntype KeyringModule = {\n AsyncEntry: new (\n service: string,\n username: string,\n options: { linux: { store: \"secret-service\" } },\n ) => KeyringEntry;\n};\n\nexport class KeyringSecretBackend implements SecretBackend {\n private constructor(private readonly keyring: KeyringModule) {}\n\n /** Read-only availability probe; never writes a setup credential. */\n public static async load(\n namespace: string,\n importer: () => Promise<unknown> = importKeyring,\n ): Promise<KeyringSecretBackend | undefined> {\n try {\n const keyring = (await importer()) as KeyringModule;\n const backend = new KeyringSecretBackend(keyring);\n await backend.entry(namespace, \"\").getPassword();\n return backend;\n } catch {\n return undefined;\n }\n }\n\n private entry(namespace: string, name: string): KeyringEntry {\n // Require persistence on Linux: the library's automatic keyutils fallback\n // is memory-only and loses credentials on reboot. Ignored on other OSes.\n return new this.keyring.AsyncEntry(`warlock:${namespace}`, name || \"__availability__\", {\n linux: { store: \"secret-service\" },\n });\n }\n\n public async get(namespace: string, name: string): Promise<string | undefined> {\n try {\n return (await this.entry(namespace, name).getPassword()) ?? undefined;\n } catch {\n throw new SecretStoreError(\"UNAVAILABLE\");\n }\n }\n\n public async set(namespace: string, name: string, value: string): Promise<void> {\n try {\n await this.entry(namespace, name).setPassword(value);\n } catch {\n throw new SecretStoreError(\"UNAVAILABLE\");\n }\n }\n\n public async remove(namespace: string, name: string): Promise<boolean> {\n try {\n return await this.entry(namespace, name).deletePassword();\n } catch {\n throw new SecretStoreError(\"UNAVAILABLE\");\n }\n }\n}\n\nasync function importKeyring(): Promise<unknown> {\n const peer = \"@napi-rs/keyring\";\n return import(peer);\n}\n"],"mappings":";;;AAoBA,IAAa,uBAAb,MAAa,qBAA8C;CACzD,AAAQ,YAAY,AAAiB,SAAwB;EAAxB;CAAyB;;CAG9D,aAAoB,KAClB,WACA,WAAmC,eACQ;EAC3C,IAAI;GACF,MAAM,UAAW,MAAM,SAAS;GAChC,MAAM,UAAU,IAAI,qBAAqB,OAAO;GAChD,MAAM,QAAQ,MAAM,WAAW,EAAE,CAAC,CAAC,YAAY;GAC/C,OAAO;EACT,QAAQ;GACN;EACF;CACF;CAEA,AAAQ,MAAM,WAAmB,MAA4B;EAG3D,OAAO,IAAI,KAAK,QAAQ,WAAW,WAAW,aAAa,QAAQ,oBAAoB,EACrF,OAAO,EAAE,OAAO,iBAAiB,EACnC,CAAC;CACH;CAEA,MAAa,IAAI,WAAmB,MAA2C;EAC7E,IAAI;GACF,OAAQ,MAAM,KAAK,MAAM,WAAW,IAAI,CAAC,CAAC,YAAY,KAAM;EAC9D,QAAQ;GACN,MAAM,IAAI,iBAAiB,aAAa;EAC1C;CACF;CAEA,MAAa,IAAI,WAAmB,MAAc,OAA8B;EAC9E,IAAI;GACF,MAAM,KAAK,MAAM,WAAW,IAAI,CAAC,CAAC,YAAY,KAAK;EACrD,QAAQ;GACN,MAAM,IAAI,iBAAiB,aAAa;EAC1C;CACF;CAEA,MAAa,OAAO,WAAmB,MAAgC;EACrE,IAAI;GACF,OAAO,MAAM,KAAK,MAAM,WAAW,IAAI,CAAC,CAAC,eAAe;EAC1D,QAAQ;GACN,MAAM,IAAI,iBAAiB,aAAa;EAC1C;CACF;AACF;AAEA,eAAe,gBAAkC;CAE/C,OAAO,OAAO;AAChB"}
1
+ {"version":3,"file":"keyring-backend.mjs","names":[],"sources":["../../../../../../../../packages/core/src/secrets/keyring-backend.ts"],"sourcesContent":["import { SecretStoreError } from \"./errors\";\nimport type { SecretBackend } from \"./types\";\n\n// Verified against @napi-rs/keyring 2.1.1's published index.d.ts and README:\n// https://github.com/Brooooooklyn/keyring-node (2026-10-19).\n// Structural types keep the optional peer unnecessary for TypeScript consumers.\ninterface KeyringEntry {\n getPassword(): Promise<string | null>;\n setPassword(value: string): Promise<void>;\n deletePassword(): Promise<boolean>;\n}\n\ntype KeyringModule = {\n AsyncEntry: new (\n service: string,\n username: string,\n options: { linux: { store: \"secret-service\" } },\n ) => KeyringEntry;\n};\n\nexport class KeyringSecretBackend implements SecretBackend {\n public readonly type = \"keychain\";\n private constructor(private readonly keyring: KeyringModule) {}\n\n /** Read-only availability probe; never writes a setup credential. */\n public static async load(\n namespace: string,\n importer: () => Promise<unknown> = importKeyring,\n ): Promise<KeyringSecretBackend | undefined> {\n try {\n const keyring = (await importer()) as KeyringModule;\n const backend = new KeyringSecretBackend(keyring);\n await backend.entry(namespace, \"\").getPassword();\n return backend;\n } catch {\n return undefined;\n }\n }\n\n private entry(namespace: string, name: string): KeyringEntry {\n // Require persistence on Linux: the library's automatic keyutils fallback\n // is memory-only and loses credentials on reboot. Ignored on other OSes.\n return new this.keyring.AsyncEntry(`warlock:${namespace}`, name || \"__availability__\", {\n linux: { store: \"secret-service\" },\n });\n }\n\n public async get(namespace: string, name: string): Promise<string | undefined> {\n try {\n return (await this.entry(namespace, name).getPassword()) ?? undefined;\n } catch {\n throw new SecretStoreError(\"UNAVAILABLE\");\n }\n }\n\n public async set(namespace: string, name: string, value: string): Promise<void> {\n try {\n await this.entry(namespace, name).setPassword(value);\n } catch {\n throw new SecretStoreError(\"UNAVAILABLE\");\n }\n }\n\n public async remove(namespace: string, name: string): Promise<boolean> {\n try {\n return await this.entry(namespace, name).deletePassword();\n } catch {\n throw new SecretStoreError(\"UNAVAILABLE\");\n }\n }\n}\n\nasync function importKeyring(): Promise<unknown> {\n const peer = \"@napi-rs/keyring\";\n return import(peer);\n}\n"],"mappings":";;;AAoBA,IAAa,uBAAb,MAAa,qBAA8C;CAEzD,AAAQ,YAAY,AAAiB,SAAwB;EAAxB;cADd;CACuC;;CAG9D,aAAoB,KAClB,WACA,WAAmC,eACQ;EAC3C,IAAI;GACF,MAAM,UAAW,MAAM,SAAS;GAChC,MAAM,UAAU,IAAI,qBAAqB,OAAO;GAChD,MAAM,QAAQ,MAAM,WAAW,EAAE,CAAC,CAAC,YAAY;GAC/C,OAAO;EACT,QAAQ;GACN;EACF;CACF;CAEA,AAAQ,MAAM,WAAmB,MAA4B;EAG3D,OAAO,IAAI,KAAK,QAAQ,WAAW,WAAW,aAAa,QAAQ,oBAAoB,EACrF,OAAO,EAAE,OAAO,iBAAiB,EACnC,CAAC;CACH;CAEA,MAAa,IAAI,WAAmB,MAA2C;EAC7E,IAAI;GACF,OAAQ,MAAM,KAAK,MAAM,WAAW,IAAI,CAAC,CAAC,YAAY,KAAM;EAC9D,QAAQ;GACN,MAAM,IAAI,iBAAiB,aAAa;EAC1C;CACF;CAEA,MAAa,IAAI,WAAmB,MAAc,OAA8B;EAC9E,IAAI;GACF,MAAM,KAAK,MAAM,WAAW,IAAI,CAAC,CAAC,YAAY,KAAK;EACrD,QAAQ;GACN,MAAM,IAAI,iBAAiB,aAAa;EAC1C;CACF;CAEA,MAAa,OAAO,WAAmB,MAAgC;EACrE,IAAI;GACF,OAAO,MAAM,KAAK,MAAM,WAAW,IAAI,CAAC,CAAC,eAAe;EAC1D,QAAQ;GACN,MAAM,IAAI,iBAAiB,aAAa;EAC1C;CACF;AACF;AAEA,eAAe,gBAAkC;CAE/C,OAAO,OAAO;AAChB"}
@@ -2,6 +2,7 @@ import { SecretBackend } from "./types.mjs";
2
2
  //#region ../../packages/core/src/secrets/memory-backend.d.ts
3
3
  /** Isolated, namespace-aware storage. No OS, environment or filesystem access. */
4
4
  export declare class MemorySecretBackend implements SecretBackend {
5
+ readonly type = "memory";
5
6
  private readonly values;
6
7
  get(namespace: string, name: string): Promise<string | undefined>;
7
8
  set(namespace: string, name: string, value: string): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"memory-backend.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/secrets/memory-backend.ts"],"mappings":";;;qBAGa,+BAA+B;mBACzB;EAEJ,IAAI,mBAAmB,eAAe;EAItC,IAAI,mBAAmB,cAAc,gBAAgB;EASrD,OAAO,mBAAmB,eAAe;EAI/C"}
1
+ {"version":3,"file":"memory-backend.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/secrets/memory-backend.ts"],"mappings":";;;qBAGa,+BAA+B;WAC1B;mBACC;EAEJ,IAAI,mBAAmB,eAAe;EAItC,IAAI,mBAAmB,cAAc,gBAAgB;EASrD,OAAO,mBAAmB,eAAe;EAI/C"}
@@ -2,6 +2,7 @@
2
2
  /** Isolated, namespace-aware storage. No OS, environment or filesystem access. */
3
3
  var MemorySecretBackend = class {
4
4
  constructor() {
5
+ this.type = "memory";
5
6
  this.values = /* @__PURE__ */ new Map();
6
7
  }
7
8
  async get(namespace, name) {
@@ -1 +1 @@
1
- {"version":3,"file":"memory-backend.mjs","names":[],"sources":["../../../../../../../../packages/core/src/secrets/memory-backend.ts"],"sourcesContent":["import type { SecretBackend } from \"./types\";\n\n/** Isolated, namespace-aware storage. No OS, environment or filesystem access. */\nexport class MemorySecretBackend implements SecretBackend {\n private readonly values = new Map<string, Map<string, string>>();\n\n public async get(namespace: string, name: string): Promise<string | undefined> {\n return this.values.get(namespace)?.get(name);\n }\n\n public async set(namespace: string, name: string, value: string): Promise<void> {\n let entries = this.values.get(namespace);\n if (!entries) {\n entries = new Map();\n this.values.set(namespace, entries);\n }\n entries.set(name, value);\n }\n\n public async remove(namespace: string, name: string): Promise<boolean> {\n return this.values.get(namespace)?.delete(name) ?? false;\n }\n\n public clear(): void {\n this.values.clear();\n }\n}\n"],"mappings":";;AAGA,IAAa,sBAAb,MAA0D;;gCAC9B,IAAI,IAAiC;;CAE/D,MAAa,IAAI,WAAmB,MAA2C;EAC7E,OAAO,KAAK,OAAO,IAAI,SAAS,CAAC,EAAE,IAAI,IAAI;CAC7C;CAEA,MAAa,IAAI,WAAmB,MAAc,OAA8B;EAC9E,IAAI,UAAU,KAAK,OAAO,IAAI,SAAS;EACvC,IAAI,CAAC,SAAS;GACZ,0BAAU,IAAI,IAAI;GAClB,KAAK,OAAO,IAAI,WAAW,OAAO;EACpC;EACA,QAAQ,IAAI,MAAM,KAAK;CACzB;CAEA,MAAa,OAAO,WAAmB,MAAgC;EACrE,OAAO,KAAK,OAAO,IAAI,SAAS,CAAC,EAAE,OAAO,IAAI,KAAK;CACrD;CAEA,AAAO,QAAc;EACnB,KAAK,OAAO,MAAM;CACpB;AACF"}
1
+ {"version":3,"file":"memory-backend.mjs","names":[],"sources":["../../../../../../../../packages/core/src/secrets/memory-backend.ts"],"sourcesContent":["import type { SecretBackend } from \"./types\";\n\n/** Isolated, namespace-aware storage. No OS, environment or filesystem access. */\nexport class MemorySecretBackend implements SecretBackend {\n public readonly type = \"memory\";\n private readonly values = new Map<string, Map<string, string>>();\n\n public async get(namespace: string, name: string): Promise<string | undefined> {\n return this.values.get(namespace)?.get(name);\n }\n\n public async set(namespace: string, name: string, value: string): Promise<void> {\n let entries = this.values.get(namespace);\n if (!entries) {\n entries = new Map();\n this.values.set(namespace, entries);\n }\n entries.set(name, value);\n }\n\n public async remove(namespace: string, name: string): Promise<boolean> {\n return this.values.get(namespace)?.delete(name) ?? false;\n }\n\n public clear(): void {\n this.values.clear();\n }\n}\n"],"mappings":";;AAGA,IAAa,sBAAb,MAA0D;;cACjC;gCACG,IAAI,IAAiC;;CAE/D,MAAa,IAAI,WAAmB,MAA2C;EAC7E,OAAO,KAAK,OAAO,IAAI,SAAS,CAAC,EAAE,IAAI,IAAI;CAC7C;CAEA,MAAa,IAAI,WAAmB,MAAc,OAA8B;EAC9E,IAAI,UAAU,KAAK,OAAO,IAAI,SAAS;EACvC,IAAI,CAAC,SAAS;GACZ,0BAAU,IAAI,IAAI;GAClB,KAAK,OAAO,IAAI,WAAW,OAAO;EACpC;EACA,QAAQ,IAAI,MAAM,KAAK;CACzB;CAEA,MAAa,OAAO,WAAmB,MAAgC;EACrE,OAAO,KAAK,OAAO,IAAI,SAAS,CAAC,EAAE,OAAO,IAAI,KAAK;CACrD;CAEA,AAAO,QAAc;EACnB,KAAK,OAAO,MAAM;CACpB;AACF"}
@@ -0,0 +1,14 @@
1
+ import { SecretStoreError } from "./errors.mjs";
2
+
3
+ //#region ../../packages/core/src/secrets/resolve-driver.ts
4
+ /** Resolve and enforce policy before looking up even an already cached store. */
5
+ function resolveSecretsDriver(options) {
6
+ const driver = options.driver ?? process.env.SECRETS_DRIVER ?? "auto";
7
+ if (driver !== "auto" && driver !== "memory") throw new SecretStoreError("INVALID_DRIVER");
8
+ if (driver === "memory" && process.env.NODE_ENV === "production" && options.allowMemoryInProduction !== true) throw new SecretStoreError("MEMORY_IN_PRODUCTION");
9
+ return driver;
10
+ }
11
+
12
+ //#endregion
13
+ export { resolveSecretsDriver };
14
+ //# sourceMappingURL=resolve-driver.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-driver.mjs","names":[],"sources":["../../../../../../../../packages/core/src/secrets/resolve-driver.ts"],"sourcesContent":["import { SecretStoreError } from \"./errors\";\nimport type { SecretsConfigurations } from \"./types\";\n\n/** Resolve and enforce policy before looking up even an already cached store. */\nexport function resolveSecretsDriver(options: SecretsConfigurations): \"auto\" | \"memory\" {\n const driver = options.driver ?? process.env.SECRETS_DRIVER ?? \"auto\";\n if (driver !== \"auto\" && driver !== \"memory\") throw new SecretStoreError(\"INVALID_DRIVER\");\n if (\n driver === \"memory\" &&\n process.env.NODE_ENV === \"production\" &&\n options.allowMemoryInProduction !== true\n ) {\n throw new SecretStoreError(\"MEMORY_IN_PRODUCTION\");\n }\n return driver;\n}\n"],"mappings":";;;;AAIA,SAAgB,qBAAqB,SAAmD;CACtF,MAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI,kBAAkB;CAC/D,IAAI,WAAW,UAAU,WAAW,UAAU,MAAM,IAAI,iBAAiB,gBAAgB;CACzF,IACE,WAAW,YACX,QAAQ,IAAI,aAAa,gBACzB,QAAQ,4BAA4B,MAEpC,MAAM,IAAI,iBAAiB,sBAAsB;CAEnD,OAAO;AACT"}
@@ -1,16 +1,18 @@
1
- import { SecretStoreOptions } from "./types.mjs";
1
+ import { SecretBackendType, SecretStoreOptions } from "./types.mjs";
2
2
  //#region ../../packages/core/src/secrets/secret-store.d.ts
3
3
  /** Lazily prepared, application-scoped credentials. All operations are asynchronous. */
4
4
  export declare class SecretStore {
5
5
  private primary;
6
6
  private readonly file;
7
- private readonly backend;
7
+ private readonly selectedBackend;
8
8
  readonly namespace: string;
9
9
  constructor(options: SecretStoreOptions);
10
10
  private validate;
11
11
  /** Exact, collision-free environment variable name (UTF-8 encoded as uppercase hex). */
12
12
  environmentName(name: string): string;
13
13
  private keyring;
14
+ /** Resolve the active store using the same memoized probe as credential operations. */
15
+ backend(): Promise<SecretBackendType>;
14
16
  private register;
15
17
  private environment;
16
18
  private assertWritable;
@@ -1 +1 @@
1
- {"version":3,"file":"secret-store.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/secrets/secret-store.ts"],"mappings":";;;qBASa;UACH;mBACS;mBACA;WACD;EAEhB,YAAmB,SAAS;UAmBpB;;EAYD,gBAAgB;UAMf;UAKA;UAIA;UAIA;UAQM;EAUD,IAAI,eAAe;EAkBnB,IAAI,eAAe;EAInB,IAAI,cAAc,gBAAgB;;EA2BlC,OAAO,eAAe"}
1
+ {"version":3,"file":"secret-store.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/secrets/secret-store.ts"],"mappings":";;;qBAWa;UACH;mBACS;mBACA;WACD;EAEhB,YAAmB,SAAS;UAqBpB;;EAYD,gBAAgB;UAMf;;EAMK,WAAW,QAAQ;UAWxB;UAIA;UAIA;UAQM;EAUD,IAAI,eAAe;EAkBnB,IAAI,eAAe;EAInB,IAAI,cAAc,gBAAgB;;EA2BlC,OAAO,eAAe"}