{"version":3,"file":"application-Dxhdq_nu.mjs","names":["semverLt","fs","CLIError","fs","fs","fs","sanitizePluginId","toCamelCase","toKebabCase","fs","importExpr","callExpr","callExpr","callExpr","arg","fs","exportDecl","NAME_PATTERN","fs"],"sources":["../src/parser/app-config/log-level.ts","../src/parser/app-config/schema.ts","../src/parser/generator-config/schema.ts","../src/parser/plugin-config/schema.ts","../src/plugin/builtin/registry.ts","../src/cli/shared/apply-concurrency.ts","../src/cli/shared/client.ts","../src/cli/shared/token-store.ts","../src/cli/shared/context.ts","../src/cli/shared/mock.ts","../src/cli/shared/config-loader.ts","../src/cli/cache/hasher.ts","../src/cli/shared/dist-dir.ts","../src/cli/cache/dep-collector-plugin.ts","../src/cli/cache/bundle-cache.ts","../src/cli/shared/plugin-import.ts","../src/plugin/guards.ts","../src/cli/commands/generate/plugin-executor-generator.ts","../src/cli/commands/generate/plugin-type-generator.ts","../src/cli/services/stale-cleanup.ts","../src/cli/shared/bundle-log-level.ts","../src/cli/shared/function-treeshake.ts","../src/cli/shared/platform-bundle-plugin.ts","../src/cli/services/workflow/ast-utils.ts","../src/cli/services/workflow/sdk-binding-collector.ts","../src/cli/services/workflow/job-detector.ts","../src/cli/services/workflow/workflow-detector.ts","../src/cli/services/workflow/trigger-transformer.ts","../src/cli/shared/trigger-context.ts","../src/cli/services/auth/bundler.ts","../src/parser/service/tailordb/hooks-validate-precompiled-expr.ts","../src/parser/service/tailordb/field.ts","../src/parser/service/tailordb/permission.ts","../src/parser/service/tailordb/relation.ts","../src/parser/service/tailordb/type-parser.ts","../src/parser/service/tailordb/schema.ts","../src/cli/services/tailordb/es-builtins.ts","../src/cli/services/tailordb/hooks-validate-bundler.ts","../src/cli/services/tailordb/type-name-validation.ts","../src/cli/services/tailordb/service.ts","../src/cli/services/auth/service.ts","../src/cli/shared/bundle-concurrency.ts","../src/cli/shared/runtime-exprs.ts","../src/cli/services/executor/loader.ts","../src/cli/services/executor/bundler.ts","../src/cli/services/http-adapter/node-builtins.ts","../src/parser/service/http-adapter/methods.ts","../src/parser/service/http-adapter/schema.ts","../src/cli/services/http-adapter/bundler.ts","../src/cli/services/http-adapter/service.ts","../src/parser/service/resolver/schema.ts","../src/cli/services/resolver/loader.ts","../src/cli/services/resolver/bundler.ts","../src/cli/services/resolver/service.ts","../src/cli/services/workflow/source-transformer.ts","../src/cli/services/workflow/bundler.ts","../src/parser/service/workflow/schema.ts","../src/cli/services/workflow/service.ts","../src/cli/shared/inline-sourcemap.ts","../src/parser/service/aigateway/schema.ts","../src/parser/service/idp/schema.ts","../src/parser/service/secrets/schema.ts","../src/parser/service/staticwebsite/schema.ts","../src/cli/services/application.ts"],"sourcesContent":["export const LOG_LEVELS = [\"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"SILENT\"] as const;\n\nexport function isLogLevel(value: string): value is (typeof LOG_LEVELS)[number] {\n  return (LOG_LEVELS as readonly string[]).includes(value);\n}\n","import { z } from \"zod\";\nimport { LOG_LEVELS } from \"./log-level\";\n\nconst envValueSchema = z.union([z.string(), z.number(), z.boolean()]);\n\nexport const LogLevelSchema = z.enum(LOG_LEVELS);\n\nconst logLevelSchema = z\n  .string()\n  .refine((value) => LogLevelSchema.safeParse(value.trim().toUpperCase()).success, {\n    message: `'logLevel' must be one of: ${LOG_LEVELS.join(\", \")}.`,\n  });\n\n/**\n * Structural validation schema for `defineConfig({...})`. Validates only\n * top-level fields with platform-side constraints (notably `id`); fields\n * that carry SDK builder objects (`auth`, `idp`, `db`, ...) are accepted\n * as opaque values, since their internal shapes are validated by their\n * own factory functions and parser-level schemas.\n *\n * The `id` is auto-managed by `deploy` and stored as a plain UUID. A\n * label-compatible prefix is added at the metadata boundary, so user-facing\n * configs only need to carry a UUID.\n */\nexport const AppConfigSchema = z.object({\n  id: z.uuid({ message: \"'id' must be a UUID.\" }).optional(),\n  name: z.string().min(1, { message: \"'name' must be a non-empty string.\" }),\n  env: z.record(z.string(), envValueSchema).optional(),\n  cors: z.array(z.string()).optional(),\n  allowedIpAddresses: z.array(z.string()).optional(),\n  disableIntrospection: z.boolean().optional(),\n  inlineSourcemap: z.boolean().optional(),\n  logLevel: logLevelSchema.optional(),\n  db: z.unknown().optional(),\n  resolver: z.unknown().optional(),\n  idp: z.unknown().optional(),\n  auth: z.unknown().optional(),\n  executor: z.unknown().optional(),\n  workflow: z.unknown().optional(),\n  httpAdapter: z.unknown().optional(),\n  staticWebsites: z.unknown().optional(),\n  aiGateways: z.unknown().optional(),\n  secrets: z.unknown().optional(),\n});\n","import { z } from \"zod\";\n\n// Dependency kind enum for generators\nconst DependencyKindSchema = z.enum([\"tailordb\", \"resolver\", \"executor\"]);\nexport type DependencyKind = z.infer<typeof DependencyKindSchema>;\n\n// Literal-based schemas for each generator\nconst KyselyTypeConfigSchema = z.tuple([\n  z.literal(\"@tailor-platform/kysely-type\"),\n  z.object({ distPath: z.string() }),\n]);\n\nconst SeedConfigSchema = z.tuple([\n  z.literal(\"@tailor-platform/seed\"),\n  z.object({\n    distPath: z.string(),\n    machineUserName: z.string().optional(),\n    disableIdpUserSync: z\n      .object({\n        userToIdp: z.boolean().optional(),\n        idpToUser: z.boolean().optional(),\n      })\n      .optional(),\n  }),\n]);\n\nconst EnumConstantsConfigSchema = z.tuple([\n  z.literal(\"@tailor-platform/enum-constants\"),\n  z.object({ distPath: z.string() }),\n]);\n\nconst FileUtilsConfigSchema = z.tuple([\n  z.literal(\"@tailor-platform/file-utils\"),\n  z.object({ distPath: z.string() }),\n]);\n\n// Custom generator schema with dependencies\nexport const CodeGeneratorSchema = z.object({\n  id: z.string(),\n  description: z.string(),\n  dependencies: z.array(DependencyKindSchema),\n  processType: z.function().optional(),\n  processResolver: z.function().optional(),\n  processExecutor: z.function().optional(),\n  processTailorDBNamespace: z.function().optional(),\n  processResolverNamespace: z.function().optional(),\n  aggregate: z.function({ output: z.any() }),\n});\n\n// Base schema for generator config (before transformation to actual Generator instances)\nexport const BaseGeneratorConfigSchema = z.union([\n  KyselyTypeConfigSchema,\n  SeedConfigSchema,\n  EnumConstantsConfigSchema,\n  FileUtilsConfigSchema,\n  CodeGeneratorSchema,\n]);\n","import { z } from \"zod\";\nimport { functionSchema } from \"#/parser/service/common\";\nimport type { Plugin } from \"#/plugin/types\";\n\n// Custom plugin schema (object form)\n// Using passthrough() to preserve additional properties on Plugin instances\nexport const PluginConfigSchema = z\n  .object({\n    id: z.string(),\n    description: z.string(),\n    importPath: z.string().optional(),\n    pluginConfig: z.unknown().optional(),\n    typeConfigRequired: z.union([z.boolean(), functionSchema]).optional(),\n    // Definition-time hooks\n    onTypeLoaded: functionSchema.optional(),\n    onNamespaceLoaded: functionSchema.optional(),\n    // Generation-time hooks\n    onTailorDBReady: functionSchema.optional(),\n    onResolverReady: functionSchema.optional(),\n    onExecutorReady: functionSchema.optional(),\n  })\n  .passthrough()\n  .refine(\n    (p) => {\n      // importPath is required when plugin has definition-time hooks\n      const hasDefineHooks = p.onTypeLoaded || p.onNamespaceLoaded;\n      return !hasDefineHooks || !!p.importPath;\n    },\n    {\n      message:\n        \"importPath is required when plugin has definition-time hooks (onTypeLoaded/onNamespaceLoaded)\",\n    },\n  )\n  .transform((plugin) => plugin as Plugin);\n","import { enumConstantsPlugin, EnumConstantsGeneratorID } from \"./enum-constants\";\nimport { fileUtilsPlugin, FileUtilsGeneratorID } from \"./file-utils\";\nimport { kyselyTypePlugin, KyselyGeneratorID } from \"./kysely-type\";\nimport { seedPlugin, SeedGeneratorID } from \"./seed\";\nimport type { Plugin } from \"#/plugin/types\";\n\n// Map of builtin generator IDs to plugin factory functions\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- builtin plugins accept heterogeneous options\nexport const builtinPlugins = new Map<string, (options: any) => Plugin<unknown, any>>([\n  [KyselyGeneratorID, (options) => kyselyTypePlugin(options)],\n  [SeedGeneratorID, (options) => seedPlugin(options)],\n  [EnumConstantsGeneratorID, (options) => enumConstantsPlugin(options)],\n  [FileUtilsGeneratorID, (options) => fileUtilsPlugin(options)],\n]);\n","import pLimit from \"p-limit\";\n\n/**\n * Default cap on concurrent operator RPCs when `TAILOR_APPLY_CONCURRENCY` is\n * unset. Chosen to tame the create burst (a fresh workspace fires one\n * `create*` per resource at once) that triggers the platform-side\n * `already_exists` race on compound creates, while still deploying quickly.\n */\nconst DEFAULT_APPLY_CONCURRENCY = 16;\n\n/**\n * Resolve the maximum number of operator RPCs to run in parallel.\n *\n * Resolution order:\n * 1. `TAILOR_APPLY_CONCURRENCY` env var (positive integer)\n * 2. `DEFAULT_APPLY_CONCURRENCY`\n *\n * A fresh-workspace apply creates every resource at once; firing all of them\n * concurrently overloads the platform, whose responses then come back as\n * `Unavailable`/`ResourceExhausted` and drive retries into the non-idempotent\n * compound-create `already_exists` race. Capping bounds the worst case.\n * @returns Concurrency cap (always >= 1)\n */\nexport function resolveApplyConcurrency(): number {\n  const envValue = process.env.TAILOR_APPLY_CONCURRENCY;\n  if (envValue !== undefined) {\n    const trimmed = envValue.trim();\n    if (trimmed !== \"\" && /^[1-9]\\d*$/.test(trimmed)) {\n      return Number.parseInt(trimmed, 10);\n    }\n  }\n  return DEFAULT_APPLY_CONCURRENCY;\n}\n\n/**\n * Create a limiter capped at the resolved apply concurrency. The returned\n * function defers a task until a slot is free, then resolves with its result.\n *\n * Share a single instance across all RPCs that should contend for the same\n * budget (e.g. one per operator client) so the cap bounds total in-flight\n * calls, not per-call-site bursts.\n * @returns A limiter that defers tasks beyond the concurrency cap\n */\nexport function createApplyLimiter(): <R>(task: () => Promise<R>) => Promise<R> {\n  return pLimit(resolveApplyConcurrency());\n}\n\n/**\n * Comparator that orders `name`-bearing items by `name`, for a stable,\n * reproducible apply order within the concurrency cap.\n *\n * Uses a code-point comparison rather than `localeCompare` so the order does\n * not depend on the runtime's default locale/collation.\n * @param a - Left item\n * @param b - Right item\n * @returns Negative, zero, or positive per code-point ordering of the names\n */\nexport function byName(a: { name: string }, b: { name: string }): number {\n  if (a.name < b.name) return -1;\n  if (a.name > b.name) return 1;\n  return 0;\n}\n","import { OAuth2Client } from \"@badgateway/oauth2-client\";\nimport { create } from \"@bufbuild/protobuf\";\nimport { MethodOptions_IdempotencyLevel } from \"@bufbuild/protobuf/wkt\";\nimport {\n  type Client,\n  Code,\n  ConnectError,\n  createClient,\n  type Interceptor,\n  type Transport,\n  type UnaryResponse,\n} from \"@connectrpc/connect\";\nimport { getGlobalDispatcher } from \"undici\";\nimport { z } from \"zod\";\nimport { createApplyLimiter } from \"./apply-concurrency\";\nimport { logger } from \"./logger\";\nimport { userAgent } from \"./user-agent\";\nimport type { OperatorService } from \"@tailor-platform/tailor-proto/service_pb\";\n\nexport const defaultPlatformBaseUrl = \"https://api.tailor.tech\";\nexport const defaultConsoleBaseUrl = \"https://console.tailor.tech\";\n\nconst defaultOAuth2ClientId = \"cpoc_0Iudir72fqSpqC6GQ58ri1cLAqcq5vJl\";\nconst oauth2DiscoveryEndpoint = \"/.well-known/oauth-authorization-server/oauth2/platform\";\n\nexport type PlatformClientConfig = {\n  platformUrl?: string;\n  oauth2ClientId?: string;\n  consoleUrl?: string;\n};\n\nconst tokenPlatformConfigs = new Map<string, PlatformClientConfig>();\n\nfunction getEnvPlatformUrl(): string | undefined {\n  return process.env.TAILOR_PLATFORM_URL ?? process.env.PLATFORM_URL;\n}\n\nfunction getEnvOAuth2ClientId(): string | undefined {\n  return process.env.TAILOR_PLATFORM_OAUTH2_CLIENT_ID ?? process.env.PLATFORM_OAUTH2_CLIENT_ID;\n}\n\nexport function normalizeBaseUrl(value: string): string {\n  const url = new URL(value);\n  url.hash = \"\";\n  url.search = \"\";\n  return url.toString().replace(/\\/$/, \"\");\n}\n\nexport function getEffectivePlatformConfig(config: PlatformClientConfig = {}) {\n  const platformUrl = config.platformUrl ?? getEnvPlatformUrl();\n  const oauth2ClientId = config.oauth2ClientId ?? getEnvOAuth2ClientId();\n  const consoleUrl = config.consoleUrl ?? process.env.TAILOR_PLATFORM_CONSOLE_URL;\n  const effective = {\n    ...(platformUrl ? { platformUrl } : {}),\n    ...(oauth2ClientId ? { oauth2ClientId } : {}),\n    ...(consoleUrl ? { consoleUrl } : {}),\n  };\n  return Object.keys(effective).length > 0 ? effective : undefined;\n}\n\nexport function rememberPlatformConfigForToken(accessToken: string, config?: PlatformClientConfig) {\n  const effectiveConfig = getEffectivePlatformConfig(config);\n  if (effectiveConfig) {\n    tokenPlatformConfigs.set(accessToken, effectiveConfig);\n  } else {\n    tokenPlatformConfigs.delete(accessToken);\n  }\n}\n\nfunction getPlatformConfigForToken(accessToken: string): PlatformClientConfig | undefined {\n  return tokenPlatformConfigs.get(accessToken);\n}\n\nexport function getPlatformBaseUrl(config: PlatformClientConfig = {}) {\n  return normalizeBaseUrl(config.platformUrl ?? getEnvPlatformUrl() ?? defaultPlatformBaseUrl);\n}\n\nexport function isDefaultPlatform(config?: PlatformClientConfig): boolean {\n  return getPlatformBaseUrl(config) === normalizeBaseUrl(defaultPlatformBaseUrl);\n}\n\nexport function getOAuth2ClientId(config: PlatformClientConfig = {}) {\n  return config.oauth2ClientId ?? getEnvOAuth2ClientId() ?? defaultOAuth2ClientId;\n}\n\nfunction inferConsoleBaseUrl(platformBaseUrl: string) {\n  const platformUrl = new URL(platformBaseUrl);\n  if (platformUrl.hostname.startsWith(\"api.\")) {\n    platformUrl.hostname = platformUrl.hostname.replace(/^api\\./, \"console.\");\n    return normalizeBaseUrl(platformUrl.toString());\n  }\n  return defaultConsoleBaseUrl;\n}\n\nexport function getConsoleBaseUrl(config: PlatformClientConfig = {}) {\n  if (config.consoleUrl) return normalizeBaseUrl(config.consoleUrl);\n  if (config.platformUrl) {\n    const inferredUrl = inferConsoleBaseUrl(config.platformUrl);\n    if (inferredUrl !== defaultConsoleBaseUrl) return inferredUrl;\n  }\n  if (process.env.TAILOR_PLATFORM_CONSOLE_URL)\n    return normalizeBaseUrl(process.env.TAILOR_PLATFORM_CONSOLE_URL);\n  return inferConsoleBaseUrl(getPlatformBaseUrl(config));\n}\n\n/**\n * Initialize an OAuth2 client for Tailor Platform.\n * @param config - Optional platform connection settings\n * @returns Configured OAuth2 client\n */\nexport function initOAuth2Client(config?: PlatformClientConfig) {\n  return new OAuth2Client({\n    clientId: getOAuth2ClientId(config),\n    server: getPlatformBaseUrl(config),\n    discoveryEndpoint: oauth2DiscoveryEndpoint,\n  });\n}\n\nexport type OperatorClient = Client<typeof OperatorService>;\n\n/**\n * Initialize an Operator client with the given access token.\n * @param accessToken - Access token for authentication\n * @param config - Optional platform connection settings\n * @returns Configured Operator client\n */\nexport async function initOperatorClient(accessToken: string, config?: PlatformClientConfig) {\n  const platformConfig = config ?? getPlatformConfigForToken(accessToken);\n  const [{ createTracingInterceptor }, { OperatorService }] = await Promise.all([\n    import(\"#/cli/telemetry/interceptor\"),\n    import(\"@tailor-platform/tailor-proto/service_pb\"),\n  ]);\n\n  const interceptors: Interceptor[] = [\n    await userAgentInterceptor(),\n    await bearerTokenInterceptor(accessToken),\n    retryInterceptor(),\n    errorHandlingInterceptor(),\n    createTracingInterceptor(),\n    // Innermost: gates the actual network attempt so each retry re-acquires a\n    // slot and backoff waits happen outside the cap.\n    concurrencyLimitInterceptor(),\n  ];\n\n  const transport = await createTransport(getPlatformBaseUrl(platformConfig), interceptors);\n  return createClient(OperatorService, transport);\n}\n\n/**\n * Create a Connect transport using connect-node (HTTP/2).\n *\n * connect-node works on both Node.js and Bun. connect-web is not used because\n * it does not support client_streaming, which is required for function uploads.\n * @param baseUrl - Base URL for the transport\n * @param interceptors - Request interceptors\n * @returns Configured transport\n */\nexport async function createTransport(\n  baseUrl: string,\n  interceptors: Interceptor[],\n): Promise<Transport> {\n  const { createConnectTransport } = await import(\"@connectrpc/connect-node\");\n  return createConnectTransport({ httpVersion: \"2\", baseUrl, interceptors });\n}\n\n/**\n * Create an interceptor that sets a User-Agent header.\n * @returns User-Agent interceptor\n */\nasync function userAgentInterceptor(): Promise<Interceptor> {\n  const ua = await userAgent();\n  return (next) => async (req) => {\n    req.header.set(\"User-Agent\", ua);\n    return await next(req);\n  };\n}\n\nexport { userAgent };\n\n/**\n * Create an interceptor that sets the Authorization bearer token.\n * @param accessToken - Access token to use\n * @returns Bearer token interceptor\n */\nasync function bearerTokenInterceptor(accessToken: string): Promise<Interceptor> {\n  return (next) => async (req) => {\n    req.header.set(\"Authorization\", `Bearer ${accessToken}`);\n    return await next(req);\n  };\n}\n\n/**\n * Create an interceptor that retries failed unary requests with backoff.\n *\n * Retries any unary method on `Unavailable`/`ResourceExhausted`, and `Internal`\n * only for methods declared idempotent, up to 3 attempts (despite the historical\n * \"idempotent\" naming, the first two codes are retried regardless of idempotency).\n * As a targeted exception for the deploy/apply flow, a post-retry `AlreadyExists`\n * from an allowlisted Create (see `RETRY_SAFE_CREATE_METHODS`) is treated as\n * success, since it means a prior attempt already committed the resource\n * server-side. A first-attempt `AlreadyExists` from such a Create still\n * surfaces, but is routed to crash/error reporting first (the top-level handler\n * skips `ConnectError`), so the otherwise-silent compound-create race is\n * trackable.\n * @internal\n * @returns Retry interceptor\n */\nexport function retryInterceptor(): Interceptor {\n  return (next) => async (req) => {\n    if (req.stream) {\n      return await next(req);\n    }\n\n    let lastError: unknown;\n    for (let i = 0; i < 3; i++) {\n      if (i > 0) {\n        await waitRetryBackoff(i);\n      }\n\n      try {\n        return await next(req);\n      } catch (error) {\n        // A retry that comes back AlreadyExists is treated as success: a prior\n        // attempt (the one whose retriable error sent us here) already created\n        // the resource server-side, but its response was lost as\n        // Unavailable/ResourceExhausted under load. The identical retry then\n        // races against that committed write and fails with `already_exists`.\n        // Restricted to RETRY_SAFE_CREATE_METHODS (deploy creates whose response\n        // body is unused) and to actual retries (i > 0).\n        if (isRetrySafeCreateAlreadyExists(error, req.method.name)) {\n          if (i > 0) {\n            logger.debug(\n              `retry: ${req.method.name} returned AlreadyExists on attempt ${i + 1}; ` +\n                `treating as success (prior attempt likely committed)`,\n            );\n            return synthesizeEmptyUnaryResponse(req);\n          }\n          // First-attempt AlreadyExists on a retry-safe create: no retry of ours\n          // preceded it, so the resource was committed out-of-band (a concurrent\n          // or non-idempotent compound create under load — #1350). The top-level\n          // handler skips ConnectError, so route it to error tracking here before\n          // letting it surface as the deploy error.\n          const { reportCrash } = await import(\"#/cli/crashreport/index\");\n          await reportCrash(error, \"handledError\");\n        }\n        if (isRetirable(error, req.method.idempotency)) {\n          lastError = error;\n          logger.debug(\n            `retry: ${req.method.name} attempt ${i + 1} failed with ` +\n              `${connectCodeName(error)}; retrying`,\n          );\n          continue;\n        }\n        throw error;\n      }\n    }\n    throw lastError;\n  };\n}\n\n/**\n * Create an interceptor that caps the number of concurrent unary RPCs.\n *\n * A fresh-workspace apply fires one `create*` per resource at once; left\n * unbounded, the platform sheds load as `Unavailable`/`ResourceExhausted`,\n * which drives retries into the non-idempotent compound-create `already_exists`\n * race (#1350). One shared limiter per client bounds total in-flight calls\n * across every deploy resource, not just a single call site. Streaming RPCs\n * (e.g. function uploads) are not gated.\n * @internal\n * @returns Concurrency-limiting interceptor\n */\nexport function concurrencyLimitInterceptor(): Interceptor {\n  const limit = createApplyLimiter();\n  return (next) => async (req) => {\n    if (req.stream) {\n      return await next(req);\n    }\n    return await limit(() => next(req));\n  };\n}\n\n/**\n * Human-readable name for the Connect status code of an error, for diagnostics.\n * @param error - Error thrown by a request (expected to be a ConnectError)\n * @returns The Code name (e.g., \"Unavailable\"), or \"unknown\" for non-ConnectError\n */\nfunction connectCodeName(error: unknown): string {\n  return error instanceof ConnectError ? Code[error.code] : \"unknown\";\n}\n\n/**\n * Create RPCs for which a post-retry `AlreadyExists` may be treated as success.\n *\n * Membership is deliberately an allowlist, not `startsWith(\"Create\")`: swallowing\n * synthesizes an empty response (see `synthesizeEmptyUnaryResponse`), which is only\n * safe when every caller ignores the response body. These are the deploy/apply\n * resource creations that fire under heavy parallelism and discard their response.\n *\n * Intentionally excluded because their callers read the response body — swallowing\n * would hand back an empty message and corrupt downstream state:\n * - `CreateIdPClient` (uses `resp.client.clientSecret` to seed the secret vault)\n * - `CreateWorkflowJobFunction` (uses `response.jobFunction.version`)\n * - `CreateWorkspace` / `CreatePersonalAccessToken` / `CreateDeployment` /\n *   `CreateOrganizationFolder` (interactive commands that return created data)\n *\n * `CreateFunctionRegistry` is client-streaming and never reaches this path\n * (streaming requests bypass the retry loop entirely).\n *\n * An allowlist miss is safe: the resource simply loses race protection and an\n * `already_exists` surfaces loudly, as before — never a silent empty response.\n *\n * A drift guard (see client.test.ts) fails CI if any `client.create*` used in the\n * deploy flow is neither listed here nor explicitly classified as response-consuming,\n * so a newly added apply create cannot silently miss this list.\n * @internal\n */\nexport const RETRY_SAFE_CREATE_METHODS: ReadonlySet<string> = new Set([\n  \"CreateAIGateway\",\n  \"CreateApplication\",\n  \"CreateAuthConnection\",\n  \"CreateAuthHook\",\n  \"CreateAuthIDPConfig\",\n  \"CreateAuthMachineUser\",\n  \"CreateAuthOAuth2Client\",\n  \"CreateAuthSCIMConfig\",\n  \"CreateAuthSCIMResource\",\n  \"CreateAuthService\",\n  \"CreateExecutorExecutor\",\n  \"CreateIdPService\",\n  \"CreatePipelineResolver\",\n  \"CreatePipelineService\",\n  \"CreateSecretManagerSecret\",\n  \"CreateSecretManagerVault\",\n  \"CreateStaticWebsite\",\n  \"CreateTailorDBGQLPermission\",\n  \"CreateTailorDBService\",\n  \"CreateTailorDBType\",\n  \"CreateTenantConfig\",\n  \"CreateUserProfileConfig\",\n  \"CreateWorkflow\",\n]);\n\n/**\n * Whether an error is an `AlreadyExists` from a retry-safe Create RPC.\n *\n * Only `AlreadyExists` stands in for \"my prior write already landed\"; for other\n * verbs/codes it would be a real conflict that must surface.\n * @param error - Error thrown by the request\n * @param methodName - RPC method name (e.g., \"CreateTailorDBType\")\n * @returns True if the error is an `AlreadyExists` from a retry-safe Create method\n */\nfunction isRetrySafeCreateAlreadyExists(error: unknown, methodName: string): boolean {\n  return (\n    error instanceof ConnectError &&\n    error.code === Code.AlreadyExists &&\n    RETRY_SAFE_CREATE_METHODS.has(methodName)\n  );\n}\n\n/**\n * Build a default (empty) unary response for the request's output message.\n *\n * Used when a retried Create is determined to have already succeeded on a prior\n * attempt: callers in the deploy pipeline ignore Create response bodies, so an\n * empty message faithfully represents the already-applied state.\n * @param req - Unary request whose output schema is used\n * @returns A synthesized unary response with an empty output message\n */\nfunction synthesizeEmptyUnaryResponse(req: {\n  service: UnaryResponse[\"service\"];\n  method: UnaryResponse[\"method\"];\n}): UnaryResponse {\n  return {\n    stream: false,\n    service: req.service,\n    method: req.method,\n    header: new Headers(),\n    message: create(req.method.output),\n    trailer: new Headers(),\n  };\n}\n\n/**\n * Base delay (ms) for the first retry. Subsequent attempts double it.\n *\n * Kept relatively large so a retry does not immediately race an original request\n * that is still settling server-side under load (e.g. a compound create whose\n * response was lost), which is what triggers the `already_exists` race.\n */\nconst RETRY_BASE_DELAY_MS = 500;\n\n/**\n * Wait for an exponential backoff delay with jitter.\n * @param attempt - Current retry attempt number (1-based)\n * @returns Promise that resolves after the delay\n */\nfunction waitRetryBackoff(attempt: number) {\n  const base = RETRY_BASE_DELAY_MS * 2 ** (attempt - 1);\n  const jitter = 0.1 * (Math.random() * 2 - 1);\n  const backoff = base * (1 + jitter);\n  return new Promise((resolve) => setTimeout(resolve, backoff));\n}\n\n/**\n * Determine whether the given error is retriable for the method idempotency.\n * @param error - Error thrown by the request\n * @param idempotency - Method idempotency level\n * @returns True if the error should be retried\n */\nfunction isRetirable(error: unknown, idempotency: MethodOptions_IdempotencyLevel) {\n  if (!(error instanceof ConnectError)) {\n    return false;\n  }\n\n  switch (error.code) {\n    case Code.ResourceExhausted:\n    case Code.Unavailable:\n      return true;\n    case Code.Internal:\n      return (\n        idempotency === MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS ||\n        idempotency === MethodOptions_IdempotencyLevel.IDEMPOTENT\n      );\n    default:\n      return false;\n  }\n}\n\n/**\n * Create an interceptor that enhances error messages from the Operator API.\n * @returns Error handling interceptor\n */\nfunction errorHandlingInterceptor(): Interceptor {\n  return (next) => async (req) => {\n    try {\n      return await next(req);\n    } catch (error) {\n      if (error instanceof ConnectError) {\n        const { operation, resourceType } = parseMethodName(req.method.name);\n        const requestParams = formatRequestParams(req.message);\n\n        // Re-throw as ConnectError with enhanced message to avoid re-wrapping\n        // Use rawMessage to avoid duplicating the error code prefix\n        throw new ConnectError(\n          `Failed to ${operation} ${resourceType}: ${error.rawMessage}\\nRequest: ${requestParams}`,\n          error.code,\n          error.metadata,\n        );\n      }\n      throw error;\n    }\n  };\n}\n\n/**\n * @internal\n * @param methodName - RPC method name (e.g., \"CreateWorkspace\")\n * @returns Parsed operation and resource type\n */\nexport function parseMethodName(methodName: string): {\n  operation: string;\n  resourceType: string;\n} {\n  const match = methodName.match(/^(Create|Update|Delete|Set|List|Get)(.+)$/);\n  if (!match) {\n    return { operation: \"perform\", resourceType: \"resource\" };\n  }\n\n  const [, action, resource] = match as [string, string, string];\n  return { operation: action.toLowerCase(), resourceType: resource };\n}\n\n/**\n * JSON.stringify replacer that converts BigInt values to strings.\n * @param _key - Object key (unused)\n * @param value - Value to serialize\n * @returns Serializable value\n */\nfunction bigIntReplacer(_key: string, value: unknown): unknown {\n  if (typeof value === \"bigint\") {\n    return value.toString();\n  }\n  return value;\n}\n\n/**\n * @internal\n * @param message - Request message to format\n * @returns Pretty-printed JSON or error placeholder\n */\nexport function formatRequestParams(message: unknown): string {\n  try {\n    if (message && typeof message === \"object\" && \"toJson\" in message) {\n      return JSON.stringify((message as { toJson: () => unknown }).toJson(), bigIntReplacer, 2);\n    }\n    return JSON.stringify(message, bigIntReplacer, 2);\n  } catch {\n    return \"(unable to serialize request)\";\n  }\n}\n\nexport const MAX_PAGE_SIZE = 1000;\n\n/**\n * Fetch all paginated resources by repeatedly calling the given function.\n * @template T\n * @param fn - Page fetcher returning items and next page token\n * @returns All fetched items\n */\nexport async function fetchAll<T>(\n  fn: (pageToken: string, maxPageSize: number) => Promise<[T[], string]>,\n) {\n  const items: T[] = [];\n  let pageToken = \"\";\n\n  // loop exits when the platform stops returning a page token\n  // oxlint-disable-next-line typescript/no-unnecessary-condition\n  while (true) {\n    const [batch, nextPageToken] = await fn(pageToken, MAX_PAGE_SIZE);\n    items.push(...batch);\n    // loop exits when the platform stops returning a page token\n    // oxlint-disable-next-line typescript/no-unnecessary-condition\n    if (!nextPageToken) break;\n    pageToken = nextPageToken;\n  }\n  return items;\n}\n\ninterface FetchPagedOptions {\n  /** Maximum number of items to return. 0 or undefined means unlimited. */\n  limit?: number;\n}\n\n/**\n * Fetch paginated resources with an optional upper bound on the number of\n * items returned. When `limit` is 0 or undefined the function behaves\n * like `fetchAll` and returns every page. When `limit` is positive the\n * function stops once enough items are collected, requesting smaller\n * pages as it approaches the boundary.\n * @template T\n * @param fn - Page fetcher returning items and next page token\n * @param options - Pagination options\n * @returns Fetched items (length <= limit when limit > 0)\n */\nexport async function fetchPaged<T>(\n  fn: (pageToken: string, pageSize: number) => Promise<[T[], string]>,\n  options?: FetchPagedOptions,\n): Promise<T[]> {\n  const limit = options?.limit;\n  const unbounded = limit === undefined || limit === 0;\n  const items: T[] = [];\n  let pageToken = \"\";\n\n  // loop exits when the platform stops returning a page token\n  // oxlint-disable-next-line typescript/no-unnecessary-condition\n  while (true) {\n    const pageSize = unbounded ? MAX_PAGE_SIZE : Math.min(limit - items.length, MAX_PAGE_SIZE);\n    if (!unbounded && pageSize <= 0) break;\n\n    const [batch, nextPageToken] = await fn(pageToken, pageSize);\n    items.push(...batch);\n    if (!unbounded && items.length >= limit) break;\n    // loop exits when the platform stops returning a page token\n    // oxlint-disable-next-line typescript/no-unnecessary-condition\n    if (!nextPageToken) break;\n    pageToken = nextPageToken;\n  }\n\n  if (!unbounded && items.length > limit) {\n    return items.slice(0, limit);\n  }\n  return items;\n}\n\n/**\n * Fetch user info from the Tailor Platform userinfo endpoint.\n * @param accessToken - Access token for the current user\n * @param config - Optional platform connection settings\n * @returns Parsed user info\n */\nexport async function fetchUserInfo(accessToken: string, config?: PlatformClientConfig) {\n  const userInfoUrl = new URL(\"/auth/platform/userinfo\", getPlatformBaseUrl(config)).href;\n  const resp = await fetch(userInfoUrl, {\n    headers: {\n      Authorization: `Bearer ${accessToken}`,\n      \"User-Agent\": await userAgent(),\n    },\n  });\n  if (!resp.ok) {\n    throw new Error(`Failed to fetch user info: ${resp.statusText}`);\n  }\n\n  const rawJson = await resp.json();\n  const schema = z.object({\n    email: z.string(),\n  });\n  return schema.parse(rawJson);\n}\n\n// Converting \"name:url\" patterns to actual Static Website URLs\n/**\n * Options for `resolveStaticWebsiteUrls`.\n */\nexport type ResolveStaticWebsiteUrlsOptions = {\n  /**\n   * Names of static websites that are defined locally in the current\n   * configuration. When the platform-side lookup for a name in this set\n   * fails specifically with a `NotFound` error, the warning is suppressed\n   * and the original `name:url[/path]` pattern is returned unresolved\n   * instead of being dropped.\n   *\n   * Use this from plan-phase callers to avoid noisy warnings on the first\n   * deployment, where the static website will be created later in the same\n   * apply run. Other failure modes (\"URL not yet assigned\", transient RPC\n   * errors, permission errors) are intentionally not suppressed so that\n   * real platform problems still surface during planning.\n   */\n  expectedLocalNames?: ReadonlySet<string>;\n};\n\n/**\n * Resolve \"name:url\" patterns to actual Static Website URLs.\n * @param client - Operator client instance\n * @param workspaceId - Workspace ID\n * @param urls - URLs or name:url patterns\n * @param context - Logging context (e.g., \"CORS\", \"OAuth2 redirect URIs\")\n * @param options - Optional behavior overrides\n * @returns Resolved URLs (or the original pattern for entries marked as\n *   expected-but-not-yet-deployed via `options.expectedLocalNames`)\n */\nexport async function resolveStaticWebsiteUrls(\n  client: OperatorClient,\n  workspaceId: string,\n  urls: string[] | undefined,\n  context: string, // for logging context (e.g., \"CORS\", \"OAuth2 redirect URIs\")\n  options: ResolveStaticWebsiteUrlsOptions = {},\n): Promise<string[]> {\n  if (!urls) {\n    return [];\n  }\n\n  const { expectedLocalNames } = options;\n\n  const results = await Promise.all(\n    urls.map(async (url) => {\n      const urlPattern = /:url(\\/.*)?$/;\n      const match = url.match(urlPattern);\n\n      if (match && match.index !== undefined) {\n        const siteName = url.substring(0, match.index);\n        const pathSuffix = match[1] || \"\";\n\n        try {\n          const response = await client.getStaticWebsite({\n            workspaceId,\n            name: siteName,\n          });\n\n          if (response.staticwebsite?.url) {\n            return [response.staticwebsite.url + pathSuffix];\n          }\n          logger.warn(\n            `Static website \"${siteName}\" has no URL assigned yet. Excluding from ${context}.`,\n          );\n          return [];\n        } catch (error) {\n          const isNotFound = error instanceof ConnectError && error.code === Code.NotFound;\n          if (isNotFound && expectedLocalNames?.has(siteName)) {\n            return [url];\n          }\n          logger.warn(\n            `Static website \"${siteName}\" not found for ${context} configuration. Excluding from ${context}.`,\n          );\n          return [];\n        }\n      }\n      return [url];\n    }),\n  );\n\n  return results.flat();\n}\n\n/**\n * Fetch an OAuth2 access token for a machine user.\n * @param url - OAuth2 server base URL\n * @param clientId - Client ID for the machine user\n * @param clientSecret - Client secret for the machine user\n * @returns Access token\n */\nexport async function fetchMachineUserToken(url: string, clientId: string, clientSecret: string) {\n  const tokenEndpoint = new URL(\"/oauth2/token\", url).href;\n  const formData = new URLSearchParams();\n  formData.append(\"grant_type\", \"client_credentials\");\n  formData.append(\"client_id\", clientId);\n  formData.append(\"client_secret\", clientSecret);\n\n  const resp = await fetch(tokenEndpoint, {\n    method: \"POST\",\n    headers: {\n      \"User-Agent\": await userAgent(),\n      \"Content-Type\": \"application/x-www-form-urlencoded\",\n    },\n    body: formData,\n  });\n  if (!resp.ok) {\n    const body = await resp.text().catch(() => \"\");\n    throw new Error(\n      `Failed to fetch machine user token: ${resp.status} ${resp.statusText} ${body.slice(0, 500)}`,\n    );\n  }\n  const rawJson = await resp.json();\n\n  const schema = z.object({\n    token_type: z.string(),\n    access_token: z.string(),\n    expires_in: z.number(),\n  });\n  return schema.parse(rawJson);\n}\n\n/**\n * Fetch an OAuth2 token for a platform machine user via client_credentials grant.\n * @param clientId - Client ID for the platform machine user\n * @param clientSecret - Client secret for the platform machine user\n * @param config - Optional platform connection settings\n * @returns OAuth2 token\n */\nexport async function fetchPlatformMachineUserToken(\n  clientId: string,\n  clientSecret: string,\n  config?: PlatformClientConfig,\n) {\n  const client = new OAuth2Client({\n    clientId,\n    clientSecret,\n    server: getPlatformBaseUrl(config),\n    discoveryEndpoint: oauth2DiscoveryEndpoint,\n  });\n  return await client.clientCredentials();\n}\n\n/**\n * Close undici's global HTTP connection pool to prevent libuv UV_HANDLE_CLOSING\n * assertion failure on Windows at process exit (Node.js 23.x+).\n * See: https://github.com/nodejs/node/issues/56645\n */\nexport async function closeConnectionPool() {\n  await getGlobalDispatcher().close();\n}\n","import { logger } from \"./logger\";\n\nconst SERVICE_NAME = \"tailor-platform-cli\";\n\ntype TokenData = {\n  accessToken: string;\n  refreshToken?: string;\n};\n\ntype EntryLike = {\n  setPassword(password: string): void;\n  getPassword(): string | null;\n  deletePassword(): void;\n};\n\ntype EntryConstructor = new (service: string, account: string) => EntryLike;\n\nlet entryClass: EntryConstructor | false | undefined;\n\nasync function getEntryClass(): Promise<EntryConstructor | false> {\n  if (entryClass !== undefined) return entryClass;\n\n  try {\n    const mod = await import(\"@napi-rs/keyring\");\n    const probe = new mod.Entry(SERVICE_NAME, \"__probe__\");\n    probe.setPassword(\"probe\");\n    probe.deletePassword();\n    entryClass = mod.Entry;\n  } catch {\n    logger.warn(\n      \"System keyring is not available. Tokens will be stored in the config file. Set TAILOR_PLATFORM_TOKEN environment variable for CI environments.\",\n    );\n    entryClass = false;\n  }\n\n  return entryClass;\n}\n\n/**\n * Check whether the OS keyring is available and functional.\n * @returns true if keyring is available\n */\nexport async function isKeyringAvailable(): Promise<boolean> {\n  return (await getEntryClass()) !== false;\n}\n\n/**\n * Load tokens from the OS keyring for a given account.\n * @param account - User identifier (e.g. email or client ID)\n * @returns Token data or undefined if not found or keyring unavailable\n */\nexport async function loadKeyringTokens(account: string): Promise<TokenData | undefined> {\n  const Entry = await getEntryClass();\n  if (!Entry) return undefined;\n\n  try {\n    const entry = new Entry(SERVICE_NAME, account);\n    const raw = entry.getPassword();\n    if (raw === null) return undefined;\n    return JSON.parse(raw) as TokenData;\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Save tokens to the OS keyring for a given account.\n * @param account - User identifier (e.g. email or client ID)\n * @param tokens - Token data to store\n */\nexport async function saveKeyringTokens(account: string, tokens: TokenData): Promise<void> {\n  const Entry = await getEntryClass();\n  if (!Entry) return;\n\n  const entry = new Entry(SERVICE_NAME, account);\n  entry.setPassword(JSON.stringify(tokens));\n}\n\n/**\n * Delete tokens from the OS keyring for a given account.\n * @param account - User identifier (e.g. email or client ID)\n */\nexport async function deleteKeyringTokens(account: string): Promise<void> {\n  const Entry = await getEntryClass();\n  if (!Entry) return;\n\n  try {\n    const entry = new Entry(SERVICE_NAME, account);\n    entry.deletePassword();\n  } catch {\n    // Ignore \"not found\" errors\n  }\n}\n\n/**\n * Reset the cached keyring state. Used for testing.\n */\nexport function resetKeyringState(): void {\n  entryClass = undefined;\n}\n\nexport type { TokenData };\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport { parseYAML, stringifyYAML, parseTOML } from \"confbox\";\nimport { findUpSync } from \"find-up-simple\";\nimport * as path from \"pathe\";\nimport { lt as semverLt } from \"semver\";\nimport { xdgConfig } from \"xdg-basedir\";\nimport { z } from \"zod\";\nimport { assertDefined } from \"#/utils/assert\";\nimport ml from \"#/utils/multiline\";\nimport {\n  defaultPlatformBaseUrl,\n  getConsoleBaseUrl,\n  getPlatformBaseUrl,\n  initOAuth2Client,\n  normalizeBaseUrl,\n  rememberPlatformConfigForToken,\n  type PlatformClientConfig,\n} from \"./client\";\nimport { CLIError } from \"./errors\";\nimport { logger } from \"./logger\";\nimport { readPackageJson } from \"./package-json\";\nimport { tightenSecretFilePermissions, writeSecretFile } from \"./secret-file\";\nimport {\n  isKeyringAvailable,\n  loadKeyringTokens,\n  saveKeyringTokens,\n  deleteKeyringTokens,\n} from \"./token-store\";\n\nconst pfProfileSchema = z.object({\n  user: z.string(),\n  workspace_id: z.string(),\n  readonly: z.boolean().optional(),\n  machine_user: z.string().optional(),\n  machine_user_override: z.enum([\"allow\", \"deny\"]).optional(),\n  platform_url: z.url().optional(),\n  oauth2_client_id: z.string().optional(),\n  console_url: z.url().optional(),\n});\n\nconst pfUserSchemaV1 = z.object({\n  access_token: z.string(),\n  refresh_token: z.string().optional(),\n  token_expires_at: z.string(),\n});\n\nconst pfUserKeyringSchema = z.object({\n  storage: z.literal(\"keyring\"),\n  token_expires_at: z.string(),\n});\n\nconst pfUserFileSchema = z.object({\n  storage: z.literal(\"file\"),\n  token_expires_at: z.string(),\n  access_token: z.string(),\n  refresh_token: z.string().optional(),\n});\n\nconst pfUserSchemaV2 = z.discriminatedUnion(\"storage\", [pfUserKeyringSchema, pfUserFileSchema]);\n\ntype PfUserV2 = z.output<typeof pfUserSchemaV2>;\n\nconst pfConfigSchemaV1 = z.object({\n  version: z.literal(1),\n  users: z.partialRecord(z.string(), pfUserSchemaV1),\n  profiles: z.partialRecord(z.string(), pfProfileSchema),\n  current_user: z.string().nullable(),\n});\n\nconst V2_CONFIG_VERSION = 2;\nconst LATEST_CONFIG_VERSION = 3;\nconst V2_MIN_SDK_VERSION = \"1.29.0\";\nconst V3_MIN_SDK_VERSION = \"1.70.0\";\n\nconst semverSchema = z.templateLiteral([\n  z.number().int(),\n  \".\",\n  z.number().int(),\n  \".\",\n  z.number().int(),\n]);\n\nconst pfConfigSchema = z.object({\n  version: z.union([z.literal(V2_CONFIG_VERSION), z.literal(LATEST_CONFIG_VERSION)]),\n  min_sdk_version: semverSchema,\n  latest_version: z.number().int().optional(),\n  latest_min_sdk_version: semverSchema.optional(),\n  users: z.partialRecord(z.string(), pfUserSchemaV2),\n  profiles: z.partialRecord(z.string(), pfProfileSchema),\n  current_user: z.string().nullable(),\n});\n\ntype PfConfigV1 = z.output<typeof pfConfigSchemaV1>;\ntype PfConfig = z.output<typeof pfConfigSchema>;\ntype PfConfigV2 = PfConfig & { version: typeof V2_CONFIG_VERSION };\ntype PfConfigV3 = PfConfig & { version: typeof LATEST_CONFIG_VERSION };\ntype LoadWorkspaceIdOptions = {\n  workspaceId?: string;\n  profile?: string;\n};\ntype LoadAccessTokenOptions = {\n  profile?: string;\n};\ntype LoadPlatformClientConfigOptions = {\n  profile?: string;\n  allowMissingProfile?: boolean;\n};\ntype LoadConsoleBaseUrlOptions = {\n  profile?: string;\n  allowMissingProfile?: boolean;\n};\ntype LoadMachineUserNameOptions = {\n  machineUser?: string;\n  profile?: string;\n};\n\nfunction platformConfigPath() {\n  if (!xdgConfig) {\n    throw new Error(\"User home directory not found\");\n  }\n  return path.join(xdgConfig, \"tailor-platform\", \"config.yaml\");\n}\n\ntype ProfilePlatformSettings = {\n  platform_url?: string;\n  oauth2_client_id?: string;\n  console_url?: string;\n};\n\n/**\n * Convert stored profile platform fields to platform client settings.\n * @param profile - Profile platform settings\n * @returns Platform client settings\n */\nexport function platformConfigFromProfile(\n  profile: ProfilePlatformSettings | undefined,\n): PlatformClientConfig | undefined {\n  const config = {\n    ...(profile?.platform_url ? { platformUrl: profile.platform_url } : {}),\n    ...(profile?.oauth2_client_id ? { oauth2ClientId: profile.oauth2_client_id } : {}),\n    ...(profile?.console_url ? { consoleUrl: profile.console_url } : {}),\n  };\n  return Object.keys(config).length > 0 ? config : undefined;\n}\n\nfunction platformUserKey(user: string, config?: PlatformClientConfig): string {\n  const platformUrl = getPlatformBaseUrl(config);\n  if (platformUrl === normalizeBaseUrl(defaultPlatformBaseUrl)) {\n    return user;\n  }\n  return `${platformUrl}|${user}`;\n}\n\nfunction canUseLegacyUserKey(platformUrl: string): boolean {\n  try {\n    return getPlatformBaseUrl() === platformUrl;\n  } catch {\n    return false;\n  }\n}\n\ntype UserEntryLookupOptions = {\n  allowLegacyUserKey?: boolean;\n};\n\nfunction findUserEntry(\n  config: PfConfig,\n  user: string,\n  platformConfig?: PlatformClientConfig,\n  opts: UserEntryLookupOptions = {},\n) {\n  const userKey = platformUserKey(user, platformConfig);\n  const userEntry = config.users[userKey];\n  if (userEntry) {\n    return { userKey, userEntry };\n  }\n  const platformUrl = getPlatformBaseUrl(platformConfig);\n  if (\n    userKey !== user &&\n    (opts.allowLegacyUserKey === false || !canUseLegacyUserKey(platformUrl))\n  ) {\n    return { userKey, userEntry };\n  }\n  const legacyEntry = config.users[user];\n  return legacyEntry ? { userKey: user, userEntry: legacyEntry } : { userKey, userEntry };\n}\n\n/**\n * Resolve the config user key that would be used for a user on the selected platform.\n * @param config - Platform config\n * @param user - User name\n * @param platformConfig - Optional platform connection settings\n * @param opts - Token lookup options\n * @returns Resolved config user key\n */\nexport function resolveUserTokenKey(\n  config: PfConfig,\n  user: string,\n  platformConfig?: PlatformClientConfig,\n  opts?: UserEntryLookupOptions,\n): string {\n  return findUserEntry(config, user, platformConfig, opts).userKey;\n}\n\n/**\n * Check whether tokens are registered for a user on the selected platform.\n * @param config - Platform config\n * @param user - User name\n * @param platformConfig - Optional platform connection settings\n * @param opts - Token lookup options\n * @returns True when the user has a registered token entry\n */\nexport function hasUserTokenEntry(\n  config: PfConfig,\n  user: string,\n  platformConfig?: PlatformClientConfig,\n  opts?: UserEntryLookupOptions,\n): boolean {\n  return findUserEntry(config, user, platformConfig, opts).userEntry !== undefined;\n}\n\nfunction hasUserKeyForName(users: Record<string, unknown>, user: string): boolean {\n  return users[user] !== undefined || Object.keys(users).some((key) => key.endsWith(`|${user}`));\n}\n\n/**\n * Check whether any platform has tokens registered for a user.\n * @param config - Platform config\n * @param user - User name\n * @returns True when the user has a token entry for any platform\n */\nexport function hasAnyUserTokenEntry(config: Pick<PfConfig, \"users\">, user: string): boolean {\n  return hasUserKeyForName(config.users, user);\n}\n\nfunction hasCurrentUserEntry(users: PfConfigV1[\"users\"], currentUser: string): boolean {\n  return hasUserKeyForName(users, currentUser);\n}\n\n/**\n * Migrate a v1 config to v2.\n * Tokens are kept in the config file (storage: \"file\") during migration.\n * They will be moved to the OS keyring on next login or token refresh.\n * @param v1Config - v1 configuration to migrate\n * @returns Migrated v2 configuration\n */\nfunction migrateV1ToV2(v1Config: PfConfigV1): PfConfigV2 {\n  const users: PfConfig[\"users\"] = {};\n\n  for (const [name, v1User] of Object.entries(v1Config.users)) {\n    if (!v1User) continue;\n\n    users[name] = {\n      access_token: v1User.access_token,\n      refresh_token: v1User.refresh_token,\n      token_expires_at: v1User.token_expires_at,\n      storage: \"file\",\n    };\n  }\n\n  return {\n    version: V2_CONFIG_VERSION,\n    min_sdk_version: V2_MIN_SDK_VERSION,\n    users,\n    profiles: v1Config.profiles,\n    current_user: v1Config.current_user,\n  };\n}\n\nasync function warnIfNewerConfigAvailable(config: PfConfig) {\n  if (!config.latest_min_sdk_version) return;\n  const packageJson = await readPackageJson();\n  const sdkVersion = packageJson.version ?? \"0.0.0\";\n  if (semverLt(sdkVersion, config.latest_min_sdk_version)) {\n    logger.warn(ml`\n      A newer config version (${String(config.latest_version)}) is available.\n      Please update your SDK to >= ${config.latest_min_sdk_version}: pnpm update @tailor-platform/sdk\n    `);\n  }\n}\n\n/**\n * Read Tailor Platform CLI configuration, migrating from tailorctl or v1 if necessary.\n * @returns Parsed platform configuration\n */\nexport async function readPlatformConfig(): Promise<PfConfig> {\n  const configPath = platformConfigPath();\n\n  // If platform config doesn't exist, try to read tailorctl config and migrate\n  if (!fs.existsSync(configPath)) {\n    logger.warn(`Config not found at ${configPath}, migrating from tailorctl config...`);\n    const tcConfig = readTailorctlConfig();\n    const v1Config = tcConfig\n      ? fromTailorctlConfig(tcConfig)\n      : ({ version: 1, users: {}, profiles: {}, current_user: null } as const);\n    writePlatformConfig(v1Config);\n    return migrateV1ToV2(v1Config);\n  }\n\n  const rawConfig = parseYAML(fs.readFileSync(configPath, \"utf-8\"));\n\n  // Legacy installs may have left the config world-readable (umask default\n  // 0o644). Tighten it here so users who only run read-only commands still\n  // get the secret-file permissions applied without waiting for a write.\n  tightenSecretFilePermissions(configPath);\n\n  // Check for unsupported future versions\n  const version =\n    rawConfig != null && typeof rawConfig === \"object\" && \"version\" in rawConfig\n      ? (rawConfig as { version: unknown }).version\n      : undefined;\n  if (typeof version === \"number\" && version > LATEST_CONFIG_VERSION) {\n    const minSdk =\n      \"min_sdk_version\" in (rawConfig as object)\n        ? String((rawConfig as { min_sdk_version: unknown }).min_sdk_version)\n        : undefined;\n    const updateHint = minSdk\n      ? `Please update your SDK to >= ${minSdk}: pnpm update @tailor-platform/sdk`\n      : \"Please update your SDK: pnpm update @tailor-platform/sdk\";\n    throw new Error(ml`\n      Config file uses version ${String(version)}, but this SDK only supports up to version ${String(LATEST_CONFIG_VERSION)}.\n      ${updateHint}\n    `);\n  }\n\n  const configResult = pfConfigSchema.safeParse(rawConfig);\n  if (configResult.success) {\n    await warnIfNewerConfigAvailable(configResult.data);\n    return configResult.data;\n  }\n\n  // Fall back to v1 (convert to v2 in memory, but don't rewrite disk)\n  const v1Result = pfConfigSchemaV1.safeParse(rawConfig);\n  if (v1Result.success) {\n    return migrateV1ToV2(v1Result.data);\n  }\n\n  // Neither v1, v2, nor the latest format\n  throw new Error(ml`\n    Failed to parse config file at ${configPath}.\n    The file may be corrupted or created by an incompatible SDK version.\n  `);\n}\n\nfunction toV1ForDisk(config: PfConfig): PfConfigV1 {\n  const users: PfConfigV1[\"users\"] = {};\n  for (const [name, entry] of Object.entries(config.users)) {\n    if (!entry || entry.storage === \"keyring\") continue;\n    users[name] = {\n      access_token: entry.access_token,\n      refresh_token: entry.refresh_token,\n      token_expires_at: entry.token_expires_at,\n    };\n  }\n  const currentUser =\n    config.current_user && hasCurrentUserEntry(users, config.current_user)\n      ? config.current_user\n      : null;\n  return {\n    version: 1,\n    users,\n    profiles: config.profiles,\n    current_user: currentUser,\n  };\n}\n\nfunction hasProfilePlatformSettings(config: Pick<PfConfig | PfConfigV1, \"profiles\">): boolean {\n  return Object.values(config.profiles).some(\n    (profile) =>\n      profile?.platform_url !== undefined ||\n      profile?.oauth2_client_id !== undefined ||\n      profile?.console_url !== undefined,\n  );\n}\n\nfunction hasScopedUserKeys(config: Pick<PfConfig | PfConfigV1, \"users\">): boolean {\n  return Object.keys(config.users).some((userKey) => userKey.includes(\"|\"));\n}\n\nfunction toLatestForDisk(config: PfConfig | PfConfigV1): PfConfigV3 {\n  const latestInput = config.version === 1 ? migrateV1ToV2(config) : config;\n  return {\n    ...latestInput,\n    version: LATEST_CONFIG_VERSION,\n    min_sdk_version: V3_MIN_SDK_VERSION,\n  };\n}\n\n/**\n * Write Tailor Platform CLI configuration to disk.\n * By default, file-backed configs without newer fields are converted to V1 for\n * backward compatibility, so an older SDK can still read the file. Configs\n * containing a keyring user are kept in V2 or later because the keyring storage\n * variant is not representable in V1. Configs containing profile-level Platform\n * settings or platform-scoped user tokens are written in the latest\n * min-SDK-gated format because older SDKs would silently drop or misread those\n * settings.\n * Set TAILOR_USE_KEYRING to write the current in-memory format unconditionally.\n *\n * The config file may contain access/refresh tokens when the OS keyring is\n * unavailable, so it is written via {@link writeSecretFile} so other users\n * on the host cannot read it.\n * @param config - Platform configuration to write\n */\nexport function writePlatformConfig(config: PfConfig | PfConfigV1) {\n  const configPath = platformConfigPath();\n  const hasKeyringUser =\n    config.version !== 1 && Object.values(config.users).some((u) => u?.storage === \"keyring\");\n  const diskConfig =\n    hasProfilePlatformSettings(config) || hasScopedUserKeys(config)\n      ? toLatestForDisk(config)\n      : config.version !== 1 && !process.env.TAILOR_USE_KEYRING && !hasKeyringUser\n        ? toV1ForDisk(config)\n        : config;\n  writeSecretFile(configPath, stringifyYAML(diskConfig));\n}\n\nconst tcContextConfigSchema = z.object({\n  username: z.string().optional(),\n  controlplaneaccesstoken: z.string().optional(),\n  controlplanerefreshtoken: z.string().optional(),\n  controlplanetokenexpiresat: z.string().optional(),\n  workspaceid: z.string().optional(),\n});\n\nconst tcConfigSchema = z\n  .object({\n    global: z\n      .object({\n        context: z.string().optional(),\n      })\n      .optional(),\n  })\n  .catchall(tcContextConfigSchema.optional());\n\ntype TcConfig = z.output<typeof tcConfigSchema>;\ntype TcContextConfig = z.output<typeof tcContextConfigSchema>;\n\nfunction readTailorctlConfig(): TcConfig | undefined {\n  const configPath = path.join(os.homedir(), \".tailorctl\", \"config\");\n  if (!fs.existsSync(configPath)) {\n    return;\n  }\n  const rawConfig = parseTOML(fs.readFileSync(configPath, \"utf-8\"));\n  return tcConfigSchema.parse(rawConfig);\n}\n\nfunction fromTailorctlConfig(config: TcConfig): PfConfigV1 {\n  const users: PfConfigV1[\"users\"] = {};\n  const profiles: PfConfigV1[\"profiles\"] = {};\n  let currentUser: PfConfigV1[\"current_user\"] = null;\n\n  const currentContext = config.global?.context || \"default\";\n  for (const [key, val] of Object.entries(config)) {\n    if (key === \"global\") {\n      continue;\n    }\n    const context = val as TcContextConfig;\n    if (\n      !context.username ||\n      !context.controlplaneaccesstoken ||\n      !context.controlplanerefreshtoken ||\n      !context.controlplanetokenexpiresat ||\n      !context.workspaceid\n    ) {\n      continue;\n    }\n    if (key === currentContext) {\n      currentUser = context.username;\n    }\n    profiles[key] = {\n      user: context.username,\n      workspace_id: context.workspaceid,\n    };\n    const user = users[context.username];\n    if (!user || new Date(user.token_expires_at) < new Date(context.controlplanetokenexpiresat)) {\n      users[context.username] = {\n        access_token: context.controlplaneaccesstoken,\n        refresh_token: context.controlplanerefreshtoken,\n        token_expires_at: context.controlplanetokenexpiresat,\n      };\n    }\n  }\n  return { version: 1, users, profiles, current_user: currentUser };\n}\n\nfunction validateUUID(value: string, source: string): string {\n  const result = z.uuid().safeParse(value);\n  if (!result.success) {\n    throw new Error(`Invalid value from ${source}: must be a valid UUID`);\n  }\n  return result.data;\n}\n\n/**\n * Load workspace ID from command options, environment variables, or platform config.\n * In CLI context, env fallback is also handled by politty's arg env option.\n * Priority: opts/workspaceId > env/workspaceId > opts/profile > error\n * @param opts - Workspace and profile options\n * @returns Resolved workspace ID\n */\nexport async function loadWorkspaceId(opts?: LoadWorkspaceIdOptions): Promise<string> {\n  const profile = opts?.profile || process.env.TAILOR_PLATFORM_PROFILE;\n\n  if (opts?.workspaceId) {\n    return validateUUID(opts.workspaceId, \"--workspace-id option\");\n  }\n\n  if (process.env.TAILOR_PLATFORM_WORKSPACE_ID) {\n    return validateUUID(\n      process.env.TAILOR_PLATFORM_WORKSPACE_ID,\n      \"TAILOR_PLATFORM_WORKSPACE_ID environment variable\",\n    );\n  }\n\n  if (profile) {\n    const pfConfig = await readPlatformConfig();\n    const profileEntry = pfConfig.profiles[profile];\n    const wsId = profileEntry?.workspace_id;\n    if (!wsId) {\n      throw new Error(`Profile \"${profile}\" not found`);\n    }\n    return validateUUID(wsId, `profile \"${profile}\"`);\n  }\n\n  throw new Error(ml`\n    Workspace ID not found.\n    Please specify workspace ID via --workspace-id option or TAILOR_PLATFORM_WORKSPACE_ID environment variable.\n  `);\n}\n\n/**\n * Load machine user name from command options, environment variables, or platform config.\n * In CLI context, env fallback is also handled by politty's arg env option.\n * Priority: opts/machineUser > env/TAILOR_PLATFORM_MACHINE_USER_NAME > opts/profile (profile default) > undefined.\n * An explicitly empty `opts.machineUser` is rejected with a CLIError (`MACHINE_USER_NAME_EMPTY`) rather than falling back to the env var or profile default.\n * When the active profile has `machine_user_override: \"deny\"`, an explicit value that differs from the profile's machine user throws a CLIError with code `PROFILE_MACHINE_USER_OVERRIDE_DENIED`.\n * @param opts - Machine user and profile options\n * @returns Resolved machine user name, or undefined if not set\n */\nexport async function loadMachineUserName(\n  opts?: LoadMachineUserNameOptions,\n): Promise<string | undefined> {\n  if (opts?.machineUser === \"\") {\n    throw CLIError({\n      code: \"MACHINE_USER_NAME_EMPTY\",\n      message: \"Machine user name cannot be empty.\",\n      suggestion:\n        \"Pass a non-empty machine user name, or omit the option to use the environment variable or profile default.\",\n    });\n  }\n\n  const explicit = opts?.machineUser || process.env.TAILOR_PLATFORM_MACHINE_USER_NAME || undefined;\n\n  const profile = opts?.profile || process.env.TAILOR_PLATFORM_PROFILE;\n  if (!profile) return explicit;\n\n  const pfConfig = await readPlatformConfig();\n  const entry = pfConfig.profiles[profile];\n  if (!entry) {\n    if (explicit) return explicit;\n    throw new Error(`Profile \"${profile}\" not found`);\n  }\n\n  if (entry.machine_user && entry.machine_user_override === \"deny\") {\n    if (explicit && explicit !== entry.machine_user) {\n      throw CLIError({\n        code: \"PROFILE_MACHINE_USER_OVERRIDE_DENIED\",\n        message: `Profile \"${profile}\" denies overriding the machine user.`,\n        details: `This profile fixes the machine user to \"${entry.machine_user}\" for application-data commands.`,\n        suggestion: `Omit the machine user option, unset TAILOR_PLATFORM_MACHINE_USER_NAME, or run 'tailor-sdk profile update ${profile} --machine-user-override allow'.`,\n      });\n    }\n    return entry.machine_user;\n  }\n\n  return explicit || entry.machine_user;\n}\n\n/**\n * Load access token from environment variables, command options, or platform config.\n * In CLI context, profile env fallback is also handled by politty's arg env option.\n * Priority: env/TAILOR_PLATFORM_TOKEN > env/TAILOR_TOKEN (deprecated) > opts/profile > env/profile > config/currentUser > error\n * @param opts - Profile options\n * @returns Resolved access token\n */\nexport async function loadAccessToken(opts?: LoadAccessTokenOptions) {\n  const profile = opts?.profile || process.env.TAILOR_PLATFORM_PROFILE;\n  const envToken = process.env.TAILOR_PLATFORM_TOKEN ?? process.env.TAILOR_TOKEN;\n  if (envToken && !process.env.TAILOR_PLATFORM_TOKEN) {\n    logger.warn(\"TAILOR_TOKEN is deprecated. Please use TAILOR_PLATFORM_TOKEN instead.\");\n  }\n\n  if (envToken) {\n    const platformConfig = await loadPlatformClientConfig({ profile, allowMissingProfile: true });\n    rememberPlatformConfigForToken(envToken, platformConfig);\n    return envToken;\n  }\n\n  const pfConfig = await readPlatformConfig();\n  const profileEntry = profile ? pfConfig.profiles[profile] : undefined;\n  if (profile && !profileEntry) {\n    throw new Error(`Profile \"${profile}\" not found`);\n  }\n  const user = profileEntry?.user ?? pfConfig.current_user;\n  if (!user) {\n    throw new Error(ml`\n      Tailor Platform token not found.\n      Please specify token via TAILOR_PLATFORM_TOKEN environment variable or login using 'tailor-sdk login' command.\n    `);\n  }\n  const fromProfile = profileEntry ? platformConfigFromProfile(profileEntry) : undefined;\n  return await fetchLatestToken(pfConfig, user, fromProfile);\n}\n\n/**\n * Load platform connection settings from the active profile.\n * @param opts - Profile options\n * @returns Resolved platform connection settings, or undefined for the default environment\n */\nexport async function loadPlatformClientConfig(\n  opts?: LoadPlatformClientConfigOptions,\n): Promise<PlatformClientConfig | undefined> {\n  const profile = opts?.profile || process.env.TAILOR_PLATFORM_PROFILE;\n  if (!profile) {\n    return undefined;\n  }\n\n  let pfConfig: PfConfig;\n  try {\n    pfConfig = await readPlatformConfig();\n  } catch (error) {\n    if (opts?.allowMissingProfile) {\n      return undefined;\n    }\n    throw error;\n  }\n  const profileEntry = pfConfig.profiles[profile];\n  if (!profileEntry) {\n    if (opts?.allowMissingProfile) {\n      return undefined;\n    }\n    throw new Error(`Profile \"${profile}\" not found`);\n  }\n  return platformConfigFromProfile(profileEntry);\n}\n\n/**\n * Load the Tailor Platform Console base URL from environment variables or the active profile.\n * @param opts - Profile options\n * @returns Resolved Console base URL\n */\nexport async function loadConsoleBaseUrl(opts?: LoadConsoleBaseUrlOptions): Promise<string> {\n  const platformConfig = await loadPlatformClientConfig(opts);\n  return getConsoleBaseUrl(platformConfig);\n}\n\n/**\n * Resolve the actual token values for a user, reading from keyring or config as appropriate.\n * @param userEntry - User entry from the config\n * @param user - User identifier\n * @param label - User-facing identifier used in error messages\n * @returns Access token and optional refresh token\n */\nexport async function resolveTokens(\n  userEntry: PfUserV2,\n  user: string,\n  label = user,\n): Promise<{ accessToken: string; refreshToken?: string }> {\n  if (userEntry.storage === \"keyring\") {\n    const tokens = await loadKeyringTokens(user);\n    if (!tokens) {\n      throw new Error(ml`\n        Credentials not found in OS keyring for \"${label}\".\n        Please run 'tailor-sdk login' and try again.\n      `);\n    }\n    return tokens;\n  }\n\n  return {\n    accessToken: userEntry.access_token,\n    refreshToken: userEntry.refresh_token,\n  };\n}\n\ninterface UserTokenData {\n  accessToken: string;\n  refreshToken?: string;\n}\n\n/**\n * Save tokens for a user, writing to keyring or config as appropriate.\n * @param config - Platform config\n * @param user - User identifier\n * @param tokens - Token data to save\n * @param tokens.accessToken - Access token to persist\n * @param tokens.refreshToken - Refresh token to persist when available\n * @param expiresAt - Token expiration date\n * @param platformConfig - Optional platform connection settings\n */\nexport async function saveUserTokens(\n  config: PfConfig,\n  user: string,\n  tokens: UserTokenData,\n  expiresAt: string,\n  platformConfig?: PlatformClientConfig,\n): Promise<void> {\n  const userKey = platformUserKey(user, platformConfig);\n  if (process.env.TAILOR_USE_KEYRING && (await isKeyringAvailable())) {\n    await saveKeyringTokens(userKey, tokens);\n    config.users[userKey] = {\n      token_expires_at: expiresAt,\n      storage: \"keyring\",\n    };\n  } else {\n    config.users[userKey] = {\n      access_token: tokens.accessToken,\n      refresh_token: tokens.refreshToken,\n      token_expires_at: expiresAt,\n      storage: \"file\",\n    };\n  }\n}\n\n/**\n * Delete tokens for a user from keyring if applicable.\n * @param config - Platform config\n * @param user - User identifier\n * @param platformConfig - Optional platform connection settings\n * @param opts - Token lookup options\n */\nexport async function deleteUserTokens(\n  config: PfConfig,\n  user: string,\n  platformConfig?: PlatformClientConfig,\n  opts?: UserEntryLookupOptions,\n): Promise<void> {\n  const { userKey, userEntry } = findUserEntry(config, user, platformConfig, opts);\n  if (userEntry?.storage === \"keyring\") {\n    await deleteKeyringTokens(userKey);\n  }\n  delete config.users[userKey];\n}\n\n/**\n * Resolve stored tokens for a user on the selected platform.\n * @param config - Platform config\n * @param user - User name\n * @param platformConfig - Optional platform connection settings\n * @param opts - Token lookup options\n * @returns Stored user entry and token values, or undefined when the user is not logged in\n */\nexport async function loadStoredUserTokens(\n  config: PfConfig,\n  user: string,\n  platformConfig?: PlatformClientConfig,\n  opts?: UserEntryLookupOptions,\n): Promise<\n  | {\n      userEntry: PfUserV2;\n      accessToken: string;\n      refreshToken?: string;\n    }\n  | undefined\n> {\n  const { userKey, userEntry } = findUserEntry(config, user, platformConfig, opts);\n  if (!userEntry) return undefined;\n  const tokens = await resolveTokens(userEntry, userKey, user);\n  return { userEntry, ...tokens };\n}\n\n/**\n * Fetch the latest access token, refreshing if necessary.\n * @param config - Platform config\n * @param user - User name\n * @param platformConfig - Optional platform connection settings\n * @returns Latest access token\n */\nexport async function fetchLatestToken(\n  config: PfConfig,\n  user: string,\n  platformConfig?: PlatformClientConfig,\n): Promise<string> {\n  const { userKey, userEntry } = findUserEntry(config, user, platformConfig);\n  if (!userEntry) {\n    throw new Error(ml`\n      User \"${user}\" not found.\n      Please verify your user name and login using 'tailor-sdk login' command.\n    `);\n  }\n\n  const tokens = await resolveTokens(userEntry, userKey, user);\n\n  if (new Date(userEntry.token_expires_at) > new Date()) {\n    rememberPlatformConfigForToken(tokens.accessToken, platformConfig);\n    return tokens.accessToken;\n  }\n\n  if (!tokens.refreshToken) {\n    throw new Error(ml`\n      Token expired.\n      Please run 'tailor-sdk login' and try again.\n    `);\n  }\n\n  const client = initOAuth2Client(platformConfig);\n  let resp;\n  try {\n    resp = await client.refreshToken({\n      accessToken: tokens.accessToken,\n      refreshToken: tokens.refreshToken,\n      expiresAt: Date.parse(userEntry.token_expires_at),\n    });\n  } catch {\n    throw new Error(ml`\n      Failed to refresh token. Your session may have expired.\n      Please run 'tailor-sdk login' and try again.\n    `);\n  }\n\n  const newExpiresAt = new Date(\n    assertDefined(resp.expiresAt, \"token refresh response missing expiresAt\"),\n  ).toISOString();\n  await saveUserTokens(\n    config,\n    user,\n    {\n      accessToken: resp.accessToken,\n      refreshToken: resp.refreshToken ?? undefined,\n    },\n    newExpiresAt,\n    platformConfig,\n  );\n  const refreshedUserKey = platformUserKey(user, platformConfig);\n  if (userKey !== refreshedUserKey) {\n    if (userEntry.storage === \"keyring\") {\n      await deleteKeyringTokens(userKey);\n    }\n    delete config.users[userKey];\n  }\n  writePlatformConfig(config);\n  rememberPlatformConfigForToken(resp.accessToken, platformConfig);\n  return resp.accessToken;\n}\n\nconst DEFAULT_CONFIG_FILENAME = \"tailor.config.ts\";\n\n/**\n * Load config path from command options, environment variables, or search parent directories.\n * In CLI context, env fallback is also handled by politty's arg env option.\n * Priority: opts/config > env/config > search parent directories\n * @param configPath - Optional explicit config path\n * @returns Resolved config path or undefined\n */\nexport function loadConfigPath(configPath?: string): string | undefined {\n  if (configPath) {\n    return configPath;\n  }\n  if (process.env.TAILOR_PLATFORM_SDK_CONFIG_PATH) {\n    return process.env.TAILOR_PLATFORM_SDK_CONFIG_PATH;\n  }\n\n  // Search for config file in current directory and parent directories\n  return findUpSync(DEFAULT_CONFIG_FILENAME);\n}\n","/**\n * Install a stub `globalThis.tailordb` so that user code loaded by the CLI\n * (e.g. via `createGetDB` in `@tailor-platform/sdk/kysely`) can reference\n * `tailordb.Client` without hitting a `ReferenceError`. The CLI never\n * actually executes the user code paths that issue queries, so a no-op\n * client suffices.\n *\n * Exposed as a function (rather than a top-level statement) so that\n * `package.json#sideEffects` can keep the file marked side-effect-free\n * without bundlers eliminating the install step.\n */\nexport function installCliTailordbStub(): void {\n  (\n    globalThis as unknown as {\n      tailordb: {\n        Client: typeof tailordb.Client;\n      };\n    }\n  ).tailordb = {\n    Client: class {\n      constructor(_config: { namespace: string }) {}\n      async connect(): Promise<void> {}\n      async end(): Promise<void> {}\n      async queryObject<O>(): Promise<tailordb.QueryResult<O>> {\n        return {} as Promise<tailordb.QueryResult<O>>;\n      }\n    },\n  };\n}\n","import * as fs from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport { AppConfigSchema } from \"#/parser/app-config/schema\";\nimport { CodeGeneratorSchema, BaseGeneratorConfigSchema } from \"#/parser/generator-config/schema\";\nimport { PluginConfigSchema } from \"#/parser/plugin-config/index\";\nimport { builtinPlugins } from \"#/plugin/builtin/registry\";\nimport { loadConfigPath } from \"./context\";\nimport { installCliTailordbStub } from \"./mock\";\nimport type { AppConfig } from \"#/configure/config/types\";\nimport type { Plugin } from \"#/plugin/types\";\nimport type { z } from \"zod\";\n\n/**\n * Loaded configuration with resolved path\n */\nexport type LoadedConfig = AppConfig & { path: string };\n\nexport interface LoadConfigOptions {\n  /** Import cache-busting value for watch-mode reloads. */\n  importNonce?: string;\n}\n\n// Generator schema for custom CodeGenerator objects (builtin generators are handled as plugins)\nconst GeneratorConfigSchema = CodeGeneratorSchema.brand(\"CodeGenerator\");\n\nexport type Generator = z.output<typeof GeneratorConfigSchema>;\n\n/**\n * Load Tailor configuration file and associated generators and plugins.\n * @param configPath - Optional explicit config path\n * @param options - Optional module import behavior.\n * @returns Loaded config, generators, plugins, and config path\n */\nexport async function loadConfig(\n  configPath?: string,\n  options: LoadConfigOptions = {},\n): Promise<{ config: LoadedConfig; generators: Generator[]; plugins: Plugin[] }> {\n  installCliTailordbStub();\n  const foundPath = loadConfigPath(configPath);\n  if (!foundPath) {\n    throw new Error(\n      \"Configuration file not found: tailor.config.ts not found in current or parent directories\",\n    );\n  }\n  const resolvedPath = path.resolve(process.cwd(), foundPath);\n\n  if (!fs.existsSync(resolvedPath)) {\n    throw new Error(`Configuration file not found: ${configPath}`);\n  }\n\n  const configUrl = pathToFileURL(resolvedPath);\n  if (options.importNonce) {\n    configUrl.searchParams.set(\"tailorImportNonce\", options.importNonce);\n  }\n  const configModule = await import(configUrl.href);\n  if (!configModule || !configModule.default) {\n    throw new Error(\"Invalid Tailor config module: default export not found\");\n  }\n\n  const validated = AppConfigSchema.safeParse(configModule.default);\n  if (!validated.success) {\n    const issues = validated.error.issues\n      .map((i) => `  - ${i.path.join(\".\") || \"(root)\"}: ${i.message}`)\n      .join(\"\\n\");\n    throw new Error(`Invalid Tailor config in ${resolvedPath}:\\n${issues}`);\n  }\n\n  // Collect all generator exports (generators, generators2, etc.)\n  const allGenerators: Generator[] = [];\n  // Collect all plugin exports (plugins, plugins2, etc.)\n  const allPlugins: Plugin[] = [];\n\n  for (const value of Object.values(configModule)) {\n    if (Array.isArray(value)) {\n      // Try to parse as generators (converting builtin tuples to plugins)\n      const generatorParsed = value.reduce(\n        (acc, item) => {\n          if (!acc.success) return acc;\n\n          // Check if this is a builtin generator tuple that should be converted to a plugin\n          const baseResult = BaseGeneratorConfigSchema.safeParse(item);\n          if (baseResult.success && Array.isArray(baseResult.data)) {\n            const [id, options] = baseResult.data as [string, Record<string, unknown>];\n            const pluginFactory = builtinPlugins.get(id);\n            if (pluginFactory) {\n              acc.convertedPlugins.push(pluginFactory(options));\n              return acc;\n            }\n          }\n\n          // Try to parse as a custom CodeGenerator object\n          const result = GeneratorConfigSchema.safeParse(item);\n          if (result.success) {\n            acc.items.push(result.data);\n          } else {\n            acc.success = false;\n          }\n          return acc;\n        },\n        { success: true, items: [] as Generator[], convertedPlugins: [] as Plugin[] },\n      );\n      if (\n        generatorParsed.success &&\n        (generatorParsed.items.length > 0 || generatorParsed.convertedPlugins.length > 0)\n      ) {\n        allGenerators.push(...generatorParsed.items);\n        allPlugins.push(...generatorParsed.convertedPlugins);\n        continue;\n      }\n\n      // Try to parse as plugins\n      const pluginParsed = value.reduce(\n        (acc, item) => {\n          if (!acc.success) return acc;\n\n          const result = PluginConfigSchema.safeParse(item);\n          if (result.success) {\n            acc.items.push(result.data);\n          } else {\n            acc.success = false;\n          }\n          return acc;\n        },\n        { success: true, items: [] as Plugin[] },\n      );\n      if (pluginParsed.success && pluginParsed.items.length > 0) {\n        allPlugins.push(...pluginParsed.items);\n      }\n    }\n  }\n\n  return {\n    config: { ...configModule.default, path: resolvedPath } as LoadedConfig,\n    generators: allGenerators,\n    plugins: allPlugins,\n  };\n}\n","import * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\n\n/**\n * Compute the SHA-256 hex digest of an arbitrary string.\n * @param content - The string content to hash\n * @returns Hex-encoded SHA-256 hash\n */\nfunction hashContent(content: string): string {\n  return crypto.createHash(\"sha256\").update(content, \"utf-8\").digest(\"hex\");\n}\n\n/**\n * Read a file and return its SHA-256 hex digest.\n * @param filePath - Absolute path to the file\n * @returns Hex-encoded SHA-256 hash of the file content\n */\nfunction hashFile(filePath: string): string {\n  const content = fs.readFileSync(filePath);\n  return crypto.createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/**\n * Compute a deterministic SHA-256 hash for multiple files.\n *\n * Paths are sorted alphabetically before hashing so that the result\n * is independent of the order the paths are supplied (e.g. glob ordering).\n * Each file's individual hash is concatenated and then hashed again.\n * @param filePaths - Array of absolute file paths\n * @returns Hex-encoded SHA-256 hash representing all files\n */\nfunction hashFiles(filePaths: string[]): string {\n  const sorted = filePaths.toSorted();\n  const combined = sorted.map((fp) => hashFile(fp)).join(\"\");\n  return hashContent(combined);\n}\n\nexport { hashContent, hashFile, hashFiles };\n","let distPath: string | null = null;\n\nexport const getDistDir = (): string => {\n  const configured = process.env.TAILOR_SDK_OUTPUT_DIR;\n  if (configured && configured !== distPath) {\n    distPath = configured;\n  } else if (distPath === null) {\n    distPath = configured || \".tailor-sdk\";\n  }\n  return distPath;\n};\n","import type { Plugin } from \"rolldown\";\n\ntype DepCollectorResult = {\n  plugin: Plugin;\n  getResult: () => string[];\n};\n\n/**\n * Create a rolldown plugin that collects all resolved module paths during a build.\n * The plugin is purely observational and does not modify any code or behavior.\n * Collected paths exclude node_modules and generated entry files.\n * node_modules changes (package upgrades) are not tracked per-bundle;\n * lockfile hash and SDK version changes invalidate the entire cache.\n * @returns An object containing the plugin and a getResult function that returns sorted, deduplicated paths\n */\nexport function createDepCollectorPlugin(): DepCollectorResult {\n  const collectedPaths = new Set<string>();\n\n  const plugin: Plugin = {\n    name: \"cache-dep-collector\",\n    load: {\n      filter: {\n        id: {\n          // Match all file types (not just JS/TS) so that JSON, CJS,\n          // and other imported files are tracked for cache invalidation.\n          include: [/\\.[^/]+$/],\n        },\n      },\n      handler(id) {\n        if (!id.includes(\"node_modules\") && !id.endsWith(\".entry.js\")) {\n          collectedPaths.add(id);\n        }\n        return null;\n      },\n    },\n  };\n\n  function getResult(): string[] {\n    return Array.from(collectedPaths).toSorted();\n  }\n\n  return { plugin, getResult };\n}\n","import * as path from \"pathe\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { createDepCollectorPlugin } from \"./dep-collector-plugin\";\nimport { hashContent, hashFile, hashFiles } from \"./hasher\";\nimport type { CacheStore } from \"./store\";\nimport type { Plugin } from \"rolldown\";\n\ntype BundleKind =\n  | \"resolver\"\n  | \"executor\"\n  | \"workflow-job\"\n  | \"auth-hook\"\n  | \"http-adapter-input\"\n  | \"http-adapter-output\";\n\ntype BundleCacheRestoreParams = {\n  kind: BundleKind;\n  name: string;\n  /** Optional hash of non-file context (e.g., env variables) to include in cache validation. */\n  contextHash?: string;\n};\n\ntype BundleCacheSaveParams = {\n  kind: BundleKind;\n  name: string;\n  sourceFile: string;\n  content: string;\n  dependencyPaths: string[];\n  /** Optional hash of non-file context (e.g., env variables) to include in cache key computation. */\n  contextHash?: string;\n};\n\n/**\n * Cache strategy that determines whether a bundled output can be\n * restored from cache or needs rebuilding.\n */\ntype BundleCache = {\n  /** Attempt to restore cached bundle content. Returns the code string if cache is valid, undefined otherwise. */\n  tryRestore(params: BundleCacheRestoreParams): string | undefined;\n  /** Save bundle content and its metadata to the cache. */\n  save(params: BundleCacheSaveParams): void;\n};\n\nfunction buildCacheKey(kind: string, name: string): string {\n  return `${kind}:${name}`;\n}\n\nfunction combineHash(fileHash: string, contextHash?: string): string {\n  if (!contextHash) return fileHash;\n  return hashContent(fileHash + contextHash);\n}\n\ntype ComputeBundlerContextHashParams = {\n  sourceFile: string;\n  serializedTriggerContext: string;\n  tsconfig?: string;\n  inlineSourcemap?: boolean;\n  bundleLogLevel?: string;\n  prefix?: string;\n};\n\n/**\n * Compute a context hash for cache invalidation across bundlers.\n *\n * Combines the source file path, serialized trigger context, tsconfig hash,\n * sourcemap mode, bundle log level, and an optional prefix (e.g., serialized\n * env variables) into a single SHA-256 hash.\n * @param params - Context hash computation parameters\n * @returns SHA-256 hex digest of the combined context\n */\nfunction computeBundlerContextHash(params: ComputeBundlerContextHashParams): string {\n  const {\n    sourceFile,\n    serializedTriggerContext,\n    tsconfig,\n    inlineSourcemap,\n    bundleLogLevel,\n    prefix,\n  } = params;\n  return hashContent(\n    (prefix ?? \"\") +\n      path.resolve(sourceFile) +\n      serializedTriggerContext +\n      (tsconfig ? hashFile(tsconfig) : \"\") +\n      String(inlineSourcemap ?? false) +\n      (bundleLogLevel ?? \"\"),\n  );\n}\n\ntype WithCacheParams = {\n  cache: BundleCache | undefined;\n  kind: BundleKind;\n  name: string;\n  sourceFile: string;\n  contextHash: string | undefined;\n  build: (plugins: Plugin[]) => Promise<string>;\n};\n\n/**\n * Run a build with optional cache restore/save around it.\n * When caching is active, attempts to restore from cache first,\n * and saves the build result (with collected dependencies) on a cache miss.\n * @param params - Cache and build parameters\n * @returns The bundled code string\n */\nasync function withCache(params: WithCacheParams): Promise<string> {\n  const { cache, kind, name, sourceFile, contextHash, build } = params;\n\n  if (!cache) {\n    return await build([]);\n  }\n\n  const content = cache.tryRestore({ kind, name, contextHash });\n  if (content !== undefined) {\n    logger.debug(`  ${styles.dim(\"cached\")}: ${name}`);\n    return content;\n  }\n\n  const { plugin, getResult } = createDepCollectorPlugin();\n  const code = await build([plugin]);\n\n  cache.save({ kind, name, sourceFile, content: code, dependencyPaths: getResult(), contextHash });\n\n  return code;\n}\n\n/**\n * Create a bundle cache backed by the given store.\n * @param store - The cache store for persistence\n * @returns A BundleCache instance\n */\nfunction createBundleCache(store: CacheStore): BundleCache {\n  function tryRestore(params: BundleCacheRestoreParams): string | undefined {\n    const cacheKey = buildCacheKey(params.kind, params.name);\n    const entry = store.getEntry(cacheKey);\n\n    if (!entry) {\n      return undefined;\n    }\n\n    // Recompute hash of all stored dependency paths.\n    // If any file is missing or unreadable, treat as cache miss.\n    let currentHash: string;\n    try {\n      currentHash = combineHash(hashFiles(entry.dependencyPaths), params.contextHash);\n    } catch {\n      return undefined;\n    }\n\n    if (currentHash !== entry.inputHash) {\n      return undefined;\n    }\n\n    return store.restoreBundleContent(cacheKey);\n  }\n\n  function save(params: BundleCacheSaveParams): void {\n    const { kind, name, sourceFile, content, dependencyPaths, contextHash } = params;\n    const cacheKey = buildCacheKey(kind, name);\n    // Always include sourceFile in dependency paths so that changes to the\n    // source file itself are detected even when dep-collector only finds\n    // node_modules imports (which are filtered out).\n    const allDeps = dependencyPaths.includes(sourceFile)\n      ? dependencyPaths\n      : [sourceFile, ...dependencyPaths];\n    const inputHash = combineHash(hashFiles(allDeps), contextHash);\n    const contentHash = hashContent(content);\n\n    store.storeBundleContent(cacheKey, content);\n\n    store.setEntry(cacheKey, {\n      kind: \"bundle\",\n      inputHash,\n      dependencyPaths: allDeps,\n      outputFiles: [{ outputPath: cacheKey, contentHash }],\n      createdAt: new Date().toISOString(),\n    });\n  }\n\n  return { tryRestore, save };\n}\n\nexport { computeBundlerContextHash, createBundleCache, withCache };\nexport type { BundleCache, BundleCacheRestoreParams, BundleCacheSaveParams };\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\n\n/**\n * Collect base directories for resolving plugin import paths.\n * @param configPath - Path to tailor.config.ts\n * @returns Ordered list of base directories\n */\nexport function getPluginImportBaseDirs(configPath?: string): string[] {\n  if (configPath) {\n    return [path.dirname(configPath)];\n  }\n\n  return [process.cwd()];\n}\n\n/**\n * Resolve a relative plugin import path against candidate base directories.\n * @param pluginImportPath - Relative plugin import path\n * @param baseDirs - Candidate base directories\n * @returns Absolute path if found, otherwise null\n */\nexport function resolveRelativePluginImportPath(\n  pluginImportPath: string,\n  baseDirs: string[],\n): string | null {\n  if (!pluginImportPath.startsWith(\".\")) {\n    return null;\n  }\n\n  for (const baseDir of baseDirs) {\n    const absolutePath = path.resolve(baseDir, pluginImportPath);\n    if (fs.existsSync(absolutePath)) {\n      return absolutePath;\n    }\n  }\n\n  return null;\n}\n","// Runtime guards and helpers for plugin authoring types.\n//\n// These live outside plugin/types.ts (a pure type module) because they are\n// runtime functions. The types they operate on are imported type-only.\nimport type {\n  DependencyKind,\n  PluginGeneratedExecutor,\n  PluginGeneratedExecutorWithFile,\n} from \"./types\";\n\n/**\n * Collects the generation-time dependency kinds a plugin requires.\n * @param plugin - The plugin object to inspect.\n * @param plugin.onTailorDBReady - Hook for TailorDB readiness.\n * @param plugin.onResolverReady - Hook for resolver readiness.\n * @param plugin.onExecutorReady - Hook for executor readiness.\n * @returns Set of dependency kinds required by the plugin.\n */\nexport function getPluginGenerationDependencies(plugin: {\n  onTailorDBReady?: unknown;\n  onResolverReady?: unknown;\n  onExecutorReady?: unknown;\n}): Set<DependencyKind> {\n  const deps = new Set<DependencyKind>();\n  if (plugin.onTailorDBReady) {\n    deps.add(\"tailordb\");\n  }\n  if (plugin.onResolverReady) {\n    deps.add(\"resolver\");\n  }\n  if (plugin.onExecutorReady) {\n    deps.add(\"executor\");\n  }\n  return deps;\n}\n\n/**\n * Checks if a plugin has any generation-time hooks.\n * @param plugin - The plugin object to inspect.\n * @param plugin.onTailorDBReady - Hook for TailorDB readiness.\n * @param plugin.onResolverReady - Hook for resolver readiness.\n * @param plugin.onExecutorReady - Hook for executor readiness.\n * @returns True if the plugin has at least one generation hook.\n */\nexport function hasGenerationHooks(plugin: {\n  onTailorDBReady?: unknown;\n  onResolverReady?: unknown;\n  onExecutorReady?: unknown;\n}): boolean {\n  return !!(plugin.onTailorDBReady || plugin.onResolverReady || plugin.onExecutorReady);\n}\n\n/**\n * Checks if a plugin executor uses file-based resolution.\n * @param executor - The plugin executor to check.\n * @returns True if the executor uses file-based resolution.\n */\nexport function isPluginExecutorWithFile(\n  executor: PluginGeneratedExecutor,\n): executor is PluginGeneratedExecutorWithFile {\n  return \"resolve\" in executor && \"context\" in executor;\n}\n","/**\n * Plugin Executor Generator\n *\n * Generates TypeScript files for plugin-generated executors.\n * Supports both legacy format (inline trigger/operation) and new format (executorFile/context).\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"pathe\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport {\n  getPluginImportBaseDirs,\n  resolveRelativePluginImportPath,\n} from \"#/cli/shared/plugin-import\";\nimport { isPluginExecutorWithFile } from \"#/plugin/guards\";\nimport {\n  type PluginGeneratedExecutorLegacy,\n  type PluginGeneratedExecutorWithFile,\n  type PluginTriggerConfig,\n  type PluginOperationConfig,\n  type PluginInjectMap,\n  type PluginExecutorContext,\n} from \"#/plugin/types\";\nimport { assertDefined } from \"#/utils/assert\";\nimport ml from \"#/utils/multiline\";\nimport type {\n  PluginExecutorInfoExtended,\n  PluginTypeGenerationResult,\n  SourceTypeInfo,\n} from \"#/plugin/manager\";\n\n/**\n * Information needed for type import resolution.\n */\ninterface TypeImportInfo {\n  /** Variable name to use in generated code */\n  variableName: string;\n  /** Import path for the type */\n  importPath: string;\n  /** Whether this is a generated type (vs user-defined) */\n  isGeneratedType: boolean;\n}\n\n/**\n * Generate TypeScript files for plugin-generated executors.\n * These files will be processed by the standard executor bundler.\n * @param executors - Array of plugin executor information\n * @param outputDir - Base output directory (e.g., .tailor-sdk)\n * @param typeGenerationResult - Result from plugin type generation (for import resolution)\n * @param sourceTypeInfoMap - Map of source type names to their source info\n * @param configPath - Path to tailor.config.ts (used for resolving plugin import paths)\n * @returns Array of generated file paths\n */\nexport function generatePluginExecutorFiles(\n  executors: ReadonlyArray<PluginExecutorInfoExtended>,\n  outputDir: string,\n  typeGenerationResult?: PluginTypeGenerationResult,\n  sourceTypeInfoMap?: Map<string, SourceTypeInfo>,\n  configPath?: string,\n): string[] {\n  if (executors.length === 0) {\n    return [];\n  }\n\n  const generatedFiles: string[] = [];\n  const baseDirs = getPluginImportBaseDirs(configPath);\n\n  for (const info of executors) {\n    const filePath = generateSingleExecutorFile(\n      info,\n      outputDir,\n      typeGenerationResult,\n      sourceTypeInfoMap,\n      baseDirs,\n    );\n    generatedFiles.push(filePath);\n\n    const relativePath = path.relative(process.cwd(), filePath);\n    logger.log(\n      `  Plugin Executor File: ${styles.success(relativePath)} from plugin ${styles.info(info.pluginId)}`,\n    );\n  }\n\n  return generatedFiles;\n}\n\n/**\n * Generate a single executor file.\n * @param info - Plugin executor metadata and definition\n * @param outputDir - Base output directory (e.g., .tailor-sdk)\n * @param typeGenerationResult - Result from plugin type generation\n * @param sourceTypeInfoMap - Map of source type names to their source info\n * @param baseDirs - Base directories for resolving plugin import paths\n * @returns Absolute path to the generated file\n */\nfunction generateSingleExecutorFile(\n  info: PluginExecutorInfoExtended,\n  outputDir: string,\n  typeGenerationResult?: PluginTypeGenerationResult,\n  sourceTypeInfoMap?: Map<string, SourceTypeInfo>,\n  baseDirs: string[] = [],\n): string {\n  const pluginDir = sanitizePluginId(info.pluginId);\n  const executorOutputDir = path.join(outputDir, pluginDir, \"executors\");\n  fs.mkdirSync(executorOutputDir, { recursive: true });\n\n  const fileName = sanitizeExecutorFileName(info.executor.name);\n  const filePath = path.join(executorOutputDir, `${fileName}.ts`);\n\n  let content: string;\n  if (isPluginExecutorWithFile(info.executor)) {\n    content = generateExecutorFileContentNew(\n      info,\n      info.executor,\n      outputDir,\n      typeGenerationResult,\n      sourceTypeInfoMap,\n      baseDirs,\n    );\n  } else {\n    content = generateExecutorFileContentLegacy(info.executor);\n  }\n\n  fs.writeFileSync(filePath, content);\n  return filePath;\n}\n\n/**\n * Generate TypeScript file content for new format executor (dynamic import).\n * Uses the executor's resolve function to dynamically import the module.\n * @param info - Plugin executor information\n * @param executor - Executor definition with resolve\n * @param outputDir - Base output directory\n * @param typeGenerationResult - Result from plugin type generation\n * @param sourceTypeInfoMap - Map of source type names to their source info\n * @param baseDirs - Base directories for resolving plugin import paths\n * @returns TypeScript source code for executor file\n */\nfunction generateExecutorFileContentNew(\n  info: PluginExecutorInfoExtended,\n  executor: PluginGeneratedExecutorWithFile,\n  outputDir: string,\n  typeGenerationResult?: PluginTypeGenerationResult,\n  sourceTypeInfoMap?: Map<string, SourceTypeInfo>,\n  baseDirs: string[] = [],\n): string {\n  const { resolve, context } = executor;\n  const pluginDir = sanitizePluginId(info.pluginId);\n  const executorOutputDir = path.join(outputDir, pluginDir, \"executors\");\n\n  const executorImportPath = resolveExecutorImportPath(\n    resolve,\n    info.pluginImportPath,\n    executorOutputDir,\n    baseDirs,\n  );\n\n  // Collect type imports from context\n  const typeImports = collectTypeImports(\n    context,\n    outputDir,\n    info.pluginId,\n    typeGenerationResult,\n    sourceTypeInfoMap,\n  );\n\n  // Generate import statements\n  const imports: string[] = [];\n\n  for (const [, importInfo] of typeImports) {\n    imports.push(`import { ${importInfo.variableName} } from \"${importInfo.importPath}\";`);\n  }\n\n  // Generate context object code\n  const contextCode = generateContextCode(context, typeImports);\n\n  return ml /* ts */ `\n    /**\n     * Auto-generated executor by plugin: ${info.pluginId}\n     * DO NOT EDIT - This file is generated by @tailor-platform/sdk\n     */\n    ${imports.join(\"\\n\")}\n\n    const { default: executorFactory } = await import(${JSON.stringify(executorImportPath)});\n    if (typeof executorFactory !== \"function\") {\n      throw new Error(\n        \"Plugin executor module must export a default function created by withPluginContext().\",\n      );\n    }\n    export default executorFactory(${contextCode});\n  `;\n}\n\n/**\n * Collect type imports needed for context.\n * @param context - Executor context values from plugin\n * @param outputDir - Base output directory for generated files\n * @param pluginId - Plugin identifier used for output paths\n * @param typeGenerationResult - Result from plugin type generation\n * @param sourceTypeInfoMap - Map of source type names to their source info\n * @returns Map of context keys to their import information\n */\nfunction collectTypeImports(\n  context: PluginExecutorContext,\n  outputDir: string,\n  pluginId: string,\n  typeGenerationResult?: PluginTypeGenerationResult,\n  sourceTypeInfoMap?: Map<string, SourceTypeInfo>,\n): Map<string, TypeImportInfo> {\n  const typeImports = new Map<string, TypeImportInfo>();\n  const pluginDir = sanitizePluginId(pluginId);\n  const executorDir = path.join(outputDir, pluginDir, \"executors\");\n\n  for (const [key, value] of Object.entries(context)) {\n    if (isTypeObject(value)) {\n      const typeName = value.name;\n      const sourceInfo = sourceTypeInfoMap?.get(typeName);\n      const variableName = sourceInfo?.exportName ?? toCamelCase(typeName);\n\n      // Check if it's a generated type\n      let importPath: string;\n      let isGeneratedType = false;\n\n      if (typeGenerationResult?.typeFilePaths.has(typeName)) {\n        // It's a generated type - import from plugin types directory\n        const typeFilePath = assertDefined(\n          typeGenerationResult.typeFilePaths.get(typeName),\n          \"type file path missing\",\n        );\n        const absoluteTypePath = path.join(outputDir, typeFilePath);\n        importPath = path.relative(executorDir, absoluteTypePath).replace(/\\.ts$/, \"\");\n        if (!importPath.startsWith(\".\")) {\n          importPath = `./${importPath}`;\n        }\n        isGeneratedType = true;\n      } else if (sourceInfo) {\n        // It's a user-defined type\n        const sourceFilePath = sourceInfo.filePath;\n        importPath = path.relative(executorDir, sourceFilePath).replace(/\\.ts$/, \"\");\n        if (!importPath.startsWith(\".\")) {\n          importPath = `./${importPath}`;\n        }\n      } else {\n        // Fallback: generate relative path assumption\n        // This might need adjustment based on actual project structure\n        importPath = `../../../../tailordb/${toKebabCase(typeName)}`;\n      }\n\n      typeImports.set(key, {\n        variableName,\n        importPath,\n        isGeneratedType,\n      });\n    }\n  }\n\n  return typeImports;\n}\n\n/**\n * Generate TypeScript code for context object.\n * @param context - Executor context values from plugin\n * @param typeImports - Resolved type import information for context keys\n * @returns TypeScript object literal code\n */\nfunction generateContextCode(\n  context: PluginExecutorContext,\n  typeImports: Map<string, TypeImportInfo>,\n): string {\n  const entries: string[] = [];\n\n  for (const [key, value] of Object.entries(context)) {\n    if (isTypeObject(value)) {\n      const importInfo = typeImports.get(key);\n      if (importInfo) {\n        entries.push(`  ${key}: ${importInfo.variableName}`);\n      }\n    } else if (value !== undefined) {\n      entries.push(`  ${key}: ${JSON.stringify(value)}`);\n    }\n  }\n\n  return `{\\n${entries.join(\",\\n\")},\\n}`;\n}\n\n/**\n * Check if a value is a TailorDB type object.\n * @param value - Value to inspect\n * @returns True if value is a type object with name and fields\n */\nfunction isTypeObject(value: unknown): value is { name: string; fields: Record<string, unknown> } {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"name\" in value &&\n    \"fields\" in value &&\n    typeof (value as { name: unknown }).name === \"string\"\n  );\n}\n\n// ============================================================================\n// Legacy format support\n// ============================================================================\n\n/**\n * Generate TypeScript file content for legacy format executor (trigger/operation).\n * @param executor - Legacy executor definition\n * @returns TypeScript source code for executor file\n */\nfunction generateExecutorFileContentLegacy(executor: PluginGeneratedExecutorLegacy): string {\n  const triggerCode = generateTriggerCode(executor.trigger);\n  const operationCode = generateOperationCode(executor.operation);\n\n  // Extract inject from function operation\n  const inject = executor.operation.kind === \"function\" ? executor.operation.inject : undefined;\n  const injectDeclarations = generateInjectDeclarations(inject);\n\n  const descriptionLine = executor.description\n    ? `\\n  description: ${JSON.stringify(executor.description)},`\n    : \"\";\n\n  return ml /* ts */ `\n    /**\n     * Auto-generated executor by plugin\n     * DO NOT EDIT - This file is generated by @tailor-platform/sdk\n     */\n    import { createExecutor } from \"@tailor-platform/sdk\";\n    ${injectDeclarations}\n    export default createExecutor({\n      name: ${JSON.stringify(executor.name)},${descriptionLine}\n      trigger: ${triggerCode},\n      operation: ${operationCode},\n    });\n  `;\n}\n\n/**\n * Generate const declarations for injected variables.\n * @param inject - Map of injected values keyed by variable name\n * @returns TypeScript const declarations or empty string\n */\nfunction generateInjectDeclarations(inject: PluginInjectMap | undefined): string {\n  if (!inject || Object.keys(inject).length === 0) {\n    return \"\";\n  }\n\n  const declarations = Object.entries(inject)\n    .map(([name, value]) => `const ${name} = ${JSON.stringify(value)};`)\n    .join(\"\\n\");\n\n  return `\\n// Injected variables from plugin\\n${declarations}\\n`;\n}\n\n/**\n * Generate TypeScript code for trigger configuration.\n * @param trigger - Trigger configuration for executor\n * @returns TypeScript code for trigger object\n */\nfunction generateTriggerCode(trigger: PluginTriggerConfig): string {\n  switch (trigger.kind) {\n    case \"tailordb\":\n      return `{\n    kind: ${JSON.stringify(trigger.kind)},\n    events: ${JSON.stringify(trigger.events)},\n    typeName: ${JSON.stringify(trigger.typeName)},\n  }`;\n\n    case \"schedule\":\n      return `{\n    kind: \"schedule\",\n    cron: ${JSON.stringify(trigger.cron)},\n    timezone: ${JSON.stringify(trigger.timezone ?? \"UTC\")},\n  }`;\n\n    case \"incomingWebhook\":\n      return `{\n    kind: \"incomingWebhook\",\n  }`;\n\n    default:\n      throw new Error(`Unknown trigger kind: ${(trigger as PluginTriggerConfig).kind}`);\n  }\n}\n\n/**\n * Generate TypeScript code for operation configuration.\n * @param operation - Operation configuration for executor\n * @returns TypeScript code for operation object\n */\nfunction generateOperationCode(operation: PluginOperationConfig): string {\n  switch (operation.kind) {\n    case \"graphql\": {\n      const appNameLine = operation.appName\n        ? `\\n    appName: ${JSON.stringify(operation.appName)},`\n        : \"\";\n      const variablesLine = operation.variables ? `\\n    variables: ${operation.variables},` : \"\";\n\n      return `{\n    kind: \"graphql\",\n    query: \\`${escapeTemplateLiteral(operation.query)}\\`,${appNameLine}${variablesLine}\n  }`;\n    }\n\n    case \"function\":\n      return `{\n    kind: \"function\",\n    body: ${operation.body},\n  }`;\n\n    case \"webhook\":\n      return `{\n    kind: \"webhook\",\n    url: () => ${JSON.stringify(operation.url)},\n  }`;\n\n    case \"workflow\":\n      return `{\n    kind: \"workflow\",\n    workflowName: ${JSON.stringify(operation.workflowName)},\n  }`;\n\n    default:\n      throw new Error(`Unknown operation kind: ${(operation as PluginOperationConfig).kind}`);\n  }\n}\n\n/**\n * Escape special characters in template literal content.\n * @param str - Raw template literal content\n * @returns Escaped string safe for template literals\n */\nfunction escapeTemplateLiteral(str: string): string {\n  return str.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\").replace(/\\$\\{/g, \"\\\\${\");\n}\n\n// ============================================================================\n// Utility functions\n// ============================================================================\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Resolve the import path for a plugin executor module.\n * @param resolve - Executor resolve function\n * @param pluginImportPath - Plugin's import path\n * @param executorOutputDir - Directory where the generated executor will be written\n * @param baseDirs - Base directories for resolving plugin import paths\n * @returns Import path string for the executor module\n */\nfunction resolveExecutorImportPath(\n  resolve: () => Promise<{ default: unknown }>,\n  pluginImportPath: string,\n  executorOutputDir: string,\n  baseDirs: string[],\n): string {\n  const specifier = extractDynamicImportSpecifier(resolve);\n  if (!specifier.startsWith(\".\")) {\n    return specifier;\n  }\n\n  const pluginBaseDir = resolvePluginBaseDir(pluginImportPath, baseDirs);\n  if (!pluginBaseDir) {\n    throw new Error(\n      `Unable to resolve plugin import base for \"${pluginImportPath}\". ` +\n        `Tried base dirs: ${baseDirs.join(\", \") || \"(none)\"}. ` +\n        `Use an absolute import specifier in resolve(), or ensure the plugin path is resolvable.`,\n    );\n  }\n\n  const absolutePath = path.resolve(pluginBaseDir, specifier);\n  let relativePath = path.relative(executorOutputDir, absolutePath).replace(/\\\\/g, \"/\");\n  relativePath = stripSourceExtension(relativePath);\n  if (!relativePath.startsWith(\".\")) {\n    relativePath = `./${relativePath}`;\n  }\n  return relativePath;\n}\n\n/**\n * Extract the dynamic import specifier from a resolve function.\n * @param resolve - Executor resolve function\n * @returns The module specifier string\n */\nfunction extractDynamicImportSpecifier(resolve: () => Promise<{ default: unknown }>): string {\n  const source = resolve.toString();\n  const match = source.match(/import\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/);\n  if (!match) {\n    throw new Error(\n      `resolve() must return a dynamic import, e.g. \\`async () => await import(\"./executors/on-create\")\\`.`,\n    );\n  }\n  return assertDefined(match[1], \"dynamic import specifier capture group missing\");\n}\n\n/**\n * Resolve plugin base directory for relative imports.\n * @param pluginImportPath - Plugin import path\n * @param baseDirs - Base directories for resolving plugin import paths\n * @returns Directory path or null if not resolvable\n */\nfunction resolvePluginBaseDir(pluginImportPath: string, baseDirs: string[]): string | null {\n  if (pluginImportPath.startsWith(\".\")) {\n    const resolvedPath =\n      resolveRelativePluginImportPath(pluginImportPath, baseDirs) ??\n      path.resolve(baseDirs[0] ?? process.cwd(), pluginImportPath);\n    if (fs.existsSync(resolvedPath)) {\n      const stats = fs.statSync(resolvedPath);\n      return stats.isDirectory() ? resolvedPath : path.dirname(resolvedPath);\n    }\n    return path.extname(resolvedPath) ? path.dirname(resolvedPath) : resolvedPath;\n  }\n\n  for (const baseDir of baseDirs) {\n    try {\n      const resolved = require.resolve(pluginImportPath, { paths: [baseDir] });\n      return path.dirname(resolved);\n    } catch {\n      continue;\n    }\n  }\n  return null;\n}\n\n/**\n * Strip TypeScript source extensions from import paths.\n * @param importPath - Path to normalize\n * @returns Path without .ts/.tsx extension\n */\nfunction stripSourceExtension(importPath: string): string {\n  return importPath.replace(/\\.(ts|tsx)$/, \"\");\n}\n\n/**\n * Convert plugin ID to safe directory name.\n * @param pluginId - Plugin identifier (e.g., \"@scope/name\")\n * @returns Safe directory name\n */\nfunction sanitizePluginId(pluginId: string): string {\n  return pluginId.replace(/^@/, \"\").replace(/\\//g, \"-\");\n}\n\n/**\n * Convert executor name to safe filename.\n * @param executorName - Executor name\n * @returns Safe filename without extension\n */\nfunction sanitizeExecutorFileName(executorName: string): string {\n  const baseName = path.basename(executorName);\n  const withoutExtension = baseName.replace(/\\.[^/.]+$/, \"\");\n  const sanitized = withoutExtension.replace(/[^a-zA-Z0-9_-]/g, \"-\");\n  if (!sanitized) {\n    throw new Error(`Invalid executor name: \"${executorName}\"`);\n  }\n  return sanitized;\n}\n\n/**\n * Convert string to camelCase.\n * @param str - Input string to convert\n * @returns camelCase string\n */\nfunction toCamelCase(str: string): string {\n  const result = str.replace(/[-_\\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : \"\"));\n  return result.charAt(0).toLowerCase() + result.slice(1);\n}\n\n/**\n * Convert string to kebab-case.\n * @param str - Input string to convert\n * @returns kebab-case string\n */\nfunction toKebabCase(str: string): string {\n  return str\n    .replace(/([a-z])([A-Z])/g, \"$1-$2\")\n    .replace(/[\\s_]+/g, \"-\")\n    .toLowerCase();\n}\n","/**\n * Plugin Type Generator\n *\n * Generates TypeScript files for plugin-generated types (TailorDB types).\n * These files can be imported by plugin executors to reference generated types.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\nimport type { PluginGeneratedTypeInfo, PluginTypeGenerationResult } from \"#/plugin/manager\";\nimport type { PluginGeneratedType } from \"#/plugin/types\";\n\ntype FieldMetadata = {\n  required?: boolean;\n  index?: boolean;\n  unique?: boolean;\n  description?: string;\n  allowedValues?: ReadonlyArray<{ value: string }>;\n};\n\ntype FieldDefinition = {\n  type?: string;\n  _metadata?: FieldMetadata;\n  metadata?: FieldMetadata;\n};\n\nfunction isFieldDefinition(value: unknown): value is FieldDefinition {\n  return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Generate TypeScript files for plugin-generated types.\n * These files export the type definition and can be imported by executor files.\n * @param types - Array of plugin type information\n * @param outputDir - Base output directory (e.g., .tailor-sdk)\n * @returns Generation result with file paths\n */\nexport function generatePluginTypeFiles(\n  types: ReadonlyArray<PluginGeneratedTypeInfo>,\n  outputDir: string,\n): PluginTypeGenerationResult {\n  const typeFilePaths = new Map<string, string>();\n  const generatedFiles: string[] = [];\n\n  if (types.length === 0) {\n    return { typeFilePaths, generatedFiles };\n  }\n\n  const seenTypeNames = new Map<string, PluginGeneratedTypeInfo>();\n\n  for (const info of types) {\n    const existing = seenTypeNames.get(info.type.name);\n    if (existing) {\n      throw new Error(\n        `Duplicate plugin-generated type name \"${info.type.name}\" detected. ` +\n          `First: plugin \"${existing.pluginId}\" (kind: \"${existing.kind}\", source type: \"${existing.sourceTypeName}\"), ` +\n          `Second: plugin \"${info.pluginId}\" (kind: \"${info.kind}\", source type: \"${info.sourceTypeName}\"). ` +\n          `Plugin-generated type names must be unique.`,\n      );\n    }\n    seenTypeNames.set(info.type.name, info);\n\n    const pluginDir = sanitizePluginId(info.pluginId);\n    const typeOutputDir = path.join(outputDir, pluginDir, \"types\");\n    fs.mkdirSync(typeOutputDir, { recursive: true });\n\n    const fileName = `${toKebabCase(info.type.name)}.ts`;\n    const filePath = path.join(typeOutputDir, fileName);\n    const content = generateTypeFileContent(info);\n\n    fs.writeFileSync(filePath, content);\n    generatedFiles.push(filePath);\n\n    // Store relative path from outputDir for import resolution\n    const relativePath = path.relative(outputDir, filePath);\n    typeFilePaths.set(info.type.name, relativePath);\n\n    const displayPath = path.relative(process.cwd(), filePath);\n    logger.log(\n      `  Plugin Type File: ${styles.success(displayPath)} (${styles.dim(info.kind)}) from plugin ${styles.info(info.pluginId)}`,\n    );\n  }\n\n  return { typeFilePaths, generatedFiles };\n}\n\n/**\n * Generate TypeScript file content for a single type.\n * @param info - Plugin type information\n * @returns TypeScript source code\n */\nfunction generateTypeFileContent(info: PluginGeneratedTypeInfo): string {\n  const { type, pluginId, sourceTypeName, kind } = info;\n  const variableName = toCamelCase(type.name);\n  const fieldsCode = generateFieldsCode(type);\n\n  return ml /* ts */ `\n    /**\n     * Auto-generated type by plugin: ${pluginId}\n     * Source type: ${sourceTypeName}\n     * Kind: ${kind}\n     *\n     * DO NOT EDIT - This file is generated by @tailor-platform/sdk\n     */\n    import { db } from \"@tailor-platform/sdk\";\n\n    export const ${variableName} = db.type(${JSON.stringify(type.name)}, ${fieldsCode});\n\n    export type ${type.name} = typeof ${variableName};\n  `;\n}\n\n/**\n * Generate TypeScript code for field definitions.\n * This creates a simplified version of the type's fields.\n * @param type - TailorDB type\n * @returns TypeScript code for fields object\n */\nfunction generateFieldsCode(type: PluginGeneratedType): string {\n  const fieldEntries: string[] = [];\n\n  for (const [fieldName, field] of Object.entries(type.fields)) {\n    if (!isFieldDefinition(field)) continue;\n    const fieldCode = generateSingleFieldCode(field);\n    if (fieldCode) {\n      fieldEntries.push(`  ${fieldName}: ${fieldCode}`);\n    }\n  }\n\n  return `{\\n${fieldEntries.join(\",\\n\")},\\n}`;\n}\n\n/**\n * Map from TailorDB type to SDK method name.\n */\nconst typeToMethodMap: Record<string, string> = {\n  string: \"string\",\n  integer: \"int\",\n  float: \"float\",\n  boolean: \"bool\",\n  uuid: \"uuid\",\n  datetime: \"datetime\",\n  date: \"date\",\n  time: \"time\",\n  enum: \"enum\",\n  nested: \"nested\",\n};\n\n/**\n * Generate TypeScript code for a single field definition.\n * @param field - Field definition object\n * @returns TypeScript code for the field\n */\nfunction generateSingleFieldCode(field: FieldDefinition): string | null {\n  const fieldType = field.type;\n  if (!fieldType) {\n    return null;\n  }\n\n  const method = typeToMethodMap[fieldType] ?? fieldType;\n  const metadata: FieldMetadata = field._metadata ?? field.metadata ?? {};\n\n  // Build options object\n  const optionParts: string[] = [];\n  if (metadata.required === false) {\n    optionParts.push(\"optional: true\");\n  }\n\n  const optionsArg = optionParts.length > 0 ? `{ ${optionParts.join(\", \")} }` : \"\";\n\n  // Handle enum type with values\n  if (fieldType === \"enum\") {\n    // Extract enum values from allowedValues array\n    const allowedValues = metadata.allowedValues;\n    let enumValues: string[] = [];\n    if (Array.isArray(allowedValues)) {\n      enumValues = allowedValues.map((v: { value: string }) => v.value);\n    }\n\n    let code = `db.enum(${JSON.stringify(enumValues)}${optionsArg ? `, ${optionsArg}` : \"\"})`;\n    if (metadata.index) {\n      code += \".index()\";\n    }\n    if (metadata.unique) {\n      code += \".unique()\";\n    }\n    if (metadata.description) {\n      code += `.description(${JSON.stringify(metadata.description)})`;\n    }\n    return code;\n  }\n\n  // Build method chain for other types\n  let code = `db.${method}(${optionsArg})`;\n\n  // Add index if present\n  if (metadata.index) {\n    code += \".index()\";\n  }\n\n  // Add unique if present\n  if (metadata.unique) {\n    code += \".unique()\";\n  }\n\n  // Add description if present\n  if (metadata.description) {\n    code += `.description(${JSON.stringify(metadata.description)})`;\n  }\n\n  return code;\n}\n\n/**\n * Convert plugin ID to safe directory name.\n * @param pluginId - Plugin identifier (e.g., \"@tailor-platform/change-history\")\n * @returns Safe directory name (e.g., \"tailor-platform-change-history\")\n */\nfunction sanitizePluginId(pluginId: string): string {\n  return pluginId.replace(/^@/, \"\").replace(/\\//g, \"-\");\n}\n\n/**\n * Convert string to kebab-case.\n * @param str - Input string\n * @returns kebab-case string\n */\nfunction toKebabCase(str: string): string {\n  return str\n    .replace(/([a-z])([A-Z])/g, \"$1-$2\")\n    .replace(/[\\s_]+/g, \"-\")\n    .toLowerCase();\n}\n\n/**\n * Convert string to camelCase.\n * @param str - Input string\n * @returns camelCase string\n */\nfunction toCamelCase(str: string): string {\n  const result = str.replace(/[-_\\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : \"\"));\n  return result.charAt(0).toLowerCase() + result.slice(1);\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"pathe\";\n\n/**\n * Remove stale `.entry.js` files from the output directory.\n *\n * Must be called before parallel bundling; concurrent builds\n * sharing the same output directory would otherwise conflict.\n * @param outputDir - Directory to clean\n */\nexport async function removeStaleEntryFiles(outputDir: string): Promise<void> {\n  const files = await fs.readdir(outputDir);\n  await Promise.all(\n    files\n      .filter((file) => file.endsWith(\".entry.js\"))\n      .map((file) => fs.rm(path.join(outputDir, file), { force: true })),\n  );\n}\n","import { isLogLevel, LOG_LEVELS } from \"#/parser/app-config/log-level\";\nimport type { LogLevel, LogLevelInput } from \"#/configure/config/types\";\nimport type { TreeshakingOptions } from \"rolldown\";\n\nconst INFO_LEVEL_CONSOLE_METHODS = [\n  \"console.info\",\n  \"console.table\",\n  \"console.dir\",\n  \"console.dirxml\",\n  \"console.count\",\n  \"console.countReset\",\n  \"console.time\",\n  \"console.timeLog\",\n  \"console.timeEnd\",\n  \"console.group\",\n  \"console.groupCollapsed\",\n  \"console.groupEnd\",\n  \"console.clear\",\n] as const;\n\n// `console.log` is treated as a DEBUG-level method to stay consistent with the\n// platform's OpenTelemetry severity mapping, where the deployment runtime emits\n// `console.log` at DEBUG severity rather than INFO.\nconst DEBUG_LEVEL_CONSOLE_METHODS = [\"console.debug\", \"console.log\", \"console.trace\"] as const;\n\nconst WARN_LEVEL_CONSOLE_METHODS = [\"console.warn\"] as const;\n\n// `console.assert` is intentionally excluded: on the deployment runtime\n// (deno_core/V8) only log/debug/info/warn/error are wrapped with a log\n// severity, so `console.assert` sits outside the platform's severity system\n// and is never dropped by the log-level treeshaking.\nconst ERROR_LEVEL_CONSOLE_METHODS = [\"console.error\"] as const;\n\nconst MANUAL_PURE_FUNCTIONS_BY_LOG_LEVEL: Record<LogLevel, readonly string[]> = {\n  DEBUG: [],\n  INFO: DEBUG_LEVEL_CONSOLE_METHODS,\n  WARN: [...DEBUG_LEVEL_CONSOLE_METHODS, ...INFO_LEVEL_CONSOLE_METHODS],\n  ERROR: [\n    ...DEBUG_LEVEL_CONSOLE_METHODS,\n    ...INFO_LEVEL_CONSOLE_METHODS,\n    ...WARN_LEVEL_CONSOLE_METHODS,\n  ],\n  SILENT: [\n    ...DEBUG_LEVEL_CONSOLE_METHODS,\n    ...INFO_LEVEL_CONSOLE_METHODS,\n    ...WARN_LEVEL_CONSOLE_METHODS,\n    ...ERROR_LEVEL_CONSOLE_METHODS,\n  ],\n};\n\nexport function normalizeBundleLogLevel(value: string): LogLevel | undefined {\n  const normalized = value.trim().toUpperCase();\n  return isLogLevel(normalized) ? normalized : undefined;\n}\n\nexport function resolveBundleLogLevel(configValue?: LogLevelInput): LogLevel {\n  if (configValue === undefined) return \"DEBUG\";\n  const resolved = normalizeBundleLogLevel(configValue);\n  if (resolved) return resolved;\n\n  throw new Error(`Invalid logLevel \"${configValue}\". Expected one of: ${LOG_LEVELS.join(\", \")}`);\n}\n\nexport function manualPureFunctionsForLogLevel(logLevel: LogLevel): readonly string[] {\n  return MANUAL_PURE_FUNCTIONS_BY_LOG_LEVEL[logLevel];\n}\n\nexport function createLogLevelTreeshakeOptions(logLevel: LogLevel): TreeshakingOptions {\n  const manualPureFunctions = manualPureFunctionsForLogLevel(logLevel);\n  return manualPureFunctions.length > 0 ? { manualPureFunctions } : {};\n}\n","import type { TreeshakingOptions } from \"rolldown\";\n\nconst BASE_FUNCTION_TREESHAKE_OPTIONS = {\n  moduleSideEffects: false,\n  annotations: true,\n  unknownGlobalSideEffects: false,\n} as const satisfies TreeshakingOptions;\n\nexport function mergeFunctionTreeshakeOptions(\n  fragments: readonly TreeshakingOptions[],\n): TreeshakingOptions {\n  const merged: TreeshakingOptions = {};\n  const manualPureFunctions = new Set<string>();\n\n  for (const fragment of fragments) {\n    Object.assign(merged, fragment);\n    for (const name of fragment.manualPureFunctions ?? []) {\n      manualPureFunctions.add(name);\n    }\n  }\n\n  if (manualPureFunctions.size > 0) {\n    merged.manualPureFunctions = [...manualPureFunctions];\n  } else {\n    delete merged.manualPureFunctions;\n  }\n\n  return merged;\n}\n\nexport function composeFunctionTreeshakeOptions(\n  fragments: readonly TreeshakingOptions[] = [],\n): TreeshakingOptions {\n  return mergeFunctionTreeshakeOptions([BASE_FUNCTION_TREESHAKE_OPTIONS, ...fragments]);\n}\n","import type * as rolldown from \"rolldown\";\n\n// Match the exact `process.env.TAILOR_PLATFORM_BUNDLE` member-expression: the\n// leading lookbehind rejects a longer owner (`foo.process.env…`) or identifier,\n// the trailing `\\b` rejects a longer key (`…_BUNDLE_MODE`).\nconst GATE = /(?<![\\w$.])process\\.env\\.TAILOR_PLATFORM_BUNDLE\\b/g;\n\n// Fold the gate to `true` so the minifier DCEs the test-only workflow\n// registry/serialize runner. Apply in every bundler that builds runnable\n// functions; a missed path leaves the env read in place and fails loudly on the\n// Platform's Web runtime (no `process`), which an e2e catches. rolldown exposes\n// no `define`, so this is a transform-level replace rather than a define.\nexport const platformBundleDefinePlugin: rolldown.Plugin = {\n  name: \"tailor-platform-bundle-define\",\n  transform(code) {\n    if (!code.includes(\"process.env.TAILOR_PLATFORM_BUNDLE\")) return null;\n    return { code: code.replace(GATE, \"true\") };\n  },\n};\n","import type {\n  Expression,\n  AwaitExpression,\n  ImportExpression,\n  CallExpression,\n  ObjectPropertyKind,\n  ObjectProperty,\n  ArrowFunctionExpression,\n  Function as FunctionExpression,\n} from \"@oxc-project/types\";\n\n/** A generic AST node for walking purposes */\nexport type ASTNode = Record<string, unknown>;\n\nexport interface Replacement {\n  start: number;\n  end: number;\n  text: string;\n}\n\nexport interface FoundProperty {\n  key: ObjectProperty[\"key\"];\n  value: Expression;\n  start: number;\n  end: number;\n}\n\n/**\n * Check if a module source is from the Tailor SDK package (including subpaths)\n * @param source - Module source string\n * @returns True if the source is from the Tailor SDK package\n */\nexport function isTailorSdkSource(source: string): boolean {\n  return /^@tailor-platform\\/sdk(\\/|$)/.test(source);\n}\n\n/**\n * Get the source string from a dynamic import or require call\n * @param node - AST node to inspect\n * @returns Resolved import/require source string or null\n */\nexport function getImportSource(node: Expression | null | undefined): string | null {\n  if (!node) return null;\n  // await import(\"@tailor-platform/sdk\")\n  if (node.type === \"ImportExpression\") {\n    const importExpr = node as ImportExpression;\n    const source = importExpr.source;\n    if (source.type === \"Literal\" && typeof source.value === \"string\") {\n      return source.value;\n    }\n  }\n  // require(\"@tailor-platform/sdk\")\n  if (node.type === \"CallExpression\") {\n    const callExpr = node as CallExpression;\n    if (callExpr.callee.type === \"Identifier\" && callExpr.callee.name === \"require\") {\n      const arg = callExpr.arguments[0];\n      if (\n        // callee may be a ComputedMemberExpression at runtime\n        // oxlint-disable-next-line typescript/no-unnecessary-condition\n        arg &&\n        \"type\" in arg &&\n        arg.type === \"Literal\" &&\n        \"value\" in arg &&\n        typeof arg.value === \"string\"\n      ) {\n        return arg.value;\n      }\n    }\n  }\n  return null;\n}\n\n/**\n * Unwrap AwaitExpression to get the inner expression\n * @param node - AST expression node\n * @returns Inner expression if node is an AwaitExpression\n */\nexport function unwrapAwait(node: Expression | null | undefined): Expression | null | undefined {\n  if (node?.type === \"AwaitExpression\") {\n    return (node as AwaitExpression).argument;\n  }\n  return node;\n}\n\n/**\n * Check if a node is a string literal\n * @param node - AST expression node\n * @returns True if node is a string literal\n */\nexport function isStringLiteral(\n  node: Expression | null | undefined,\n): node is Expression & { type: \"Literal\"; value: string } {\n  // Note: oxc uses \"Literal\" for all literals, distinguishing by value type\n  return node?.type === \"Literal\" && typeof (node as { value?: unknown }).value === \"string\";\n}\n\n/**\n * Check if a node is a function expression (arrow or regular)\n * @param node - AST expression node\n * @returns True if node is a function expression\n */\nexport function isFunctionExpression(\n  node: Expression | null | undefined,\n): node is ArrowFunctionExpression | FunctionExpression {\n  return node?.type === \"ArrowFunctionExpression\" || node?.type === \"FunctionExpression\";\n}\n\n/**\n * Find a property in an object expression\n * @param properties - Object properties to search\n * @param name - Property name to find\n * @returns Found property info or null\n */\nexport function findProperty(properties: ObjectPropertyKind[], name: string): FoundProperty | null {\n  for (const prop of properties) {\n    // Note: oxc uses \"Property\" for object properties\n    if (prop.type === \"Property\") {\n      const objProp = prop as ObjectProperty;\n      const keyName =\n        objProp.key.type === \"Identifier\"\n          ? objProp.key.name\n          : objProp.key.type === \"Literal\"\n            ? (objProp.key as { value?: string }).value\n            : null;\n      if (keyName === name) {\n        return {\n          key: objProp.key,\n          value: objProp.value,\n          start: objProp.start,\n          end: objProp.end,\n        };\n      }\n    }\n  }\n  return null;\n}\n\n/**\n * Apply string replacements to source code\n * Replacements are applied from end to start to maintain positions\n * @param source - Original source code\n * @param replacements - Replacements to apply\n * @returns Transformed source code\n */\nexport function applyReplacements(source: string, replacements: Replacement[]): string {\n  const sorted = replacements.toSorted((a, b) => b.start - a.start);\n  let result = source;\n  for (const r of sorted) {\n    result = result.slice(0, r.start) + r.text + result.slice(r.end);\n  }\n  return result;\n}\n\n/**\n * Find the end of a statement including any trailing newline\n * @param source - Source code\n * @param position - Start position of the statement\n * @returns Index of the end of the statement including trailing newline\n */\nexport function findStatementEnd(source: string, position: number): number {\n  let i = position;\n  // Skip any trailing semicolons and whitespace on the same line\n  while (i < source.length && (source[i] === \";\" || source[i] === \" \" || source[i] === \"\\t\")) {\n    i++;\n  }\n  // Include the newline if present\n  if (i < source.length && source[i] === \"\\n\") {\n    i++;\n  }\n  return i;\n}\n\n/**\n * Resolve a relative path from a base directory\n * Simple implementation that handles ./ and ../ prefixes\n * @param baseDir - Base directory\n * @param relativePath - Relative path to resolve\n * @returns Resolved absolute path\n */\nexport function resolvePath(baseDir: string, relativePath: string): string {\n  // Normalize separators to forward slash\n  const normalized = relativePath.replace(/\\\\/g, \"/\");\n\n  // Split into parts\n  const parts = normalized.split(\"/\");\n  const baseParts = baseDir.replace(/\\\\/g, \"/\").split(\"/\");\n\n  for (const part of parts) {\n    if (part === \".\") {\n      // Current directory, do nothing\n    } else if (part === \"..\") {\n      // Go up one directory\n      baseParts.pop();\n    } else {\n      // Add the part\n      baseParts.push(part);\n    }\n  }\n\n  return baseParts.join(\"/\");\n}\n","import { type ASTNode, isTailorSdkSource, getImportSource, unwrapAwait } from \"./ast-utils\";\nimport type {\n  Program,\n  ImportDeclaration,\n  VariableDeclaration,\n  ImportSpecifier,\n  ImportDefaultSpecifier,\n  ImportNamespaceSpecifier,\n  ObjectPattern,\n  BindingProperty,\n  CallExpression,\n  StaticMemberExpression,\n  IdentifierReference,\n} from \"@oxc-project/types\";\n\n/**\n * Collect all import bindings for a specific function from the Tailor SDK package\n * Returns a Set of local names that refer to the function\n * @param program - Parsed TypeScript program\n * @param functionName - Function name to collect bindings for\n * @returns Set of local names bound to the SDK function\n */\nexport function collectSdkBindings(program: Program, functionName: string): Set<string> {\n  const bindings = new Set<string>();\n\n  function walk(node: ASTNode | null | undefined): void {\n    if (!node || typeof node !== \"object\") return;\n\n    const nodeType = node.type as string | undefined;\n\n    // Static imports: import { createWorkflowJob } from \"@tailor-platform/sdk\"\n    if (nodeType === \"ImportDeclaration\") {\n      const importDecl = node as unknown as ImportDeclaration;\n      const source = importDecl.source.value;\n      if (typeof source === \"string\" && isTailorSdkSource(source)) {\n        for (const specifier of importDecl.specifiers) {\n          // import { createWorkflowJob } from \"@tailor-platform/sdk\"\n          // import { createWorkflowJob as create } from \"@tailor-platform/sdk\"\n          if (specifier.type === \"ImportSpecifier\") {\n            const importSpec = specifier as ImportSpecifier;\n            const imported =\n              importSpec.imported.type === \"Identifier\"\n                ? importSpec.imported.name\n                : (importSpec.imported as { value?: string }).value;\n            if (imported === functionName) {\n              bindings.add(importSpec.local.name);\n            }\n          }\n          // import sdk from \"@tailor-platform/sdk\" → sdk.createWorkflowJob\n          // import * as sdk from \"@tailor-platform/sdk\" → sdk.createWorkflowJob\n          // callee may be a ComputedMemberExpression at runtime\n          // oxlint-disable typescript/no-unnecessary-condition\n          else if (\n            specifier.type === \"ImportDefaultSpecifier\" ||\n            specifier.type === \"ImportNamespaceSpecifier\"\n            // oxlint-enable typescript/no-unnecessary-condition\n          ) {\n            const spec = specifier as ImportDefaultSpecifier | ImportNamespaceSpecifier;\n            // Store namespace/default with special prefix to track member access\n            bindings.add(`__namespace__:${spec.local.name}`);\n          }\n        }\n      }\n    }\n\n    // Dynamic imports and require:\n    // const sdk = await import(\"@tailor-platform/sdk\")\n    // const sdk = require(\"@tailor-platform/sdk\")\n    // const { createWorkflowJob } = await import(\"@tailor-platform/sdk\")\n    // const { createWorkflowJob } = require(\"@tailor-platform/sdk\")\n    if (nodeType === \"VariableDeclaration\") {\n      const varDecl = node as unknown as VariableDeclaration;\n      for (const decl of varDecl.declarations) {\n        const init = unwrapAwait(decl.init);\n        const source = getImportSource(init);\n\n        if (source && isTailorSdkSource(source)) {\n          const id = decl.id;\n\n          // const sdk = await import(...) / const sdk = require(...)\n          if (id.type === \"Identifier\") {\n            bindings.add(`__namespace__:${id.name}`);\n          }\n          // const { createWorkflowJob } = await import(...) / require(...)\n          // const { createWorkflowJob: create } = await import(...) / require(...)\n          else if (id.type === \"ObjectPattern\") {\n            const objPattern = id as unknown as ObjectPattern;\n            for (const prop of objPattern.properties) {\n              if (prop.type === \"Property\") {\n                const bindingProp = prop as BindingProperty;\n                const keyName =\n                  bindingProp.key.type === \"Identifier\"\n                    ? bindingProp.key.name\n                    : (bindingProp.key as { value?: string }).value;\n                if (keyName === functionName) {\n                  const localName =\n                    bindingProp.value.type === \"Identifier\" ? bindingProp.value.name : keyName;\n                  bindings.add(localName);\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n\n    for (const key of Object.keys(node)) {\n      const child = node[key] as unknown;\n      if (Array.isArray(child)) {\n        child.forEach((c: unknown) => walk(c as ASTNode | null));\n      } else if (child && typeof child === \"object\") {\n        walk(child as ASTNode);\n      }\n    }\n  }\n\n  walk(program as unknown as ASTNode);\n  return bindings;\n}\n\n/**\n * Check if a CallExpression is a call to a specific SDK function\n * @param node - AST node to inspect\n * @param bindings - Collected SDK bindings\n * @param functionName - SDK function name\n * @returns True if node is a call to the SDK function\n */\nexport function isSdkFunctionCall(\n  node: ASTNode,\n  bindings: Set<string>,\n  functionName: string,\n): node is ASTNode & { type: \"CallExpression\" } {\n  if (node.type !== \"CallExpression\") return false;\n\n  const callExpr = node as unknown as CallExpression;\n  const callee = callExpr.callee;\n\n  // Direct call: createWorkflowJob(...) or create(...)\n  if (callee.type === \"Identifier\") {\n    const identifier = callee as IdentifierReference;\n    return bindings.has(identifier.name);\n  }\n\n  // Member access: sdk.createWorkflowJob(...)\n  // Note: oxc uses MemberExpression with computed: false for static member access\n  if (callee.type === \"MemberExpression\") {\n    const memberExpr = callee as unknown as StaticMemberExpression;\n    // callee may be a ComputedMemberExpression at runtime\n    // oxlint-disable-next-line typescript/no-unnecessary-condition\n    if (!memberExpr.computed) {\n      const object = memberExpr.object;\n      const property = memberExpr.property;\n      if (\n        object.type === \"Identifier\" &&\n        bindings.has(`__namespace__:${(object as IdentifierReference).name}`) &&\n        property.name === functionName\n      ) {\n        return true;\n      }\n    }\n  }\n\n  return false;\n}\n","import { assertDefined } from \"#/utils/assert\";\nimport { type ASTNode, isStringLiteral, isFunctionExpression, findProperty } from \"./ast-utils\";\nimport { collectSdkBindings, isSdkFunctionCall } from \"./sdk-binding-collector\";\nimport type {\n  Program,\n  CallExpression,\n  ObjectExpression,\n  StaticMemberExpression,\n  IdentifierReference,\n} from \"@oxc-project/types\";\n\nexport interface JobLocation {\n  name: string;\n  exportName?: string;\n  nameRange: { start: number; end: number };\n  bodyValueRange: { start: number; end: number };\n  // Range of the entire variable declaration statement (for removal)\n  statementRange?: { start: number; end: number };\n}\n\nexport interface TriggerCall {\n  identifierName: string;\n  callRange: { start: number; end: number };\n  argsText: string;\n}\n\n/**\n * Find all workflow jobs by detecting createWorkflowJob calls from `@tailor-platform/sdk`\n * @param program - Parsed TypeScript program\n * @param _sourceText - Source code text (currently unused)\n * @returns Detected job locations\n */\nexport function findAllJobs(program: Program, _sourceText: string): JobLocation[] {\n  const jobs: JobLocation[] = [];\n  const bindings = collectSdkBindings(program, \"createWorkflowJob\");\n\n  function walk(node: ASTNode | null | undefined, parents: ASTNode[] = []): void {\n    if (!node || typeof node !== \"object\") return;\n\n    // Detect createWorkflowJob(...) calls\n    if (isSdkFunctionCall(node, bindings, \"createWorkflowJob\")) {\n      const callExpr = node as unknown as CallExpression;\n      const args = callExpr.arguments;\n      const firstArg = args[0];\n      if (args.length >= 1 && firstArg?.type === \"ObjectExpression\") {\n        const configObj = assertDefined(\n          firstArg,\n          \"createWorkflowJob first argument missing\",\n        ) as ObjectExpression;\n        const nameProp = findProperty(configObj.properties, \"name\");\n        const bodyProp = findProperty(configObj.properties, \"body\");\n\n        if (\n          nameProp &&\n          isStringLiteral(nameProp.value) &&\n          bodyProp &&\n          isFunctionExpression(bodyProp.value)\n        ) {\n          // Find the outermost enclosing statement and export name\n          // Iterate from closest parent (end of array) to farthest (start of array)\n          let statementRange: { start: number; end: number } | undefined;\n          let exportName: string | undefined;\n          for (let i = parents.length - 1; i >= 0; i--) {\n            const parent = assertDefined(parents[i], `parent at index ${i} missing`);\n            if (parent.type === \"VariableDeclarator\") {\n              const declarator = parent as unknown as {\n                id?: { type?: string; name?: string };\n              };\n              if (declarator.id?.type === \"Identifier\") {\n                exportName = declarator.id.name;\n              }\n            }\n            // Keep track of the outermost statement (ExportNamedDeclaration > VariableDeclaration)\n            if (parent.type === \"ExportNamedDeclaration\" || parent.type === \"VariableDeclaration\") {\n              statementRange = {\n                start: parent.start as number,\n                end: parent.end as number,\n              };\n              // Don't break - continue to find ExportNamedDeclaration if it exists\n            }\n          }\n\n          jobs.push({\n            name: nameProp.value.value,\n            exportName,\n            nameRange: { start: nameProp.start, end: nameProp.end },\n            bodyValueRange: {\n              start: bodyProp.value.start,\n              end: bodyProp.value.end,\n            },\n            statementRange,\n          });\n        }\n      }\n    }\n\n    const newParents = [...parents, node];\n    for (const key of Object.keys(node)) {\n      const child = node[key] as unknown;\n      if (Array.isArray(child)) {\n        child.forEach((c: unknown) => walk(c as ASTNode | null, newParents));\n      } else if (child && typeof child === \"object\") {\n        walk(child as ASTNode, newParents);\n      }\n    }\n  }\n\n  walk(program as unknown as ASTNode);\n  return jobs;\n}\n\n/**\n * Build a map from export name to job name from detected jobs\n * @param jobs - Detected job locations\n * @returns Map from export name to job name\n */\nexport function buildJobNameMap(jobs: JobLocation[]): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const job of jobs) {\n    if (job.exportName) {\n      map.set(job.exportName, job.name);\n    }\n  }\n  return map;\n}\n\n/**\n * Detect all .trigger() calls in the source code\n * Returns information about each trigger call for transformation\n * @param program - Parsed TypeScript program\n * @param sourceText - Source code text\n * @returns Detected trigger calls\n */\nexport function detectTriggerCalls(program: Program, sourceText: string): TriggerCall[] {\n  const calls: TriggerCall[] = [];\n\n  function walk(node: ASTNode | null | undefined): void {\n    if (!node || typeof node !== \"object\") return;\n\n    // Detect pattern: identifier.trigger(args)\n    if (node.type === \"CallExpression\") {\n      const callExpr = node as unknown as CallExpression;\n      const callee = callExpr.callee;\n\n      if (callee.type === \"MemberExpression\") {\n        const memberExpr = callee as unknown as StaticMemberExpression;\n        if (\n          // callee may be a ComputedMemberExpression at runtime\n          // oxlint-disable-next-line typescript/no-unnecessary-condition\n          !memberExpr.computed &&\n          memberExpr.object.type === \"Identifier\" &&\n          memberExpr.property.name === \"trigger\"\n        ) {\n          const identifierName = (memberExpr.object as IdentifierReference).name;\n\n          let argsText = \"\";\n          if (callExpr.arguments.length > 0) {\n            const firstArg = callExpr.arguments[0];\n            // callee may be a ComputedMemberExpression at runtime\n            // oxlint-disable-next-line typescript/no-unnecessary-condition\n            if (firstArg && \"start\" in firstArg && \"end\" in firstArg) {\n              argsText = sourceText.slice(firstArg.start as number, firstArg.end as number);\n            }\n          }\n\n          calls.push({\n            identifierName,\n            callRange: { start: callExpr.start, end: callExpr.end },\n            argsText,\n          });\n        }\n      }\n    }\n\n    for (const key of Object.keys(node)) {\n      const child = node[key] as unknown;\n      if (Array.isArray(child)) {\n        child.forEach((c: unknown) => walk(c as ASTNode | null));\n      } else if (child && typeof child === \"object\") {\n        walk(child as ASTNode);\n      }\n    }\n  }\n\n  walk(program as unknown as ASTNode);\n  return calls;\n}\n","import { assertDefined } from \"#/utils/assert\";\nimport { type ASTNode, isStringLiteral, findProperty } from \"./ast-utils\";\nimport { collectSdkBindings, isSdkFunctionCall } from \"./sdk-binding-collector\";\nimport type {\n  Program,\n  CallExpression,\n  ObjectExpression,\n  ImportDeclaration,\n  ImportDefaultSpecifier,\n} from \"@oxc-project/types\";\n\nexport interface WorkflowLocation {\n  name: string;\n  exportName?: string;\n  isDefaultExport?: boolean;\n}\n\n/**\n * Find all workflows by detecting createWorkflow calls from `@tailor-platform/sdk`\n * @param program - Parsed TypeScript program\n * @param _sourceText - Source code text (currently unused)\n * @returns Detected workflows\n */\nexport function findAllWorkflows(program: Program, _sourceText: string): WorkflowLocation[] {\n  const workflows: WorkflowLocation[] = [];\n  const bindings = collectSdkBindings(program, \"createWorkflow\");\n\n  function walk(node: ASTNode | null | undefined, parents: ASTNode[] = []): void {\n    if (!node || typeof node !== \"object\") return;\n\n    // Detect createWorkflow(...) calls\n    if (isSdkFunctionCall(node, bindings, \"createWorkflow\")) {\n      const callExpr = node as unknown as CallExpression;\n      const args = callExpr.arguments;\n      const firstArg = args[0];\n      if (args.length >= 1 && firstArg?.type === \"ObjectExpression\") {\n        const configObj = assertDefined(\n          firstArg,\n          \"createWorkflow first argument missing\",\n        ) as ObjectExpression;\n        const nameProp = findProperty(configObj.properties, \"name\");\n\n        if (nameProp && isStringLiteral(nameProp.value)) {\n          // Find export name from parent declarations\n          let exportName: string | undefined;\n          let isDefaultExport = false;\n          for (let i = parents.length - 1; i >= 0; i--) {\n            const parent = assertDefined(parents[i], `parent at index ${i} missing`);\n            if (parent.type === \"VariableDeclarator\") {\n              const declarator = parent as unknown as {\n                id?: { type?: string; name?: string };\n              };\n              if (declarator.id?.type === \"Identifier\") {\n                exportName = declarator.id.name;\n                break;\n              }\n            }\n            // Check for export default createWorkflow(...)\n            if (parent.type === \"ExportDefaultDeclaration\") {\n              isDefaultExport = true;\n            }\n          }\n\n          workflows.push({\n            name: nameProp.value.value,\n            exportName,\n            isDefaultExport,\n          });\n        }\n      }\n    }\n\n    const newParents = [...parents, node];\n    for (const key of Object.keys(node)) {\n      const child = node[key] as unknown;\n      if (Array.isArray(child)) {\n        child.forEach((c: unknown) => walk(c as ASTNode | null, newParents));\n      } else if (child && typeof child === \"object\") {\n        walk(child as ASTNode, newParents);\n      }\n    }\n  }\n\n  walk(program as unknown as ASTNode);\n  return workflows;\n}\n\n/**\n * Build a map from export name to workflow name from detected workflows\n * @param workflows - Detected workflows\n * @returns Map from export name to workflow name\n */\nexport function buildWorkflowNameMap(workflows: WorkflowLocation[]): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const workflow of workflows) {\n    if (workflow.exportName) {\n      map.set(workflow.exportName, workflow.name);\n    }\n  }\n  return map;\n}\n\n/**\n * Detect default imports in a source file and return a map from local name to import source\n * @param program - Parsed TypeScript program\n * @returns Map from local name to import source\n */\nexport function detectDefaultImports(program: Program): Map<string, string> {\n  const imports = new Map<string, string>();\n\n  function walk(node: ASTNode | null | undefined): void {\n    if (!node || typeof node !== \"object\") return;\n\n    const nodeType = node.type as string | undefined;\n\n    if (nodeType === \"ImportDeclaration\") {\n      const importDecl = node as unknown as ImportDeclaration;\n      const source = importDecl.source.value;\n\n      if (typeof source === \"string\") {\n        for (const specifier of importDecl.specifiers) {\n          // import foo from \"module\"\n          if (specifier.type === \"ImportDefaultSpecifier\") {\n            const spec = specifier as ImportDefaultSpecifier;\n            if (spec.local.name) {\n              imports.set(spec.local.name, source);\n            }\n          }\n        }\n      }\n    }\n\n    for (const key of Object.keys(node)) {\n      const child = node[key] as unknown;\n      if (Array.isArray(child)) {\n        child.forEach((c: unknown) => walk(c as ASTNode | null));\n      } else if (child && typeof child === \"object\") {\n        walk(child as ASTNode);\n      }\n    }\n  }\n\n  walk(program as unknown as ASTNode);\n  return imports;\n}\n","import { parseSync } from \"oxc-parser\";\nimport {\n  type ASTNode,\n  type Replacement,\n  applyReplacements,\n  findStatementEnd,\n  resolvePath,\n} from \"./ast-utils\";\nimport { detectDefaultImports } from \"./workflow-detector\";\nimport type {\n  Program,\n  CallExpression,\n  ObjectExpression,\n  ObjectProperty,\n  StaticMemberExpression,\n  IdentifierReference,\n  ImportDeclaration,\n  ImportDefaultSpecifier,\n} from \"@oxc-project/types\";\n\ninterface AuthInvokerInfo {\n  isShorthand: boolean;\n  valueText: string;\n}\n\ninterface ExtendedTriggerCall {\n  kind: \"job\" | \"workflow\";\n  identifierName: string;\n  callRange: { start: number; end: number };\n  argsText: string;\n  // For workflow triggers, extracted authInvoker info from config\n  authInvoker?: AuthInvokerInfo;\n}\n\n/**\n * Name of the injected runtime normalizer helper. Chosen to be unique enough\n * to avoid collisions with user code.\n */\nconst NORMALIZER_IDENTIFIER = \"__tailor_normalizeAuthInvoker\";\n\n/**\n * Build the source text of the injected normalizer helper.\n *\n * Accepts either a plain string (machine user name) or the object form\n * `{ namespace, machineUserName }`, and always returns the object form.\n * The auth namespace is baked in at bundle time.\n * @param authNamespace - Auth service namespace to embed\n * @returns Source line defining the helper\n */\nfunction buildNormalizerHelperSource(authNamespace: string): string {\n  return `const ${NORMALIZER_IDENTIFIER} = (v) => typeof v === \"string\" ? { namespace: ${JSON.stringify(authNamespace)}, machineUserName: v } : v;\\n`;\n}\n\n/**\n * Extract authInvoker info from a config object expression\n * Returns the authInvoker value text and whether it's a shorthand property\n * @param configArg - Config argument node\n * @param sourceText - Source code text\n * @returns Extracted authInvoker info, if any\n */\nfunction extractAuthInvokerInfo(\n  configArg: unknown,\n  sourceText: string,\n): AuthInvokerInfo | undefined {\n  if (!configArg || typeof configArg !== \"object\") return undefined;\n\n  const arg = configArg as { type?: string };\n  if (arg.type !== \"ObjectExpression\") return undefined;\n\n  const objExpr = configArg as ObjectExpression;\n\n  // Find authInvoker property\n  for (const prop of objExpr.properties) {\n    if (prop.type !== \"Property\") continue;\n\n    const objProp = prop as ObjectProperty;\n    const keyName =\n      objProp.key.type === \"Identifier\"\n        ? objProp.key.name\n        : objProp.key.type === \"Literal\"\n          ? (objProp.key as { value?: string }).value\n          : null;\n\n    if (keyName === \"authInvoker\") {\n      if (objProp.shorthand) {\n        return { isShorthand: true, valueText: \"authInvoker\" };\n      }\n      // Extract value text directly from source\n      const valueText = sourceText.slice(objProp.value.start, objProp.value.end);\n      return { isShorthand: false, valueText };\n    }\n  }\n\n  return undefined;\n}\n\n/**\n * Check if an AST binding pattern (parameter, catch clause, etc.) contains an Identifier with the given name.\n * @param node - AST node to inspect\n * @param name - Identifier name to look for\n * @returns True if the binding pattern contains the name\n */\nfunction containsBindingName(node: ASTNode | null | undefined, name: string): boolean {\n  if (!node || typeof node !== \"object\") return false;\n  if (\n    (node as { type?: string }).type === \"Identifier\" &&\n    (node as { name?: string }).name === name\n  )\n    return true;\n  for (const key of Object.keys(node)) {\n    const child = node[key] as unknown;\n    if (Array.isArray(child)) {\n      if (child.some((c) => containsBindingName(c as ASTNode, name))) return true;\n    } else if (child && typeof child === \"object\") {\n      if (containsBindingName(child as ASTNode, name)) return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Build a map of reference counts for multiple identifiers in a single AST pass.\n * Scope-aware: references inside functions or catch clauses that shadow the name\n * via parameters are excluded, so only references to the original import binding\n * are counted.\n * Excludes import declarations and property names in non-computed member expressions.\n * @param program - The parsed AST program\n * @param names - Set of identifier names to count\n * @returns Map from identifier name to reference count\n */\nfunction buildReferenceCountMap(program: Program, names: Set<string>): Map<string, number> {\n  if (names.size === 0) return new Map();\n\n  const counts = new Map<string, number>();\n  const shadowDepth = new Map<string, number>();\n  for (const name of names) {\n    counts.set(name, 0);\n    shadowDepth.set(name, 0);\n  }\n\n  function walk(node: ASTNode | null | undefined, parentNode?: ASTNode, parentKey?: string): void {\n    if (!node || typeof node !== \"object\") return;\n\n    const nodeType = (node as { type?: string }).type;\n\n    if (nodeType === \"ImportDeclaration\") return;\n\n    // Track scope shadowing from function/catch parameters\n    const shadowedHere: string[] = [];\n    if (\n      nodeType === \"FunctionDeclaration\" ||\n      nodeType === \"FunctionExpression\" ||\n      nodeType === \"ArrowFunctionExpression\"\n    ) {\n      const params = (node as { params?: unknown[] }).params;\n      if (params) {\n        for (const name of names) {\n          if (params.some((p) => containsBindingName(p as ASTNode, name))) {\n            shadowDepth.set(name, (shadowDepth.get(name) ?? 0) + 1);\n            shadowedHere.push(name);\n          }\n        }\n      }\n    }\n    if (nodeType === \"CatchClause\") {\n      const param = (node as { param?: unknown }).param;\n      if (param) {\n        for (const name of names) {\n          if (containsBindingName(param as ASTNode, name)) {\n            shadowDepth.set(name, (shadowDepth.get(name) ?? 0) + 1);\n            shadowedHere.push(name);\n          }\n        }\n      }\n    }\n\n    if (nodeType === \"Identifier\") {\n      const identName = (node as { name?: string }).name;\n      if (identName && names.has(identName) && (shadowDepth.get(identName) ?? 0) === 0) {\n        const isMemberProperty =\n          parentNode &&\n          (parentNode as { type?: string }).type === \"MemberExpression\" &&\n          parentKey === \"property\" &&\n          !(parentNode as { computed?: boolean }).computed;\n        const isObjectPropertyKey =\n          parentNode &&\n          (parentNode as { type?: string }).type === \"Property\" &&\n          parentKey === \"key\" &&\n          !(parentNode as { shorthand?: boolean }).shorthand &&\n          !(parentNode as { computed?: boolean }).computed;\n\n        if (!isMemberProperty && !isObjectPropertyKey) {\n          counts.set(identName, (counts.get(identName) ?? 0) + 1);\n        }\n      }\n    }\n\n    for (const key of Object.keys(node)) {\n      const child = node[key] as unknown;\n      if (Array.isArray(child)) {\n        child.forEach((c: unknown) => walk(c as ASTNode | null, node, key));\n      } else if (child && typeof child === \"object\") {\n        walk(child as ASTNode, node, key);\n      }\n    }\n\n    for (const name of shadowedHere) {\n      shadowDepth.set(name, (shadowDepth.get(name) ?? 0) - 1);\n    }\n  }\n\n  walk(program as unknown as ASTNode);\n  return counts;\n}\n\ninterface ImportRemovalRange {\n  start: number;\n  end: number;\n  /** True when the entire import declaration should be removed (including trailing newline). */\n  isFullDeclaration: boolean;\n}\n\n/**\n * Find the text range to remove for a dead default import.\n *\n * - Default-only import (`import wf from \"...\"`): returns the full declaration range.\n * - Mixed import (`import wf, { helper } from \"...\"`): returns the range covering\n *   the default specifier and trailing comma/whitespace so the result becomes\n *   `import { helper } from \"...\"`.\n * @param program - The parsed AST program\n * @param localName - The local name of the default import\n * @param source - The source code text (used to locate the `{` in mixed imports)\n * @returns Range to remove, or null if the import was not found\n */\nfunction findDefaultImportRemovalRange(\n  program: Program,\n  localName: string,\n  source: string,\n): ImportRemovalRange | null {\n  for (const statement of program.body) {\n    if (statement.type !== \"ImportDeclaration\") continue;\n\n    const importDecl = statement as unknown as ImportDeclaration;\n    const specifiers = importDecl.specifiers;\n\n    for (const spec of specifiers) {\n      if (spec.type !== \"ImportDefaultSpecifier\") continue;\n\n      const defaultSpec = spec as ImportDefaultSpecifier;\n      if (defaultSpec.local.name !== localName) continue;\n\n      if (specifiers.length === 1) {\n        return { start: importDecl.start, end: importDecl.end, isFullDeclaration: true };\n      }\n\n      // Mixed import: remove \"wf, \" up to the \"{\" so the result is \"import { ... } from ...\"\n      const braceIndex = source.indexOf(\"{\", defaultSpec.end);\n      if (braceIndex !== -1) {\n        return { start: defaultSpec.start, end: braceIndex, isFullDeclaration: false };\n      }\n      return null;\n    }\n  }\n\n  return null;\n}\n\n/**\n * Detect .trigger() calls for known workflows and jobs\n * Only detects calls where the identifier is in workflowNames or jobNames\n * @param program - The parsed AST program\n * @param sourceText - The source code text\n * @param workflowNames - Set of known workflow identifier names\n * @param jobNames - Set of known job identifier names\n * @returns Detected trigger call metadata\n */\nfunction detectExtendedTriggerCalls(\n  program: Program,\n  sourceText: string,\n  workflowNames: Set<string>,\n  jobNames: Set<string>,\n): ExtendedTriggerCall[] {\n  const calls: ExtendedTriggerCall[] = [];\n\n  function walk(node: ASTNode | null | undefined): void {\n    if (!node || typeof node !== \"object\") return;\n\n    // Detect pattern: identifier.trigger(args) or identifier.trigger(args, config)\n    if (node.type === \"CallExpression\") {\n      const callExpr = node as unknown as CallExpression;\n      const callee = callExpr.callee;\n\n      if (callee.type === \"MemberExpression\") {\n        const memberExpr = callee as unknown as StaticMemberExpression;\n\n        // callee may be a ComputedMemberExpression at runtime\n        // oxlint-disable typescript/no-unnecessary-condition\n        const identifierName =\n          !memberExpr.computed && memberExpr.object.type === \"Identifier\"\n            ? (memberExpr.object as IdentifierReference).name\n            : null;\n        const propertyName = !memberExpr.computed ? memberExpr.property.name : null;\n        // oxlint-enable typescript/no-unnecessary-condition\n\n        if (identifierName && propertyName === \"trigger\") {\n          const isWorkflow = workflowNames.has(identifierName);\n          const isJob = jobNames.has(identifierName);\n          if (isWorkflow || isJob) {\n            const argCount = callExpr.arguments.length;\n\n            let argsText = \"\";\n            if (argCount > 0) {\n              const firstArg = callExpr.arguments[0];\n              // callee may be a ComputedMemberExpression at runtime\n              // oxlint-disable-next-line typescript/no-unnecessary-condition\n              if (firstArg && \"start\" in firstArg && \"end\" in firstArg) {\n                argsText = sourceText.slice(firstArg.start as number, firstArg.end as number);\n              }\n            }\n\n            if (isWorkflow && argCount >= 2) {\n              const secondArg = callExpr.arguments[1];\n              const authInvoker = extractAuthInvokerInfo(secondArg, sourceText);\n              if (authInvoker) {\n                calls.push({\n                  kind: \"workflow\",\n                  identifierName,\n                  callRange: { start: callExpr.start, end: callExpr.end },\n                  argsText,\n                  authInvoker,\n                });\n              }\n            } else if (isJob) {\n              calls.push({\n                kind: \"job\",\n                identifierName,\n                callRange: { start: callExpr.start, end: callExpr.end },\n                argsText,\n              });\n            }\n          }\n        }\n      }\n    }\n\n    for (const key of Object.keys(node)) {\n      const child = node[key] as unknown;\n      if (Array.isArray(child)) {\n        child.forEach((c: unknown) => walk(c as ASTNode | null));\n      } else if (child && typeof child === \"object\") {\n        walk(child as ASTNode);\n      }\n    }\n  }\n\n  walk(program as unknown as ASTNode);\n  return calls;\n}\n\n/**\n * Transform trigger calls for resolver/executor/workflow functions\n * Handles job.trigger() and workflow.trigger() calls\n * @param source - The source code to transform\n * @param workflowNameMap - Map from variable name to workflow name\n * @param jobNameMap - Map from variable name to job name\n * @param workflowFileMap - Map from file path (without extension) to workflow name for default exports\n * @param currentFilePath - Path of the current file being transformed (for resolving relative imports)\n * @param authNamespace - Auth service namespace used to expand string-literal `authInvoker` to object form\n * @returns Transformed source code with trigger calls rewritten\n */\nexport function transformFunctionTriggers(\n  source: string,\n  workflowNameMap: Map<string, string>,\n  jobNameMap: Map<string, string>,\n  workflowFileMap?: Map<string, string>,\n  currentFilePath?: string,\n  authNamespace?: string,\n): string {\n  const { program } = parseSync(\"input.ts\", source);\n\n  // Build a map from local identifier name to workflow name\n  // This includes both named exports (from workflowNameMap) and default imports (resolved via workflowFileMap)\n  const localWorkflowNameMap = new Map(workflowNameMap);\n\n  // Track which default imports resolved to workflows (candidates for dead import removal)\n  const workflowDefaultImportNames = new Set<string>();\n\n  if (workflowFileMap && currentFilePath) {\n    // Detect default imports and resolve them to workflow names\n    const defaultImports = detectDefaultImports(program);\n    const currentDir = currentFilePath.replace(/[/\\\\][^/\\\\]+$/, \"\");\n\n    for (const [localName, importSource] of defaultImports) {\n      // Skip non-relative imports\n      if (!importSource.startsWith(\".\")) continue;\n\n      // Resolve the import path relative to the current file. Strip a trailing\n      // extension (e.g. `./simple.mjs` from a `.mts` source) so it can match\n      // workflowFileMap keys, which are stored without extensions.\n      const resolvedPath = resolvePath(currentDir, importSource).replace(\n        /\\.(ts|mts|cts|js|mjs|cjs)$/,\n        \"\",\n      );\n      const workflowName = workflowFileMap.get(resolvedPath);\n      if (workflowName) {\n        localWorkflowNameMap.set(localName, workflowName);\n        workflowDefaultImportNames.add(localName);\n      }\n    }\n  }\n\n  // Build sets of known workflow and job identifier names for filtering\n  const workflowNames = new Set(localWorkflowNameMap.keys());\n  const jobNames = new Set(jobNameMap.keys());\n\n  // Detect trigger calls only for known workflows and jobs\n  const triggerCalls = detectExtendedTriggerCalls(program, source, workflowNames, jobNames);\n\n  const replacements: Replacement[] = [];\n  // Whether any workflow trigger authInvoker was wrapped with the runtime\n  // normalizer. Used to decide whether to inject the helper at the top.\n  let needsNormalizerHelper = false;\n\n  // Track how many trigger calls were transformed per identifier (for dead import detection)\n  const transformedCallsPerIdentifier = new Map<string, number>();\n\n  for (const call of triggerCalls) {\n    if (call.kind === \"workflow\" && call.authInvoker) {\n      // Workflow trigger - get workflow name from map\n      const workflowName = localWorkflowNameMap.get(call.identifierName);\n      if (workflowName) {\n        // Resolve the source expression for authInvoker.\n        const rawExpr = call.authInvoker.isShorthand ? \"authInvoker\" : call.authInvoker.valueText;\n        // Wrap with the runtime normalizer so any form (string literal,\n        // variable reference, function call, or `{ namespace, machineUserName }`\n        // object) becomes the object form the platform RPC expects. The\n        // normalizer is injected once at the top of the file.\n        // When no auth service is configured we can't expand a string, so\n        // we pass through unchanged (platform will reject a string with a\n        // clear error).\n        let authInvokerExpr: string;\n        if (authNamespace) {\n          authInvokerExpr = `${NORMALIZER_IDENTIFIER}(${rawExpr})`;\n          needsNormalizerHelper = true;\n        } else {\n          authInvokerExpr = rawExpr;\n        }\n        // Transform to tailor.workflow.triggerWorkflow\n        const transformedCall = `tailor.workflow.triggerWorkflow(\"${workflowName}\", ${call.argsText || \"undefined\"}, { authInvoker: ${authInvokerExpr} })`;\n        replacements.push({\n          start: call.callRange.start,\n          end: call.callRange.end,\n          text: transformedCall,\n        });\n        transformedCallsPerIdentifier.set(\n          call.identifierName,\n          (transformedCallsPerIdentifier.get(call.identifierName) ?? 0) + 1,\n        );\n      }\n    } else if (call.kind === \"job\") {\n      const jobName = jobNameMap.get(call.identifierName);\n      if (jobName) {\n        const transformedCall = `(async () => tailor.workflow.triggerJobFunction(\"${jobName}\", ${call.argsText || \"undefined\"}))()`;\n\n        replacements.push({\n          start: call.callRange.start,\n          end: call.callRange.end,\n          text: transformedCall,\n        });\n        transformedCallsPerIdentifier.set(\n          call.identifierName,\n          (transformedCallsPerIdentifier.get(call.identifierName) ?? 0) + 1,\n        );\n      }\n    }\n  }\n\n  // Remove default import declarations that became dead after trigger transformation.\n  // A default import is dead when it has no remaining references, either because\n  // it was already unused or because all references to its local identifier were\n  // .trigger() calls that have been rewritten above.\n  // Single AST pass for all candidate names; scope-aware to ignore shadowed references.\n  const refCounts = buildReferenceCountMap(program, workflowDefaultImportNames);\n\n  for (const localName of workflowDefaultImportNames) {\n    const transformedCount = transformedCallsPerIdentifier.get(localName) ?? 0;\n    const refCount = refCounts.get(localName) ?? 0;\n\n    if (refCount === 0 || transformedCount >= refCount) {\n      const removal = findDefaultImportRemovalRange(program, localName, source);\n      if (removal) {\n        replacements.push({\n          start: removal.start,\n          end: removal.isFullDeclaration ? findStatementEnd(source, removal.end) : removal.end,\n          text: \"\",\n        });\n      }\n    }\n  }\n\n  const transformed = applyReplacements(source, replacements);\n\n  // Inject the normalizer helper at the top of the file if we referenced it.\n  // Each module gets its own copy; rolldown keeps module scopes separate so\n  // there is no cross-module naming conflict.\n  if (needsNormalizerHelper && authNamespace) {\n    return buildNormalizerHelperSource(authNamespace) + transformed;\n  }\n\n  return transformed;\n}\n","import * as fs from \"node:fs\";\nimport { parseSync } from \"oxc-parser\";\nimport * as path from \"pathe\";\nimport { loadFilesWithIgnores, type FileLoadConfig } from \"#/cli/services/file-loader\";\nimport { findAllJobs, buildJobNameMap } from \"#/cli/services/workflow/job-detector\";\nimport { transformFunctionTriggers } from \"#/cli/services/workflow/trigger-transformer\";\nimport { findAllWorkflows, buildWorkflowNameMap } from \"#/cli/services/workflow/workflow-detector\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { Plugin } from \"rolldown\";\n\n/**\n * Context for trigger transformation\n * Maps variable names to workflow/job names\n */\nexport interface TriggerContext {\n  workflowNameMap: Map<string, string>;\n  jobNameMap: Map<string, string>;\n  /** Maps file path (without extension) to workflow name for default exports */\n  workflowFileMap: Map<string, string>;\n  /**\n   * Auth service namespace used to expand a string-literal `authInvoker`\n   * (e.g. `\"kiosk\"`) to the `{ namespace, machineUserName }` form expected by\n   * the runtime. Undefined when no Auth service is configured.\n   */\n  authNamespace?: string;\n}\n\n/**\n * Normalize a file path by removing extension and resolving to absolute path\n * @param filePath - File path to normalize\n * @returns Normalized absolute path without extension\n */\nexport function normalizeFilePath(filePath: string): string {\n  const absolutePath = path.resolve(filePath);\n  const ext = path.extname(absolutePath);\n  return absolutePath.slice(0, -ext.length);\n}\n\n/**\n * Build trigger context from workflow configuration\n * Scans workflow files to collect workflow and job mappings\n * @param workflowConfig - Workflow file loading configuration\n * @param authNamespace - Auth service namespace (optional, used for string-literal authInvoker expansion)\n * @returns Trigger context built from workflow sources\n */\nexport async function buildTriggerContext(\n  workflowConfig: FileLoadConfig | undefined,\n  authNamespace?: string,\n): Promise<TriggerContext> {\n  const workflowNameMap = new Map<string, string>();\n  const jobNameMap = new Map<string, string>();\n  const workflowFileMap = new Map<string, string>();\n\n  if (!workflowConfig) {\n    return {\n      workflowNameMap,\n      jobNameMap,\n      workflowFileMap,\n      authNamespace,\n    };\n  }\n\n  const workflowFiles = loadFilesWithIgnores(workflowConfig);\n\n  for (const file of workflowFiles) {\n    try {\n      const source = await fs.promises.readFile(file, \"utf-8\");\n      const { program } = parseSync(\"input.ts\", source);\n\n      // Detect workflows\n      const workflows = findAllWorkflows(program, source);\n      const workflowMap = buildWorkflowNameMap(workflows);\n      for (const [exportName, workflowName] of workflowMap) {\n        workflowNameMap.set(exportName, workflowName);\n      }\n\n      // Also track default exported workflows by file path\n      for (const workflow of workflows) {\n        if (workflow.isDefaultExport) {\n          const normalizedPath = normalizeFilePath(file);\n          workflowFileMap.set(normalizedPath, workflow.name);\n        }\n      }\n\n      // Detect jobs\n      const jobs = findAllJobs(program, source);\n      const jobMap = buildJobNameMap(jobs);\n      for (const [exportName, jobName] of jobMap) {\n        jobNameMap.set(exportName, jobName);\n      }\n    } catch (error) {\n      const errorMessage = error instanceof Error ? error.message : String(error);\n      logger.warn(`Failed to process workflow file ${file}: ${errorMessage}`, {\n        mode: \"stream\",\n      });\n      continue;\n    }\n  }\n\n  return {\n    workflowNameMap,\n    jobNameMap,\n    workflowFileMap,\n    authNamespace,\n  };\n}\n\nfunction sortedMapToJson(m: Map<string, string>): string {\n  return JSON.stringify([...m.entries()].toSorted(([a], [b]) => a.localeCompare(b)));\n}\n\n/**\n * Serialize trigger context to a deterministic string for cache hashing.\n * Returns an empty string if no context is provided.\n * @param ctx - Trigger context to serialize\n * @returns Deterministic string representation\n */\nexport function serializeTriggerContext(ctx: TriggerContext | undefined): string {\n  if (!ctx) return \"\";\n  return (\n    sortedMapToJson(ctx.workflowNameMap) +\n    sortedMapToJson(ctx.jobNameMap) +\n    sortedMapToJson(ctx.workflowFileMap) +\n    (ctx.authNamespace ?? \"\")\n  );\n}\n\n/**\n * Create a rolldown plugin for transforming trigger calls\n * Returns undefined if no trigger context is provided\n * @param triggerContext - Trigger context to use for transformations\n * @returns Rolldown plugin or undefined when no context\n */\nexport function createTriggerTransformPlugin(\n  triggerContext: TriggerContext | undefined,\n): Plugin | undefined {\n  if (!triggerContext) {\n    return undefined;\n  }\n\n  return {\n    name: \"trigger-transform\",\n    transform: {\n      filter: {\n        id: {\n          include: [/\\.(ts|mts|cts|js|mjs|cjs)$/],\n        },\n      },\n      handler(code, id) {\n        // Only transform source files that contain trigger calls\n        if (!code.includes(\".trigger(\")) {\n          return null;\n        }\n        const transformed = transformFunctionTriggers(\n          code,\n          triggerContext.workflowNameMap,\n          triggerContext.jobNameMap,\n          triggerContext.workflowFileMap,\n          id,\n          triggerContext.authNamespace,\n        );\n        return { code: transformed };\n      },\n    },\n  };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { resolveTSConfig } from \"pkg-types\";\nimport * as rolldown from \"rolldown\";\nimport { computeBundlerContextHash, withCache, type BundleCache } from \"#/cli/cache/bundle-cache\";\nimport { removeStaleEntryFiles } from \"#/cli/services/stale-cleanup\";\nimport { createLogLevelTreeshakeOptions } from \"#/cli/shared/bundle-log-level\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { composeFunctionTreeshakeOptions } from \"#/cli/shared/function-treeshake\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport {\n  createTriggerTransformPlugin,\n  serializeTriggerContext,\n  type TriggerContext,\n} from \"#/cli/shared/trigger-context\";\nimport ml from \"#/utils/multiline\";\nimport type { LogLevel } from \"#/configure/config/types\";\n\n/**\n * Options for bundling auth hooks\n */\nexport interface BundleAuthHooksOptions {\n  /** Absolute path to the config file that exports the auth definition */\n  configPath: string;\n  /** Auth namespace name */\n  authName: string;\n  /** Dot-path expression to reach the handler from the config's default export */\n  handlerAccessPath: string;\n  /** Environment variables to inject into the hook args */\n  env?: Record<string, string | number | boolean>;\n  /** Trigger context for workflow/job transformations */\n  triggerContext?: TriggerContext;\n  /** Optional bundle cache for skipping unchanged builds */\n  cache?: BundleCache;\n  /** Whether to enable inline sourcemaps */\n  inlineSourcemap?: boolean;\n  /** Controls which console calls are kept in bundled code */\n  bundleLogLevel?: LogLevel;\n}\n\n/**\n * Bundle a single auth hook handler.\n *\n * Follows the same pattern as the executor bundler:\n * 1. Generate an entry file that re-exports the handler as `main`\n * 2. Bundle with rolldown + tree-shaking\n * @param options - Bundle options\n * @returns Map of function name to bundled code\n */\nexport async function bundleAuthHooks(\n  options: BundleAuthHooksOptions,\n): Promise<Map<string, string>> {\n  const {\n    configPath,\n    authName,\n    handlerAccessPath,\n    env = {},\n    triggerContext,\n    cache,\n    inlineSourcemap,\n    bundleLogLevel = \"DEBUG\",\n  } = options;\n\n  logger.newline();\n  logger.log(`Bundling auth hook for ${styles.info(`\"${authName}\"`)}`);\n\n  const outputDir = path.resolve(getDistDir(), \"auth-hooks\");\n  fs.mkdirSync(outputDir, { recursive: true });\n\n  await removeStaleEntryFiles(outputDir);\n\n  let tsconfig: string | undefined;\n  try {\n    tsconfig = await resolveTSConfig();\n  } catch {\n    tsconfig = undefined;\n  }\n\n  const functionName = `auth-hook--${authName}--before-login`;\n  const absoluteConfigPath = path.resolve(configPath);\n\n  const serializedTriggerContext = serializeTriggerContext(triggerContext);\n\n  // Include sorted env variables as a prefix so that env changes invalidate the cache\n  const sortedEnvPrefix = JSON.stringify(\n    Object.fromEntries(Object.entries(env).toSorted(([a], [b]) => a.localeCompare(b))),\n  );\n  const contextHash = computeBundlerContextHash({\n    sourceFile: absoluteConfigPath,\n    serializedTriggerContext,\n    tsconfig,\n    inlineSourcemap,\n    bundleLogLevel,\n    prefix: sortedEnvPrefix,\n  });\n\n  const code = await withCache({\n    cache,\n    kind: \"auth-hook\",\n    name: functionName,\n    sourceFile: absoluteConfigPath,\n    contextHash,\n    async build(cachePlugins) {\n      const entryPath = path.join(outputDir, `${functionName}.entry.js`);\n\n      const entryContent = ml /* js */ `\n        import _config from \"${absoluteConfigPath}\";\n        const __auth_hook_function = _config.${handlerAccessPath};\n        export async function main(args) {\n          const env = ${JSON.stringify(env)};\n          return await __auth_hook_function({ ...args, env });\n        }\n      `;\n      fs.writeFileSync(entryPath, entryContent);\n\n      const triggerPlugin = createTriggerTransformPlugin(triggerContext);\n      const plugins: rolldown.Plugin[] = triggerPlugin ? [triggerPlugin] : [];\n      plugins.push(platformBundleDefinePlugin, ...cachePlugins);\n\n      const result = await rolldown.build({\n        input: entryPath,\n        write: false,\n        output: {\n          format: \"esm\",\n          sourcemap: inlineSourcemap ? \"inline\" : true,\n          minify: inlineSourcemap\n            ? {\n                mangle: {\n                  keepNames: true,\n                },\n              }\n            : true,\n          codeSplitting: false,\n        },\n        tsconfig,\n        plugins,\n        transform: {\n          define: {\n            \"process.env.LOG_LEVEL\": JSON.stringify(bundleLogLevel),\n          },\n        },\n        treeshake: composeFunctionTreeshakeOptions([\n          createLogLevelTreeshakeOptions(bundleLogLevel),\n        ]),\n        logLevel: \"silent\",\n      } as rolldown.BuildOptions);\n\n      return result.output[0].code;\n    },\n  });\n\n  logger.log(`${styles.success(\"Bundled\")} auth hook for ${styles.info(`\"${authName}\"`)}`);\n\n  const bundledCode = new Map<string, string>();\n  bundledCode.set(functionName, code);\n  return bundledCode;\n}\n","const PRECOMPILED_EXPR_KEY = \"__precompiledScriptExpr\";\n\ntype AnyFunction = (...args: never[]) => unknown;\n\n/**\n * Attach a precompiled script expression to a function object.\n * @param fn - Function metadata object.\n * @param expr - Precompiled script expression.\n */\nexport function setPrecompiledScriptExpr(fn: AnyFunction, expr: string) {\n  (fn as unknown as Record<string, unknown>)[PRECOMPILED_EXPR_KEY] = expr;\n}\n\n/**\n * Read a precompiled script expression from a function object.\n * @param fn - Function metadata object.\n * @returns Precompiled script expression if attached.\n */\nexport function getPrecompiledScriptExpr(fn: AnyFunction): string | undefined {\n  const value = (fn as unknown as Record<string, unknown>)[PRECOMPILED_EXPR_KEY];\n  return typeof value === \"string\" ? value : undefined;\n}\n","import { getPrecompiledScriptExpr } from \"./hooks-validate-precompiled-expr\";\nimport type {\n  TailorAnyDBField,\n  DBFieldMetadata,\n  RawRelationConfig,\n} from \"#/configure/services/tailordb/types\";\nimport type { OperatorFieldConfig } from \"#/parser/service/tailordb/types\";\nimport type { TailorDBTypeRaw as TailorDBTypeSchemaOutput } from \"#/types/tailordb.generated\";\n\n// Since there's naming difference between platform and sdk,\n// use this mapping in all scripts to provide variables that match sdk types.\nexport const tailorUserMap = /* js */ `{ id: user.id, type: user.type, workspaceId: user.workspace_id, attributes: user.attribute_map, attributeList: user.attributes }`;\n\n/**\n * Convert a function to a string representation.\n * Handles method shorthand syntax (e.g., `create() { ... }`) by converting it to\n * a function expression (e.g., `function create() { ... }`).\n * @param fn - Function to stringify\n * @returns Stringified function source\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport const stringifyFunction = (fn: Function): string => {\n  const src = fn.toString().trim();\n  // Method shorthand pattern: methodName(...) { ... }\n  // Needs to be converted to: function methodName(...) { ... }\n  if (\n    /^[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/.test(src) &&\n    !src.startsWith(\"function\") &&\n    !src.startsWith(\"(\") &&\n    !src.includes(\"=>\")\n  ) {\n    return `function ${src}`;\n  }\n  return src;\n};\n\n/**\n * Convert a hook function to a script expression.\n * @param fn - Hook function\n * @returns JavaScript expression calling the hook\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nconst convertHookToExpr = (fn: Function): string => {\n  const precompiledExpr = getPrecompiledScriptExpr(fn as (...args: never[]) => unknown);\n  if (precompiledExpr) {\n    return precompiledExpr;\n  }\n  const normalized = stringifyFunction(fn);\n  return `(${normalized})({ value: _value, data: _data, user: ${tailorUserMap} })`;\n};\n\n/**\n * Parse TailorDBField into OperatorFieldConfig.\n * This transforms user-defined functions into script expressions.\n * @param field - TailorDB field definition\n * @returns Parsed operator field configuration\n */\nexport function parseFieldConfig(\n  field: TailorDBTypeSchemaOutput[\"fields\"][string],\n): OperatorFieldConfig {\n  const metadata = field.metadata as DBFieldMetadata;\n  const fieldType = field.type;\n  // Access rawRelation via getter (if available)\n  const rawRelation = (field as unknown as { rawRelation?: RawRelationConfig }).rawRelation;\n\n  const nestedFields = field.fields as Record<string, TailorAnyDBField> | undefined;\n  return {\n    type: fieldType,\n    ...metadata,\n    rawRelation,\n    ...(fieldType === \"nested\" && nestedFields && Object.keys(nestedFields).length > 0\n      ? {\n          fields: Object.entries(nestedFields).reduce(\n            (acc, [key, nestedField]) => {\n              acc[key] = parseFieldConfig(nestedField);\n              return acc;\n            },\n            {} as Record<string, OperatorFieldConfig>,\n          ),\n        }\n      : {}),\n    validate: metadata.validate?.map((v) => {\n      const { fn, message } =\n        typeof v === \"function\"\n          ? { fn: v, message: `failed by \\`${v.toString().trim()}\\`` }\n          : { fn: v[0], message: v[1] };\n\n      return {\n        script: {\n          expr:\n            getPrecompiledScriptExpr(fn) ??\n            `(${fn.toString().trim()})({ value: _value, data: _data, user: ${tailorUserMap} })`,\n        },\n        errorMessage: message,\n      };\n    }),\n    hooks: metadata.hooks\n      ? {\n          create: metadata.hooks.create\n            ? {\n                expr: convertHookToExpr(metadata.hooks.create),\n              }\n            : undefined,\n          update: metadata.hooks.update\n            ? {\n                expr: convertHookToExpr(metadata.hooks.update),\n              }\n            : undefined,\n        }\n      : undefined,\n    serial: metadata.serial\n      ? {\n          start: metadata.serial.start,\n          maxValue: metadata.serial.maxValue,\n          format: \"format\" in metadata.serial ? metadata.serial.format : undefined,\n        }\n      : undefined,\n  };\n}\n","import type {\n  StandardTailorTypePermission,\n  StandardTailorTypeGqlPermission,\n  StandardActionPermission,\n  StandardPermissionCondition,\n  StandardGqlPermissionPolicy,\n  Permissions,\n} from \"#/parser/service/tailordb/types\";\nimport type { RawPermissions } from \"#/types/tailordb.generated\";\n\n// Raw permission types for normalize function parameters\ntype PermissionOperator = \"=\" | \"!=\" | \"in\" | \"not in\" | \"hasAny\" | \"not hasAny\";\n\ntype ObjectOperand =\n  | { user: string }\n  | { record: string }\n  | { oldRecord: string }\n  | { newRecord: string }\n  | { value: unknown };\n\ntype ValueOperand = string | boolean | string[] | boolean[];\n\n// GQL string reference pattern (e.g., \"user.id\", \"user.roles\")\ntype GqlStringRef = `user.${string}`;\n\ntype PermissionOperand = ObjectOperand | ValueOperand | GqlStringRef;\n\ntype PermissionCondition = readonly [PermissionOperand, PermissionOperator, PermissionOperand];\n\nconst operatorMap: Record<PermissionOperator, string> = {\n  \"=\": \"eq\",\n  \"!=\": \"ne\",\n  in: \"in\",\n  \"not in\": \"nin\",\n  hasAny: \"hasAny\",\n  \"not hasAny\": \"nhasAny\",\n};\n\ntype GqlPermissionPolicy = {\n  conditions: readonly PermissionCondition[];\n  actions: \"all\" | readonly GqlPermissionAction[];\n  permit?: boolean;\n  description?: string;\n};\n\ntype GqlPermissionAction = \"read\" | \"create\" | \"update\" | \"delete\" | \"aggregate\" | \"bulkUpsert\";\n\nfunction normalizeOperand(operand: PermissionOperand): PermissionOperand {\n  if (typeof operand === \"object\" && \"user\" in operand) {\n    const mapped = operand.user === \"id\" ? \"_id\" : operand.user;\n    return { user: mapped };\n  }\n  return operand;\n}\n\nfunction normalizeConditions(\n  conditions: readonly PermissionCondition[],\n): StandardPermissionCondition[] {\n  return conditions.map((cond) => {\n    const [left, operator, right] = cond;\n    return [normalizeOperand(left), operatorMap[operator], normalizeOperand(right)];\n  }) as StandardPermissionCondition[];\n}\n\nfunction isObjectFormat(\n  p: unknown,\n): p is { conditions: unknown; permit?: boolean; description?: string } {\n  return typeof p === \"object\" && p !== null && \"conditions\" in p;\n}\n\nfunction isSingleArrayConditionFormat(cond: readonly unknown[]): boolean {\n  return cond.length >= 2 && typeof cond[1] === \"string\"; // Check if middle element is an operator\n}\n\n/**\n * Normalize record-level permissions into a standard structure.\n * @param permission - Tailor type permission\n * @returns Normalized record permissions\n */\nfunction normalizePermission(\n  permission: NonNullable<RawPermissions[\"record\"]>,\n): StandardTailorTypePermission {\n  const keys = Object.keys(permission) as Array<keyof typeof permission>;\n  return keys.reduce((acc, action) => {\n    acc[action] = permission[action].map((p) => normalizeActionPermission(p));\n    return acc;\n    // oxlint-disable-next-line no-explicit-any\n  }, {} as any);\n}\n\n/**\n * Normalize GraphQL permissions into a standard structure.\n * @param permission - Tailor GQL permission\n * @returns Normalized GQL permissions\n */\nexport function normalizeGqlPermission(\n  permission: NonNullable<RawPermissions[\"gql\"]>,\n): StandardTailorTypeGqlPermission {\n  return (permission as readonly GqlPermissionPolicy[]).map((policy) =>\n    normalizeGqlPolicy(policy),\n  ) as StandardTailorTypeGqlPermission;\n}\n\nfunction normalizeGqlPolicy(policy: GqlPermissionPolicy): StandardGqlPermissionPolicy {\n  return {\n    conditions: normalizeConditions(policy.conditions),\n    actions: policy.actions === \"all\" ? [\"all\"] : policy.actions,\n    permit: policy.permit ? \"allow\" : \"deny\",\n    description: policy.description,\n  } as StandardGqlPermissionPolicy;\n}\n\n/**\n * Parse raw permissions into normalized permissions.\n * This is the main entry point for permission parsing in the parser layer.\n * @param rawPermissions - Raw permissions definition\n * @returns Normalized permissions\n */\nexport function parsePermissions(rawPermissions: RawPermissions): Permissions {\n  return {\n    ...(rawPermissions.record && {\n      record: normalizePermission(rawPermissions.record),\n    }),\n    ...(rawPermissions.gql && {\n      gql: normalizeGqlPermission(rawPermissions.gql),\n    }),\n  };\n}\n\n/**\n * Normalize a single action permission into the standard format.\n * @param permission - Raw permission definition\n * @returns Normalized action permission\n */\nexport function normalizeActionPermission(permission: unknown): StandardActionPermission {\n  // object format\n  if (isObjectFormat(permission)) {\n    const conditions = permission.conditions as\n      | PermissionCondition\n      | readonly PermissionCondition[];\n    return {\n      conditions: normalizeConditions(\n        isSingleArrayConditionFormat(conditions)\n          ? [conditions as PermissionCondition]\n          : (conditions as readonly PermissionCondition[]),\n      ),\n      permit: permission.permit ? \"allow\" : \"deny\",\n      description: permission.description,\n    };\n  }\n\n  if (!Array.isArray(permission)) {\n    throw new Error(\"Invalid permission format\");\n  }\n\n  if (isSingleArrayConditionFormat(permission)) {\n    const [op1, operator, op2, permit] = [...permission, true] as [\n      PermissionOperand,\n      string,\n      PermissionOperand,\n      boolean,\n    ];\n    return {\n      conditions: normalizeConditions([[op1, operator, op2] as PermissionCondition]),\n      permit: permit ? \"allow\" : \"deny\",\n    };\n  }\n\n  // Array of conditions format\n  const conditions: PermissionCondition[] = [];\n  const conditionArray = permission as readonly unknown[];\n  let conditionArrayPermit = true;\n\n  for (const item of conditionArray) {\n    if (typeof item === \"boolean\") {\n      conditionArrayPermit = item;\n      continue;\n    }\n    conditions.push(item as PermissionCondition);\n  }\n\n  return {\n    conditions: normalizeConditions(conditions),\n    permit: conditionArrayPermit ? \"allow\" : \"deny\",\n  };\n}\n\n/**\n * Find object-format permission rules that omit `permit`.\n *\n * Object-format rules default to `deny` when `permit` is omitted, whereas the\n * array shorthand defaults to `allow`. Omitting `permit` on an object rule is\n * therefore an easy way to accidentally deny access you meant to grant, so the\n * CLI warns about these locations to nudge authors toward setting `permit`\n * explicitly.\n * @param rawPermissions - Raw permissions definition\n * @returns Dotted locations of offending rules, e.g. `record.read[0]`, `gql[1]`\n */\nexport function findOmittedPermitRules(rawPermissions: RawPermissions): string[] {\n  const locations: string[] = [];\n\n  const record = rawPermissions.record;\n  if (record) {\n    for (const action of Object.keys(record) as Array<keyof typeof record>) {\n      record[action].forEach((rule: unknown, index: number) => {\n        if (isObjectFormat(rule) && rule.permit === undefined) {\n          locations.push(`record.${String(action)}[${index}]`);\n        }\n      });\n    }\n  }\n\n  // GQL policies are always object form, so no isObjectFormat guard is needed.\n  const gql = rawPermissions.gql;\n  if (gql) {\n    (gql as readonly GqlPermissionPolicy[]).forEach((policy, index) => {\n      if (policy.permit === undefined) {\n        locations.push(`gql[${index}]`);\n      }\n    });\n  }\n\n  return locations;\n}\n","import * as inflection from \"inflection\";\nimport type { RawRelationConfig } from \"#/configure/services/tailordb/types\";\nimport type { OperatorFieldConfig } from \"#/parser/service/tailordb/types\";\nimport type { UnionToTuple } from \"type-fest\";\n\nconst relationTypes = {\n  \"1-1\": \"1-1\",\n  oneToOne: \"1-1\",\n  \"n-1\": \"n-1\",\n  manyToOne: \"n-1\",\n  \"N-1\": \"n-1\",\n  keyOnly: \"keyOnly\",\n} as const;\nexport const relationTypesKeys = Object.keys(relationTypes) as UnionToTuple<\n  keyof typeof relationTypes\n>;\n\nexport interface RelationProcessingContext {\n  typeName: string;\n  fieldName: string;\n  allTypeNames: Set<string>;\n}\n\nexport interface ProcessedRelationMetadata {\n  index: boolean;\n  foreignKey: boolean;\n  relationType: string;\n  unique: boolean;\n  foreignKeyType: string;\n  foreignKeyField: string;\n}\n\nexport interface RelationInfo {\n  targetType: string;\n  forwardName: string;\n  backwardName: string;\n  key: string;\n  unique: boolean;\n}\n\nfunction fieldRef(context: RelationProcessingContext): string {\n  return `Field \"${context.fieldName}\" on type \"${context.typeName}\"`;\n}\n\n/**\n * Validate relation configuration.\n * @param rawRelation - Raw relation configuration from TailorDB type definition\n * @param context - Context information for the relation (type name, field name, all type names)\n */\nexport function validateRelationConfig(\n  rawRelation: RawRelationConfig,\n  context: RelationProcessingContext,\n): void {\n  // raw user config may omit the field\n  // oxlint-disable-next-line typescript/no-unnecessary-condition\n  if (!rawRelation.type) {\n    throw new Error(\n      `${fieldRef(context)} has a relation but is missing the required 'type' property. ` +\n        `Valid values: ${relationTypesKeys.join(\", \")}.`,\n    );\n  }\n  if (!(rawRelation.type in relationTypes)) {\n    throw new Error(\n      `${fieldRef(context)} has invalid relation type '${rawRelation.type}'. ` +\n        `Valid values: ${relationTypesKeys.join(\", \")}.`,\n    );\n  }\n\n  // Validate target type exists (for non-self relations)\n  if (rawRelation.toward.type !== \"self\" && !context.allTypeNames.has(rawRelation.toward.type)) {\n    throw new Error(`${fieldRef(context)} references unknown type \"${rawRelation.toward.type}\".`);\n  }\n}\n\n/**\n * Process raw relation config and compute derived metadata values.\n * @param rawRelation - Raw relation configuration\n * @param context - Context information for the relation\n * @param isArrayField - Whether the target field is an array field\n * @returns Computed relation metadata to apply to field config\n */\nexport function processRelationMetadata(\n  rawRelation: RawRelationConfig,\n  context: RelationProcessingContext,\n  isArrayField: boolean = false,\n): ProcessedRelationMetadata {\n  const isUnique = relationTypes[rawRelation.type] === \"1-1\";\n  const key = rawRelation.toward.key ?? \"id\";\n\n  // Resolve target type name (handle \"self\" reference)\n  const targetTypeName =\n    rawRelation.toward.type === \"self\" ? context.typeName : rawRelation.toward.type;\n\n  // Index and unique are not supported on array fields\n  const shouldSetIndex = !isArrayField;\n  const shouldSetUnique = !isArrayField && isUnique;\n\n  return {\n    index: shouldSetIndex,\n    foreignKey: true,\n    relationType: rawRelation.type,\n    unique: shouldSetUnique,\n    foreignKeyType: targetTypeName,\n    foreignKeyField: key,\n  };\n}\n\n/**\n * Build relation info for creating forward/backward relationships.\n * Returns undefined for keyOnly relations.\n * @param rawRelation - Raw relation configuration\n * @param context - Context information for the relation\n * @returns Relation information or undefined for keyOnly relations\n */\nexport function buildRelationInfo(\n  rawRelation: RawRelationConfig,\n  context: RelationProcessingContext,\n): RelationInfo | undefined {\n  // keyOnly relations don't create forward/backward relationships\n  if (rawRelation.type === \"keyOnly\") {\n    return undefined;\n  }\n\n  const isUnique = relationTypes[rawRelation.type] === \"1-1\";\n  const key = rawRelation.toward.key ?? \"id\";\n\n  // Resolve target type name (handle \"self\" reference)\n  const targetTypeName =\n    rawRelation.toward.type === \"self\" ? context.typeName : rawRelation.toward.type;\n\n  // Compute forward name\n  let forwardName = rawRelation.toward.as;\n  if (!forwardName) {\n    if (rawRelation.toward.type === \"self\") {\n      // For self-relations, derive from field name by removing ID suffix\n      forwardName = context.fieldName.replace(/(ID|Id|id)$/u, \"\");\n    } else {\n      // Use inflection to generate default forward name\n      forwardName = inflection.camelize(targetTypeName, true);\n    }\n  }\n\n  return {\n    targetType: targetTypeName,\n    forwardName,\n    backwardName: rawRelation.backward ?? \"\",\n    key,\n    unique: isUnique,\n  };\n}\n\n/**\n * Apply processed relation metadata to field config.\n * @param fieldConfig - Original operator field configuration\n * @param metadata - Processed relation metadata to apply\n * @returns Field config with relation metadata applied\n */\nexport function applyRelationMetadataToFieldConfig(\n  fieldConfig: OperatorFieldConfig,\n  metadata: ProcessedRelationMetadata,\n): OperatorFieldConfig {\n  return {\n    ...fieldConfig,\n    index: metadata.index,\n    foreignKey: metadata.foreignKey,\n    unique: metadata.unique,\n    foreignKeyType: metadata.foreignKeyType,\n    foreignKeyField: metadata.foreignKeyField,\n  };\n}\n","import * as inflection from \"inflection\";\nimport { isPluginGeneratedType } from \"#/parser/service/tailordb/type-source\";\nimport { parseFieldConfig } from \"./field\";\nimport { parsePermissions } from \"./permission\";\nimport {\n  validateRelationConfig,\n  processRelationMetadata,\n  buildRelationInfo,\n  applyRelationMetadataToFieldConfig,\n} from \"./relation\";\nimport type { TailorDBField } from \"#/configure/services/tailordb/types\";\nimport type {\n  TypeSourceInfo,\n  ParsedField,\n  ParsedRelationship,\n  TailorDBType,\n} from \"#/parser/service/tailordb/types\";\nimport type { TailorDBTypeRaw as TailorDBTypeSchemaOutput } from \"#/types/tailordb.generated\";\n\n/**\n * Parse multiple TailorDB types, build relationships, and validate uniqueness.\n * This is the main entry point for parsing TailorDB types.\n * @param rawTypes - Raw TailorDB types keyed by name\n * @param namespace - TailorDB namespace name\n * @param typeSourceInfo - Optional type source information\n * @returns Parsed types\n */\nexport function parseTypes(\n  rawTypes: Record<string, TailorDBTypeSchemaOutput>,\n  namespace: string,\n  typeSourceInfo?: TypeSourceInfo,\n): Record<string, TailorDBType> {\n  const types = createRecord<TailorDBType>();\n  const allTypeNames = new Set(Object.keys(rawTypes));\n\n  for (const [typeName, type] of Object.entries(rawTypes)) {\n    types[typeName] = parseTailorDBType(type, allTypeNames, rawTypes);\n  }\n\n  buildBackwardRelationships(types, namespace, typeSourceInfo);\n  validatePluralFormUniqueness(types, namespace, typeSourceInfo);\n\n  return types;\n}\n\n/**\n * Parse a TailorDBTypeSchemaOutput into a TailorDBType.\n * @param type - TailorDB type to parse\n * @param allTypeNames - Set of all TailorDB type names\n * @param rawTypes - All raw TailorDB types keyed by name\n * @returns Parsed TailorDB type\n */\nfunction parseTailorDBType(\n  type: TailorDBTypeSchemaOutput,\n  allTypeNames: Set<string>,\n  rawTypes: Record<string, TailorDBTypeSchemaOutput>,\n): TailorDBType {\n  const metadata = type.metadata;\n  const pluralForm = metadata.settings?.pluralForm || inflection.pluralize(type.name);\n\n  const fields = createRecord<ParsedField>();\n  const forwardRelationships = createRecord<ParsedRelationship>();\n\n  for (const [fieldName, fieldDef] of Object.entries(type.fields) as [\n    string,\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- TailorDBField requires generic type parameters\n    TailorDBField<any, any>,\n  ][]) {\n    let fieldConfig = parseFieldConfig(fieldDef);\n    const rawRelation = fieldConfig.rawRelation;\n    const context = { typeName: type.name, fieldName, allTypeNames };\n\n    // Process relation if rawRelation is present\n    if (rawRelation) {\n      validateRelationConfig(rawRelation, context);\n\n      // Validate that n-1/manyToOne relations cannot have explicit unique\n      const isNToOne = [\"n-1\", \"manyToOne\", \"N-1\"].includes(rawRelation.type);\n      if (isNToOne && fieldConfig.unique) {\n        throw new Error(\n          `Field \"${fieldName}\" on type \"${type.name}\": cannot set unique on n-1 (manyToOne) relation. ` +\n            `Use 1-1 (oneToOne) relation instead, or remove the unique constraint.`,\n        );\n      }\n\n      const relationMetadata = processRelationMetadata(rawRelation, context, fieldConfig.array);\n      fieldConfig = applyRelationMetadataToFieldConfig(fieldConfig, relationMetadata);\n    }\n\n    // Validate that index/unique are not set on array fields\n    if (fieldConfig.array && fieldConfig.index) {\n      throw new Error(\n        `Field \"${fieldName}\" on type \"${type.name}\": index cannot be set on array fields`,\n      );\n    }\n    if (fieldConfig.array && fieldConfig.unique) {\n      throw new Error(\n        `Field \"${fieldName}\" on type \"${type.name}\": unique cannot be set on array fields`,\n      );\n    }\n\n    const parsedField: ParsedField = { name: fieldName, config: fieldConfig };\n\n    // Build relation info for forward/backward relationships\n    const relationInfo = rawRelation ? buildRelationInfo(rawRelation, context) : undefined;\n    if (relationInfo) {\n      parsedField.relation = { ...relationInfo };\n\n      const targetType = rawTypes[relationInfo.targetType];\n      forwardRelationships[relationInfo.forwardName] = {\n        name: relationInfo.forwardName,\n        targetType: relationInfo.targetType,\n        targetField: fieldName,\n        sourceField: relationInfo.key,\n        isArray: false,\n        description: targetType?.metadata.description || \"\",\n      };\n    }\n\n    fields[fieldName] = parsedField;\n  }\n\n  return {\n    name: type.name,\n    pluralForm,\n    description: metadata.description,\n    fields,\n    forwardRelationships,\n    backwardRelationships: createRecord<ParsedRelationship>(),\n    settings: metadata.settings ?? {},\n    permissions: parsePermissions(metadata.permissions),\n    indexes: metadata.indexes,\n    files: metadata.files,\n  };\n}\n\n/**\n * Build backward relationships between parsed types.\n * Also validates that backward relation names are unique within each type.\n * @param types - Parsed types\n * @param namespace - TailorDB namespace name\n * @param typeSourceInfo - Optional type source information\n */\nfunction buildBackwardRelationships(\n  types: Record<string, TailorDBType>,\n  namespace: string,\n  typeSourceInfo?: TypeSourceInfo,\n): void {\n  // Track backward name sources for duplicate detection\n  // Map: targetTypeName -> backwardName -> array of source info\n  const backwardNameSources: Record<\n    string,\n    Record<string, { sourceType: string; fieldName: string }[]>\n  > = Object.create(null);\n\n  // Initialize tracking for all types\n  for (const typeName of Object.keys(types)) {\n    backwardNameSources[typeName] = Object.create(null) as Record<\n      string,\n      { sourceType: string; fieldName: string }[]\n    >;\n  }\n\n  // Build backward relationships and track sources\n  for (const [typeName, type] of Object.entries(types)) {\n    for (const [otherTypeName, otherType] of Object.entries(types)) {\n      for (const [fieldName, field] of Object.entries(otherType.fields)) {\n        if (field.relation && field.relation.targetType === typeName) {\n          let backwardName = field.relation.backwardName;\n\n          if (!backwardName) {\n            const lowerName = inflection.camelize(otherTypeName, true);\n            backwardName = field.relation.unique\n              ? inflection.singularize(lowerName)\n              : inflection.pluralize(lowerName);\n          }\n\n          // Track the source of this backward name\n          const typeBackwardNames = backwardNameSources[typeName];\n          if (typeBackwardNames === undefined) {\n            throw new Error(`backward name sources not initialized for type: ${typeName}`);\n          }\n          if (!typeBackwardNames[backwardName]) {\n            typeBackwardNames[backwardName] = [];\n          }\n          const sources = typeBackwardNames[backwardName];\n          if (sources === undefined) {\n            throw new Error(`backward name sources entry not initialized for: ${backwardName}`);\n          }\n          sources.push({\n            sourceType: otherTypeName,\n            fieldName,\n          });\n\n          type.backwardRelationships[backwardName] = {\n            name: backwardName,\n            targetType: otherTypeName,\n            targetField: fieldName,\n            sourceField: field.relation.key,\n            isArray: !field.relation.unique,\n            description: otherType.description || \"\",\n          };\n        }\n      }\n    }\n  }\n\n  // Check for duplicates and collect errors\n  const errors: string[] = [];\n\n  for (const [targetTypeName, backwardNames] of Object.entries(backwardNameSources)) {\n    const targetType = types[targetTypeName];\n    if (targetType === undefined) {\n      throw new Error(`type not found: ${targetTypeName}`);\n    }\n    const targetTypeSourceInfo = getTypeSourceInfo(typeSourceInfo, targetTypeName);\n    const targetLocation = targetTypeSourceInfo\n      ? isPluginGeneratedType(targetTypeSourceInfo)\n        ? ` (plugin: ${targetTypeSourceInfo.pluginId})`\n        : ` (${targetTypeSourceInfo.filePath})`\n      : \"\";\n\n    for (const [backwardName, sources] of Object.entries(backwardNames)) {\n      // Check for duplicate backward relation names\n      if (sources.length > 1) {\n        const sourceList = sources\n          .map((s) => {\n            const sourceInfo = getTypeSourceInfo(typeSourceInfo, s.sourceType);\n            const location = sourceInfo\n              ? isPluginGeneratedType(sourceInfo)\n                ? ` (plugin: ${sourceInfo.pluginId})`\n                : ` (${sourceInfo.filePath})`\n              : \"\";\n            return `${s.sourceType}.${s.fieldName}${location}`;\n          })\n          .join(\", \");\n        errors.push(\n          `Backward relation name \"${backwardName}\" on type \"${targetTypeName}\" is duplicated from: ${sourceList}. ` +\n            `Use the \"backward\" option in .relation() to specify unique names.`,\n        );\n      }\n\n      // Check for conflict with existing fields\n      if (Object.hasOwn(targetType.fields, backwardName)) {\n        const source = sources[0];\n        if (source === undefined) {\n          throw new Error(`no source found for backward name: ${backwardName}`);\n        }\n        const sourceInfo = getTypeSourceInfo(typeSourceInfo, source.sourceType);\n        const sourceLocation = sourceInfo\n          ? isPluginGeneratedType(sourceInfo)\n            ? ` (plugin: ${sourceInfo.pluginId})`\n            : ` (${sourceInfo.filePath})`\n          : \"\";\n        errors.push(\n          `Backward relation name \"${backwardName}\" from ${source.sourceType}.${source.fieldName}${sourceLocation} ` +\n            `conflicts with existing field \"${backwardName}\" on type \"${targetTypeName}\"${targetLocation}. ` +\n            `Use the \"backward\" option in .relation() to specify a different name.`,\n        );\n      }\n\n      // Check for conflict with files fields\n      if (targetType.files && Object.hasOwn(targetType.files, backwardName)) {\n        const source = sources[0];\n        if (source === undefined) {\n          throw new Error(`no source found for backward name: ${backwardName}`);\n        }\n        const sourceInfo = getTypeSourceInfo(typeSourceInfo, source.sourceType);\n        const sourceLocation = sourceInfo\n          ? isPluginGeneratedType(sourceInfo)\n            ? ` (plugin: ${sourceInfo.pluginId})`\n            : ` (${sourceInfo.filePath})`\n          : \"\";\n        errors.push(\n          `Backward relation name \"${backwardName}\" from ${source.sourceType}.${source.fieldName}${sourceLocation} ` +\n            `conflicts with files field \"${backwardName}\" on type \"${targetTypeName}\"${targetLocation}. ` +\n            `Use the \"backward\" option in .relation() to specify a different name.`,\n        );\n      }\n    }\n  }\n\n  if (errors.length > 0) {\n    throw new Error(\n      `Backward relation name conflicts detected in TailorDB service \"${namespace}\".\\n` +\n        `${errors.map((e) => `  - ${e}`).join(\"\\n\")}`,\n    );\n  }\n}\n\n/**\n * Validate GraphQL query field name uniqueness.\n * Checks for:\n * 1. Each type's singular query name != plural query name\n * 2. No duplicate query names across all types\n * @param types - Parsed types\n * @param namespace - TailorDB namespace name\n * @param typeSourceInfo - Optional type source information\n */\nfunction validatePluralFormUniqueness(\n  types: Record<string, TailorDBType>,\n  namespace: string,\n  typeSourceInfo?: TypeSourceInfo,\n): void {\n  const errors: string[] = [];\n\n  // Check 1: Each type's singular and plural query names must be different\n  for (const [, parsedType] of Object.entries(types)) {\n    const singularQuery = inflection.camelize(parsedType.name, true);\n    const pluralQuery = inflection.camelize(parsedType.pluralForm, true);\n\n    if (singularQuery === pluralQuery) {\n      const sourceInfo = getTypeSourceInfo(typeSourceInfo, parsedType.name);\n      const location = sourceInfo\n        ? isPluginGeneratedType(sourceInfo)\n          ? ` (plugin: ${sourceInfo.pluginId})`\n          : ` (${sourceInfo.filePath})`\n        : \"\";\n      errors.push(\n        `Type \"${parsedType.name}\"${location} has identical singular and plural query names \"${singularQuery}\". ` +\n          `Use db.type([\"${parsedType.name}\", \"UniquePluralForm\"], {...}) to set a unique pluralForm.`,\n      );\n    }\n  }\n\n  // Check 2: All query names must be unique across types\n  const queryNameToSource = new Map<string, { typeName: string; kind: string }[]>();\n\n  for (const parsedType of Object.values(types)) {\n    const singularQuery = inflection.camelize(parsedType.name, true);\n    const pluralQuery = inflection.camelize(parsedType.pluralForm, true);\n\n    const singularSources = queryNameToSource.get(singularQuery) ?? [];\n    singularSources.push({\n      typeName: parsedType.name,\n      kind: \"singular\",\n    });\n    queryNameToSource.set(singularQuery, singularSources);\n\n    if (singularQuery !== pluralQuery) {\n      const pluralSources = queryNameToSource.get(pluralQuery) ?? [];\n      pluralSources.push({\n        typeName: parsedType.name,\n        kind: \"plural\",\n      });\n      queryNameToSource.set(pluralQuery, pluralSources);\n    }\n  }\n\n  const duplicates = [...queryNameToSource].filter(([, sources]) => sources.length > 1);\n\n  for (const [queryName, sources] of duplicates) {\n    const sourceList = sources\n      .map((s) => {\n        const sourceInfo = getTypeSourceInfo(typeSourceInfo, s.typeName);\n        const location = sourceInfo\n          ? isPluginGeneratedType(sourceInfo)\n            ? ` (plugin: ${sourceInfo.pluginId})`\n            : ` (${sourceInfo.filePath})`\n          : \"\";\n        return `\"${s.typeName}\"${location} (${s.kind})`;\n      })\n      .join(\", \");\n    errors.push(`GraphQL query field \"${queryName}\" conflicts between: ${sourceList}`);\n  }\n\n  if (errors.length > 0) {\n    throw new Error(\n      `GraphQL field name conflicts detected in TailorDB service \"${namespace}\".\\n` +\n        `${errors.map((e) => `  - ${e}`).join(\"\\n\")}`,\n    );\n  }\n}\n\nfunction getTypeSourceInfo(\n  typeSourceInfo: TypeSourceInfo | undefined,\n  typeName: string,\n): TypeSourceInfo[string] | undefined {\n  return typeSourceInfo && Object.hasOwn(typeSourceInfo, typeName)\n    ? typeSourceInfo[typeName]\n    : undefined;\n}\n\nfunction createRecord<T>(): Record<string, T> {\n  return Object.create(null) as Record<string, T>;\n}\n","import { z } from \"zod\";\nimport { functionSchema } from \"../common\";\nimport { relationTypesKeys } from \"./relation\";\nimport type { TailorDBFieldOutput } from \"#/parser/service/tailordb/types\";\n\n/**\n * Normalize GqlOperationsConfig (alias or object) to GqlOperations object.\n * \"query\" alias expands to read-only mode: { create: false, update: false, delete: false, read: true }\n * @param config - The config to normalize\n * @returns The normalized GqlOperations object\n */\nfunction normalizeGqlOperations(\n  config: \"query\" | { create?: boolean; update?: boolean; delete?: boolean; read?: boolean },\n) {\n  if (config === \"query\") {\n    return { create: false, update: false, delete: false, read: true };\n  }\n  return config;\n}\n\n/**\n * Zod schema for GqlOperations configuration with normalization transform.\n * Accepts \"query\" alias or detailed object, normalizes to GqlOperations object.\n */\nexport const GqlOperationsSchema = z\n  .union([\n    z.literal(\"query\"),\n    z.object({\n      create: z.boolean().optional().describe(\"Enable create mutation (default: true)\"),\n      update: z.boolean().optional().describe(\"Enable update mutation (default: true)\"),\n      delete: z.boolean().optional().describe(\"Enable delete mutation (default: true)\"),\n      read: z\n        .boolean()\n        .optional()\n        .describe(\"Enable read queries - get, list, aggregation (default: true)\"),\n    }),\n  ])\n  .describe(\n    \"Configuration for GraphQL operations on a TailorDB type.\\nAll operations are enabled by default (undefined or true = enabled, false = disabled).\",\n  )\n  .transform((val) => normalizeGqlOperations(val));\n\nconst TailorFieldTypeSchema = z.enum([\n  \"uuid\",\n  \"string\",\n  \"boolean\",\n  \"integer\",\n  \"float\",\n  \"decimal\",\n  \"enum\",\n  \"date\",\n  \"datetime\",\n  \"time\",\n  \"nested\",\n]);\n\nconst AllowedValueSchema = z.object({\n  value: z.string(),\n  description: z.string().optional(),\n});\n\nexport const DBFieldMetadataSchema = z.object({\n  required: z.boolean().optional().describe(\"Whether the field is required\"),\n  array: z.boolean().optional().describe(\"Whether the field is an array\"),\n  description: z.string().optional().describe(\"Field description\"),\n  typeName: z.string().optional().describe(\"Type name for nested or enum fields\"),\n  allowedValues: z.array(AllowedValueSchema).optional().describe(\"Allowed values for enum fields\"),\n  index: z.boolean().optional().describe(\"Whether the field is indexed for faster queries\"),\n  unique: z.boolean().optional().describe(\"Whether the field value must be unique\"),\n  vector: z\n    .boolean()\n    .optional()\n    .describe(\"Whether the field is a vector field for similarity search\"),\n  foreignKey: z.boolean().optional().describe(\"Whether the field is a foreign key\"),\n  foreignKeyType: z.string().optional().describe(\"Target type name for foreign key relations\"),\n  foreignKeyField: z.string().optional().describe(\"Target field name for foreign key relations\"),\n  hooks: z\n    .object({\n      create: functionSchema.optional().describe(\"Hook function called on record creation\"),\n      update: functionSchema.optional().describe(\"Hook function called on record update\"),\n    })\n    .optional()\n    .describe(\"Lifecycle hooks for the field\"),\n  validate: z\n    .array(z.union([functionSchema, z.tuple([functionSchema, z.string()])]))\n    .optional()\n    .describe(\"Validation functions for the field\"),\n  serial: z\n    .object({\n      start: z.number().describe(\"Starting value for the serial sequence\"),\n      maxValue: z.number().optional().describe(\"Maximum value for the serial sequence\"),\n      format: z.string().optional().describe(\"Format string for serial value (string type only)\"),\n    })\n    .optional()\n    .describe(\"Serial (auto-increment) configuration\"),\n  scale: z\n    .number()\n    .int()\n    .min(0)\n    .max(12)\n    .optional()\n    .describe(\"Decimal scale (number of digits after decimal point, 0-12)\"),\n});\n\nconst RelationTypeSchema = z.enum(relationTypesKeys);\n\nexport const RawRelationConfigSchema = z.object({\n  type: RelationTypeSchema.describe(\"Relation cardinality type\"),\n  toward: z.object({\n    type: z.string().describe(\"Target type name, or 'self' for self-relations\"),\n    as: z.string().optional().describe(\"Custom forward relation name\"),\n    key: z.string().optional().describe(\"Target field to join on (default: 'id')\"),\n  }),\n  backward: z.string().optional().describe(\"Backward relation name on the target type\"),\n});\n\nconst TailorDBFieldSchema: z.ZodType<TailorDBFieldOutput> = z.lazy(() =>\n  z.object({\n    type: TailorFieldTypeSchema,\n    fields: z.record(z.string(), TailorDBFieldSchema).optional(),\n    metadata: DBFieldMetadataSchema,\n    rawRelation: RawRelationConfigSchema.optional(),\n  }),\n);\n\n/**\n * Schema for TailorDB type settings.\n * Normalizes gqlOperations from alias (\"query\") to object format.\n */\nexport const TailorDBTypeSettingsSchema = z.object({\n  pluralForm: z.string().optional().describe(\"Custom plural form of the type name for GraphQL\"),\n  aggregation: z.boolean().optional().describe(\"Enable aggregation queries for this type\"),\n  bulkUpsert: z.boolean().optional().describe(\"Enable bulk upsert mutation for this type\"),\n  gqlOperations: GqlOperationsSchema.optional().describe(\n    'Configure GraphQL operations for this type. Use \"query\" for read-only mode, or an object for granular control.',\n  ),\n  publishEvents: z\n    .boolean()\n    .optional()\n    .describe(\n      \"Enable publishing events for this type.\\nWhen enabled, record creation/update/deletion events are published.\\nIf not specified, this is automatically set to true when an executor uses this type\\nwith recordCreated/recordUpdated/recordDeleted triggers. If explicitly set to false\\nwhile an executor uses this type, an error will be thrown during apply.\",\n    ),\n});\n\nexport const GQL_PERMISSION_INVALID_OPERAND_MESSAGE =\n  \"operand is not supported in gqlPermission. Use permission() for record-level conditions.\";\n\nconst GqlPermissionOperandSchema = z.union(\n  [\n    z.object({ user: z.string() }).strict(),\n    z.string(),\n    z.boolean(),\n    z.array(z.string()),\n    z.array(z.boolean()),\n  ],\n  {\n    error: (issue) => {\n      if (typeof issue.input === \"object\" && issue.input !== null) {\n        const keys = Object.keys(issue.input);\n        if (keys.length === 1) {\n          return `\"${keys[0]}\" ${GQL_PERMISSION_INVALID_OPERAND_MESSAGE}`;\n        }\n        return \"Operand object must have exactly 1 key\";\n      }\n      return \"Invalid operand in gqlPermission\";\n    },\n  },\n);\n\nconst RecordPermissionOperandSchema = z.union([\n  GqlPermissionOperandSchema,\n  z.object({ record: z.string() }),\n  z.object({ oldRecord: z.string() }),\n  z.object({ newRecord: z.string() }),\n]);\n\nconst PermissionOperatorSchema = z.enum([\"=\", \"!=\", \"in\", \"not in\", \"hasAny\", \"not hasAny\"]);\n\nconst RecordPermissionConditionSchema = z\n  .tuple([RecordPermissionOperandSchema, PermissionOperatorSchema, RecordPermissionOperandSchema])\n  .readonly();\n\nconst GqlPermissionConditionSchema = z\n  .tuple([GqlPermissionOperandSchema, PermissionOperatorSchema, GqlPermissionOperandSchema])\n  .readonly();\n\nconst ActionPermissionSchema = z.union([\n  // Object format: { conditions, description?, permit? }\n  z.object({\n    conditions: z.union([\n      RecordPermissionConditionSchema,\n      z.array(RecordPermissionConditionSchema).readonly(),\n    ]),\n    description: z.string().optional(),\n    permit: z.boolean().optional(),\n  }),\n  // Single condition tuple: [operand, operator, operand]\n  z\n    .tuple([RecordPermissionOperandSchema, PermissionOperatorSchema, RecordPermissionOperandSchema])\n    .readonly(),\n  // Single condition tuple with permit: [operand, operator, operand, permit]\n  z\n    .tuple([\n      RecordPermissionOperandSchema,\n      PermissionOperatorSchema,\n      RecordPermissionOperandSchema,\n      z.boolean(),\n    ])\n    .readonly(),\n  // Multiple conditions with optional trailing permit\n  z\n    .array(z.union([RecordPermissionConditionSchema, z.boolean()]))\n    .refine(\n      (arr) => {\n        const boolIndex = arr.findIndex((item) => typeof item === \"boolean\");\n        return boolIndex === -1 || boolIndex === arr.length - 1;\n      },\n      { message: \"Boolean permit flag must only appear at the end\" },\n    )\n    .readonly(),\n]);\n\nconst GqlPermissionActionSchema = z.enum([\n  \"read\",\n  \"create\",\n  \"update\",\n  \"delete\",\n  \"aggregate\",\n  \"bulkUpsert\",\n]);\n\nconst GqlPermissionPolicySchema = z.object({\n  conditions: z.array(GqlPermissionConditionSchema).readonly(),\n  actions: z.union([z.literal(\"all\"), z.array(GqlPermissionActionSchema).readonly()]),\n  permit: z.boolean().optional(),\n  description: z.string().optional(),\n});\n\nexport const RawPermissionsSchema = z.object({\n  record: z\n    .object({\n      create: z.array(ActionPermissionSchema).readonly(),\n      read: z.array(ActionPermissionSchema).readonly(),\n      update: z.array(ActionPermissionSchema).readonly(),\n      delete: z.array(ActionPermissionSchema).readonly(),\n    })\n    .optional(),\n  gql: z.array(GqlPermissionPolicySchema).readonly().optional(),\n});\n\nexport const TailorDBTypeSchema = z.object({\n  name: z.string(),\n  fields: z.record(z.string(), TailorDBFieldSchema),\n  metadata: z.object({\n    name: z.string(),\n    description: z.string().optional(),\n    settings: TailorDBTypeSettingsSchema.optional(),\n    permissions: RawPermissionsSchema,\n    files: z.record(z.string(), z.string()),\n    indexes: z\n      .record(\n        z.string(),\n        z.object({\n          fields: z.array(z.string()),\n          unique: z.boolean().optional(),\n        }),\n      )\n      .optional(),\n  }),\n});\n\nconst TailorDBMigrationConfigSchema = z.object({\n  directory: z.string().describe(\"Directory containing migration files\"),\n  machineUser: z.string().optional().describe(\"Machine user name for migration execution\"),\n});\n\n/**\n * Schema for TailorDB service configuration.\n * Normalizes gqlOperations from alias (\"query\") to object format.\n */\nexport const TailorDBServiceConfigSchema = z.object({\n  files: z.array(z.string()).describe(\"Glob patterns for TailorDB type definition files\"),\n  ignores: z.array(z.string()).optional().describe(\"Glob patterns to exclude from type discovery\"),\n  erdSite: z.string().optional().describe(\"URL for the ERD (Entity Relationship Diagram) site\"),\n  migration: TailorDBMigrationConfigSchema.optional().describe(\"Migration configuration\"),\n  gqlOperations: GqlOperationsSchema.optional().describe(\n    \"Default GraphQL operations for all types in this service\",\n  ),\n});\n","import * as globals from \"globals\";\n\ntype GlobalsShape = {\n  builtin?: Record<string, boolean>;\n  \"shared-node-browser\"?: Record<string, boolean>;\n};\n\nconst globalsMap: GlobalsShape =\n  (globals as unknown as { default?: GlobalsShape }).default ??\n  (globals as unknown as GlobalsShape);\n\n/**\n * Runtime globals available in the PF execution environment.\n * Identifiers in this set are excluded from free variable detection\n * since they are always available in the runtime environment.\n *\n * Combines globals.builtin (ECMAScript language builtins) and\n * globals['shared-node-browser'] (shared runtime globals like\n * console, fetch, setTimeout, etc.) from the `globals` npm package.\n */\nexport const ES_BUILTINS = new Set([\n  ...Object.keys(globalsMap.builtin ?? {}),\n  ...Object.keys(globalsMap[\"shared-node-browser\"] ?? {}),\n]);\n","import { mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { parseSync } from \"oxc-parser\";\nimport { join, resolve } from \"pathe\";\nimport * as rolldown from \"rolldown\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport { stringifyFunction, tailorUserMap } from \"#/parser/service/tailordb/field\";\nimport { setPrecompiledScriptExpr } from \"#/parser/service/tailordb/hooks-validate-precompiled-expr\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { ES_BUILTINS } from \"./es-builtins\";\nimport type { TailorDBTypeRaw as TailorDBTypeSchemaOutput } from \"#/types/tailordb.generated\";\nimport type {\n  BindingPattern,\n  ExportNamedDeclaration,\n  Function as OxcFunction,\n  ImportDeclaration,\n  Node,\n  ParamPattern,\n  VariableDeclaration,\n} from \"@oxc-project/types\";\n\ntype ScriptFunction = (...args: unknown[]) => unknown;\n\ntype ScriptTarget = {\n  fn: ScriptFunction;\n  kind: \"hooks\" | \"validate\";\n};\n\n/** Binding found in the source file: either an import or a top-level declaration */\nexport type SourceBinding = {\n  name: string;\n  /** The original source text of the import/declaration statement */\n  sourceText: string;\n  kind: \"import\" | \"declaration\";\n};\n\n/**\n * Recursively extract binding names from a destructuring pattern node.\n * @param pattern - The binding pattern AST node.\n * @param bindings - Set to collect binding names into.\n */\nfunction collectBindingsFromPattern(pattern: BindingPattern, bindings: Set<string>): void {\n  switch (pattern.type) {\n    case \"Identifier\":\n      bindings.add(pattern.name);\n      break;\n    case \"ObjectPattern\":\n      for (const prop of pattern.properties) {\n        if (prop.type === \"RestElement\") {\n          collectBindingsFromPattern(prop.argument, bindings);\n        } else {\n          collectBindingsFromPattern(prop.value, bindings);\n        }\n      }\n      break;\n    case \"ArrayPattern\":\n      for (const elem of pattern.elements) {\n        if (elem) {\n          if (elem.type === \"RestElement\") {\n            collectBindingsFromPattern(elem.argument, bindings);\n          } else {\n            collectBindingsFromPattern(elem, bindings);\n          }\n        }\n      }\n      break;\n    case \"AssignmentPattern\":\n      collectBindingsFromPattern(pattern.left, bindings);\n      break;\n  }\n}\n\n/** Fields that contain TypeScript type annotations (not runtime references). */\nconst TS_TYPE_FIELDS = new Set([\n  \"typeAnnotation\",\n  \"typeParameters\",\n  \"returnType\",\n  \"superTypeArguments\",\n  \"typeArguments\",\n]);\n\nfunction isBindingPattern(param: ParamPattern): param is BindingPattern {\n  return param.type !== \"TSParameterProperty\";\n}\n\nfunction toScriptFunction(value: unknown): ScriptFunction | undefined {\n  if (typeof value !== \"function\") return undefined;\n  return value as unknown as ScriptFunction;\n}\n\nfunction collectScriptTargets(type: TailorDBTypeSchemaOutput): ScriptTarget[] {\n  const targets: ScriptTarget[] = [];\n\n  const collectFieldTargets = (field: TailorDBTypeSchemaOutput[\"fields\"][string]) => {\n    const metadata = field.metadata;\n\n    const createHook = toScriptFunction(metadata.hooks?.create);\n    if (createHook) {\n      targets.push({ fn: createHook, kind: \"hooks\" });\n    }\n    const updateHook = toScriptFunction(metadata.hooks?.update);\n    if (updateHook) {\n      targets.push({ fn: updateHook, kind: \"hooks\" });\n    }\n\n    for (const validateInput of metadata.validate ?? []) {\n      if (typeof validateInput === \"function\") {\n        const validateFn = toScriptFunction(validateInput);\n        if (validateFn) targets.push({ fn: validateFn, kind: \"validate\" });\n      } else {\n        const validateFn = toScriptFunction(validateInput[0]);\n        if (validateFn) targets.push({ fn: validateFn, kind: \"validate\" });\n      }\n    }\n\n    if (field.type === \"nested\" && field.fields) {\n      for (const nestedField of Object.values(field.fields as TailorDBTypeSchemaOutput[\"fields\"])) {\n        collectFieldTargets(nestedField);\n      }\n    }\n  };\n\n  for (const field of Object.values(type.fields)) {\n    collectFieldTargets(field);\n  }\n\n  return targets;\n}\n\n/**\n * Parse a code string with oxc-parser and return identifiers that are referenced\n * but never bound anywhere in the snippet (free variables), excluding ES builtins.\n * @param code - Valid JavaScript code to analyze.\n * @returns Set of undefined variable names.\n */\nexport function findUndefinedReferences(code: string): Set<string> {\n  const { program } = parseSync(\"_.js\", code);\n  const references = new Set<string>();\n  const bindings = new Set<string>();\n\n  const walk = (node: Node | null | undefined): void => {\n    if (!node) return;\n\n    switch (node.type) {\n      case \"VariableDeclarator\":\n        collectBindingsFromPattern(node.id, bindings);\n        walk(node.init);\n        return;\n\n      case \"FunctionDeclaration\":\n      case \"FunctionExpression\":\n        if (node.id) bindings.add(node.id.name);\n        for (const param of node.params) {\n          if (isBindingPattern(param)) {\n            collectBindingsFromPattern(param, bindings);\n            walk(param);\n          }\n        }\n        walk(node.body);\n        return;\n\n      case \"ArrowFunctionExpression\":\n        for (const param of node.params) {\n          if (isBindingPattern(param)) {\n            collectBindingsFromPattern(param, bindings);\n            walk(param);\n          }\n        }\n        walk(node.body);\n        return;\n\n      case \"ClassDeclaration\":\n      case \"ClassExpression\":\n        if (node.id) bindings.add(node.id.name);\n        walk(node.superClass);\n        walk(node.body);\n        return;\n\n      case \"CatchClause\":\n        if (node.param) collectBindingsFromPattern(node.param, bindings);\n        walk(node.body);\n        return;\n\n      case \"MemberExpression\":\n        walk(node.object);\n        if (node.computed) walk(node.property);\n        return;\n\n      case \"Property\":\n        if (node.computed) walk(node.key);\n        walk(node.value);\n        return;\n\n      case \"LabeledStatement\":\n        walk(node.body);\n        return;\n\n      case \"Identifier\":\n        references.add(node.name);\n        return;\n    }\n\n    // Generic child walk for all other node types, skipping TS type-annotation fields\n    const rec = node as unknown as Record<string, unknown>;\n    for (const [key, value] of Object.entries(rec)) {\n      if (key === \"type\" || TS_TYPE_FIELDS.has(key)) continue;\n      if (Array.isArray(value)) {\n        for (const item of value) walk(item as Node);\n      } else if (value && typeof value === \"object\" && \"type\" in value) {\n        walk(value as Node);\n      }\n    }\n  };\n\n  walk(program);\n\n  // Free variables = references - bindings - builtins\n  const freeVars = new Set<string>();\n  for (const ref of references) {\n    if (!bindings.has(ref) && !ES_BUILTINS.has(ref)) {\n      freeVars.add(ref);\n    }\n  }\n  return freeVars;\n}\n\n/**\n * Collect all Identifier names from a TypeScript/JavaScript code string using oxc-parser.\n * @param code - Code string to analyze.\n * @returns Set of identifier names found in the code.\n */\nfunction collectIdentifierNames(code: string): Set<string> {\n  const { program } = parseSync(\"_.ts\", code);\n  const names = new Set<string>();\n  const walk = (node: unknown): void => {\n    if (!node || typeof node !== \"object\") return;\n    const record = node as Record<string, unknown>;\n    if (record.type === \"Identifier\" && typeof record.name === \"string\") {\n      names.add(record.name);\n    }\n    for (const [key, value] of Object.entries(record)) {\n      // Skip non-computed MemberExpression property (e.g. `length` in `value.length`)\n      // but keep computed properties (e.g. `foo` in `obj[foo]`) as they are real references\n      if (key === \"property\" && record.type === \"MemberExpression\" && !record.computed) continue;\n      // Skip non-computed Property keys (e.g. `format` in `{ format: \"x\" }` is not a reference)\n      if (key === \"key\" && record.type === \"Property\" && !record.computed) continue;\n      // Skip TypeScript type annotation fields (not runtime references)\n      if (TS_TYPE_FIELDS.has(key)) continue;\n      if (Array.isArray(value)) {\n        for (const item of value) walk(item);\n      } else if (value && typeof value === \"object\" && \"type\" in value) {\n        walk(value);\n      }\n    }\n  };\n  walk(program);\n  return names;\n}\n\n/**\n * Collect top-level bindings (imports and declarations) from a TypeScript source file.\n * @param sourceFilePath - Absolute path to the source file.\n * @returns Map of binding name to SourceBinding.\n */\nexport function collectSourceBindings(sourceFilePath: string): Map<string, SourceBinding> {\n  const source = readFileSync(sourceFilePath, \"utf-8\");\n  const { program } = parseSync(sourceFilePath, source);\n  const bindings = new Map<string, SourceBinding>();\n\n  for (const stmt of program.body) {\n    if (stmt.type === \"ImportDeclaration\") {\n      const importDecl = stmt as ImportDeclaration;\n      const text = source.slice(importDecl.start, importDecl.end);\n      for (const spec of importDecl.specifiers) {\n        bindings.set(spec.local.name, {\n          name: spec.local.name,\n          sourceText: text,\n          kind: \"import\",\n        });\n      }\n    } else if (stmt.type === \"VariableDeclaration\") {\n      const varDecl = stmt as VariableDeclaration;\n      const text = source.slice(varDecl.start, varDecl.end);\n      for (const decl of varDecl.declarations) {\n        if (decl.id.type === \"Identifier\") {\n          bindings.set(decl.id.name, { name: decl.id.name, sourceText: text, kind: \"declaration\" });\n        }\n      }\n    } else if (stmt.type === \"FunctionDeclaration\") {\n      const funcDecl = stmt as OxcFunction;\n      if (funcDecl.id) {\n        const text = source.slice(funcDecl.start, funcDecl.end);\n        bindings.set(funcDecl.id.name, {\n          name: funcDecl.id.name,\n          sourceText: text,\n          kind: \"declaration\",\n        });\n      }\n    } else if (stmt.type === \"ExportNamedDeclaration\") {\n      const exportDecl = stmt as ExportNamedDeclaration;\n      const innerDecl = exportDecl.declaration;\n      if (!innerDecl) continue;\n\n      if (innerDecl.type === \"VariableDeclaration\") {\n        const varDecl = innerDecl as VariableDeclaration;\n        // Slice only the inner declaration (without export keyword) so it is valid standalone\n        const text = source.slice(varDecl.start, varDecl.end);\n        for (const decl of varDecl.declarations) {\n          if (decl.id.type === \"Identifier\") {\n            bindings.set(decl.id.name, {\n              name: decl.id.name,\n              sourceText: text,\n              kind: \"declaration\",\n            });\n          }\n        }\n      } else if (innerDecl.type === \"FunctionDeclaration\") {\n        const funcDecl = innerDecl as OxcFunction;\n        if (funcDecl.id) {\n          const text = source.slice(funcDecl.start, funcDecl.end);\n          bindings.set(funcDecl.id.name, {\n            name: funcDecl.id.name,\n            sourceText: text,\n            kind: \"declaration\",\n          });\n        }\n      }\n    }\n  }\n\n  return bindings;\n}\n\n/**\n * Resolve all bindings needed by a function, recursively including\n * dependencies of top-level declarations.\n * @param freeVars - Set of free variable names extracted from the function.\n * @param sourceBindings - Available bindings from the source file.\n * @returns Object with needed import statements and declaration texts.\n */\nexport function resolveNeededBindings(\n  freeVars: Set<string>,\n  sourceBindings: Map<string, SourceBinding>,\n): { imports: string[]; declarations: string[]; unresolved: string[] } {\n  const neededImports = new Set<string>();\n  const neededDeclarations = new Set<string>();\n  const unresolved: string[] = [];\n  const resolved = new Set<string>();\n\n  const resolveVars = (vars: Set<string>): void => {\n    for (const varName of vars) {\n      if (resolved.has(varName)) continue;\n      resolved.add(varName);\n\n      const binding = sourceBindings.get(varName);\n      if (!binding) {\n        unresolved.push(varName);\n        continue;\n      }\n\n      if (binding.kind === \"import\") {\n        neededImports.add(binding.sourceText);\n      } else {\n        // Parse the declaration with oxc-parser (handles TypeScript) and collect\n        // all Identifier names, then resolve those that match other source bindings.\n        const identifiers = collectIdentifierNames(binding.sourceText);\n        const referencedVars = new Set<string>();\n        for (const id of identifiers) {\n          if (id !== varName && sourceBindings.has(id)) {\n            referencedVars.add(id);\n          }\n        }\n        resolveVars(referencedVars);\n        neededDeclarations.add(binding.sourceText);\n      }\n    }\n  };\n\n  resolveVars(freeVars);\n\n  return {\n    imports: [...neededImports],\n    declarations: [...neededDeclarations],\n    unresolved,\n  };\n}\n\nfunction buildPrecompiledExpr(bundleCode: string): string {\n  return (\n    \"(() => {\\n\" +\n    \"  const module = { exports: {} };\\n\" +\n    \"  const exports = module.exports;\\n\" +\n    `${bundleCode}\\n` +\n    `  return module.exports.main({ value: _value, data: _data, user: ${tailorUserMap} });\\n` +\n    \"})()\"\n  );\n}\n\n/**\n * Build entry file content from already-resolved imports and declarations.\n * @param imports - Import statement texts.\n * @param declarations - Declaration statement texts.\n * @param fnSource - The function source code.\n * @param sourceFilePath - Path to the source file for resolving relative imports.\n * @returns Entry file content string.\n */\nexport function buildMinimalEntryFromResolved(\n  imports: string[],\n  declarations: string[],\n  fnSource: string,\n  sourceFilePath: string,\n): string {\n  const sourceDir = resolve(sourceFilePath, \"..\").replace(/\\\\/g, \"/\");\n\n  // Rewrite relative import paths to absolute paths so rolldown can resolve them\n  const resolvedImports = imports.map((imp) =>\n    imp.replace(\n      /from\\s+[\"'](\\.[^\"']+)[\"']/g,\n      (_match, relPath: string) => `from \"${resolve(sourceDir, relPath).replace(/\\\\/g, \"/\")}\"`,\n    ),\n  );\n\n  const lines = [\n    ...resolvedImports,\n    ...declarations,\n    `export function main(input) { return (${fnSource})(input); }`,\n  ];\n  return lines.join(\"\\n\");\n}\n\nasync function bundleScriptTarget(args: {\n  fn: ScriptFunction;\n  kind: \"hooks\" | \"validate\";\n  sourceFilePath: string;\n  sourceBindings: Map<string, SourceBinding>;\n  tempDir: string;\n  targetIndex: number;\n  tsconfig: string | undefined;\n}): Promise<string> {\n  const { fn, kind, sourceFilePath, sourceBindings, tempDir, targetIndex, tsconfig } = args;\n  const fnSource = stringifyFunction(fn);\n  const inlineExpr = `(${fnSource})({ value: _value, data: _data, user: ${tailorUserMap} })`;\n\n  // Check if the function has free variables that need bundling\n  const freeVars = findUndefinedReferences(`const __fn = ${fnSource};`);\n  if (freeVars.size === 0) {\n    // No external dependencies - use inline expression without bundling\n    return inlineExpr;\n  }\n\n  const { imports, declarations, unresolved } = resolveNeededBindings(freeVars, sourceBindings);\n  if (unresolved.length > 0) {\n    throw new Error(\n      `${kind} in ${sourceFilePath} captures unresolvable variables (${unresolved.join(\", \")}). ` +\n        \"Hooks and validators must not reference variables that cannot be resolved from the source file.\\n\" +\n        `  ${kind}: ${fnSource}`,\n    );\n  }\n\n  const entryContent = buildMinimalEntryFromResolved(\n    imports,\n    declarations,\n    fnSource,\n    sourceFilePath,\n  );\n  const entryPath = join(tempDir, `tailordb-script-${targetIndex}.entry.ts`);\n\n  writeFileSync(entryPath, entryContent);\n\n  const buildResult = await rolldown.build({\n    plugins: [platformBundleDefinePlugin],\n    input: entryPath,\n    write: false,\n    output: {\n      format: \"cjs\",\n      sourcemap: false,\n      minify: true,\n      codeSplitting: false,\n    },\n    tsconfig,\n    treeshake: {\n      moduleSideEffects: false,\n      annotations: true,\n      unknownGlobalSideEffects: false,\n    },\n    logLevel: \"silent\",\n  } as rolldown.BuildOptions);\n\n  const bundledCode = buildResult.output[0].code;\n  return buildPrecompiledExpr(bundledCode);\n}\n\n/**\n * Precompile TailorDB hooks/validators into self-contained script expressions using rolldown.\n * Uses oxc-parser AST walking to extract free variables from functions, then builds\n * minimal entry points containing only the needed imports and declarations.\n * @param type - TailorDB type schema output.\n * @param sourceFilePath - Source file where the type is defined.\n * @param tsconfig - Resolved tsconfig path, or undefined if not found.\n */\nexport async function precompileTailorDBTypeScripts(\n  type: TailorDBTypeSchemaOutput,\n  sourceFilePath: string,\n  tsconfig: string | undefined,\n): Promise<void> {\n  const targets = collectScriptTargets(type);\n  if (targets.length === 0) return;\n\n  // Collect source bindings once for all targets in this file\n  const sourceBindings = collectSourceBindings(sourceFilePath);\n\n  // Use type name in temp dir to avoid race conditions when multiple type files\n  // are precompiled concurrently via Promise.all in service.ts\n  const tempDir = resolve(getDistDir(), \"hooks-validate-scripts\", type.name);\n  mkdirSync(tempDir, { recursive: true });\n\n  try {\n    const results = await Promise.allSettled(\n      targets.map((target, index) =>\n        bundleScriptTarget({\n          fn: target.fn,\n          kind: target.kind,\n          sourceFilePath,\n          sourceBindings,\n          tempDir,\n          targetIndex: index,\n          tsconfig,\n        }),\n      ),\n    );\n    const firstError = results.find((r): r is PromiseRejectedResult => r.status === \"rejected\");\n    if (firstError) {\n      throw firstError.reason;\n    }\n    for (const [index, result] of results.entries()) {\n      if (result.status === \"fulfilled\") {\n        setPrecompiledScriptExpr(\n          assertDefined(targets[index], `bundle target at index ${index} missing`).fn,\n          result.value,\n        );\n      }\n    }\n  } finally {\n    rmSync(tempDir, { recursive: true, force: true });\n  }\n}\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { fetchAll } from \"#/cli/shared/client\";\nimport { isPluginGeneratedType } from \"#/parser/service/tailordb/type-source\";\nimport type { TypeSourceInfo, TypeSourceInfoEntry } from \"#/parser/service/tailordb/types\";\n\ntype LocalTailorDBService = {\n  readonly namespace: string;\n  readonly types: Readonly<Record<string, unknown>>;\n  readonly typeSourceInfo: Readonly<TypeSourceInfo>;\n};\n\ntype TailorDBTypeNameSourceKind = \"local\" | \"external\";\n\nexport type TailorDBTypeNameSource = {\n  readonly namespace: string;\n  readonly typeName: string;\n  readonly kind: TailorDBTypeNameSourceKind;\n  readonly detail?: string;\n};\n\ntype ListTailorDBTypesArgs = {\n  workspaceId: string;\n  namespaceName: string;\n  pageToken?: string;\n  pageSize?: number;\n};\n\ntype ListTailorDBTypesResult = {\n  tailordbTypes: Array<{ name: string }>;\n  nextPageToken?: string;\n};\n\ntype ListTailorDBTypesClient = {\n  listTailorDBTypes(args: ListTailorDBTypesArgs): Promise<ListTailorDBTypesResult>;\n};\n\nexport interface CollectLocalTailorDBTypeNameSourcesArgs {\n  /** Loaded local TailorDB services. */\n  tailorDBServices: ReadonlyArray<LocalTailorDBService>;\n}\n\nexport interface FetchExternalTailorDBTypeNameSourcesArgs {\n  /** Client used to read TailorDB metadata. */\n  client: ListTailorDBTypesClient;\n  /** Workspace that owns the configured namespaces. */\n  workspaceId: string;\n  /** External TailorDB namespaces declared in the application config. */\n  externalTailorDBNamespaces: ReadonlyArray<string>;\n}\n\nexport interface AssertUniqueTailorDBTypeNamesArgs {\n  /** Type-name sources to validate. */\n  sources: ReadonlyArray<TailorDBTypeNameSource>;\n}\n\nexport interface AssertUniqueTailorDBTypeNamesWithExternalArgs\n  extends CollectLocalTailorDBTypeNameSourcesArgs, FetchExternalTailorDBTypeNameSourcesArgs {}\n\n/**\n * Format a TailorDB type source for validation errors.\n * @param sourceInfo - Source information captured when loading the type\n * @returns Human-readable source detail\n */\nexport function formatTailorDBTypeSourceInfo(\n  sourceInfo: TypeSourceInfoEntry | undefined,\n): string | undefined {\n  if (!sourceInfo) {\n    return undefined;\n  }\n\n  if (isPluginGeneratedType(sourceInfo)) {\n    const parts = [`plugin ${sourceInfo.pluginId}`];\n    if (sourceInfo.generatedTypeKind) {\n      parts.push(`kind ${sourceInfo.generatedTypeKind}`);\n    }\n    if (sourceInfo.originalFilePath) {\n      parts.push(`source ${sourceInfo.originalFilePath}`);\n    }\n    if (sourceInfo.originalExportName) {\n      parts.push(`export ${sourceInfo.originalExportName}`);\n    }\n    return parts.join(\", \");\n  }\n\n  return `${sourceInfo.filePath} export ${sourceInfo.exportName}`;\n}\n\n/**\n * Collect TailorDB type-name sources from loaded local services.\n * @param args - Collection inputs\n * @returns Type-name sources for local services\n */\nexport function collectLocalTailorDBTypeNameSources(\n  args: CollectLocalTailorDBTypeNameSourcesArgs,\n): TailorDBTypeNameSource[] {\n  const sources: TailorDBTypeNameSource[] = [];\n\n  for (const service of args.tailorDBServices) {\n    for (const typeName of Object.keys(service.types)) {\n      sources.push({\n        namespace: service.namespace,\n        typeName,\n        kind: \"local\",\n        detail: formatTailorDBTypeSourceInfo(service.typeSourceInfo[typeName]),\n      });\n    }\n  }\n\n  return sources;\n}\n\n/**\n * Fetch TailorDB type-name sources for external namespaces.\n * @param args - Fetch inputs\n * @returns Type-name sources for external services\n */\nexport async function fetchExternalTailorDBTypeNameSources(\n  args: FetchExternalTailorDBTypeNameSourcesArgs,\n): Promise<TailorDBTypeNameSource[]> {\n  const sourcesByNamespace = await Promise.all(\n    args.externalTailorDBNamespaces.map(async (namespace) => {\n      const sources: TailorDBTypeNameSource[] = [];\n      const tailordbTypes = await fetchAll(async (pageToken, maxPageSize) => {\n        try {\n          const { tailordbTypes, nextPageToken } = await args.client.listTailorDBTypes({\n            workspaceId: args.workspaceId,\n            namespaceName: namespace,\n            pageToken,\n            pageSize: maxPageSize,\n          });\n          return [tailordbTypes, nextPageToken ?? \"\"];\n        } catch (error) {\n          if (error instanceof ConnectError && error.code === Code.NotFound) {\n            return [[], \"\"];\n          }\n          throw error;\n        }\n      });\n\n      for (const type of tailordbTypes) {\n        sources.push({\n          namespace,\n          typeName: type.name,\n          kind: \"external\",\n        });\n      }\n\n      return sources;\n    }),\n  );\n\n  return sourcesByNamespace.flat();\n}\n\n/**\n * Assert that TailorDB type names are unique across all supplied sources.\n * @param args - Validation inputs\n */\nexport function assertUniqueTailorDBTypeNames(args: AssertUniqueTailorDBTypeNamesArgs): void {\n  const sourcesByTypeName = new Map<string, TailorDBTypeNameSource[]>();\n\n  for (const source of args.sources) {\n    const existing = sourcesByTypeName.get(source.typeName);\n    if (existing) {\n      existing.push(source);\n    } else {\n      sourcesByTypeName.set(source.typeName, [source]);\n    }\n  }\n\n  const errors: string[] = [];\n  for (const [typeName, sources] of sourcesByTypeName) {\n    if (sources.length <= 1) {\n      continue;\n    }\n\n    const sourceList = sources.map(formatTailorDBTypeNameSource).join(\", \");\n    errors.push(`Type \"${typeName}\" is defined more than once: ${sourceList}`);\n  }\n\n  if (errors.length > 0) {\n    throw new Error(\n      \"Duplicate TailorDB type names detected.\\n\" +\n        `${errors.map((error) => `  - ${error}`).join(\"\\n\")}\\n` +\n        \"TailorDB type names must be unique across all TailorDB namespaces in an application.\",\n    );\n  }\n}\n\n/**\n * Assert local TailorDB type names are unique.\n * @param args - Validation inputs\n */\nexport function assertUniqueLocalTailorDBTypeNames(\n  args: CollectLocalTailorDBTypeNameSourcesArgs,\n): void {\n  assertUniqueTailorDBTypeNames({\n    sources: collectLocalTailorDBTypeNameSources(args),\n  });\n}\n\n/**\n * Assert TailorDB type names are unique across local and external namespaces.\n * @param args - Validation inputs\n */\nexport async function assertUniqueTailorDBTypeNamesWithExternal(\n  args: AssertUniqueTailorDBTypeNamesWithExternalArgs,\n): Promise<void> {\n  const localSources = collectLocalTailorDBTypeNameSources(args);\n  const externalSources =\n    args.externalTailorDBNamespaces.length > 0\n      ? await fetchExternalTailorDBTypeNameSources(args)\n      : [];\n\n  assertUniqueTailorDBTypeNames({\n    sources: [...localSources, ...externalSources],\n  });\n}\n\nfunction formatTailorDBTypeNameSource(source: TailorDBTypeNameSource): string {\n  const namespaceLabel =\n    source.kind === \"external\"\n      ? `external namespace \"${source.namespace}\"`\n      : `namespace \"${source.namespace}\"`;\n\n  return source.detail ? `${namespaceLabel} (${source.detail})` : namespaceLabel;\n}\n","import { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport { resolveTSConfig } from \"pkg-types\";\nimport { loadFilesWithIgnores } from \"#/cli/services/file-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { parseTypes, TailorDBTypeSchema } from \"#/parser/service/tailordb/index\";\nimport { findOmittedPermitRules } from \"#/parser/service/tailordb/permission\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { isSdkBranded } from \"#/utils/brand\";\nimport { precompileTailorDBTypeScripts } from \"./hooks-validate-bundler\";\nimport { formatTailorDBTypeSourceInfo } from \"./type-name-validation\";\nimport type {\n  TypeSourceInfo,\n  TypeSourceInfoEntry,\n  TailorDBType,\n} from \"#/parser/service/tailordb/types\";\nimport type { PluginManager } from \"#/plugin/manager\";\nimport type { PluginAttachment } from \"#/plugin/types\";\nimport type {\n  TailorDBServiceConfig,\n  TailorDBTypeRaw as TailorDBTypeSchemaOutput,\n} from \"#/types/tailordb.generated\";\n\nexport type TailorDBService = {\n  readonly namespace: string;\n  readonly config: TailorDBServiceConfig;\n  readonly types: Readonly<Record<string, TailorDBType>>;\n  readonly typeSourceInfo: Readonly<TypeSourceInfo>;\n  readonly pluginAttachments: ReadonlyMap<string, readonly PluginAttachment[]>;\n  loadTypes: () => Promise<Record<string, TailorDBType> | undefined>;\n  processNamespacePlugins: () => Promise<void>;\n};\n\n/**\n * Parameters for creating a TailorDBService\n */\nexport interface CreateTailorDBServiceParams {\n  /** The namespace for this TailorDB service */\n  namespace: string;\n  /** The TailorDB service configuration */\n  config: TailorDBServiceConfig;\n  /** Plugin manager for processing plugins */\n  pluginManager?: PluginManager;\n}\n\n/**\n * Creates a new TailorDBService instance.\n * @param params - Parameters for creating the service\n * @returns A new TailorDBService instance\n */\nexport function createTailorDBService(params: CreateTailorDBServiceParams): TailorDBService {\n  const { namespace, config, pluginManager } = params;\n  type TailorDBTypesByName = Record<string, TailorDBTypeSchemaOutput>;\n  const createRawTypesByName = (): TailorDBTypesByName =>\n    Object.create(null) as TailorDBTypesByName;\n  const rawTypes = Object.create(null) as Record<string, TailorDBTypesByName>;\n  let types: Record<string, TailorDBType> = {};\n  const typeSourceInfo = Object.create(null) as TypeSourceInfo;\n  const pluginAttachments: Map<string, PluginAttachment[]> = new Map();\n  let loadPromise: Promise<Record<string, TailorDBType> | undefined> | undefined;\n\n  const registerRawType = (\n    rawTypesKey: string,\n    typeName: string,\n    type: TailorDBTypeSchemaOutput,\n    sourceInfo: TypeSourceInfoEntry,\n  ): void => {\n    const existingSourceInfo = Object.hasOwn(typeSourceInfo, typeName)\n      ? typeSourceInfo[typeName]\n      : undefined;\n    if (existingSourceInfo) {\n      const firstSource = formatTailorDBTypeSourceInfo(existingSourceInfo) ?? \"unknown source\";\n      const secondSource = formatTailorDBTypeSourceInfo(sourceInfo) ?? \"unknown source\";\n      throw new Error(\n        `Duplicate TailorDB type name \"${typeName}\" detected in TailorDB service \"${namespace}\". ` +\n          `First: ${firstSource}. Second: ${secondSource}. ` +\n          \"TailorDB type names must be unique across all TailorDB files in a service.\",\n      );\n    }\n\n    assertDefined(rawTypes[rawTypesKey], `raw types entry missing for key: ${rawTypesKey}`)[\n      typeName\n    ] = type;\n    typeSourceInfo[typeName] = sourceInfo;\n  };\n\n  const doParseTypes = (): void => {\n    const allTypes = createRawTypesByName();\n    for (const fileTypes of Object.values(rawTypes)) {\n      for (const [typeName, type] of Object.entries(fileTypes)) {\n        allTypes[typeName] = type;\n      }\n    }\n\n    types = parseTypes(allTypes, namespace, typeSourceInfo);\n  };\n\n  // Warn about object-format permission rules that omit `permit`. Those default\n  // to \"deny\" (unlike the array shorthand, which defaults to \"allow\"), an easy\n  // way to accidentally lock out access the rule was meant to grant.\n  const warnOmittedPermit = (): void => {\n    for (const fileTypes of Object.values(rawTypes)) {\n      for (const [typeName, type] of Object.entries(fileTypes)) {\n        const locations = findOmittedPermitRules(type.metadata.permissions);\n        if (locations.length > 0) {\n          logger.warn(\n            `TailorDB type \"${typeName}\" has permission rule(s) ${locations.join(\", \")} in object form without an explicit \"permit\"; they default to \"deny\". Set permit: true (allow) or permit: false (deny) to silence this warning.`,\n          );\n        }\n      }\n    }\n  };\n\n  /**\n   * Process plugins for a type and add generated types to rawTypes\n   * @param rawType - The raw TailorDB type being processed\n   * @param attachments - Plugin attachments for this type\n   * @param sourceFilePath - The file path where the type was loaded from\n   */\n  const processPluginsForType = async (\n    rawType: TailorDBTypeSchemaOutput,\n    attachments: PluginAttachment[],\n    sourceFilePath: string,\n  ): Promise<void> => {\n    if (!pluginManager) return;\n\n    const { extendedType, generatedTypes, events } = await pluginManager.processAttachmentsForType({\n      rawType,\n      attachments,\n      namespace,\n    });\n\n    if (extendedType) {\n      assertDefined(\n        rawTypes[sourceFilePath],\n        `raw types entry missing for file: ${sourceFilePath}`,\n      )[rawType.name] = extendedType;\n    }\n    for (const gen of generatedTypes) {\n      // Plugin-generated types don't have a source file.\n      // Generators that need to import these types should generate their own type files.\n      const sourceInfo: TypeSourceInfoEntry = {\n        exportName: gen.typeName,\n        pluginId: gen.pluginId,\n        pluginImportPath: gen.pluginImportPath,\n        originalFilePath: sourceFilePath,\n        originalExportName: typeSourceInfo[rawType.name]?.exportName || rawType.name,\n        generatedTypeKind: gen.kind,\n        pluginConfig: gen.pluginConfig,\n        namespace,\n      };\n      registerRawType(sourceFilePath, gen.typeName, gen.type, sourceInfo);\n    }\n    for (const ev of events) {\n      if (ev.kind === \"extended\") {\n        logger.log(\n          `  Extended: ${styles.success(ev.typeName)} with ${styles.highlight(ev.fieldCount.toString())} fields by plugin ${styles.info(ev.pluginId)}`,\n        );\n      } else {\n        logger.log(\n          `  Generated: ${styles.success(ev.typeName)} by plugin ${styles.info(ev.pluginId)}`,\n        );\n      }\n    }\n  };\n\n  const loadTypeFile = async (\n    typeFile: string,\n    tsconfig: string | undefined,\n  ): Promise<TailorDBTypesByName> => {\n    rawTypes[typeFile] = createRawTypesByName();\n    const loadedTypes = createRawTypesByName();\n    try {\n      const module = await import(pathToFileURL(typeFile).href);\n\n      for (const exportName of Object.keys(module)) {\n        const exportedValue = module[exportName];\n\n        const result = TailorDBTypeSchema.safeParse(exportedValue);\n        if (!result.success) {\n          if (isSdkBranded(exportedValue, \"tailordb-type\")) {\n            throw result.error;\n          }\n          continue;\n        }\n\n        const relativePath = path.relative(process.cwd(), typeFile);\n        logger.log(\n          `Type: ${styles.successBright(`\"${result.data.name}\"`)} loaded from ${styles.path(relativePath)}`,\n        );\n        await precompileTailorDBTypeScripts(result.data, typeFile, tsconfig);\n        loadedTypes[result.data.name] = result.data;\n        registerRawType(typeFile, result.data.name, result.data, {\n          filePath: typeFile,\n          exportName,\n        });\n\n        // Process plugins if any\n        if (\n          exportedValue.plugins &&\n          Array.isArray(exportedValue.plugins) &&\n          exportedValue.plugins.length > 0\n        ) {\n          pluginAttachments.set(exportedValue.name, [...exportedValue.plugins]);\n          logger.log(\n            `  Plugin attachments: ${styles.info(exportedValue.plugins.map((p: PluginAttachment) => p.pluginId).join(\", \"))}`,\n          );\n\n          await processPluginsForType(exportedValue, exportedValue.plugins, typeFile);\n        }\n      }\n    } catch (error) {\n      const relativePath = path.relative(process.cwd(), typeFile);\n      logger.error(`Failed to load type from ${styles.bold(relativePath)}`);\n      logger.error(String(error));\n      throw error;\n    }\n    return loadedTypes;\n  };\n\n  return {\n    namespace,\n    config,\n    get types() {\n      return types;\n    },\n    get typeSourceInfo() {\n      return typeSourceInfo;\n    },\n    get pluginAttachments() {\n      return pluginAttachments as ReadonlyMap<string, readonly PluginAttachment[]>;\n    },\n    loadTypes: async () => {\n      if (!loadPromise) {\n        loadPromise = (async () => {\n          if (config.files.length === 0) {\n            return undefined;\n          }\n\n          const typeFiles = [...new Set(loadFilesWithIgnores(config))];\n\n          let tsconfig: string | undefined;\n          try {\n            tsconfig = await resolveTSConfig();\n          } catch {\n            tsconfig = undefined;\n          }\n\n          logger.newline();\n          logger.log(\n            `Found ${styles.highlight(typeFiles.length.toString())} type files for TailorDB service ${styles.highlight(`\"${namespace}\"`)}`,\n          );\n\n          if (pluginManager) {\n            for (const typeFile of typeFiles) {\n              await loadTypeFile(typeFile, tsconfig);\n            }\n          } else {\n            await Promise.all(typeFiles.map((typeFile) => loadTypeFile(typeFile, tsconfig)));\n          }\n          doParseTypes();\n          warnOmittedPermit();\n          return types;\n        })();\n      }\n      return loadPromise;\n    },\n    processNamespacePlugins: async () => {\n      if (!pluginManager) return;\n\n      const results = await pluginManager.processNamespacePlugins(namespace);\n      const pluginGeneratedKey = \"__plugin_generated__\";\n\n      const successfulResults = results.map(({ pluginId, config, result }) => {\n        if (!result.success) {\n          logger.error(result.error);\n          throw new Error(result.error);\n        }\n        return { pluginId, config, output: result.output };\n      });\n\n      const hasPreviousGeneratedTypes = Object.hasOwn(rawTypes, pluginGeneratedKey);\n      const previousGeneratedTypes = rawTypes[pluginGeneratedKey];\n      const previousGeneratedTypeKeys = previousGeneratedTypes\n        ? Object.keys(previousGeneratedTypes)\n        : [];\n      const hadPreviousGeneratedTypes = previousGeneratedTypeKeys.length > 0;\n      if (hasPreviousGeneratedTypes) {\n        for (const typeName of previousGeneratedTypeKeys) {\n          delete typeSourceInfo[typeName];\n        }\n      }\n      rawTypes[pluginGeneratedKey] = createRawTypesByName();\n\n      let hasGeneratedTypes = false;\n      for (const { pluginId, config, output } of successfulResults) {\n        // Add generated types to rawTypes\n        for (const [kind, generatedType] of Object.entries(output.types ?? {})) {\n          const sourceInfo: TypeSourceInfoEntry = {\n            exportName: generatedType.name,\n            pluginId,\n            pluginImportPath: pluginManager.getPluginImportPath(pluginId) ?? \"\",\n            originalFilePath: \"\",\n            originalExportName: \"\",\n            generatedTypeKind: kind,\n            pluginConfig: config,\n            namespace,\n          };\n          registerRawType(\n            pluginGeneratedKey,\n            generatedType.name,\n            generatedType as TailorDBTypeSchemaOutput,\n            sourceInfo,\n          );\n          hasGeneratedTypes = true;\n\n          logger.log(\n            `  Generated: ${styles.success(generatedType.name)} by namespace plugin ${styles.info(pluginId)}`,\n          );\n        }\n      }\n\n      // Re-parse types to include namespace plugin types\n      if (hasGeneratedTypes || hadPreviousGeneratedTypes) {\n        doParseTypes();\n      }\n    },\n  };\n}\n","import { type TailorDBService } from \"#/cli/services/tailordb/service\";\nimport { type AuthConfigSchema } from \"#/parser/service/auth/index\";\nimport { assertDefined } from \"#/utils/assert\";\nimport type { AuthConnectionConfig } from \"#/types/auth-connection.generated\";\nimport type { z } from \"zod\";\n\n/**\n * Auth config after `AuthConfigSchema.parse`. The Zod `.brand(\"AuthConfig\")` makes\n * this type inhabitable only by parse output, so `createAuthService` can only be\n * called with a validated/transformed config (e.g. token lifetimes as Duration).\n * Passing a raw, unparsed config is a compile error.\n */\ntype ParsedAuthConfig = z.output<typeof AuthConfigSchema>;\n\ntype UserProfile = NonNullable<ParsedAuthConfig[\"userProfile\"]> & {\n  namespace: string;\n};\n\nexport type AuthService = {\n  readonly config: ParsedAuthConfig;\n  readonly tailorDBServices: ReadonlyArray<TailorDBService>;\n  readonly externalTailorDBNamespaces: ReadonlyArray<string>;\n  readonly connections: Readonly<Record<string, AuthConnectionConfig>>;\n  readonly userProfile: UserProfile | undefined;\n  resolveNamespaces: () => Promise<void>;\n};\n\n/**\n * Creates a new AuthService instance.\n * @param config - The auth configuration\n * @param tailorDBServices - The TailorDB services\n * @param externalTailorDBNamespaces - External TailorDB namespaces\n * @returns A new AuthService instance\n */\nexport function createAuthService(\n  config: ParsedAuthConfig,\n  tailorDBServices: ReadonlyArray<TailorDBService>,\n  externalTailorDBNamespaces: ReadonlyArray<string>,\n): AuthService {\n  const connections: Record<string, AuthConnectionConfig> = config.connections\n    ? { ...config.connections }\n    : {};\n\n  let userProfile: UserProfile | undefined;\n\n  return {\n    config,\n    tailorDBServices,\n    externalTailorDBNamespaces,\n    connections,\n    get userProfile() {\n      return userProfile;\n    },\n    resolveNamespaces: async () => {\n      // No userProfile defined\n      if (!config.userProfile) {\n        return;\n      }\n\n      // 1. Explicit namespace\n      if (config.userProfile.namespace) {\n        userProfile = {\n          ...config.userProfile,\n          namespace: config.userProfile.namespace,\n        };\n        return;\n      }\n\n      const totalNamespaceCount = tailorDBServices.length + externalTailorDBNamespaces.length;\n      let userProfileNamespace: string | undefined;\n\n      // 2. Single TailorDB\n      if (totalNamespaceCount === 1) {\n        userProfileNamespace =\n          tailorDBServices[0]?.namespace ??\n          assertDefined(externalTailorDBNamespaces[0], \"external TailorDB namespace missing\");\n      } else {\n        // 3. Multiple TailorDBs\n        await Promise.all(tailorDBServices.map((tailordb) => tailordb.loadTypes()));\n\n        const userProfileTypeName =\n          typeof config.userProfile.type === \"object\" && \"name\" in config.userProfile.type\n            ? config.userProfile.type.name\n            : undefined;\n\n        if (userProfileTypeName) {\n          for (const service of tailorDBServices) {\n            const types = service.types;\n            if (Object.prototype.hasOwnProperty.call(types, userProfileTypeName)) {\n              userProfileNamespace = service.namespace;\n              break;\n            }\n          }\n        }\n\n        if (!userProfileNamespace) {\n          throw new Error(\n            `userProfile type \"${config.userProfile.type.name}\" not found in any TailorDB namespace`,\n          );\n        }\n      }\n\n      userProfile = {\n        ...config.userProfile,\n        namespace: userProfileNamespace,\n      };\n    },\n  };\n}\n","import * as os from \"node:os\";\nimport pLimit from \"p-limit\";\n\n/**\n * Resolve the maximum number of bundle operations to run in parallel.\n *\n * Resolution order:\n * 1. `TAILOR_BUNDLE_CONCURRENCY` env var (positive integer)\n * 2. `os.cpus().length`, clamped to at least 1\n *\n * Each `rolldown.build` invocation drives its own module graph and Rust thread\n * pool, so unbounded parallelism can exhaust native memory on constrained\n * runners (e.g. ubuntu-latest GitHub Actions runners with hundreds of\n * resolvers). Capping at CPU count keeps the worst case predictable.\n * @returns Concurrency cap (always >= 1)\n */\nexport function resolveBundleConcurrency(): number {\n  const envValue = process.env.TAILOR_BUNDLE_CONCURRENCY;\n  if (envValue !== undefined) {\n    const trimmed = envValue.trim();\n    if (trimmed !== \"\" && /^[1-9]\\d*$/.test(trimmed)) {\n      return Number.parseInt(trimmed, 10);\n    }\n  }\n  return Math.max(1, os.cpus().length);\n}\n\n/**\n * Run an async worker over each item with the bundle-concurrency cap applied.\n * Results are returned in the same order as the input items.\n * @param items - Items to process\n * @param worker - Async worker function\n * @returns Worker results in input order\n */\nexport function withBundleConcurrency<T, R>(\n  items: T[],\n  worker: (item: T) => Promise<R>,\n): Promise<R[]> {\n  const limit = pLimit(resolveBundleConcurrency());\n  return Promise.all(items.map((item) => limit(() => worker(item))));\n}\n","/**\n * JS expressions that shape the inputs passed to user-authored code.\n *\n * Two delivery paths:\n * - Apply config: shipped with apply and evaluated by the platform before\n *   invoking user code.\n * - Bundle inline: interpolated into the generated `.entry.js` wrapper and\n *   evaluated inside the bundled script at function entry.\n *\n * The user field mapping (server → SDK) shared across services is defined in\n * `@/parser/service/tailordb` as `tailorUserMap`.\n */\nimport { tailorUserMap } from \"#/parser/service/tailordb/index\";\nimport type { Trigger } from \"#/types/executor.generated\";\n\n// ---------------------------------------------------------------------------\n// Bundle inline\n// ---------------------------------------------------------------------------\n\n/**\n * `invoker` value expression, inlined into bundler entry wrappers.\n *\n * Calls `tailor.context.getInvoker()` at function entry and maps the server\n * shape to TailorInvoker. Anonymous callers (`null`) pass through as `null`.\n */\nexport const INVOKER_EXPR = `(($raw) => $raw ? ({\n  id: $raw.id,\n  type: $raw.type,\n  workspaceId: $raw.workspaceId,\n  attributes: $raw.attributeMap,\n  attributeList: $raw.attributes,\n}) : null)(tailor.context.getInvoker())`;\n\n// ---------------------------------------------------------------------------\n// Executor\n// ---------------------------------------------------------------------------\n\n/**\n * Actor field transformation expression.\n *\n * Transforms the server's actor object to match the SDK's TailorActor type:\n *   server `attributeMap`  → SDK `attributes`\n *   server `attributes`    → SDK `attributeList`\n *   other fields           → passed through\n *   null/undefined actor   → null\n */\nconst ACTOR_TRANSFORM_EXPR =\n  `actor: args.actor ? (({ attributeMap, attributes: attrList, ...rest }) => ` +\n  `({ ...rest, attributes: attributeMap, attributeList: attrList }))(args.actor) : null`;\n\n/**\n * Build the JavaScript expression that transforms server-format executor event\n * args into SDK-format args at runtime.\n *\n * The Tailor Platform server delivers event args with server-side field names.\n * The SDK exposes different field names to user code. This function produces a\n * JavaScript expression string that performs the mapping when evaluated\n * server-side.\n * @param triggerKind - The trigger kind discriminant from the parsed executor\n * @param env - Application env record to embed in the expression\n * @returns A JavaScript expression string, e.g. `({ ...args, ... })`\n */\nexport function buildExecutorArgsExpr(\n  triggerKind: Trigger[\"kind\"],\n  env: Record<string, string | number | boolean>,\n): string {\n  const envExpr = `env: ${JSON.stringify(env)}`;\n\n  switch (triggerKind) {\n    case \"schedule\":\n      return `({ ...args, appNamespace: args.namespaceName, ${ACTOR_TRANSFORM_EXPR}, ${envExpr} })`;\n\n    case \"resolverExecuted\":\n      return `({ ...args, appNamespace: args.namespaceName, ${ACTOR_TRANSFORM_EXPR}, success: !!args.succeeded, result: args.succeeded?.result.resolver, error: args.failed?.error, ${envExpr} })`;\n\n    case \"incomingWebhook\":\n      return `({ ...args, appNamespace: args.namespaceName, rawBody: args.raw_body, ${envExpr} })`;\n\n    default:\n      // All event triggers: inject event (short name) and rawEvent (full event type) from server-side eventType\n      return `({ ...args, event: args.eventType?.split(\".\").pop(), rawEvent: args.eventType, appNamespace: args.namespaceName, ${ACTOR_TRANSFORM_EXPR}, ${envExpr} })`;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Resolver\n// ---------------------------------------------------------------------------\n\n/**\n * Build the operationHook expression for resolver pipelines.\n *\n * Transforms server context to SDK resolver context:\n *   context.args        → input\n *   context.pipeline     → spread into result\n *   user (global var)    → TailorUser (via tailorUserMap: workspace_id→workspaceId, attribute_map→attributes, attributes→attributeList)\n *   env                 → injected as JSON\n * @param env - Application env record to embed in the expression\n * @returns A JavaScript expression string for the operationHook\n */\nexport function buildResolverOperationHookExpr(\n  env: Record<string, string | number | boolean>,\n): string {\n  return `({ ...context.pipeline, input: context.args, user: ${tailorUserMap}, env: ${JSON.stringify(env)} });`;\n}\n","import { pathToFileURL } from \"node:url\";\nimport { ExecutorSchema } from \"#/parser/service/executor/index\";\nimport type { Executor } from \"#/types/executor.generated\";\n\n/**\n * Load and validate an executor definition from a file.\n * @param executorFilePath - Path to the executor file\n * @returns Parsed executor or null if invalid\n */\nexport async function loadExecutor(executorFilePath: string): Promise<Executor | null> {\n  const executorModule = await import(pathToFileURL(executorFilePath).href);\n  const executor = executorModule.default;\n\n  const parseResult = ExecutorSchema.safeParse(executor);\n  if (!parseResult.success) {\n    return null;\n  }\n\n  return parseResult.data;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { resolveTSConfig } from \"pkg-types\";\nimport * as rolldown from \"rolldown\";\nimport { computeBundlerContextHash, withCache, type BundleCache } from \"#/cli/cache/bundle-cache\";\nimport { loadFilesWithIgnores, type FileLoadConfig } from \"#/cli/services/file-loader\";\nimport { removeStaleEntryFiles } from \"#/cli/services/stale-cleanup\";\nimport { withBundleConcurrency } from \"#/cli/shared/bundle-concurrency\";\nimport { createLogLevelTreeshakeOptions } from \"#/cli/shared/bundle-log-level\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { composeFunctionTreeshakeOptions } from \"#/cli/shared/function-treeshake\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport { INVOKER_EXPR } from \"#/cli/shared/runtime-exprs\";\nimport {\n  createTriggerTransformPlugin,\n  serializeTriggerContext,\n  type TriggerContext,\n} from \"#/cli/shared/trigger-context\";\nimport ml from \"#/utils/multiline\";\nimport { loadExecutor } from \"./loader\";\nimport type { LogLevel } from \"#/configure/config/types\";\n\ninterface ExecutorInfo {\n  name: string;\n  sourceFile: string;\n}\n\n/**\n * Options for bundling executors\n */\nexport interface BundleExecutorsOptions {\n  /** Executor file loading configuration */\n  config: FileLoadConfig;\n  /** Trigger context for workflow/job transformations */\n  triggerContext?: TriggerContext;\n  /** Additional files to bundle (e.g., plugin-generated executors) */\n  additionalFiles?: string[];\n  /** Optional bundle cache for skipping unchanged builds */\n  cache?: BundleCache;\n  /** Whether to enable inline sourcemaps */\n  inlineSourcemap?: boolean;\n  /** Controls which console calls are kept in bundled code */\n  bundleLogLevel?: LogLevel;\n}\n\n/**\n * Bundle executors from the specified configuration\n *\n * This function:\n * 1. Creates entry file that extracts operation.body\n * 2. Bundles in a single step with tree-shaking\n * @param options - Bundle executor options\n * @returns Map of executor name to bundled code\n */\nexport async function bundleExecutors(\n  options: BundleExecutorsOptions,\n): Promise<Map<string, string>> {\n  const bundledCode = new Map<string, string>();\n  const {\n    config,\n    triggerContext,\n    additionalFiles = [],\n    cache,\n    inlineSourcemap,\n    bundleLogLevel = \"DEBUG\",\n  } = options;\n  const configFiles = loadFilesWithIgnores(config);\n  const files = [...configFiles, ...additionalFiles];\n  if (files.length === 0) {\n    logger.warn(`No executor files found for patterns: ${config.files.join(\", \")}`);\n    return bundledCode;\n  }\n\n  logger.newline();\n  logger.log(\n    `Bundling ${styles.highlight(files.length.toString())} files for ${styles.info('\"executor\"')}`,\n  );\n\n  // Load all executors and filter to function/jobFunction only\n  const executors: ExecutorInfo[] = [];\n  for (const file of files) {\n    const executor = await loadExecutor(file);\n    if (!executor) {\n      logger.debug(`  Skipping: ${file} (could not be loaded)`);\n      continue;\n    }\n\n    // Only bundle function and jobFunction executors\n    if (![\"function\", \"jobFunction\"].includes(executor.operation.kind)) {\n      logger.debug(`  Skipping: ${executor.name} (not a function executor)`);\n      continue;\n    }\n\n    executors.push({\n      name: executor.name,\n      sourceFile: file,\n    });\n  }\n\n  if (executors.length === 0) {\n    logger.debug(\"  No function executors to bundle\");\n    return bundledCode;\n  }\n\n  const outputDir = path.resolve(getDistDir(), \"executors\");\n\n  fs.mkdirSync(outputDir, { recursive: true });\n\n  // Clean stale entry files from previous builds.\n  // Must complete before Promise.all below; parallel processing\n  // would require separate output directories.\n  await removeStaleEntryFiles(outputDir);\n\n  let tsconfig: string | undefined;\n  try {\n    tsconfig = await resolveTSConfig();\n  } catch {\n    tsconfig = undefined;\n  }\n\n  // Process each executor, capped by TAILOR_BUNDLE_CONCURRENCY to bound native\n  // memory use (each rolldown.build allocates its own module graph).\n  const results = await withBundleConcurrency(executors, (executor) =>\n    bundleSingleExecutor(\n      executor,\n      outputDir,\n      tsconfig,\n      triggerContext,\n      cache,\n      inlineSourcemap,\n      bundleLogLevel,\n    ),\n  );\n\n  for (const [name, code] of results) {\n    bundledCode.set(name, code);\n  }\n\n  logger.log(`${styles.success(\"Bundled\")} ${styles.info('\"executor\"')}`);\n\n  return bundledCode;\n}\n\nasync function bundleSingleExecutor(\n  executor: ExecutorInfo,\n  outputDir: string,\n  tsconfig: string | undefined,\n  triggerContext?: TriggerContext,\n  cache?: BundleCache,\n  inlineSourcemap?: boolean,\n  bundleLogLevel: LogLevel = \"DEBUG\",\n): Promise<[string, string]> {\n  const serializedTriggerContext = serializeTriggerContext(triggerContext);\n\n  const contextHash = computeBundlerContextHash({\n    sourceFile: executor.sourceFile,\n    serializedTriggerContext,\n    tsconfig,\n    inlineSourcemap,\n    bundleLogLevel,\n  });\n\n  const code = await withCache({\n    cache,\n    kind: \"executor\",\n    name: executor.name,\n    sourceFile: executor.sourceFile,\n    contextHash,\n    async build(cachePlugins) {\n      // Step 1: Create entry file that imports and extracts operation.body\n      const entryPath = path.join(outputDir, `${executor.name}.entry.js`);\n      const absoluteSourcePath = path.resolve(executor.sourceFile);\n\n      const entryContent = ml /* js */ `\n        import _internalExecutor from \"${absoluteSourcePath}\";\n\n        const __executor_function = async (args) => {\n          const invoker = ${INVOKER_EXPR};\n          return _internalExecutor.operation.body({ ...args, invoker });\n        };\n\n        export { __executor_function as main };\n      `;\n      fs.writeFileSync(entryPath, entryContent);\n\n      // Step 2: Bundle with tree-shaking (write: false to avoid unnecessary disk I/O)\n      const triggerPlugin = createTriggerTransformPlugin(triggerContext);\n      const plugins: rolldown.Plugin[] = triggerPlugin ? [triggerPlugin] : [];\n      plugins.push(platformBundleDefinePlugin, ...cachePlugins);\n\n      const result = await rolldown.build({\n        input: entryPath,\n        write: false,\n        output: {\n          format: \"esm\",\n          sourcemap: inlineSourcemap ? \"inline\" : true,\n          minify: inlineSourcemap\n            ? {\n                mangle: {\n                  keepNames: true,\n                },\n              }\n            : true,\n          codeSplitting: false,\n        },\n        tsconfig,\n        plugins,\n        treeshake: composeFunctionTreeshakeOptions([\n          createLogLevelTreeshakeOptions(bundleLogLevel),\n        ]),\n        logLevel: \"silent\",\n      } as rolldown.BuildOptions);\n\n      return result.output[0].code;\n    },\n  });\n\n  return [executor.name, code];\n}\n","import { builtinModules } from \"node:module\";\n\n// Sobek does not implement Node's host APIs. Reject every Node built-in\n// (including subpath imports like `fs/promises`) and the `node:` prefix.\n// Internal `_*` modules are excluded since they are never valid user imports.\nconst NODE_BUILTINS = new Set(builtinModules.filter((m) => !m.startsWith(\"_\")));\n\nexport function isNodeBuiltinImport(source: string): boolean {\n  if (source.startsWith(\"node:\")) return true;\n  const root = source.includes(\"/\") ? source.slice(0, source.indexOf(\"/\")) : source;\n  return NODE_BUILTINS.has(root);\n}\n","import type { HttpAdapterConfigInput } from \"#/types/http-adapter.generated\";\n\n/**\n * Maps the lowercase `input` handler keys to the HTTP methods they serve.\n * The key set is tied to `inputHandlersSchema` in `./schema` via the\n * zinfer-generated config type, so the two cannot drift apart.\n */\nexport const HTTP_METHODS = {\n  get: \"GET\",\n  post: \"POST\",\n  put: \"PUT\",\n  patch: \"PATCH\",\n  delete: \"DELETE\",\n} as const satisfies Record<keyof Required<HttpAdapterConfigInput[\"input\"]>, string>;\n\nexport type HttpMethodKey = keyof typeof HTTP_METHODS;\n\nexport const HTTP_METHOD_KEYS = Object.keys(HTTP_METHODS) as readonly HttpMethodKey[];\n","import { z } from \"zod\";\nimport { functionSchema } from \"../common\";\n\nconst NAME_PATTERN = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;\n\nconst inputHandlersSchema = z\n  .strictObject({\n    get: functionSchema.optional().describe(\"Handler for GET requests\"),\n    post: functionSchema.optional().describe(\"Handler for POST requests\"),\n    put: functionSchema.optional().describe(\"Handler for PUT requests\"),\n    patch: functionSchema.optional().describe(\"Handler for PATCH requests\"),\n    delete: functionSchema.optional().describe(\"Handler for DELETE requests\"),\n  })\n  .refine(\n    // optional fields become undefined after zod parses them\n    // oxlint-disable-next-line typescript/no-unnecessary-condition\n    (val) => Object.values(val).some((v) => v !== undefined),\n    \"input must declare at least one HTTP method handler\",\n  )\n  .describe(\"Per-method functions that transform HTTP requests to GraphQL requests\");\n\nexport const HttpAdapterConfigSchema = z\n  .strictObject({\n    name: z\n      .string()\n      .regex(\n        NAME_PATTERN,\n        \"name must be 3-63 chars, lowercase alphanumeric with hyphens, not starting or ending with a hyphen\",\n      )\n      .describe(\"Unique adapter name within the domain\"),\n    pathPattern: z\n      .string()\n      .min(1)\n      .describe(\"Path pattern with segment wildcards (trailing or single-segment)\"),\n    enabled: z.boolean().default(true).describe(\"Whether the adapter is active\"),\n    priority: z\n      .number()\n      .int()\n      .min(0)\n      .default(0)\n      .describe(\"Matching priority; the lowest value wins when multiple adapters match\"),\n    input: inputHandlersSchema,\n    output: functionSchema\n      .optional()\n      .describe(\"Function that transforms GraphQL response to HTTP response\"),\n  })\n  .brand(\"HttpAdapterConfig\");\n","import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { parseSync } from \"oxc-parser\";\nimport * as path from \"pathe\";\nimport { resolveTSConfig } from \"pkg-types\";\nimport * as rolldown from \"rolldown\";\nimport { computeBundlerContextHash, withCache, type BundleCache } from \"#/cli/cache/bundle-cache\";\nimport { isNodeBuiltinImport } from \"#/cli/services/http-adapter/node-builtins\";\nimport { withBundleConcurrency } from \"#/cli/shared/bundle-concurrency\";\nimport { createLogLevelTreeshakeOptions } from \"#/cli/shared/bundle-log-level\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { composeFunctionTreeshakeOptions } from \"#/cli/shared/function-treeshake\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { HTTP_METHODS, type HttpMethodKey } from \"#/parser/service/http-adapter/index\";\nimport type { LogLevel } from \"#/configure/config/types\";\n\nconst ADAPTER_BUNDLE_WARN_BYTES = 64 * 1024;\nconst ADAPTER_BUNDLE_ERROR_BYTES = 256 * 1024;\nconst nodeRequire = createRequire(import.meta.url);\nconst GRAPHQL_WEB_MODULE = nodeRequire.resolve(\"@0no-co/graphql.web\");\n\nexport interface HttpAdapterBundleInput {\n  name: string;\n  sourceFile: string;\n  methods: HttpMethodKey[];\n  hasOutput: boolean;\n}\n\nexport interface HttpAdapterBundleResult {\n  /** Adapter name → bundled input JS string. */\n  bundledInputs: Map<string, string>;\n  /** Adapter name → bundled output JS string. Only populated when the adapter has an output. */\n  bundledOutputs: Map<string, string>;\n}\n\n/**\n * Bundle each adapter's `input` (and `output`, if present) into a standalone\n * IIFE defining a global `transform(input)` entry point. `input` gets a\n * generated dispatcher that routes by `req.method`; `output` is used as is.\n * @param adapters - Detected adapters to bundle\n * @param cache - Optional bundle cache for skipping unchanged builds\n * @param bundleLogLevel - Controls which console calls are kept in bundled code\n * @returns Bundled scripts keyed by adapter name\n */\nexport async function bundleHttpAdapters(\n  adapters: HttpAdapterBundleInput[],\n  cache?: BundleCache,\n  bundleLogLevel: LogLevel = \"DEBUG\",\n): Promise<HttpAdapterBundleResult> {\n  if (adapters.length === 0) {\n    return { bundledInputs: new Map(), bundledOutputs: new Map() };\n  }\n\n  logger.newline();\n  logger.log(\n    `Bundling ${styles.highlight(adapters.length.toString())} files for ${styles.info('\"http-adapter\"')}`,\n  );\n\n  const outputDir = path.resolve(getDistDir(), \"http-adapters\");\n  fs.mkdirSync(outputDir, { recursive: true });\n\n  let tsconfig: string | undefined;\n  try {\n    tsconfig = await resolveTSConfig();\n  } catch {\n    tsconfig = undefined;\n  }\n\n  // rolldown.build() is memory-intensive; cap parallelism like the other SDK bundlers.\n  const tasks = adapters.flatMap((adapter) => {\n    const kinds: Array<\"input\" | \"output\"> = adapter.hasOutput ? [\"input\", \"output\"] : [\"input\"];\n    return kinds.map((kind) => ({ adapter, kind }));\n  });\n  const results = await withBundleConcurrency(tasks, ({ adapter, kind }) =>\n    bundleAdapterScript(adapter, kind, outputDir, tsconfig, cache, bundleLogLevel),\n  );\n\n  const bundledInputs = new Map<string, string>();\n  const bundledOutputs = new Map<string, string>();\n  for (const [name, kind, code] of results) {\n    if (kind === \"input\") {\n      bundledInputs.set(name, code);\n    } else {\n      bundledOutputs.set(name, code);\n    }\n  }\n\n  logger.log(`${styles.success(\"Bundled\")} ${styles.info('\"http-adapter\"')}`);\n\n  return { bundledInputs, bundledOutputs };\n}\n\nasync function bundleAdapterScript(\n  adapter: HttpAdapterBundleInput,\n  kind: \"input\" | \"output\",\n  outputDir: string,\n  tsconfig: string | undefined,\n  cache: BundleCache | undefined,\n  bundleLogLevel: LogLevel = \"DEBUG\",\n): Promise<[string, \"input\" | \"output\", string]> {\n  const contextHash = computeBundlerContextHash({\n    sourceFile: adapter.sourceFile,\n    serializedTriggerContext: kind === \"input\" ? adapter.methods.join(\",\") : \"\",\n    tsconfig,\n    inlineSourcemap: false,\n    bundleLogLevel,\n    prefix: `${kind}:document-query-normalize-v1`,\n  });\n\n  const code = await withCache({\n    cache,\n    kind: kind === \"input\" ? \"http-adapter-input\" : \"http-adapter-output\",\n    name: adapter.name,\n    sourceFile: adapter.sourceFile,\n    contextHash,\n    async build(cachePlugins) {\n      const entryPath = path.join(outputDir, `${adapter.name}.${kind}.entry.js`);\n      const absoluteSourcePath = path.resolve(adapter.sourceFile);\n\n      const rejectNodeImports: rolldown.Plugin = {\n        name: \"http-adapter-reject-node-imports\",\n        resolveId(source) {\n          if (isNodeBuiltinImport(source)) {\n            throw new Error(\n              `HTTP adapter \"${adapter.name}\" imports Node module \"${source}\", which is unavailable in the gateway runtime`,\n            );\n          }\n          return null;\n        },\n      };\n\n      // Stub out `@tailor-platform/sdk` imports: only the brand matters at\n      // build time, and the IIFE must not depend on external globals.\n      const stubSdkImports: rolldown.Plugin = {\n        name: \"http-adapter-stub-sdk\",\n        resolveId(source) {\n          if (source === \"@tailor-platform/sdk\" || source.startsWith(\"@tailor-platform/sdk/\")) {\n            return { id: \"\\0http-adapter-sdk-stub\", moduleSideEffects: false };\n          }\n          return null;\n        },\n        load(id) {\n          if (id === \"\\0http-adapter-sdk-stub\") {\n            return \"export const createHttpAdapter = (cfg) => cfg;\\nexport default { createHttpAdapter };\\n\";\n          }\n          return null;\n        },\n      };\n\n      const plugins: rolldown.Plugin[] = [rejectNodeImports, stubSdkImports, ...cachePlugins];\n\n      let bundled: string;\n      try {\n        const entryContent =\n          kind === \"input\"\n            ? buildInputEntry(absoluteSourcePath, adapter.methods, GRAPHQL_WEB_MODULE)\n            : buildOutputEntry(absoluteSourcePath);\n        fs.writeFileSync(entryPath, entryContent);\n        const result = await rolldown.build({\n          input: entryPath,\n          write: false,\n          output: {\n            format: \"iife\",\n            sourcemap: false,\n            minify: true,\n            codeSplitting: false,\n          },\n          tsconfig,\n          plugins,\n          // es2017 on purpose: async/await must survive downleveling so\n          // rejectAsyncInBundle can reject it (lower targets rewrite it into\n          // generator+Promise code that evades the check and breaks on Sobek).\n          transform: { target: \"es2017\" },\n          treeshake: composeFunctionTreeshakeOptions([\n            createLogLevelTreeshakeOptions(bundleLogLevel),\n          ]),\n          logLevel: \"silent\",\n        } as rolldown.BuildOptions);\n        bundled = result.output[0].code;\n      } finally {\n        try {\n          fs.rmSync(entryPath, { force: true });\n        } catch {\n          // best-effort cleanup\n        }\n      }\n\n      const byteLength = Buffer.byteLength(bundled, \"utf8\");\n      if (byteLength > ADAPTER_BUNDLE_ERROR_BYTES) {\n        throw new Error(\n          `HTTP adapter \"${adapter.name}\" ${kind} script is ${byteLength} bytes, exceeding the ${ADAPTER_BUNDLE_ERROR_BYTES} byte limit`,\n        );\n      }\n      if (byteLength > ADAPTER_BUNDLE_WARN_BYTES) {\n        logger.warn(\n          `HTTP adapter \"${adapter.name}\" ${kind} script is ${byteLength} bytes, larger than the recommended ${ADAPTER_BUNDLE_WARN_BYTES} byte limit`,\n        );\n      }\n\n      // Load-time checks only see the handler functions; imported helpers can\n      // still introduce async/await, so verify the whole bundle is synchronous.\n      rejectAsyncInBundle(bundled, adapter.name, kind);\n\n      return bundled;\n    },\n  });\n\n  return [adapter.name, kind, code];\n}\n\nfunction buildInputEntry(\n  absoluteSourcePath: string,\n  methods: HttpMethodKey[],\n  graphqlPrinterModule: string,\n): string {\n  const cases = methods\n    .map((method) => {\n      const result = `__adapter.input.${method}(req)`;\n      const expression = `__normalizeHttpAdapterGraphQLRequest(${result})`;\n      return `    case \"${HTTP_METHODS[method]}\": return ${expression};`;\n    })\n    .join(\"\\n\");\n  const supported = methods.map((m) => HTTP_METHODS[m]).join(\", \");\n  const documentNormalizer = `import { print as __printHttpAdapterDocument } from ${JSON.stringify(graphqlPrinterModule)};\nfunction __normalizeHttpAdapterGraphQLRequest(result) {\n  if (!result || typeof result.query === \"string\") {\n    return result;\n  }\n  return { ...result, query: __printHttpAdapterDocument(result.query) };\n}\n`;\n  return `${documentNormalizer}import __adapter from ${JSON.stringify(absoluteSourcePath)};\nglobalThis.transform = function(req) {\n  switch (req.method) {\n${cases}\n    default: throw new Error(\"HTTP adapter received unsupported method: \" + req.method + \" (supported: ${supported})\");\n  }\n};\n`;\n}\n\nfunction buildOutputEntry(absoluteSourcePath: string): string {\n  return `import __adapter from ${JSON.stringify(absoluteSourcePath)};\nglobalThis.transform = __adapter.output;\n`;\n}\n\nfunction rejectAsyncInBundle(code: string, adapterName: string, kind: \"input\" | \"output\"): void {\n  // Use a fake filename so oxc treats this as a module. The bundle is already\n  // minified IIFE; oxc parses it without complaint.\n  const { program } = parseSync(`${adapterName}.${kind}.bundle.js`, code);\n\n  let asyncFound = false;\n  const stack: unknown[] = [program];\n  while (stack.length > 0) {\n    const node = stack.pop();\n    if (!node || typeof node !== \"object\") continue;\n    const n = node as Record<string, unknown>;\n    const type = typeof n.type === \"string\" ? (n.type as string) : \"\";\n    if (type === \"AwaitExpression\") {\n      asyncFound = true;\n      break;\n    }\n    if (\n      (type === \"FunctionDeclaration\" ||\n        type === \"FunctionExpression\" ||\n        type === \"ArrowFunctionExpression\") &&\n      n.async === true\n    ) {\n      asyncFound = true;\n      break;\n    }\n    if ((type === \"ForOfStatement\" || type === \"ForStatement\") && n.await === true) {\n      asyncFound = true;\n      break;\n    }\n    for (const key of Object.keys(n)) {\n      const child = n[key];\n      if (Array.isArray(child)) {\n        for (const c of child) stack.push(c);\n      } else if (child && typeof child === \"object\") {\n        stack.push(child);\n      }\n    }\n  }\n\n  if (asyncFound) {\n    throw new Error(\n      `HTTP adapter \"${adapterName}\" ${kind} bundle contains async/await, which is unavailable in the gateway runtime. ` +\n        `Check imported helper modules — even if your handler is synchronous, an async helper will fail at runtime.`,\n    );\n  }\n}\n","import { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport { loadFilesWithIgnores } from \"#/cli/services/file-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { type HttpAdapterServiceInput } from \"#/configure/config/types\";\nimport {\n  HTTP_METHOD_KEYS,\n  HttpAdapterConfigSchema,\n  type HttpMethodKey,\n} from \"#/parser/service/http-adapter/index\";\nimport { type HttpAdapterConfig } from \"#/types/http-adapter.generated\";\nimport { isSdkBranded } from \"#/utils/brand\";\n\nexport type HttpAdapterServiceConfig = HttpAdapterServiceInput;\n\nexport type LoadedHttpAdapter = {\n  adapter: HttpAdapterConfig;\n  sourceFile: string;\n  methods: HttpMethodKey[];\n  hasOutput: boolean;\n};\n\nexport type HttpAdapterService = {\n  readonly config: HttpAdapterServiceConfig;\n  readonly adapters: ReadonlyArray<LoadedHttpAdapter>;\n  readonly fileCount: number;\n  loadAdapters: () => Promise<void>;\n  printLoadedAdapters: () => void;\n};\n\nexport interface CreateHttpAdapterServiceParams {\n  config: HttpAdapterServiceConfig;\n}\n\nexport function createHttpAdapterService(\n  params: CreateHttpAdapterServiceParams,\n): HttpAdapterService {\n  const { config } = params;\n  let adapters: LoadedHttpAdapter[] = [];\n  let fileCount = 0;\n  let loaded = false;\n\n  return {\n    config,\n    get adapters() {\n      return adapters;\n    },\n    get fileCount() {\n      return fileCount;\n    },\n    loadAdapters: async () => {\n      if (loaded) return;\n      const result = await loadAdapterFiles(config);\n      adapters = result.adapters;\n      fileCount = result.fileCount;\n      loaded = true;\n    },\n    printLoadedAdapters: () => {\n      if (adapters.length === 0) return;\n      logger.newline();\n      logger.log(`Found ${styles.highlight(adapters.length.toString())} HTTP adapters`);\n      for (const { adapter, sourceFile } of adapters) {\n        const relativePath = path.relative(process.cwd(), sourceFile);\n        logger.log(\n          `HTTP adapter: ${styles.successBright(\n            `\"${adapter.name}\"`,\n          )} loaded from ${styles.path(relativePath)}`,\n        );\n      }\n    },\n  };\n}\n\nasync function loadAdapterFiles(\n  config: HttpAdapterServiceConfig,\n): Promise<{ adapters: LoadedHttpAdapter[]; fileCount: number }> {\n  if (config.files.length === 0) {\n    return { adapters: [], fileCount: 0 };\n  }\n\n  const files = loadFilesWithIgnores(config);\n\n  // Import every matched file and keep the ones whose default export is a\n  // createHttpAdapter() result, mirroring the resolver/executor loaders.\n  // Matched files without one (e.g. shared helpers) are skipped.\n  const loadResults = await Promise.all(files.map(loadAdapterFromFile));\n\n  const adapters: LoadedHttpAdapter[] = [];\n  const seenNames = new Map<string, string>();\n  for (const result of loadResults) {\n    if (!result) continue;\n    const existing = seenNames.get(result.adapter.name);\n    if (existing) {\n      throw new Error(\n        `Duplicate HTTP adapter name \"${result.adapter.name}\" found:\\n` +\n          `  - ${existing}\\n` +\n          `  - ${result.sourceFile}\\n` +\n          `Each HTTP adapter must have a unique name.`,\n      );\n    }\n    seenNames.set(result.adapter.name, result.sourceFile);\n    adapters.push(result);\n  }\n\n  return { adapters, fileCount: files.length };\n}\n\nasync function loadAdapterFromFile(filePath: string): Promise<LoadedHttpAdapter | null> {\n  try {\n    const module = (await import(pathToFileURL(filePath).href)) as Record<string, unknown>;\n    // Only a createHttpAdapter() result is a valid default export; a plain\n    // object that happens to match the schema is rejected by the brand check.\n    if (!isSdkBranded(module.default, \"http-adapter\")) {\n      // Not an adapter file (e.g. a shared helper matched by the glob). Guard\n      // against an adapter that is only exported under a named export, which\n      // would otherwise silently disappear from the deployment.\n      const named = Object.entries(module).find(\n        ([exportName, value]) => exportName !== \"default\" && isSdkBranded(value, \"http-adapter\"),\n      );\n      if (named) {\n        throw new Error(\n          `HTTP adapter must be the default export, but it is exported as \\`${named[0]}\\`. ` +\n            \"Re-export it: `export default createHttpAdapter({...})`.\",\n        );\n      }\n      return null;\n    }\n\n    const parsed = HttpAdapterConfigSchema.safeParse(module.default);\n    if (!parsed.success) {\n      throw parsed.error;\n    }\n\n    const adapter = parsed.data as unknown as HttpAdapterConfig;\n    const methods = collectMethodKeys(adapter);\n    rejectAsyncHandlers(adapter, methods, filePath);\n\n    return {\n      adapter,\n      sourceFile: filePath,\n      methods,\n      hasOutput: adapter.output !== undefined,\n    };\n  } catch (error) {\n    const relativePath = path.relative(process.cwd(), filePath);\n    logger.error(\n      `${styles.error(\"Failed to load HTTP adapter from\")} ${styles.errorBright(relativePath)}`,\n    );\n    logger.error(String(error));\n    throw error;\n  }\n}\n\nfunction collectMethodKeys(adapter: HttpAdapterConfig): HttpMethodKey[] {\n  const input = adapter.input as Partial<Record<HttpMethodKey, unknown>>;\n  return HTTP_METHOD_KEYS.filter((key) => typeof input[key] === \"function\");\n}\n\nfunction rejectAsyncHandlers(\n  adapter: HttpAdapterConfig,\n  methods: HttpMethodKey[],\n  sourceFile: string,\n): void {\n  const input = adapter.input as Partial<Record<HttpMethodKey, unknown>>;\n  for (const method of methods) {\n    if (isAsyncFunction(input[method])) {\n      throw new Error(\n        `HTTP adapter \"${adapter.name}\" in ${sourceFile} has an async \\`input.${method}\\` function. ` +\n          `Handlers must be synchronous; async/await is not supported.`,\n      );\n    }\n  }\n  if (adapter.output !== undefined && isAsyncFunction(adapter.output)) {\n    throw new Error(\n      `HTTP adapter \"${adapter.name}\" in ${sourceFile} has an async \\`output\\` function. ` +\n        `Handlers must be synchronous; async/await is not supported.`,\n    );\n  }\n}\n\nfunction isAsyncFunction(fn: unknown): boolean {\n  return typeof fn === \"function\" && fn.constructor.name === \"AsyncFunction\";\n}\n","import { z } from \"zod\";\nimport { AuthInvokerSchema } from \"#/parser/service/auth/schema\";\nimport { TailorFieldSchema } from \"#/parser/service/field/schema\";\nimport { functionSchema } from \"../common\";\n\nexport const QueryTypeSchema = z\n  .union([z.literal(\"query\"), z.literal(\"mutation\")])\n  .describe(\"GraphQL operation type\");\n\nexport const ResolverSchema = z.object({\n  operation: QueryTypeSchema.describe(\"GraphQL operation type (query or mutation)\"),\n  name: z.string().describe(\"Resolver name\"),\n  description: z.string().optional().describe(\"Resolver description\"),\n  input: z.record(z.string(), TailorFieldSchema).optional().describe(\"Input field definitions\"),\n  body: functionSchema.describe(\"Resolver implementation function\"),\n  output: TailorFieldSchema.describe(\"Output field definition\"),\n  publishEvents: z.boolean().optional().describe(\"Enable publishing events from this resolver\"),\n  authInvoker: AuthInvokerSchema.optional().describe(\"Machine user to execute this resolver as\"),\n});\n","import { pathToFileURL } from \"node:url\";\nimport { ResolverSchema } from \"#/parser/service/resolver/index\";\nimport type { Resolver } from \"#/types/resolver.generated\";\n\n/**\n * Load and validate a resolver definition from a file.\n * @param resolverFilePath - Path to the resolver file\n * @returns Parsed resolver or null if invalid\n */\nexport async function loadResolver(resolverFilePath: string): Promise<Resolver | null> {\n  const resolverModule = await import(pathToFileURL(resolverFilePath).href);\n  const resolver = resolverModule.default;\n\n  const parseResult = ResolverSchema.safeParse(resolver);\n  if (!parseResult.success) {\n    return null;\n  }\n\n  return parseResult.data;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { resolveTSConfig } from \"pkg-types\";\nimport * as rolldown from \"rolldown\";\nimport { type BundleCache, computeBundlerContextHash, withCache } from \"#/cli/cache/bundle-cache\";\nimport { type FileLoadConfig, loadFilesWithIgnores } from \"#/cli/services/file-loader\";\nimport { removeStaleEntryFiles } from \"#/cli/services/stale-cleanup\";\nimport { withBundleConcurrency } from \"#/cli/shared/bundle-concurrency\";\nimport { createLogLevelTreeshakeOptions } from \"#/cli/shared/bundle-log-level\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { composeFunctionTreeshakeOptions } from \"#/cli/shared/function-treeshake\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport { INVOKER_EXPR } from \"#/cli/shared/runtime-exprs\";\nimport {\n  createTriggerTransformPlugin,\n  serializeTriggerContext,\n  type TriggerContext,\n} from \"#/cli/shared/trigger-context\";\nimport ml from \"#/utils/multiline\";\nimport { loadResolver } from \"./loader\";\nimport type { LogLevel } from \"#/configure/config/types\";\n\ninterface ResolverInfo {\n  name: string;\n  sourceFile: string;\n}\n\n/**\n * Bundle resolvers for the specified namespace\n *\n * This function:\n * 1. Uses a transform plugin to add validation wrapper during bundling\n * 2. Creates entry file\n * 3. Bundles in a single step with tree-shaking\n * @param namespace - Resolver namespace name\n * @param config - Resolver file loading configuration\n * @param triggerContext - Trigger context for workflow/job transformations\n * @param cache - Optional bundle cache for skipping unchanged builds\n * @param inlineSourcemap - Whether to enable inline sourcemaps\n * @param bundleLogLevel - Controls which console calls are kept in bundled code\n * @returns Map of resolver name to bundled code\n */\nexport async function bundleResolvers(\n  namespace: string,\n  config: FileLoadConfig,\n  triggerContext?: TriggerContext,\n  cache?: BundleCache,\n  inlineSourcemap?: boolean,\n  bundleLogLevel: LogLevel = \"DEBUG\",\n): Promise<Map<string, string>> {\n  const bundledCode = new Map<string, string>();\n  const files = loadFilesWithIgnores(config);\n  if (files.length === 0) {\n    logger.warn(`No resolver files found for patterns: ${config.files.join(\", \")}`);\n    return bundledCode;\n  }\n\n  logger.newline();\n  logger.log(\n    `Bundling ${styles.highlight(files.length.toString())} files for ${styles.info(\n      `\"${namespace}\"`,\n    )}`,\n  );\n\n  // Load all resolvers to get their names\n  const resolvers: ResolverInfo[] = [];\n  for (const file of files) {\n    const resolver = await loadResolver(file);\n    if (!resolver) {\n      logger.debug(`  Skipping: ${file} (could not be loaded)`);\n      continue;\n    }\n    resolvers.push({\n      name: resolver.name,\n      sourceFile: file,\n    });\n  }\n\n  const outputDir = path.resolve(getDistDir(), \"resolvers\");\n\n  fs.mkdirSync(outputDir, { recursive: true });\n\n  // Clean stale entry files from previous builds.\n  // Must complete before Promise.all below; parallel namespace processing\n  // would require separate output directories per namespace.\n  await removeStaleEntryFiles(outputDir);\n\n  let tsconfig: string | undefined;\n  try {\n    tsconfig = await resolveTSConfig();\n  } catch {\n    tsconfig = undefined;\n  }\n\n  // Process each resolver, capped by TAILOR_BUNDLE_CONCURRENCY to bound native\n  // memory use (each rolldown.build allocates its own module graph).\n  const results = await withBundleConcurrency(resolvers, (resolver) =>\n    bundleSingleResolver(\n      resolver,\n      outputDir,\n      tsconfig,\n      triggerContext,\n      cache,\n      inlineSourcemap,\n      bundleLogLevel,\n    ),\n  );\n\n  for (const [name, code] of results) {\n    bundledCode.set(name, code);\n  }\n\n  logger.log(`${styles.success(\"Bundled\")} ${styles.info(`\"${namespace}\"`)}`);\n\n  return bundledCode;\n}\n\nasync function bundleSingleResolver(\n  resolver: ResolverInfo,\n  outputDir: string,\n  tsconfig: string | undefined,\n  triggerContext?: TriggerContext,\n  cache?: BundleCache,\n  inlineSourcemap?: boolean,\n  bundleLogLevel: LogLevel = \"DEBUG\",\n): Promise<[string, string]> {\n  const serializedTriggerContext = serializeTriggerContext(triggerContext);\n\n  const contextHash = computeBundlerContextHash({\n    sourceFile: resolver.sourceFile,\n    serializedTriggerContext,\n    tsconfig,\n    inlineSourcemap,\n    bundleLogLevel,\n  });\n\n  const code = await withCache({\n    cache,\n    kind: \"resolver\",\n    name: resolver.name,\n    sourceFile: resolver.sourceFile,\n    contextHash,\n    async build(cachePlugins) {\n      // Step 1: Create entry file that imports from the original source\n      const entryPath = path.join(outputDir, `${resolver.name}.entry.js`);\n      const absoluteSourcePath = path.resolve(resolver.sourceFile);\n\n      const entryContent = ml /* js */ `\n        import _internalResolver from \"${absoluteSourcePath}\";\n        import { t } from \"@tailor-platform/sdk\";\n\n        const $tailor_resolver_body = async (context) => {\n          const invoker = ${INVOKER_EXPR};\n          if (_internalResolver.input) {\n            const result = t.object(_internalResolver.input).parse({\n              value: context.input,\n              data: context.input,\n              user: context.user,\n            });\n\n            if (result.issues) {\n              throw new TailorErrors(result.issues.map(issue => ({\n                message: issue.message,\n                path: issue.path ?? [],\n              })));\n            }\n          }\n\n          return _internalResolver.body({ ...context, invoker });\n        };\n\n        export { $tailor_resolver_body as main };\n      `;\n      fs.writeFileSync(entryPath, entryContent);\n\n      // Step 2: Bundle with tree-shaking (write: false to avoid unnecessary disk I/O)\n      const triggerPlugin = createTriggerTransformPlugin(triggerContext);\n      const plugins: rolldown.Plugin[] = triggerPlugin ? [triggerPlugin] : [];\n      plugins.push(platformBundleDefinePlugin, ...cachePlugins);\n\n      const result = await rolldown.build({\n        input: entryPath,\n        write: false,\n        output: {\n          format: \"esm\",\n          sourcemap: inlineSourcemap ? \"inline\" : true,\n          minify: inlineSourcemap\n            ? {\n                mangle: {\n                  keepNames: true,\n                },\n              }\n            : true,\n          codeSplitting: false,\n        },\n        tsconfig,\n        plugins,\n        treeshake: composeFunctionTreeshakeOptions([\n          createLogLevelTreeshakeOptions(bundleLogLevel),\n        ]),\n        logLevel: \"silent\",\n      } as rolldown.BuildOptions);\n\n      return result.output[0].code;\n    },\n  });\n\n  return [resolver.name, code];\n}\n","import { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport { loadFilesWithIgnores } from \"#/cli/services/file-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { ResolverSchema } from \"#/parser/service/resolver/index\";\nimport { isSdkBranded } from \"#/utils/brand\";\nimport type { ResolverServiceConfig } from \"#/configure/config/types\";\nimport type { Resolver } from \"#/types/resolver.generated\";\n\nexport type ResolverService = {\n  readonly namespace: string;\n  readonly config: ResolverServiceConfig;\n  readonly resolvers: Record<string, Resolver>;\n  loadResolvers: () => Promise<void>;\n};\n\n/**\n * Creates a new ResolverService instance.\n * @param namespace - The namespace for this resolver service\n * @param config - The resolver service configuration\n * @returns A new ResolverService instance\n */\nexport function createResolverService(\n  namespace: string,\n  config: ResolverServiceConfig,\n): ResolverService {\n  const resolvers: Record<string, Resolver> = {};\n\n  const loadResolverForFile = async (resolverFile: string): Promise<Resolver | undefined> => {\n    try {\n      const resolverModule = await import(pathToFileURL(resolverFile).href);\n      const result = ResolverSchema.safeParse(resolverModule.default);\n      if (result.success) {\n        const relativePath = path.relative(process.cwd(), resolverFile);\n        logger.log(\n          `Resolver: ${styles.successBright(`\"${result.data.name}\"`)} loaded from ${styles.path(relativePath)}`,\n        );\n        resolvers[resolverFile] = result.data;\n        return result.data;\n      }\n      if (isSdkBranded(resolverModule.default, \"resolver\")) {\n        throw result.error;\n      }\n    } catch (error) {\n      const relativePath = path.relative(process.cwd(), resolverFile);\n      logger.error(`Failed to load resolver from ${styles.bold(relativePath)}`);\n      logger.error(String(error));\n      throw error;\n    }\n    return undefined;\n  };\n\n  return {\n    namespace,\n    config,\n    get resolvers() {\n      return resolvers;\n    },\n    loadResolvers: async () => {\n      if (Object.keys(resolvers).length > 0) {\n        return;\n      }\n      if (config.files.length === 0) {\n        return;\n      }\n\n      const resolverFiles = loadFilesWithIgnores(config);\n\n      logger.log(\n        `Found ${styles.highlight(resolverFiles.length.toString())} resolver files for service ${styles.highlight(`\"${namespace}\"`)}`,\n      );\n\n      await Promise.all(resolverFiles.map((resolverFile) => loadResolverForFile(resolverFile)));\n    },\n  };\n}\n","import { parseSync } from \"oxc-parser\";\nimport { type ASTNode, type Replacement, applyReplacements, findStatementEnd } from \"./ast-utils\";\nimport { findAllJobs, buildJobNameMap, detectTriggerCalls } from \"./job-detector\";\nimport { collectSdkBindings, isSdkFunctionCall } from \"./sdk-binding-collector\";\nimport type {\n  Program,\n  VariableDeclaration,\n  ExportNamedDeclaration,\n  ExportDefaultDeclaration,\n} from \"@oxc-project/types\";\n\n/**\n * Find variable declarations by export names\n * Returns a map of export name to statement range\n * @param program - Parsed TypeScript program\n * @returns Map of export name to statement range\n */\nfunction findVariableDeclarationsByName(\n  program: Program,\n): Map<string, { start: number; end: number }> {\n  const declarations = new Map<string, { start: number; end: number }>();\n\n  function walk(node: ASTNode | null | undefined): void {\n    if (!node || typeof node !== \"object\") return;\n\n    const nodeType = node.type as string | undefined;\n\n    // Handle variable declarations: const job1 = ...\n    // Only set if not already set (ExportNamedDeclaration is processed first and sets the outer range)\n    if (nodeType === \"VariableDeclaration\") {\n      const varDecl = node as unknown as VariableDeclaration;\n      for (const decl of varDecl.declarations) {\n        if (decl.id.type === \"Identifier\" && decl.id.name) {\n          if (!declarations.has(decl.id.name)) {\n            declarations.set(decl.id.name, {\n              start: varDecl.start,\n              end: varDecl.end,\n            });\n          }\n        }\n      }\n    }\n\n    // Handle export declarations: export const job1 = ...\n    if (nodeType === \"ExportNamedDeclaration\") {\n      const exportDecl = node as unknown as ExportNamedDeclaration;\n      const declaration = exportDecl.declaration;\n      if (declaration?.type === \"VariableDeclaration\") {\n        const varDecl = declaration as VariableDeclaration;\n        for (const decl of varDecl.declarations) {\n          if (decl.id.type === \"Identifier\" && decl.id.name) {\n            declarations.set(decl.id.name, {\n              start: exportDecl.start,\n              end: exportDecl.end,\n            });\n          }\n        }\n      }\n    }\n\n    for (const key of Object.keys(node)) {\n      const child = node[key] as unknown;\n      if (Array.isArray(child)) {\n        child.forEach((c: unknown) => walk(c as ASTNode | null));\n      } else if (child && typeof child === \"object\") {\n        walk(child as ASTNode);\n      }\n    }\n  }\n\n  walk(program as unknown as ASTNode);\n  return declarations;\n}\n\n/**\n * Find createWorkflow default export declarations\n * Returns the range of the export statement to remove\n * @param program - Parsed TypeScript program\n * @returns Range of the default export statement or null\n */\nfunction findWorkflowDefaultExport(program: Program): { start: number; end: number } | null {\n  const bindings = collectSdkBindings(program, \"createWorkflow\");\n\n  for (const statement of program.body) {\n    if (statement.type === \"ExportDefaultDeclaration\") {\n      const exportDecl = statement as ExportDefaultDeclaration;\n      const declaration = exportDecl.declaration;\n\n      // Check for direct createWorkflow call: export default createWorkflow({...})\n      if (isSdkFunctionCall(declaration as unknown as ASTNode, bindings, \"createWorkflow\")) {\n        return { start: exportDecl.start, end: exportDecl.end };\n      }\n\n      // Check for variable reference that was assigned from createWorkflow\n      // This handles: const wf = createWorkflow({...}); export default wf;\n      if (declaration.type === \"Identifier\") {\n        return { start: exportDecl.start, end: exportDecl.end };\n      }\n    }\n  }\n\n  return null;\n}\n\n/**\n * Transform workflow source code\n * - Transform .trigger() calls to tailor.workflow.triggerJobFunction()\n * - Other jobs: remove entire variable declaration\n * @param source - The source code to transform\n * @param targetJobName - The name of the target job (from job config)\n * @param targetJobExportName - The export name of the target job (optional, for enhanced detection)\n * @param otherJobExportNames - Export names of other jobs to remove (optional, for enhanced detection)\n * @param allJobsMap - Map from export name to job name for trigger transformation (optional)\n * @returns Transformed workflow source code\n */\nexport function transformWorkflowSource(\n  source: string,\n  targetJobName: string,\n  targetJobExportName?: string,\n  otherJobExportNames?: string[],\n  allJobsMap?: Map<string, string>,\n): string {\n  // Use .ts extension to properly parse TypeScript code\n  const { program } = parseSync(\"input.ts\", source);\n\n  // Find all jobs using AST detection\n  const detectedJobs = findAllJobs(program, source);\n\n  // Defense-in-depth: the bundler already gates this function behind an\n  // isJobSourceFile check, so dependency files should not reach here.\n  // Guard anyway so that external callers don't accidentally strip exports\n  // from files that don't contain the target job.\n  const targetJobExistsInFile = detectedJobs.some((j) => j.name === targetJobName);\n  if (!targetJobExistsInFile) {\n    return source;\n  }\n\n  // Build job name map from detected jobs if not provided\n  const jobNameMap = allJobsMap ?? buildJobNameMap(detectedJobs);\n\n  // Find all variable declarations for export name-based removal\n  const allDeclarations = findVariableDeclarationsByName(program);\n\n  // Detect all .trigger() calls\n  const triggerCalls = detectTriggerCalls(program, source);\n\n  const replacements: Replacement[] = [];\n  const removedRanges: Array<{ start: number; end: number }> = [];\n\n  // Helper to check if a position is inside any removed range\n  const isInsideRemovedRange = (pos: number) => {\n    return removedRanges.some((r) => pos >= r.start && pos < r.end);\n  };\n\n  // Helper to track removed ranges (avoid duplicate/overlapping removals)\n  // Use start position only for comparison since end position may vary due to findStatementEnd\n  const isAlreadyMarkedForRemoval = (start: number) => {\n    return removedRanges.some((r) => r.start === start);\n  };\n\n  // Step 1: First, collect all ranges that will be removed (other job declarations)\n  // This must happen before trigger transformation to know which trigger calls to skip\n  for (const job of detectedJobs) {\n    if (job.name === targetJobName) {\n      continue;\n    }\n\n    if (job.statementRange && !isAlreadyMarkedForRemoval(job.statementRange.start)) {\n      const endPos = findStatementEnd(source, job.statementRange.end);\n      removedRanges.push({ start: job.statementRange.start, end: endPos });\n      replacements.push({\n        start: job.statementRange.start,\n        end: endPos,\n        text: \"\",\n      });\n    } else if (!job.statementRange) {\n      // Fallback: replace body with empty function if we can't find the statement\n      replacements.push({\n        start: job.bodyValueRange.start,\n        end: job.bodyValueRange.end,\n        text: \"() => {}\",\n      });\n    }\n  }\n\n  // Step 2: Remove other jobs by export name (catches jobs missed by AST detection)\n  if (otherJobExportNames) {\n    for (const exportName of otherJobExportNames) {\n      if (exportName === targetJobExportName) continue;\n\n      const declRange = allDeclarations.get(exportName);\n      if (declRange && !isAlreadyMarkedForRemoval(declRange.start)) {\n        const endPos = findStatementEnd(source, declRange.end);\n        removedRanges.push({ start: declRange.start, end: endPos });\n        replacements.push({\n          start: declRange.start,\n          end: endPos,\n          text: \"\",\n        });\n      }\n    }\n  }\n\n  // Step 3: Remove createWorkflow default export (not needed in job bundles)\n  const workflowExport = findWorkflowDefaultExport(program);\n  if (workflowExport && !isAlreadyMarkedForRemoval(workflowExport.start)) {\n    const endPos = findStatementEnd(source, workflowExport.end);\n    removedRanges.push({ start: workflowExport.start, end: endPos });\n    replacements.push({\n      start: workflowExport.start,\n      end: endPos,\n      text: \"\",\n    });\n  }\n\n  // Step 4: Transform .trigger() calls to tailor.workflow.triggerJobFunction()\n  for (const call of triggerCalls) {\n    if (isInsideRemovedRange(call.callRange.start)) {\n      continue;\n    }\n\n    const jobName = jobNameMap.get(call.identifierName);\n    if (jobName) {\n      const transformedCall = `(async () => tailor.workflow.triggerJobFunction(\"${jobName}\", ${call.argsText || \"undefined\"}))()`;\n      replacements.push({\n        start: call.callRange.start,\n        end: call.callRange.end,\n        text: transformedCall,\n      });\n    }\n  }\n\n  return applyReplacements(source, replacements);\n}\n","import * as fs from \"node:fs\";\nimport { parseSync } from \"oxc-parser\";\nimport * as path from \"pathe\";\nimport { resolveTSConfig } from \"pkg-types\";\nimport * as rolldown from \"rolldown\";\nimport { computeBundlerContextHash, withCache, type BundleCache } from \"#/cli/cache/bundle-cache\";\nimport { withBundleConcurrency } from \"#/cli/shared/bundle-concurrency\";\nimport { createLogLevelTreeshakeOptions } from \"#/cli/shared/bundle-log-level\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { composeFunctionTreeshakeOptions } from \"#/cli/shared/function-treeshake\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport { INVOKER_EXPR } from \"#/cli/shared/runtime-exprs\";\nimport { serializeTriggerContext, type TriggerContext } from \"#/cli/shared/trigger-context\";\nimport ml from \"#/utils/multiline\";\nimport { detectTriggerCalls, findAllJobs } from \"./job-detector\";\nimport { transformWorkflowSource } from \"./source-transformer\";\nimport { transformFunctionTriggers } from \"./trigger-transformer\";\nimport type { LogLevel } from \"#/configure/config/types\";\n\nfunction safeRealpath(p: string): string {\n  const resolved = path.resolve(p);\n  try {\n    return fs.realpathSync(resolved);\n  } catch (e) {\n    logger.debug(`realpathSync failed for ${resolved}: ${e instanceof Error ? e.message : e}`);\n    return resolved;\n  }\n}\n\ninterface JobInfo {\n  name: string;\n  exportName: string;\n  sourceFile: string;\n}\n\nexport interface BundleWorkflowJobsResult {\n  /** Maps mainJobName -> list of all job names it depends on (including itself) */\n  mainJobDeps: Record<string, string[]>;\n  /** Job names that were actually bundled */\n  usedJobNames: string[];\n  /** Maps job name to bundled code string */\n  bundledCode: Map<string, string>;\n}\n\n/**\n * Bundle workflow jobs\n *\n * This function:\n * 1. Detects which jobs are actually used (mainJobs + their dependencies)\n * 2. Uses a transform plugin to transform trigger calls during bundling\n * 3. Creates entry file and bundles with tree-shaking\n *\n * Returns metadata about which jobs each workflow uses.\n * @param allJobs - All available job infos\n * @param mainJobNames - Names of main jobs\n * @param env - Environment variables to inject\n * @param triggerContext - Trigger context for transformations\n * @param cache - Optional bundle cache for skipping unchanged builds\n * @param inlineSourcemap - Whether to enable inline sourcemaps\n * @param bundleLogLevel - Controls which console calls are kept in bundled code\n * @returns Workflow job bundling result\n */\nexport async function bundleWorkflowJobs(\n  allJobs: JobInfo[],\n  mainJobNames: string[],\n  env: Record<string, string | number | boolean> = {},\n  triggerContext?: TriggerContext,\n  cache?: BundleCache,\n  inlineSourcemap?: boolean,\n  bundleLogLevel: LogLevel = \"DEBUG\",\n): Promise<BundleWorkflowJobsResult> {\n  if (allJobs.length === 0) {\n    logger.warn(\"No workflow jobs to bundle\");\n    return { mainJobDeps: {}, usedJobNames: [], bundledCode: new Map() };\n  }\n\n  // Filter to only used jobs and get per-mainJob dependencies\n  const { usedJobs, mainJobDeps } = await filterUsedJobs(allJobs, mainJobNames);\n\n  logger.newline();\n  logger.log(\n    `Bundling ${styles.highlight(usedJobs.length.toString())} files for ${styles.info('\"workflow-job\"')}`,\n  );\n\n  const outputDir = path.resolve(getDistDir(), \"workflow-jobs\");\n\n  // Remove stale output files (those not in the current build set)\n  fs.mkdirSync(outputDir, { recursive: true });\n  const currentJobNames = new Set(usedJobs.map((j) => j.name));\n  const existingFiles = fs.readdirSync(outputDir);\n  for (const file of existingFiles) {\n    // Remove .js and .js.map files not belonging to current jobs (covers entry files, stale outputs, and sourcemaps)\n    if (file.endsWith(\".js\") && !currentJobNames.has(path.basename(file, \".js\"))) {\n      fs.rmSync(path.join(outputDir, file), { force: true });\n    } else if (file.endsWith(\".js.map\") && !currentJobNames.has(path.basename(file, \".js.map\"))) {\n      fs.rmSync(path.join(outputDir, file), { force: true });\n    }\n  }\n\n  let tsconfig: string | undefined;\n  try {\n    tsconfig = await resolveTSConfig();\n  } catch {\n    tsconfig = undefined;\n  }\n\n  // Process each job, capped by TAILOR_BUNDLE_CONCURRENCY to bound native\n  // memory use (each rolldown.build allocates its own module graph).\n  const results = await withBundleConcurrency(usedJobs, (job) =>\n    bundleSingleJob(\n      job,\n      usedJobs,\n      outputDir,\n      tsconfig,\n      env,\n      triggerContext,\n      cache,\n      inlineSourcemap,\n      bundleLogLevel,\n    ),\n  );\n\n  const bundledCode = new Map<string, string>();\n  for (const [name, code] of results) {\n    bundledCode.set(name, code);\n  }\n\n  logger.log(`${styles.success(\"Bundled\")} ${styles.info('\"workflow-job\"')}`);\n\n  return {\n    mainJobDeps,\n    usedJobNames: usedJobs.map((job) => job.name),\n    bundledCode,\n  };\n}\n\ninterface FilterUsedJobsResult {\n  usedJobs: JobInfo[];\n  mainJobDeps: Record<string, string[]>;\n}\n\n/**\n * Filter jobs to only include those that are actually used.\n * A job is \"used\" if:\n * - It's a mainJob of a workflow\n * - It's called via .trigger() from another used job (transitively)\n *\n * Also returns a map of mainJob -> all jobs it depends on (for metadata).\n * @param allJobs - All available job infos\n * @param mainJobNames - Names of main jobs\n * @returns Used jobs and main job dependency map\n */\nasync function filterUsedJobs(\n  allJobs: JobInfo[],\n  mainJobNames: string[],\n): Promise<FilterUsedJobsResult> {\n  if (allJobs.length === 0 || mainJobNames.length === 0) {\n    return { usedJobs: [], mainJobDeps: {} };\n  }\n\n  // Build maps for lookups\n  const jobsBySourceFile = new Map<string, JobInfo[]>();\n  for (const job of allJobs) {\n    const existing = jobsBySourceFile.get(job.sourceFile) || [];\n    existing.push(job);\n    jobsBySourceFile.set(job.sourceFile, existing);\n  }\n\n  // Build export name -> job name map for all jobs\n  const exportNameToJobName = new Map<string, string>();\n  for (const job of allJobs) {\n    exportNameToJobName.set(job.exportName, job.name);\n  }\n\n  // Detect trigger calls and build dependency graph\n  // Maps job name -> set of job names it triggers\n  const dependencies = new Map<string, Set<string>>();\n\n  // Process all source files in parallel\n  const fileResults = await Promise.all(\n    Array.from(jobsBySourceFile.entries()).map(async ([sourceFile, jobs]) => {\n      try {\n        const source = await fs.promises.readFile(sourceFile, \"utf-8\");\n        const { program } = parseSync(\"input.ts\", source);\n\n        // Find all jobs in this file to get body ranges\n        const detectedJobs = findAllJobs(program, source);\n        const localExportNameToJobName = new Map<string, string>();\n        for (const detected of detectedJobs) {\n          if (detected.exportName) {\n            localExportNameToJobName.set(detected.exportName, detected.name);\n          }\n        }\n\n        // Detect trigger calls\n        const triggerCalls = detectTriggerCalls(program, source);\n\n        // For each job in this file, find which triggers are inside its body\n        const jobDependencies: Array<{ jobName: string; deps: Set<string> }> = [];\n\n        for (const job of jobs) {\n          const detectedJob = detectedJobs.find((d) => d.name === job.name);\n          if (!detectedJob) continue;\n\n          const jobDeps = new Set<string>();\n\n          for (const call of triggerCalls) {\n            // Check if this trigger call is inside the job's body\n            if (\n              call.callRange.start >= detectedJob.bodyValueRange.start &&\n              call.callRange.end <= detectedJob.bodyValueRange.end\n            ) {\n              // Look up the job name from the identifier\n              const triggeredJobName =\n                localExportNameToJobName.get(call.identifierName) ||\n                exportNameToJobName.get(call.identifierName);\n              if (triggeredJobName) {\n                jobDeps.add(triggeredJobName);\n              }\n            }\n          }\n\n          if (jobDeps.size > 0) {\n            jobDependencies.push({ jobName: job.name, deps: jobDeps });\n          }\n        }\n\n        return jobDependencies;\n      } catch {\n        // If we can't parse a file, assume no dependencies from it\n        return [];\n      }\n    }),\n  );\n\n  // Merge results into dependencies map\n  for (const jobDependencies of fileResults) {\n    for (const { jobName, deps } of jobDependencies) {\n      dependencies.set(jobName, deps);\n    }\n  }\n\n  // Collect all used jobs and per-mainJob dependencies\n  const usedJobNames = new Set<string>();\n  const mainJobDeps: Record<string, string[]> = {};\n\n  function collectDeps(jobName: string, collected: Set<string>) {\n    if (collected.has(jobName)) return;\n    collected.add(jobName);\n\n    // Recursively collect dependencies\n    const deps = dependencies.get(jobName);\n    if (deps) {\n      for (const dep of deps) {\n        collectDeps(dep, collected);\n      }\n    }\n  }\n\n  // For each mainJob, collect all its dependencies\n  for (const mainJobName of mainJobNames) {\n    const depsForMainJob = new Set<string>();\n    collectDeps(mainJobName, depsForMainJob);\n    mainJobDeps[mainJobName] = Array.from(depsForMainJob);\n\n    // Add to global used jobs\n    for (const dep of depsForMainJob) {\n      usedJobNames.add(dep);\n    }\n  }\n\n  // Filter to only used jobs\n  const usedJobs = allJobs.filter((job) => usedJobNames.has(job.name));\n  return { usedJobs, mainJobDeps };\n}\n\nasync function bundleSingleJob(\n  job: JobInfo,\n  allJobs: JobInfo[],\n  outputDir: string,\n  tsconfig: string | undefined,\n  env: Record<string, string | number | boolean>,\n  triggerContext?: TriggerContext,\n  cache?: BundleCache,\n  inlineSourcemap?: boolean,\n  bundleLogLevel: LogLevel = \"DEBUG\",\n): Promise<[string, string]> {\n  const serializedTriggerContext = serializeTriggerContext(triggerContext);\n\n  // Include sorted env variables as a prefix so that env changes invalidate the cache\n  const sortedEnvPrefix = JSON.stringify(\n    Object.fromEntries(Object.entries(env).toSorted(([a], [b]) => a.localeCompare(b))),\n  );\n  const contextHash = computeBundlerContextHash({\n    sourceFile: job.sourceFile,\n    serializedTriggerContext,\n    tsconfig,\n    inlineSourcemap,\n    bundleLogLevel,\n    prefix: sortedEnvPrefix,\n  });\n\n  const code = await withCache({\n    cache,\n    kind: \"workflow-job\",\n    name: job.name,\n    sourceFile: job.sourceFile,\n    contextHash,\n    async build(cachePlugins) {\n      // Step 1: Create entry file that imports job by named export\n      const entryPath = path.join(outputDir, `${job.name}.entry.js`);\n      const absoluteSourcePath = path.resolve(job.sourceFile);\n\n      const entryContent = ml /* js */ `\n        import { ${job.exportName} } from \"${absoluteSourcePath}\";\n\n        export async function main(input) {\n          const env = ${JSON.stringify(env)};\n          const invoker = ${INVOKER_EXPR};\n          return await ${job.exportName}.body(input, { env, invoker });\n        }\n      `;\n      fs.writeFileSync(entryPath, entryContent);\n\n      // Step 2: Bundle with a transform plugin that transforms trigger calls\n      // Collect export names for enhanced AST removal (catches jobs missed by AST detection)\n      const otherJobExportNames = allJobs\n        .filter((j) => j.name !== job.name)\n        .map((j) => j.exportName);\n\n      // Build a map from export name to job name for trigger transformation\n      const allJobsMap = new Map<string, string>();\n      for (const j of allJobs) {\n        allJobsMap.set(j.exportName, j.name);\n      }\n\n      // Pre-compute once to avoid redundant realpathSync calls per module\n      const resolvedSourceFile = safeRealpath(job.sourceFile);\n\n      // Create transform plugin to transform trigger calls and remove other job declarations\n      const transformPlugin: rolldown.Plugin = {\n        name: \"workflow-transform\",\n        transform: {\n          filter: {\n            id: {\n              include: [/\\.(ts|mts|cts|js|mjs|cjs)$/],\n            },\n          },\n          handler(code, id) {\n            // Only transform source files that contain workflow jobs or trigger calls\n            if (\n              !code.includes(\"createWorkflowJob\") &&\n              !code.includes(\"createWorkflow\") &&\n              !code.includes(\".trigger(\")\n            ) {\n              return null;\n            }\n\n            // Only apply workflow source transformation (job removal, default\n            // export removal, intra-file trigger rewriting) to the job's own\n            // source file. Dependency files imported by the source file must\n            // keep their exports intact for rolldown to resolve cross-file\n            // imports (e.g. `import workflow from \"./other-workflow\"`).\n            let transformed = code;\n            const isJobSourceFile = safeRealpath(id) === resolvedSourceFile;\n            if (isJobSourceFile) {\n              transformed = transformWorkflowSource(\n                code,\n                job.name,\n                job.exportName,\n                otherJobExportNames,\n                allJobsMap,\n              );\n            }\n\n            // Apply workflow.trigger / job.trigger transformation if context is provided\n            if (triggerContext && transformed.includes(\".trigger(\")) {\n              transformed = transformFunctionTriggers(\n                transformed,\n                triggerContext.workflowNameMap,\n                triggerContext.jobNameMap,\n                triggerContext.workflowFileMap,\n                id,\n                triggerContext.authNamespace,\n              );\n            }\n\n            if (transformed === code) return null;\n            return { code: transformed };\n          },\n        },\n      };\n\n      const plugins: rolldown.Plugin[] = [\n        transformPlugin,\n        platformBundleDefinePlugin,\n        ...cachePlugins,\n      ];\n\n      const result = await rolldown.build({\n        input: entryPath,\n        write: false,\n        output: {\n          format: \"esm\",\n          sourcemap: inlineSourcemap ? \"inline\" : true,\n          minify: inlineSourcemap\n            ? {\n                mangle: {\n                  keepNames: true,\n                },\n              }\n            : true,\n          codeSplitting: false,\n        },\n        tsconfig,\n        plugins,\n        treeshake: composeFunctionTreeshakeOptions([\n          createLogLevelTreeshakeOptions(bundleLogLevel),\n        ]),\n        logLevel: \"silent\",\n      } as rolldown.BuildOptions);\n\n      return result.output[0].code;\n    },\n  });\n\n  return [job.name, code];\n}\n","import { z } from \"zod\";\nimport { functionSchema } from \"../common\";\n\nexport const WorkflowJobSchema = z.object({\n  name: z.string().describe(\"Job name (must be unique across the project)\"),\n  trigger: functionSchema.describe(\"Trigger function that initiates the job\"),\n  body: functionSchema.describe(\"Job implementation function\"),\n});\n\nconst durationUnits = [\"ms\", \"s\", \"m\"] as const;\n\nconst unitToSeconds: Record<(typeof durationUnits)[number], number> = {\n  ms: 1 / 1000,\n  s: 1,\n  m: 60,\n};\n\nfunction durationToSeconds(duration: string): number {\n  const match = duration.match(/^(\\d+)(ms|s|m)$/);\n  if (!match) return 0;\n  const value = match[1];\n  const unit = match[2];\n  if (value === undefined || unit === undefined) return 0;\n  return parseInt(value, 10) * unitToSeconds[unit as (typeof durationUnits)[number]];\n}\n\nconst baseDurationSchema = z.templateLiteral([z.number().int().positive(), z.enum(durationUnits)]);\n\nconst durationSchema = (maxSeconds: number) =>\n  baseDurationSchema.refine((val) => durationToSeconds(val) <= maxSeconds, {\n    message: `Duration must be at most ${maxSeconds} seconds`,\n  });\n\nexport const RetryPolicySchema = z\n  .object({\n    maxRetries: z.number().int().min(1).max(10).describe(\"Maximum number of retries (1-10)\"),\n    initialBackoff: durationSchema(3600).describe(\n      \"Initial backoff duration (e.g., '1s', '500ms', '1m', max 1h)\",\n    ),\n    maxBackoff: durationSchema(86400).describe(\n      \"Maximum backoff duration (e.g., '30s', '5m', max 24h)\",\n    ),\n    backoffMultiplier: z.number().min(1).describe(\"Backoff multiplier (>= 1)\"),\n  })\n  .refine((data) => durationToSeconds(data.initialBackoff) <= durationToSeconds(data.maxBackoff), {\n    message: \"initialBackoff must be less than or equal to maxBackoff\",\n    path: [\"initialBackoff\"],\n  })\n  .refine((data) => durationToSeconds(data.initialBackoff) > 0, {\n    message: \"initialBackoff must be greater than 0\",\n    path: [\"initialBackoff\"],\n  });\n\nexport const ConcurrencyPolicySchema = z.object({\n  maxConcurrentExecutions: z\n    .number()\n    .int()\n    .min(1)\n    .max(1000)\n    .describe(\"Maximum number of concurrent executions (1-1000)\"),\n});\n\nexport const WorkflowSchema = z.object({\n  name: z.string().describe(\"Workflow name\"),\n  mainJob: WorkflowJobSchema.describe(\"Main job that starts the workflow\"),\n  retryPolicy: RetryPolicySchema.optional().describe(\"Retry policy for the workflow\"),\n  concurrencyPolicy: ConcurrencyPolicySchema.optional().describe(\n    \"Concurrency policy for the workflow\",\n  ),\n});\n","import { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport { loadFilesWithIgnores } from \"#/cli/services/file-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { WorkflowJobSchema, WorkflowSchema } from \"#/parser/service/workflow/index\";\nimport { isSdkBranded } from \"#/utils/brand\";\nimport type { WorkflowServiceConfig } from \"#/configure/config/types\";\nimport type { Workflow } from \"#/types/workflow.generated\";\n\nexport interface CollectedJob {\n  name: string;\n  exportName: string;\n  sourceFile: string;\n}\n\ninterface WorkflowLoadResult {\n  workflows: Record<string, Workflow>;\n  workflowSources: Array<{ workflow: Workflow; sourceFile: string }>;\n  jobs: CollectedJob[];\n  fileCount: number;\n}\n\nexport type WorkflowService = {\n  readonly config: WorkflowServiceConfig;\n  readonly workflows: Record<string, Workflow>;\n  readonly workflowSources: ReadonlyArray<{ workflow: Workflow; sourceFile: string }>;\n  readonly jobs: CollectedJob[];\n  readonly fileCount: number;\n  loadWorkflows: () => Promise<void>;\n  printLoadedWorkflows: () => void;\n};\n\n/**\n * Parameters for creating a WorkflowService\n */\nexport interface CreateWorkflowServiceParams {\n  /** The workflow service configuration */\n  config: WorkflowServiceConfig;\n}\n\n/**\n * Creates a new WorkflowService instance.\n * @param params - Parameters for creating the service\n * @returns A new WorkflowService instance\n */\nexport function createWorkflowService(params: CreateWorkflowServiceParams): WorkflowService {\n  const { config } = params;\n  let workflows: Record<string, Workflow> = {};\n  let workflowSources: Array<{ workflow: Workflow; sourceFile: string }> = [];\n  let jobs: CollectedJob[] = [];\n  let fileCount = 0;\n  let loaded = false;\n\n  return {\n    config,\n    get workflows() {\n      return workflows;\n    },\n    get workflowSources() {\n      return workflowSources;\n    },\n    get jobs() {\n      return jobs;\n    },\n    get fileCount() {\n      return fileCount;\n    },\n    loadWorkflows: async () => {\n      if (loaded) {\n        return;\n      }\n      const result = await loadAndCollectJobs(config);\n      workflows = result.workflows;\n      workflowSources = result.workflowSources;\n      jobs = result.jobs;\n      fileCount = result.fileCount;\n      loaded = true;\n    },\n    printLoadedWorkflows: () => {\n      if (fileCount === 0) {\n        return;\n      }\n      logger.newline();\n      logger.log(`Found ${styles.highlight(fileCount.toString())} workflow files`);\n      for (const { workflow, sourceFile } of workflowSources) {\n        const relativePath = path.relative(process.cwd(), sourceFile);\n        logger.log(\n          `Workflow: ${styles.successBright(`\"${workflow.name}\"`)} loaded from ${styles.path(relativePath)}`,\n        );\n      }\n    },\n  };\n}\n\n/**\n * Load workflow files and collect all jobs in a single pass.\n * Dependencies are detected at bundle time via AST analysis.\n * @param config - Workflow service configuration\n * @returns Loaded workflows and collected jobs\n */\nasync function loadAndCollectJobs(config: WorkflowServiceConfig): Promise<WorkflowLoadResult> {\n  const workflows: Record<string, Workflow> = {};\n  const workflowSources: Array<{ workflow: Workflow; sourceFile: string }> = [];\n  const collectedJobs: CollectedJob[] = [];\n\n  if (config.files.length === 0) {\n    return {\n      workflows,\n      workflowSources,\n      jobs: collectedJobs,\n      fileCount: 0,\n    };\n  }\n\n  const workflowFiles = loadFilesWithIgnores(config);\n  const fileCount = workflowFiles.length;\n\n  // Maps for collecting data\n  const allJobsMap = new Map<string, { name: string; exportName: string; sourceFile: string }>();\n\n  // Load all files in parallel and collect jobs and workflows\n  const loadResults = await Promise.all(\n    workflowFiles.map(async (workflowFile) => {\n      const { jobs, workflow } = await loadFileContent(workflowFile);\n      return { workflowFile, jobs, workflow };\n    }),\n  );\n\n  for (const { workflowFile, jobs, workflow } of loadResults) {\n    if (workflow) {\n      workflowSources.push({ workflow, sourceFile: workflowFile });\n      workflows[workflowFile] = workflow;\n    }\n\n    for (const job of jobs) {\n      const existing = allJobsMap.get(job.name);\n      if (existing) {\n        throw new Error(\n          `Duplicate job name \"${job.name}\" found:\\n` +\n            `  - ${existing.sourceFile} (export: ${existing.exportName})\\n` +\n            `  - ${job.sourceFile} (export: ${job.exportName})\\n` +\n            `Each job must have a unique name.`,\n        );\n      }\n      allJobsMap.set(job.name, job);\n      collectedJobs.push(job);\n    }\n  }\n\n  return {\n    workflows,\n    workflowSources,\n    jobs: collectedJobs,\n    fileCount,\n  };\n}\n\n/**\n * Load a single file and extract jobs and workflow\n * @param filePath - Path to the workflow file\n * @returns Extracted jobs and workflow\n */\nasync function loadFileContent(filePath: string): Promise<{\n  jobs: Array<{ name: string; exportName: string; sourceFile: string }>;\n  workflow: Workflow | null;\n}> {\n  const jobs: Array<{\n    name: string;\n    exportName: string;\n    sourceFile: string;\n  }> = [];\n  let workflow: Workflow | null = null;\n\n  try {\n    const module = await import(pathToFileURL(filePath).href);\n\n    for (const [exportName, exportValue] of Object.entries(module)) {\n      // Check if it's a workflow (default export)\n      if (exportName === \"default\") {\n        const workflowResult = WorkflowSchema.safeParse(exportValue);\n        if (workflowResult.success) {\n          workflow = workflowResult.data;\n        } else if (isSdkBranded(exportValue, [\"workflow\", \"workflow-job\"])) {\n          throw workflowResult.error;\n        }\n        continue;\n      }\n\n      const jobResult = WorkflowJobSchema.safeParse(exportValue);\n      if (jobResult.success) {\n        jobs.push({\n          name: jobResult.data.name,\n          exportName,\n          sourceFile: filePath,\n        });\n      } else if (isSdkBranded(exportValue, [\"workflow\", \"workflow-job\"])) {\n        throw jobResult.error;\n      }\n    }\n  } catch (error) {\n    const relativePath = path.relative(process.cwd(), filePath);\n    logger.error(\n      `${styles.error(\"Failed to load workflow from\")} ${styles.errorBright(relativePath)}`,\n    );\n    logger.error(String(error));\n    throw error;\n  }\n\n  return { jobs, workflow };\n}\n","import { parseBoolean } from \"./parse-boolean\";\n\n/**\n * Resolve whether inline sourcemaps should be enabled.\n *\n * Resolution order:\n * 1. Config value (`inlineSourcemap` in defineConfig) — if explicitly set\n * 2. Environment variable `TAILOR_ENABLE_INLINE_SOURCEMAP` — if explicitly set\n * 3. Default: `true`\n * @param configValue - The `inlineSourcemap` value from AppConfig\n * @returns Whether inline sourcemaps should be enabled\n */\nexport function resolveInlineSourcemap(configValue?: boolean): boolean {\n  if (configValue !== undefined) return configValue;\n  const envValue = parseBoolean(process.env.TAILOR_ENABLE_INLINE_SOURCEMAP);\n  if (envValue !== undefined) return envValue;\n  return true;\n}\n","import { z } from \"zod\";\n\nconst NAME_PATTERN = /^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/;\nconst AUTH_NAMESPACE_PATTERN = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;\n\nexport const AIGatewaySchema = z\n  .object({\n    name: z\n      .string()\n      .regex(NAME_PATTERN, \"Must be 3-30 lowercase alphanumeric characters or hyphens\")\n      .describe(\"AI Gateway name\"),\n    authNamespace: z\n      .string()\n      .regex(AUTH_NAMESPACE_PATTERN, \"Must be 3-63 lowercase alphanumeric characters or hyphens\")\n      .describe(\"Auth namespace used to resolve request tokens against the workspace's auth\"),\n    cors: z\n      .array(z.string())\n      .optional()\n      .describe(\n        \"Allowed CORS origins for browser-based clients. Each entry is `*`, `http(s)://*`, `http(s)://*.example.com`, or `http(s)://app.example.com`, optionally with `:port`. Empty list disables cross-origin access.\",\n      ),\n  })\n  .brand(\"AIGatewayConfig\");\n","import { z } from \"zod\";\n\n/**\n * Normalize IdPGqlOperationsConfig (alias or object) to IdPGqlOperations object.\n * \"query\" alias expands to read-only mode: every mutation is disabled while\n * queries (`read`, `requestMfaSettingsUrl`) stay enabled.\n * @param config - The config to normalize\n * @returns The normalized IdPGqlOperations object\n */\nfunction normalizeIdPGqlOperations(\n  config:\n    | \"query\"\n    | {\n        create?: boolean;\n        update?: boolean;\n        delete?: boolean;\n        read?: boolean;\n        sendPasswordResetEmail?: boolean;\n        requestMfaSettingsUrl?: boolean;\n        unenrollMfa?: boolean;\n      },\n) {\n  if (config === \"query\") {\n    return {\n      create: false,\n      update: false,\n      delete: false,\n      read: true,\n      sendPasswordResetEmail: false,\n      requestMfaSettingsUrl: true,\n      unenrollMfa: false,\n    };\n  }\n  return config;\n}\n\n/**\n * Zod schema for IdPGqlOperations configuration with normalization transform.\n * Accepts \"query\" alias or detailed object, normalizes to IdPGqlOperations object.\n */\nexport const IdPGqlOperationsSchema = z\n  .union([\n    z.literal(\"query\"),\n    z.object({\n      create: z.boolean().optional().describe(\"Enable _createUser mutation (default: true)\"),\n      update: z.boolean().optional().describe(\"Enable _updateUser mutation (default: true)\"),\n      delete: z.boolean().optional().describe(\"Enable _deleteUser mutation (default: true)\"),\n      read: z.boolean().optional().describe(\"Enable _users and _user queries (default: true)\"),\n      sendPasswordResetEmail: z\n        .boolean()\n        .optional()\n        .describe(\"Enable _sendPasswordResetEmail mutation (default: true)\"),\n      requestMfaSettingsUrl: z\n        .boolean()\n        .optional()\n        .describe(\"Enable _requestMfaSettingsUrl query (default: true)\"),\n      unenrollMfa: z.boolean().optional().describe(\"Enable _unenrollMfa mutation (default: true)\"),\n    }),\n  ])\n  .describe(\n    \"Configuration for GraphQL operations on IdP users.\\nAll operations are enabled by default (undefined or true = enabled, false = disabled).\",\n  )\n  .transform((val) => normalizeIdPGqlOperations(val));\n\nexport const IdPLangSchema = z.enum([\"en\", \"ja\"]).describe(\"IdP UI language\");\n\n// Origins are either a literal http(s) origin (scheme + host + optional port,\n// no path/query/fragment) or a static-website `<name>:url` placeholder that\n// the CLI resolves to a real origin at apply time. The placeholder branch\n// uses the same slug rule as the platform's static-website name validator so\n// typos like `https://app.example.com:url` are rejected instead of being\n// silently interpreted as a website name at apply time.\nconst allowedReturnOriginPattern =\n  /^(https?:\\/\\/[a-zA-Z0-9.-]+(:[0-9]+)?|[a-z0-9][a-z0-9-]{1,61}[a-z0-9]:url)$/;\n\nexport const IdPUserAuthPolicySchema = z\n  .object({\n    useNonEmailIdentifier: z\n      .boolean()\n      .optional()\n      .describe(\"Use non-email identifier for usernames\"),\n    allowSelfPasswordReset: z\n      .boolean()\n      .optional()\n      .describe(\"Allow users to reset their own passwords\"),\n    passwordRequireUppercase: z\n      .boolean()\n      .optional()\n      .describe(\"Require uppercase letters in passwords\"),\n    passwordRequireLowercase: z\n      .boolean()\n      .optional()\n      .describe(\"Require lowercase letters in passwords\"),\n    passwordRequireNonAlphanumeric: z\n      .boolean()\n      .optional()\n      .describe(\"Require non-alphanumeric characters in passwords\"),\n    passwordRequireNumeric: z\n      .boolean()\n      .optional()\n      .describe(\"Require numeric characters in passwords\"),\n    passwordMinLength: z\n      .number()\n      .int()\n      .refine((val) => val >= 6 && val <= 30, {\n        message: \"passwordMinLength must be between 6 and 30\",\n      })\n      .optional()\n      .describe(\"Minimum password length (6-30)\"),\n    passwordMaxLength: z\n      .number()\n      .int()\n      .refine((val) => val >= 6 && val <= 4096, {\n        message: \"passwordMaxLength must be between 6 and 4096\",\n      })\n      .optional()\n      .describe(\"Maximum password length (6-4096)\"),\n    allowedEmailDomains: z\n      .array(z.string())\n      .optional()\n      .describe(\"Restrict registration to these email domains\"),\n    allowGoogleOauth: z.boolean().optional().describe(\"Enable Google OAuth login\"),\n    allowMicrosoftOauth: z.boolean().optional().describe(\"Enable Microsoft OAuth login\"),\n    disablePasswordAuth: z.boolean().optional().describe(\"Disable password-based authentication\"),\n    enableMfa: z\n      .boolean()\n      .optional()\n      .describe(\"Make TOTP MFA available for users in this namespace\"),\n    requireMfa: z\n      .boolean()\n      .optional()\n      .describe(\n        \"Require TOTP MFA enrollment and challenge for password-authenticated users (requires enableMfa)\",\n      ),\n    allowedReturnOrigins: z\n      .array(\n        z\n          .string()\n          .regex(\n            allowedReturnOriginPattern,\n            'must be an http(s) origin like \"https://app.example.com\" (scheme + host + optional port, no path/query/fragment) or a static-website placeholder like \"<name>:url\"',\n          ),\n      )\n      .optional()\n      .describe(\n        \"Application origins (scheme + host + optional port) allowed as MFA self-service return targets\",\n      ),\n    mfaIssuer: z\n      .string()\n      .max(64, \"mfaIssuer must be 64 characters or less\")\n      .optional()\n      .describe(\"Label shown next to the user account in authenticator apps\"),\n  })\n  .refine(\n    (data) =>\n      data.passwordMinLength === undefined ||\n      data.passwordMaxLength === undefined ||\n      data.passwordMinLength <= data.passwordMaxLength,\n    {\n      message: \"passwordMinLength must be less than or equal to passwordMaxLength\",\n      path: [\"passwordMinLength\"],\n    },\n  )\n  .refine(\n    (data) =>\n      !data.allowedEmailDomains ||\n      data.allowedEmailDomains.length === 0 ||\n      !data.useNonEmailIdentifier,\n    {\n      message: \"allowedEmailDomains cannot be set when useNonEmailIdentifier is true\",\n      path: [\"allowedEmailDomains\"],\n    },\n  )\n  .refine(\n    (data) =>\n      data.allowGoogleOauth === undefined ||\n      data.allowGoogleOauth === false ||\n      !data.useNonEmailIdentifier,\n    {\n      message: \"allowGoogleOauth cannot be set when useNonEmailIdentifier is true\",\n      path: [\"allowGoogleOauth\"],\n    },\n  )\n  .refine(\n    (data) =>\n      !data.allowGoogleOauth || (data.allowedEmailDomains && data.allowedEmailDomains.length > 0),\n    {\n      message: \"allowGoogleOauth requires allowedEmailDomains to be set\",\n      path: [\"allowGoogleOauth\"],\n    },\n  )\n  .refine((data) => !data.allowMicrosoftOauth || !data.useNonEmailIdentifier, {\n    message: \"allowMicrosoftOauth cannot be set when useNonEmailIdentifier is true\",\n    path: [\"allowMicrosoftOauth\"],\n  })\n  .refine(\n    (data) =>\n      !data.allowMicrosoftOauth ||\n      (data.allowedEmailDomains && data.allowedEmailDomains.length > 0),\n    {\n      message: \"allowMicrosoftOauth requires allowedEmailDomains to be set\",\n      path: [\"allowMicrosoftOauth\"],\n    },\n  )\n  .refine((data) => !data.allowMicrosoftOauth || data.disablePasswordAuth === true, {\n    message: \"allowMicrosoftOauth requires disablePasswordAuth to be enabled\",\n    path: [\"allowMicrosoftOauth\"],\n  })\n  .refine(\n    (data) =>\n      !data.disablePasswordAuth ||\n      data.allowGoogleOauth === true ||\n      data.allowMicrosoftOauth === true,\n    {\n      message: \"disablePasswordAuth requires allowGoogleOauth or allowMicrosoftOauth to be enabled\",\n      path: [\"disablePasswordAuth\"],\n    },\n  )\n  .refine((data) => !data.disablePasswordAuth || !data.allowSelfPasswordReset, {\n    message: \"disablePasswordAuth cannot be used with allowSelfPasswordReset\",\n    path: [\"disablePasswordAuth\"],\n  })\n  .refine((data) => !data.requireMfa || data.enableMfa === true, {\n    message: \"requireMfa requires enableMfa to be enabled\",\n    path: [\"requireMfa\"],\n  })\n  .refine(\n    (data) =>\n      !data.enableMfa || (data.allowedReturnOrigins && data.allowedReturnOrigins.length > 0),\n    {\n      message:\n        \"enableMfa requires allowedReturnOrigins to list at least one origin so MFA self-service has a valid return target\",\n      path: [\"enableMfa\"],\n    },\n  );\n\nconst emailFieldSchema = z\n  .string()\n  .max(200, \"must be 200 characters or less\")\n  .regex(/^[^\\r\\n]*$/, \"must not contain newline characters\");\n\nexport const IdPEmailConfigSchema = z\n  .object({\n    fromName: emailFieldSchema.optional().describe(\"Default sender display name for emails\"),\n    passwordResetSubject: emailFieldSchema\n      .optional()\n      .describe(\"Default subject for password reset emails\"),\n  })\n  .describe(\"Namespace-level email configuration defaults\");\n\nconst IdPPermissionOperandSchema = z.union([\n  z.string(),\n  z.boolean(),\n  z.array(z.string()).readonly(),\n  z.array(z.boolean()).readonly(),\n  z.object({ user: z.string() }),\n  z.object({ idpUser: z.enum([\"id\", \"name\", \"disabled\"]) }),\n  z.object({ oldIdpUser: z.enum([\"id\", \"name\", \"disabled\"]) }),\n  z.object({ newIdpUser: z.enum([\"id\", \"name\", \"disabled\"]) }),\n]);\n\nconst IdPPermissionOperatorSchema = z.enum([\"=\", \"!=\", \"in\", \"not in\"]);\n\nconst IdPPermissionConditionSchema = z\n  .tuple([IdPPermissionOperandSchema, IdPPermissionOperatorSchema, IdPPermissionOperandSchema])\n  .readonly();\n\nconst IdPActionPermissionSchema = z.union([\n  // Object format: { conditions, description?, permit? }\n  z.object({\n    conditions: z.union([\n      IdPPermissionConditionSchema,\n      z.array(IdPPermissionConditionSchema).readonly(),\n    ]),\n    description: z.string().optional(),\n    permit: z.boolean().optional(),\n  }),\n  // Single condition tuple: [operand, operator, operand]\n  z\n    .tuple([IdPPermissionOperandSchema, IdPPermissionOperatorSchema, IdPPermissionOperandSchema])\n    .readonly(),\n  // Single condition tuple with permit: [operand, operator, operand, permit]\n  z\n    .tuple([\n      IdPPermissionOperandSchema,\n      IdPPermissionOperatorSchema,\n      IdPPermissionOperandSchema,\n      z.boolean(),\n    ])\n    .readonly(),\n  // Multiple conditions with optional trailing permit\n  z\n    .array(z.union([IdPPermissionConditionSchema, z.boolean()]))\n    .refine(\n      (arr) => {\n        const boolIndex = arr.findIndex((item) => typeof item === \"boolean\");\n        return boolIndex === -1 || boolIndex === arr.length - 1;\n      },\n      { message: \"Boolean permit flag must only appear at the end\" },\n    )\n    .readonly(),\n]);\n\nexport const IdPPermissionSchema = z\n  .object({\n    create: z.array(IdPActionPermissionSchema).readonly(),\n    read: z.array(IdPActionPermissionSchema).readonly(),\n    update: z.array(IdPActionPermissionSchema).readonly(),\n    delete: z.array(IdPActionPermissionSchema).readonly(),\n    sendPasswordResetEmail: z.array(IdPActionPermissionSchema).readonly().optional(),\n    unenrollMfa: z.array(IdPActionPermissionSchema).readonly().optional(),\n  })\n  .describe(\"Per-operation permission policies for IdP users\");\n\nexport const IdPSchema = z\n  .object({\n    name: z.string().describe(\"IdP service name\"),\n    authorization: z\n      .union([z.literal(\"insecure\"), z.literal(\"loggedIn\"), z.object({ cel: z.string() })])\n      .optional()\n      .describe(\"Authorization mode for IdP API access\"),\n    clients: z.array(z.string()).describe(\"OAuth2 client names that can use this IdP\"),\n    lang: IdPLangSchema.optional().describe(\"UI language for IdP pages\"),\n    userAuthPolicy: IdPUserAuthPolicySchema.transform((input) =>\n      // transform input may be undefined before schema parse\n      // oxlint-disable-next-line typescript/no-unnecessary-condition\n      IdPUserAuthPolicySchema.parse(input ?? {}),\n    )\n      .optional()\n      .describe(\"User authentication policy configuration\"),\n    publishUserEvents: z.boolean().optional().describe(\"Enable publishing user lifecycle events\"),\n    gqlOperations: IdPGqlOperationsSchema.optional().describe(\n      \"Configure which GraphQL operations are enabled\",\n    ),\n    emailConfig: IdPEmailConfigSchema.optional().describe(\n      \"Namespace-level email configuration defaults\",\n    ),\n    permission: IdPPermissionSchema.optional().describe(\n      \"Per-operation permission policies for IdP users\",\n    ),\n  })\n  .refine(\n    (data) =>\n      !data.userAuthPolicy?.enableMfa ||\n      data.gqlOperations?.unenrollMfa === false ||\n      (data.permission !== undefined && data.permission.unenrollMfa !== undefined),\n    {\n      message:\n        \"permission.unenrollMfa must be set explicitly when userAuthPolicy.enableMfa is true (set [{ conditions: [...], permit: true }] to allow, or [] to deny all). permission itself must also be defined. The requirement is only relaxed when gqlOperations.unenrollMfa is false.\",\n      path: [\"permission\", \"unenrollMfa\"],\n    },\n  )\n  .refine(\n    (data) =>\n      !data.permission ||\n      data.userAuthPolicy?.disablePasswordAuth === true ||\n      data.gqlOperations?.sendPasswordResetEmail === false ||\n      data.permission.sendPasswordResetEmail !== undefined,\n    {\n      message:\n        \"permission.sendPasswordResetEmail must be set explicitly when password authentication is enabled (set [{ conditions: [...], permit: true }] to allow, or [] to deny; only optional when userAuthPolicy.disablePasswordAuth is true or gqlOperations.sendPasswordResetEmail is false)\",\n      path: [\"permission\", \"sendPasswordResetEmail\"],\n    },\n  )\n  .brand(\"IdPConfig\");\n","import { z } from \"zod\";\n\nconst namePattern = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;\nconst nameSchema = z.string().regex(namePattern);\n\nconst secretsVaultSchema = z.record(nameSchema, z.string().nullish());\nexport const SecretsSchema = z.object({\n  vaults: z.record(nameSchema, secretsVaultSchema),\n  options: z.object({\n    ignoreNullishValues: z.boolean(),\n  }),\n});\n","import { z } from \"zod\";\n\nexport const StaticWebsiteSchema = z\n  .object({\n    name: z.string().describe(\"Static website name\"),\n    description: z.string().optional().describe(\"Static website description\"),\n    allowedIpAddresses: z\n      .array(z.string())\n      .optional()\n      .describe(\"IP addresses allowed to access the website\"),\n    customDomains: z.array(z.string()).optional().describe(\"Custom domains for the static website\"),\n  })\n  .brand(\"StaticWebsiteConfig\");\n","import * as path from \"pathe\";\nimport { generatePluginExecutorFiles } from \"#/cli/commands/generate/plugin-executor-generator\";\nimport { generatePluginTypeFiles } from \"#/cli/commands/generate/plugin-type-generator\";\nimport { bundleAuthHooks } from \"#/cli/services/auth/bundler\";\nimport { createAuthService, type AuthService } from \"#/cli/services/auth/service\";\nimport { bundleExecutors } from \"#/cli/services/executor/bundler\";\nimport { createExecutorService, type ExecutorService } from \"#/cli/services/executor/service\";\nimport {\n  bundleHttpAdapters,\n  type HttpAdapterBundleResult,\n} from \"#/cli/services/http-adapter/bundler\";\nimport {\n  createHttpAdapterService,\n  type HttpAdapterService,\n} from \"#/cli/services/http-adapter/service\";\nimport { bundleResolvers } from \"#/cli/services/resolver/bundler\";\nimport { createResolverService, type ResolverService } from \"#/cli/services/resolver/service\";\nimport { createTailorDBService, type TailorDBService } from \"#/cli/services/tailordb/service\";\nimport { assertUniqueLocalTailorDBTypeNames } from \"#/cli/services/tailordb/type-name-validation\";\nimport { bundleWorkflowJobs, type BundleWorkflowJobsResult } from \"#/cli/services/workflow/bundler\";\nimport { createWorkflowService, type WorkflowService } from \"#/cli/services/workflow/service\";\nimport { resolveBundleLogLevel } from \"#/cli/shared/bundle-log-level\";\nimport { type LoadedConfig } from \"#/cli/shared/config-loader\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { resolveInlineSourcemap } from \"#/cli/shared/inline-sourcemap\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { buildTriggerContext } from \"#/cli/shared/trigger-context\";\nimport {\n  type AppConfig,\n  type ExecutorServiceInput,\n  type HttpAdapterServiceInput,\n  type ResolverServiceInput,\n  type WorkflowServiceConfig,\n} from \"#/configure/config/types\";\nimport { type AuthConfig } from \"#/configure/services/auth/types\";\nimport { type IdPConfig } from \"#/configure/services/idp/types\";\nimport { AIGatewaySchema } from \"#/parser/service/aigateway/index\";\nimport { AuthConfigSchema } from \"#/parser/service/auth/index\";\nimport { IdPSchema } from \"#/parser/service/idp/index\";\nimport { SecretsSchema } from \"#/parser/service/secrets/index\";\nimport { StaticWebsiteSchema } from \"#/parser/service/staticwebsite/index\";\nimport { TailorDBServiceConfigSchema } from \"#/parser/service/tailordb/index\";\nimport type { BundleCache } from \"#/cli/cache/bundle-cache\";\nimport type { BundledScripts } from \"#/cli/commands/deploy/function-registry-types\";\nimport type { TailorDBServiceInput } from \"#/configure/services/tailordb/types\";\nimport type { PluginManager } from \"#/plugin/manager\";\nimport type { AIGateway, AIGatewayInput } from \"#/types/aigateway.generated\";\nimport type { IdP } from \"#/types/idp.generated\";\nimport type { StaticWebsite, StaticWebsiteInput } from \"#/types/staticwebsite.generated\";\n\nexport type SecretVault = {\n  readonly vaultName: string;\n  readonly secrets: ReadonlyArray<{ name: string; value: string | null | undefined }>;\n};\n\nexport type Application = {\n  readonly name: string;\n  readonly id: string | undefined;\n  readonly config: AppConfig;\n  readonly subgraphs: ReadonlyArray<{ Type: string; Name: string }>;\n  readonly tailorDBServices: ReadonlyArray<TailorDBService>;\n  readonly externalTailorDBNamespaces: ReadonlyArray<string>;\n  readonly resolverServices: ReadonlyArray<ResolverService>;\n  readonly idpServices: ReadonlyArray<IdP>;\n  readonly authService: Readonly<AuthService> | undefined;\n  readonly executorService: Readonly<ExecutorService> | undefined;\n  readonly workflowService: Readonly<WorkflowService> | undefined;\n  readonly httpAdapterService: Readonly<HttpAdapterService> | undefined;\n  readonly staticWebsiteServices: ReadonlyArray<StaticWebsite>;\n  readonly aiGatewayServices: ReadonlyArray<AIGateway>;\n  readonly secrets: ReadonlyArray<SecretVault>;\n  readonly ignoreNullishValues: boolean;\n  readonly env: Readonly<Record<string, string | number | boolean>>;\n  readonly applications: ReadonlyArray<Application>;\n};\n\n/**\n * Result of loading the application\n */\nexport interface LoadApplicationResult {\n  /** Fully initialized application */\n  application: Application;\n  /** Workflow bundling result (if workflows were bundled) */\n  workflowBuildResult?: BundleWorkflowJobsResult;\n  /** HTTP adapter bundling result (if adapters were bundled) */\n  httpAdapterBuildResult?: HttpAdapterBundleResult;\n  /** In-memory bundled scripts organized by kind */\n  bundledScripts: BundledScripts;\n}\n\ntype DefineTailorDBResult = {\n  tailorDBServices: TailorDBService[];\n  externalTailorDBNamespaces: string[];\n  subgraphs: Array<{ Type: string; Name: string }>;\n};\n\nfunction defineTailorDB(\n  config: TailorDBServiceInput | undefined,\n  pluginManager?: PluginManager,\n): DefineTailorDBResult {\n  const tailorDBServices: TailorDBService[] = [];\n  const externalTailorDBNamespaces: string[] = [];\n  const subgraphs: Array<{ Type: string; Name: string }> = [];\n\n  if (!config) {\n    return { tailorDBServices, externalTailorDBNamespaces, subgraphs };\n  }\n\n  for (const [namespace, serviceConfig] of Object.entries(config)) {\n    if (\"external\" in serviceConfig) {\n      externalTailorDBNamespaces.push(namespace);\n    } else {\n      // Parse config through schema to normalize gqlOperations\n      const parsedConfig = TailorDBServiceConfigSchema.parse(serviceConfig);\n      const tailorDB = createTailorDBService({\n        namespace,\n        config: parsedConfig,\n        pluginManager,\n      });\n      tailorDBServices.push(tailorDB);\n    }\n    subgraphs.push({ Type: \"tailordb\", Name: namespace });\n  }\n\n  return { tailorDBServices, externalTailorDBNamespaces, subgraphs };\n}\n\ntype DefineResolverResult = {\n  resolverServices: ResolverService[];\n  subgraphs: Array<{ Type: string; Name: string }>;\n};\n\nfunction defineResolver(config: ResolverServiceInput | undefined): DefineResolverResult {\n  const resolverServices: ResolverService[] = [];\n  const subgraphs: Array<{ Type: string; Name: string }> = [];\n\n  if (!config) {\n    return { resolverServices, subgraphs };\n  }\n\n  for (const [namespace, serviceConfig] of Object.entries(config)) {\n    if (!(\"external\" in serviceConfig)) {\n      const resolverService = createResolverService(namespace, serviceConfig);\n      resolverServices.push(resolverService);\n    }\n    subgraphs.push({ Type: \"pipeline\", Name: namespace });\n  }\n\n  return { resolverServices, subgraphs };\n}\n\ntype DefineIdpResult = {\n  idpServices: IdP[];\n  subgraphs: Array<{ Type: string; Name: string }>;\n};\n\nfunction defineIdp(config: readonly IdPConfig[] | undefined): DefineIdpResult {\n  const idpServices: IdP[] = [];\n  const subgraphs: Array<{ Type: string; Name: string }> = [];\n\n  if (!config) {\n    return { idpServices, subgraphs };\n  }\n\n  const idpNames = new Set<string>();\n  config.forEach((idpConfig) => {\n    const name = idpConfig.name;\n    if (idpNames.has(name)) {\n      throw new Error(`IdP with name \"${name}\" already defined.`);\n    }\n    idpNames.add(name);\n    if (!(\"external\" in idpConfig)) {\n      const idp = IdPSchema.parse(idpConfig);\n      idpServices.push(idp);\n    }\n    subgraphs.push({ Type: \"idp\", Name: name });\n  });\n\n  return { idpServices, subgraphs };\n}\n\ntype DefineAuthResult = {\n  authService: AuthService | undefined;\n  subgraphs: Array<{ Type: string; Name: string }>;\n};\n\nfunction defineAuth(\n  config: AuthConfig | undefined,\n  tailorDBServices: ReadonlyArray<TailorDBService>,\n  externalTailorDBNamespaces: ReadonlyArray<string>,\n): DefineAuthResult {\n  const subgraphs: Array<{ Type: string; Name: string }> = [];\n\n  if (!config) {\n    return { authService: undefined, subgraphs };\n  }\n\n  let authService: AuthService | undefined;\n  if (!(\"external\" in config)) {\n    authService = createAuthService(\n      AuthConfigSchema.parse(config),\n      tailorDBServices,\n      externalTailorDBNamespaces,\n    );\n  }\n  subgraphs.push({ Type: \"auth\", Name: config.name });\n\n  return { authService, subgraphs };\n}\n\nfunction defineExecutor(\n  config: ExecutorServiceInput | undefined,\n  hasPluginExecutors: boolean,\n): ExecutorService | undefined {\n  if (!config && !hasPluginExecutors) {\n    return undefined;\n  }\n  return createExecutorService({ config: config ?? { files: [] } });\n}\n\nfunction defineWorkflow(config: WorkflowServiceConfig | undefined): WorkflowService | undefined {\n  if (!config) {\n    return undefined;\n  }\n  return createWorkflowService({ config });\n}\n\nfunction defineHttpAdapterService(\n  config: HttpAdapterServiceInput | undefined,\n): HttpAdapterService | undefined {\n  if (!config) {\n    return undefined;\n  }\n  return createHttpAdapterService({ config });\n}\n\nfunction defineStaticWebsites(\n  websites: readonly StaticWebsiteInput[] | undefined,\n): StaticWebsite[] {\n  const staticWebsiteServices: StaticWebsite[] = [];\n  const websiteNames = new Set<string>();\n\n  (websites ?? []).forEach((config) => {\n    const website = StaticWebsiteSchema.parse(config);\n    if (websiteNames.has(website.name)) {\n      throw new Error(`Static website with name \"${website.name}\" already defined.`);\n    }\n    websiteNames.add(website.name);\n    staticWebsiteServices.push(website);\n  });\n\n  return staticWebsiteServices;\n}\n\nfunction defineAIGateways(gateways: readonly AIGatewayInput[] | undefined): AIGateway[] {\n  const aiGatewayServices: AIGateway[] = [];\n  const gatewayNames = new Set<string>();\n\n  (gateways ?? []).forEach((config) => {\n    const gateway = AIGatewaySchema.parse(config);\n    if (gatewayNames.has(gateway.name)) {\n      throw new Error(`AI Gateway with name \"${gateway.name}\" already defined.`);\n    }\n    gatewayNames.add(gateway.name);\n    aiGatewayServices.push(gateway);\n  });\n\n  return aiGatewayServices;\n}\n\nfunction parseSecretManager(config: AppConfig[\"secrets\"]): {\n  secrets: SecretVault[];\n  ignoreNullishValues: boolean;\n} {\n  if (!config) {\n    return { secrets: [], ignoreNullishValues: false };\n  }\n\n  const parsed = SecretsSchema.parse(config);\n  const { ignoreNullishValues } = parsed.options;\n\n  const secrets = Object.entries(parsed.vaults).map(([vaultName, vaultSecrets]) => ({\n    vaultName,\n    secrets: Object.entries(vaultSecrets).map(([name, value]) => ({ name, value })),\n  }));\n\n  // Defensive check: error if nullish values exist without ignoreNullishValues\n  if (!ignoreNullishValues) {\n    for (const vault of secrets) {\n      for (const secret of vault.secrets) {\n        if (secret.value == null) {\n          throw new Error(\n            `Secret \"${vault.vaultName}/${secret.name}\" has no value. ` +\n              `Use { ignoreNullishValues: true } option in defineSecretManager() to skip secrets without values.`,\n          );\n        }\n      }\n    }\n  }\n\n  return { secrets, ignoreNullishValues };\n}\n\ntype DefineServicesResult = {\n  tailordbResult: DefineTailorDBResult;\n  resolverResult: DefineResolverResult;\n  idpResult: DefineIdpResult;\n  authResult: DefineAuthResult;\n  staticWebsiteServices: StaticWebsite[];\n  aiGatewayServices: AIGateway[];\n  secrets: SecretVault[];\n  ignoreNullishValues: boolean;\n};\n\nfunction defineServices(config: AppConfig, pluginManager?: PluginManager): DefineServicesResult {\n  const tailordbResult = defineTailorDB(config.db, pluginManager);\n  const resolverResult = defineResolver(config.resolver);\n  const idpResult = defineIdp(config.idp);\n  const authResult = defineAuth(\n    config.auth,\n    tailordbResult.tailorDBServices,\n    tailordbResult.externalTailorDBNamespaces,\n  );\n  const staticWebsiteServices = defineStaticWebsites(config.staticWebsites);\n  const aiGatewayServices = defineAIGateways(config.aiGateways);\n  const { secrets, ignoreNullishValues } = parseSecretManager(config.secrets);\n  return {\n    tailordbResult,\n    resolverResult,\n    idpResult,\n    authResult,\n    staticWebsiteServices,\n    aiGatewayServices,\n    secrets,\n    ignoreNullishValues: ignoreNullishValues,\n  };\n}\n\nfunction buildApplication(params: {\n  config: AppConfig;\n  tailordbResult: DefineTailorDBResult;\n  resolverResult: DefineResolverResult;\n  idpResult: DefineIdpResult;\n  authResult: DefineAuthResult;\n  executorService: ExecutorService | undefined;\n  workflowService: WorkflowService | undefined;\n  httpAdapterService: HttpAdapterService | undefined;\n  staticWebsiteServices: StaticWebsite[];\n  aiGatewayServices: AIGateway[];\n  secrets: SecretVault[];\n  ignoreNullishValues: boolean;\n  env: Record<string, string | number | boolean>;\n}): Application {\n  const application: Application = {\n    name: params.config.name,\n    id: params.config.id,\n    config: params.config,\n    subgraphs: [\n      ...params.tailordbResult.subgraphs,\n      ...params.resolverResult.subgraphs,\n      ...params.idpResult.subgraphs,\n      ...params.authResult.subgraphs,\n    ],\n    tailorDBServices: params.tailordbResult.tailorDBServices,\n    externalTailorDBNamespaces: params.tailordbResult.externalTailorDBNamespaces,\n    resolverServices: params.resolverResult.resolverServices,\n    idpServices: params.idpResult.idpServices,\n    authService: params.authResult.authService,\n    executorService: params.executorService,\n    workflowService: params.workflowService,\n    httpAdapterService: params.httpAdapterService,\n    staticWebsiteServices: params.staticWebsiteServices,\n    aiGatewayServices: params.aiGatewayServices,\n    secrets: params.secrets,\n    ignoreNullishValues: params.ignoreNullishValues,\n    env: params.env,\n    get applications() {\n      return [application];\n    },\n  };\n  return application;\n}\n\n/**\n * Parameters for defining an application\n */\nexport interface DefineApplicationParams {\n  /** Application configuration object (must be loaded via loadConfig) */\n  config: LoadedConfig;\n  /** Plugin manager for processing plugins */\n  pluginManager?: PluginManager;\n  /** Optional bundle cache for skipping unchanged builds */\n  bundleCache?: BundleCache;\n}\n\n/**\n * Define a Tailor application from the given configuration.\n * This is a lightweight, synchronous function that creates the application\n * structure without loading types or bundling files.\n * @param params - Parameters for defining the application\n * @returns Configured application instance\n */\nexport function defineApplication(params: DefineApplicationParams): Application {\n  const { config, pluginManager } = params;\n  const services = defineServices(config, pluginManager);\n  // Plugin executors are not known at define-time; generate/apply flows handle them after type loading.\n  const executorService = defineExecutor(config.executor, false);\n  const workflowService = defineWorkflow(config.workflow);\n  const httpAdapterService = defineHttpAdapterService(config.httpAdapter);\n\n  return buildApplication({\n    config,\n    ...services,\n    executorService,\n    workflowService,\n    httpAdapterService,\n    env: config.env ?? {},\n  });\n}\n\n/**\n * Generate plugin type and executor files if a plugin manager is provided.\n * Collects source type info from TailorDB services and delegates to PluginManager.\n * @param pluginManager - Plugin manager instance (skips if undefined)\n * @param tailorDBServices - TailorDB services to collect type source info from\n * @param configPath - Path to tailor.config.ts for resolving plugin imports\n * @returns Generated executor file paths\n */\nexport function generatePluginFilesIfNeeded(\n  pluginManager: PluginManager | undefined,\n  tailorDBServices: ReadonlyArray<TailorDBService>,\n  configPath: string,\n): string[] {\n  if (!pluginManager) return [];\n\n  const sourceTypeInfoMap = new Map<string, { filePath: string; exportName: string }>();\n  for (const db of tailorDBServices) {\n    const typeSourceInfo = db.typeSourceInfo;\n    for (const [typeName, sourceInfo] of Object.entries(typeSourceInfo)) {\n      if (sourceInfo.filePath) {\n        sourceTypeInfoMap.set(typeName, {\n          filePath: sourceInfo.filePath,\n          exportName: sourceInfo.exportName,\n        });\n      }\n    }\n  }\n\n  return pluginManager.generatePluginFiles({\n    outputDir: path.join(getDistDir(), \"plugin\"),\n    sourceTypeInfoMap,\n    configPath,\n    typeGenerator: generatePluginTypeFiles,\n    executorGenerator: generatePluginExecutorFiles,\n  });\n}\n\n/**\n * Load and fully initialize a Tailor application.\n * This performs all I/O-heavy operations: loading types, processing plugins,\n * generating plugin files, bundling, and loading definitions for validation.\n * @param params - Parameters for defining and loading the application\n * @returns Fully initialized application with workflow results\n */\nexport async function loadApplication(\n  params: DefineApplicationParams,\n): Promise<LoadApplicationResult> {\n  const { config, pluginManager, bundleCache } = params;\n\n  // 1. Define services (synchronous)\n  const {\n    tailordbResult,\n    resolverResult,\n    idpResult,\n    authResult,\n    staticWebsiteServices,\n    aiGatewayServices,\n    secrets,\n    ignoreNullishValues,\n  } = defineServices(config, pluginManager);\n\n  // 2. Load TailorDB types and process namespace plugins\n  for (const tailordb of tailordbResult.tailorDBServices) {\n    await tailordb.loadTypes();\n    await tailordb.processNamespacePlugins();\n  }\n  assertUniqueLocalTailorDBTypeNames({\n    tailorDBServices: tailordbResult.tailorDBServices,\n  });\n\n  // 3. Generate plugin files and determine executor file paths\n  const pluginExecutorFiles = generatePluginFilesIfNeeded(\n    pluginManager,\n    tailordbResult.tailorDBServices,\n    config.path,\n  );\n\n  // 4. Determine final executorService (const, no reassignment)\n  const executorService = defineExecutor(config.executor, pluginExecutorFiles.length > 0);\n\n  // 5. Load and collect workflows\n  const workflowService = defineWorkflow(config.workflow);\n  if (workflowService) {\n    await workflowService.loadWorkflows();\n  }\n\n  // 6. Load and collect HTTP adapters\n  const httpAdapterService = defineHttpAdapterService(config.httpAdapter);\n  if (httpAdapterService) {\n    await httpAdapterService.loadAdapters();\n  }\n\n  // 7. Build trigger context for workflow/job trigger transformation\n  const triggerContext = await buildTriggerContext(\n    config.workflow,\n    authResult.authService?.config.name,\n  );\n\n  // 8. Resolve bundle settings\n  const inlineSourcemap = resolveInlineSourcemap(config.inlineSourcemap);\n  const bundleLogLevel = resolveBundleLogLevel(config.logLevel);\n\n  // Collect in-memory bundled scripts\n  const bundledScripts: BundledScripts = {\n    resolvers: new Map(),\n    executors: new Map(),\n    workflowJobs: new Map(),\n    authHooks: new Map(),\n  };\n\n  // 9. Bundle resolvers\n  for (const pipeline of resolverResult.resolverServices) {\n    const resolverBundles = await bundleResolvers(\n      pipeline.namespace,\n      pipeline.config,\n      triggerContext,\n      bundleCache,\n      inlineSourcemap,\n      bundleLogLevel,\n    );\n    for (const [name, code] of resolverBundles) {\n      bundledScripts.resolvers.set(name, code);\n    }\n  }\n\n  // 10. Bundle executors\n  if (executorService) {\n    bundledScripts.executors = await bundleExecutors({\n      config: executorService.config,\n      triggerContext,\n      additionalFiles: [...pluginExecutorFiles],\n      cache: bundleCache,\n      inlineSourcemap,\n      bundleLogLevel,\n    });\n  }\n\n  // 11. Bundle workflows\n  let workflowBuildResult: BundleWorkflowJobsResult | undefined;\n  if (workflowService && workflowService.jobs.length > 0) {\n    const mainJobNames = workflowService.workflowSources.map((ws) => ws.workflow.mainJob.name);\n    workflowBuildResult = await bundleWorkflowJobs(\n      workflowService.jobs,\n      mainJobNames,\n      config.env ?? {},\n      triggerContext,\n      bundleCache,\n      inlineSourcemap,\n      bundleLogLevel,\n    );\n    bundledScripts.workflowJobs = workflowBuildResult.bundledCode;\n  }\n\n  // 12. Bundle HTTP adapters\n  let httpAdapterBuildResult: HttpAdapterBundleResult | undefined;\n  if (httpAdapterService && httpAdapterService.adapters.length > 0) {\n    httpAdapterBuildResult = await bundleHttpAdapters(\n      httpAdapterService.adapters.map((a) => ({\n        name: a.adapter.name,\n        sourceFile: a.sourceFile,\n        methods: a.methods,\n        hasOutput: a.hasOutput,\n      })),\n      bundleCache,\n      bundleLogLevel,\n    );\n  }\n\n  // 13. Bundle auth hooks\n  if (authResult.authService?.config.hooks?.beforeLogin) {\n    const authName = authResult.authService.config.name;\n    bundledScripts.authHooks = await bundleAuthHooks({\n      configPath: config.path,\n      authName,\n      handlerAccessPath: `auth.hooks.beforeLogin.handler`,\n      env: config.env ?? {},\n      triggerContext,\n      cache: bundleCache,\n      inlineSourcemap,\n      bundleLogLevel,\n    });\n  }\n\n  // 14. Load resolver and executor definitions (for validation/logging)\n  for (const pipeline of resolverResult.resolverServices) {\n    await pipeline.loadResolvers();\n  }\n  if (executorService) {\n    await executorService.loadExecutors();\n    if (pluginExecutorFiles.length > 0) {\n      await executorService.loadPluginExecutorFiles([...pluginExecutorFiles]);\n    }\n  }\n  if (workflowService) {\n    workflowService.printLoadedWorkflows();\n  }\n  if (httpAdapterService) {\n    httpAdapterService.printLoadedAdapters();\n  }\n  logger.newline();\n\n  // 15. Build immutable Application\n  const application = buildApplication({\n    config,\n    tailordbResult,\n    resolverResult,\n    idpResult,\n    authResult,\n    executorService,\n    workflowService,\n    httpAdapterService,\n    staticWebsiteServices,\n    aiGatewayServices,\n    secrets,\n    ignoreNullishValues,\n    env: config.env ?? {},\n  });\n\n  return { application, workflowBuildResult, httpAdapterBuildResult, bundledScripts };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAa,aAAa;CAAC;CAAS;CAAQ;CAAQ;CAAS;AAAQ;AAErE,SAAgB,WAAW,OAAqD;CAC9E,OAAQ,WAAiC,SAAS,KAAK;AACzD;;;;ACDA,MAAM,iBAAiB,EAAE,MAAM;CAAC,EAAE,OAAO;CAAG,EAAE,OAAO;CAAG,EAAE,QAAQ;AAAC,CAAC;AAEpE,MAAa,iBAAiB,EAAE,KAAK,UAAU;AAE/C,MAAM,iBAAiB,EACpB,OAAO,CAAC,CACR,QAAQ,UAAU,eAAe,UA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