@tailor-platform/sdk 1.73.2 → 1.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/dist/application-BndtMTFY.mjs +3 -0
  3. package/dist/{application-Bb9NNp5m.mjs → application-DwmoI6ZQ.mjs} +231 -153
  4. package/dist/application-DwmoI6ZQ.mjs.map +1 -0
  5. package/dist/cli/commands/deploy/apply-phases.d.mts +1 -0
  6. package/dist/cli/commands/executor/trigger.d.mts +1 -1
  7. package/dist/cli/index.mjs +102 -13
  8. package/dist/cli/index.mjs.map +1 -1
  9. package/dist/cli/lib.d.mts +2 -2
  10. package/dist/cli/lib.mjs +2 -2
  11. package/dist/cli/shared/client.d.mts +1 -1
  12. package/dist/completion/zsh-worker.zsh +28 -3
  13. package/dist/{repl-editor-BmQOyZJd.mjs → repl-editor-BCozyiNq.mjs} +3 -2
  14. package/dist/{repl-editor-BmQOyZJd.mjs.map → repl-editor-BCozyiNq.mjs.map} +1 -1
  15. package/dist/{runtime-B8O6JFS2.mjs → runtime-Zkg3SUwi.mjs} +1974 -1217
  16. package/dist/runtime-Zkg3SUwi.mjs.map +1 -0
  17. package/dist/{service-DiEtAsvc.mjs → service-BCRJ-3NV.mjs} +18 -1
  18. package/dist/{service-DiEtAsvc.mjs.map → service-BCRJ-3NV.mjs.map} +1 -1
  19. package/dist/service-CPMlIg3X.mjs +3 -0
  20. package/dist/tailor-proto/src/tailor/v1/aigateway_pb.d.mts +2 -2
  21. package/dist/tailor-proto/src/tailor/v1/aigateway_resource_pb.d.mts +1 -1
  22. package/dist/tailor-proto/src/tailor/v1/application_pb.d.mts +1 -1
  23. package/dist/tailor-proto/src/tailor/v1/application_resource_pb.d.mts +1 -1
  24. package/dist/tailor-proto/src/tailor/v1/auth_pb.d.mts +1 -1
  25. package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +1 -1
  26. package/dist/tailor-proto/src/tailor/v1/events_pb.d.mts +1 -1
  27. package/dist/tailor-proto/src/tailor/v1/events_resource_pb.d.mts +1 -1
  28. package/dist/tailor-proto/src/tailor/v1/executor_pb.d.mts +1 -1
  29. package/dist/tailor-proto/src/tailor/v1/executor_resource_pb.d.mts +1 -1
  30. package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +1 -1
  31. package/dist/tailor-proto/src/tailor/v1/function_registry_pb.d.mts +1 -1
  32. package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +1 -1
  33. package/dist/tailor-proto/src/tailor/v1/http_adapter_resource_pb.d.mts +1 -1
  34. package/dist/tailor-proto/src/tailor/v1/idp_pb.d.mts +1 -1
  35. package/dist/tailor-proto/src/tailor/v1/idp_resource_pb.d.mts +1 -1
  36. package/dist/tailor-proto/src/tailor/v1/metadata_pb.d.mts +1 -1
  37. package/dist/tailor-proto/src/tailor/v1/metadata_resource_pb.d.mts +1 -1
  38. package/dist/tailor-proto/src/tailor/v1/meter_pb.d.mts +1 -1
  39. package/dist/tailor-proto/src/tailor/v1/pipeline_pb.d.mts +1 -1
  40. package/dist/tailor-proto/src/tailor/v1/pipeline_resource_pb.d.mts +1 -1
  41. package/dist/tailor-proto/src/tailor/v1/resource_pb.d.mts +1 -1
  42. package/dist/tailor-proto/src/tailor/v1/secret_manager_pb.d.mts +1 -1
  43. package/dist/tailor-proto/src/tailor/v1/secret_manager_resource_pb.d.mts +1 -1
  44. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +2 -2
  45. package/dist/tailor-proto/src/tailor/v1/stateflow_pb.d.mts +1 -1
  46. package/dist/tailor-proto/src/tailor/v1/stateflow_resource_pb.d.mts +1 -1
  47. package/dist/tailor-proto/src/tailor/v1/staticwebsite_pb.d.mts +1 -1
  48. package/dist/tailor-proto/src/tailor/v1/staticwebsite_resource_pb.d.mts +1 -1
  49. package/dist/tailor-proto/src/tailor/v1/tailordb_pb.d.mts +1 -1
  50. package/dist/tailor-proto/src/tailor/v1/tailordb_resource_pb.d.mts +1 -1
  51. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_pb.d.mts +1 -1
  52. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_resource_pb.d.mts +1 -1
  53. package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +1 -1
  54. package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +1 -1
  55. package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +2 -2
  56. package/dist/tailor-proto/src/tailor/v1/workspace_resource_pb.d.mts +1 -1
  57. package/dist/vitest/index.mjs +2 -1
  58. package/dist/vitest/index.mjs.map +1 -1
  59. package/docs/cli/application.md +21 -11
  60. package/docs/cli/setup.md +25 -0
  61. package/docs/cli-reference.md +1 -0
  62. package/docs/services/tailordb.md +23 -0
  63. package/package.json +8 -8
  64. package/dist/application-BXdCl6bp.mjs +0 -3
  65. package/dist/application-Bb9NNp5m.mjs.map +0 -1
  66. package/dist/runtime-B8O6JFS2.mjs.map +0 -1
  67. package/dist/service-BXmdFwSH.mjs +0 -3
@@ -1,5 +1,5 @@
1
- import { Message } from "@bufbuild/protobuf";
2
1
  import { GenMessage } from "@bufbuild/protobuf/codegenv2";
2
+ import { Message } from "@bufbuild/protobuf";
3
3
  import { Duration, Timestamp } from "@bufbuild/protobuf/wkt";
4
4
 
5
5
  //#region ../tailor-proto/src/tailor/v1/workflow_resource_pb.d.ts
@@ -1,7 +1,7 @@
1
- import { PageDirection } from "./resource_pb.mjs";
2
1
  import { Folder, FolderAccess, FolderRole, Organization, OrganizationAccess, OrganizationRole, PlatformAccountPlan, Team, TeamMember, TeamRole, Workspace, WorkspacePlatformUser, WorkspacePlatformUserRole } from "./workspace_resource_pb.mjs";
3
- import { Message } from "@bufbuild/protobuf";
2
+ import { PageDirection } from "./resource_pb.mjs";
4
3
  import { GenMessage } from "@bufbuild/protobuf/codegenv2";
4
+ import { Message } from "@bufbuild/protobuf";
5
5
  import { FieldMask, Timestamp } from "@bufbuild/protobuf/wkt";
6
6
 
7
7
  //#region ../tailor-proto/src/tailor/v1/workspace_pb.d.ts
@@ -1,5 +1,5 @@
1
- import { Message } from "@bufbuild/protobuf";
2
1
  import { GenMessage } from "@bufbuild/protobuf/codegenv2";
2
+ import { Message } from "@bufbuild/protobuf";
3
3
  import { Timestamp } from "@bufbuild/protobuf/wkt";
4
4
 
5
5
  //#region ../tailor-proto/src/tailor/v1/workspace_resource_pb.d.ts
@@ -49,7 +49,8 @@ function isBlockedModule(specifier) {
49
49
  * @returns Error message with optional suggestion for the Web Standard API alternative
50
50
  */
51
51
  function getBlockedMessage(specifier) {
52
- const suggestion = SUGGESTIONS[specifier.startsWith("node:") ? specifier.slice(5) : specifier];
52
+ const bare = specifier.startsWith("node:") ? specifier.slice(5) : specifier;
53
+ const suggestion = SUGGESTIONS[bare];
53
54
  const base = `"${specifier}" is not available in the Tailor Platform runtime.`;
54
55
  return suggestion ? `${base} ${suggestion}` : base;
55
56
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/vitest/blocked-modules.ts","../../src/vitest/plugin.ts","../../src/vitest/mock-kysely.ts","../../src/vitest/index.ts"],"sourcesContent":["/**\n * Blocked Node.js built-in modules and their Web Standard API alternatives.\n *\n * The Tailor Platform runtime only provides Web Standard APIs.\n * These Node.js modules are not available and should be replaced with\n * the suggested alternatives.\n */\nimport { builtinModules } from \"node:module\";\n\n// Suggestions keyed by bare specifier. Lookup also checks with \"node:\" prefix stripped.\nconst SUGGESTIONS: Record<string, string> = {\n crypto: \"Use the Web Crypto API (globalThis.crypto) instead.\",\n buffer: \"Use Uint8Array or ArrayBuffer instead.\",\n fs: \"File system access is not available in the Tailor Platform runtime.\",\n \"fs/promises\": \"File system access is not available in the Tailor Platform runtime.\",\n path: \"Use URL or URLPattern for path manipulation.\",\n http: \"Use the Fetch API (globalThis.fetch) for HTTP requests instead.\",\n https: \"Use the Fetch API (globalThis.fetch) for HTTPS requests instead.\",\n url: \"Use the URL and URLSearchParams Web APIs instead.\",\n util: \"Use Web Standard APIs instead.\",\n stream: \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n \"stream/web\": \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n events: \"Use EventTarget instead.\",\n zlib: \"Use CompressionStream and DecompressionStream Web APIs instead.\",\n querystring: \"Use URLSearchParams instead.\",\n string_decoder: \"Use TextDecoder instead.\",\n};\n\nconst BLOCKED_MODULES = new Set<string>();\nfor (const mod of builtinModules) {\n BLOCKED_MODULES.add(mod);\n BLOCKED_MODULES.add(`node:${mod}`);\n}\n\n/**\n * Check if a module specifier is a blocked Node.js built-in.\n * @param specifier - Module specifier to check (e.g. \"node:crypto\", \"fs\")\n * @returns Whether the specifier is blocked\n */\nexport function isBlockedModule(specifier: string): boolean {\n return BLOCKED_MODULES.has(specifier);\n}\n\n/**\n * Get the error message for a blocked module import.\n * @param specifier - Module specifier that was blocked\n * @returns Error message with optional suggestion for the Web Standard API alternative\n */\nexport function getBlockedMessage(specifier: string): string {\n const bare = specifier.startsWith(\"node:\") ? specifier.slice(5) : specifier;\n const suggestion = SUGGESTIONS[bare];\n const base = `\"${specifier}\" is not available in the Tailor Platform runtime.`;\n return suggestion ? `${base} ${suggestion}` : base;\n}\n","import { dirname, isAbsolute, matchesGlob, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { isBlockedModule, getBlockedMessage } from \"./blocked-modules\";\nimport type { Plugin } from \"vitest/config\";\n\nconst DEFAULT_TEST_INCLUDE = [\"**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}\"];\n\ninterface ExportSpecifierNode {\n type?: string;\n exported?: { name?: unknown } | null;\n}\n\ninterface ImportLikeNode {\n type: string;\n start: number;\n end: number;\n source?: { value?: unknown } | null;\n specifiers?: ExportSpecifierNode[] | null;\n exported?: { name?: unknown } | null;\n}\n\nconst IMPORT_LIKE_TYPES = new Set([\n \"ImportDeclaration\",\n \"ExportNamedDeclaration\",\n \"ExportAllDeclaration\",\n]);\n\n// Re-export specifiers (`export { x as Y } from \"...\"`) accept any\n// `IdentifierName` for `Y` — including reserved words like `delete`. But\n// `export const Y = ...` requires a `BindingIdentifier`, which forbids\n// reserved words and the strict-mode-banned `arguments` / `eval`. Synthesizing\n// `export const delete = ...` would yield a syntax error, so we fall back to\n// plain `throw` for unsafe names.\nconst UNSAFE_BINDING_NAMES = new Set([\n // ReservedWord (ES2022+)\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"enum\",\n \"export\",\n \"extends\",\n \"false\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"new\",\n \"null\",\n \"return\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"true\",\n \"try\",\n \"typeof\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n // Strict-mode reserved (ESM is always strict)\n \"let\",\n \"static\",\n \"implements\",\n \"interface\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n // Module-specific reserved\n \"await\",\n // Banned as binding names in strict mode\n \"arguments\",\n \"eval\",\n]);\n\nconst ID_START = /^[A-Za-z_$]/;\nconst ID_CONT = /^[A-Za-z0-9_$]*$/;\n\nfunction isSafeBindingName(name: string): boolean {\n if (UNSAFE_BINDING_NAMES.has(name)) return false;\n if (name.length === 0) return false;\n // Restrict to ASCII identifiers — Unicode bindings are valid JS but rare\n // for re-exports of node:* modules, and a regex over the full\n // ID_Start/ID_Continue sets adds substantial weight for marginal gain.\n const firstChar = name[0];\n if (firstChar === undefined) return false;\n return ID_START.test(firstChar) && ID_CONT.test(name.slice(1));\n}\n\nfunction buildBlockedReplacement(node: ImportLikeNode, message: string): string {\n // JSON.stringify yields a fully-escaped string literal (including the\n // surrounding quotes), so we don't need to manually handle backslashes,\n // newlines, or other control characters that may appear in the message.\n const literal = JSON.stringify(message);\n const throwStmt = `throw new Error(${literal});`;\n const throwExpr = `(() => { throw new Error(${literal}); })()`;\n\n if (node.type === \"ExportNamedDeclaration\") {\n const specs = node.specifiers ?? [];\n const stubs: string[] = [];\n for (const spec of specs) {\n const exportedName = spec.exported?.name;\n if (typeof exportedName !== \"string\") continue;\n if (exportedName === \"default\") {\n stubs.push(`export default ${throwExpr};`);\n continue;\n }\n // Reserved words can be re-export names but not binding names.\n // Bail to a plain throw rather than emit invalid syntax.\n if (!isSafeBindingName(exportedName)) return throwStmt;\n stubs.push(`export const ${exportedName} = ${throwExpr};`);\n }\n return stubs.length > 0 ? stubs.join(\" \") : throwStmt;\n }\n\n if (node.type === \"ExportAllDeclaration\") {\n const exportedName = node.exported?.name;\n if (typeof exportedName === \"string\" && isSafeBindingName(exportedName)) {\n return `export const ${exportedName} = ${throwExpr};`;\n }\n return throwStmt;\n }\n\n return throwStmt;\n}\n\n/**\n * Vite plugin that blocks Node.js built-in module imports from production code.\n *\n * Uses the `transform` hook to walk the Rollup-provided AST of non-test source\n * files for static `node:*` imports and re-exports.\n * `ImportDeclaration` and bare `export * from \"...\"` are replaced with a\n * `throw new Error(...)` statement so the failure surfaces at evaluation time.\n * `ExportNamedDeclaration` (`export { x, y as z } from \"...\"`) and namespaced\n * `export * as ns from \"...\"` are rewritten to per-binding stub exports\n * (`export const x = (() => { throw new Error(...) })();`). The IIFE throws\n * eagerly during module evaluation (same timing as a top-level `throw`), but\n * preserving the declared export bindings ensures the surfaced error is the\n * actual \"node:* not available\" message rather than an opaque\n * \"missing export\" raised by the loader.\n * Vitest treats `node:*` as external SSR modules (skipping `resolveId`), so\n * source-level transformation is the only reliable interception point.\n * Runs in the default phase (no `enforce: \"pre\"`) so esbuild's TypeScript\n * transform strips `import type` first; only runtime imports reach this hook.\n * Node.js globals not in the platform runtime are removed by the environment (whitelist-based).\n * Test file patterns are read from the resolved Vitest config (`test.include`).\n * Vitest setup files (`test.setupFiles`) and global-setup files\n * (`test.globalSetup`) are also exempted: they run in the test runner host,\n * not in the emulated platform runtime, so they may freely use `node:*`\n * modules (e.g. `node:url` for `pathToFileURL`).\n * @returns Vite plugin\n */\nexport function createBlockPlugin(): Plugin {\n let isTestFile: (id: string) => boolean = () => false;\n let isUserSourceFile: (id: string) => boolean = () => false;\n\n return {\n name: \"tailor-runtime-block-node\",\n\n configResolved(config) {\n type HostFileTestConfig = {\n include?: string[];\n setupFiles?: string | string[];\n globalSetup?: string | string[];\n root?: string;\n };\n const testConfig = (\n config as typeof config & {\n test?: HostFileTestConfig & {\n projects?: { test?: HostFileTestConfig }[];\n };\n }\n ).test;\n const root = testConfig?.root ?? config.root;\n // Setup files and global-setup files run in the Vitest host (not the\n // emulated runtime), so they may freely import node:* modules. Collect\n // them from the top-level config AND from each `test.projects[i]` —\n // per-project setup files run in the host too and would otherwise be\n // transformed as production code, breaking node:* imports inside them.\n const toAbsolutePaths = (value: string | string[] | undefined, baseRoot: string) =>\n (Array.isArray(value) ? value : value ? [value] : []).map((f) => resolve(baseRoot, f));\n const exemptHostFiles = new Set<string>([\n ...toAbsolutePaths(testConfig?.setupFiles, root),\n ...toAbsolutePaths(testConfig?.globalSetup, root),\n ]);\n // Vitest projects can each define their own `test.include` (and root).\n // A project that uses non-default patterns (e.g. `tests/**/*.spec.ts`)\n // must also be considered when classifying test files — otherwise its\n // tests would be treated as production code and have node:* imports\n // rewritten. Build a list of (root, patterns) pairs covering top-level\n // + every project, and accept a file if any pair matches.\n const includePairs: { root: string; patterns: string[] }[] = [\n { root, patterns: testConfig?.include ?? DEFAULT_TEST_INCLUDE },\n ];\n for (const project of testConfig?.projects ?? []) {\n const projectTest = project.test;\n if (!projectTest) continue;\n const projectRoot = projectTest.root ?? root;\n for (const f of toAbsolutePaths(projectTest.setupFiles, projectRoot)) {\n exemptHostFiles.add(f);\n }\n for (const f of toAbsolutePaths(projectTest.globalSetup, projectRoot)) {\n exemptHostFiles.add(f);\n }\n includePairs.push({\n root: projectRoot,\n patterns: projectTest.include ?? DEFAULT_TEST_INCLUDE,\n });\n }\n isTestFile = (id: string) => {\n if (exemptHostFiles.has(id)) return true;\n return includePairs.some(({ root: r, patterns }) => {\n const candidate = isAbsolute(id) ? relative(r, id) : id;\n return patterns.some((pattern) => matchesGlob(candidate, pattern));\n });\n };\n // Only transform files inside the project root. With pnpm workspaces,\n // dependencies are symlinked and Vite resolves them to absolute paths\n // outside `node_modules`, so the substring check alone is insufficient.\n // Non-absolute ids are Vite-internal: virtual modules (`\\0...`,\n // `virtual:...`), bare specifiers, etc. Those are never user source\n // files and must not be parsed/transformed.\n isUserSourceFile = (id: string) => {\n if (!isAbsolute(id)) return false;\n const rel = relative(root, id);\n return rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel);\n };\n },\n\n transform(code, id) {\n // Vite can pass ids with query/hash suffixes (e.g. `file.ts?import`,\n // `file.ts?v=hash`). Strip them so exact-path lookups (Set membership,\n // glob matching, absolute-path checks) match what callers configured.\n const queryIdx = id.search(/[?#]/);\n const cleanId = queryIdx === -1 ? id : id.slice(0, queryIdx);\n\n if (isTestFile(cleanId)) return undefined;\n if (cleanId.includes(\"node_modules\")) return undefined;\n if (!isUserSourceFile(cleanId)) return undefined;\n\n let ast: { body: ImportLikeNode[] };\n try {\n ast = this.parse(code) as unknown as { body: ImportLikeNode[] };\n } catch {\n // Not parseable as ESM (e.g. JSON, asset). Let other plugins handle it.\n return undefined;\n }\n\n const replacements: { start: number; end: number; replacement: string }[] = [];\n for (const node of ast.body) {\n if (!IMPORT_LIKE_TYPES.has(node.type)) continue;\n const specifier = node.source?.value;\n if (typeof specifier !== \"string\") continue;\n if (isBlockedModule(specifier)) {\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: buildBlockedReplacement(node, getBlockedMessage(specifier)),\n });\n }\n }\n\n if (replacements.length === 0) return undefined;\n\n let transformed = code;\n for (const r of replacements.toSorted((a, b) => b.start - a.start)) {\n transformed = transformed.slice(0, r.start) + r.replacement + transformed.slice(r.end);\n }\n\n return { code: transformed, map: null };\n },\n };\n}\n\nconst ENVIRONMENT_NAME = \"tailor-runtime\";\n\n/**\n * Vite plugin that resolves the tailor-runtime environment and injects setup files.\n *\n * Vitest resolves environments starting with \".\" or \"/\" as file paths.\n * This plugin rewrites `environment: \"tailor-runtime\"` to the absolute path\n * of the bundled environment module, both at the top-level and per-project.\n * It also injects the setup file that removes Vitest-dependent globals\n * (like `performance`) per-test via beforeEach/afterEach hooks.\n * @param options - Optional configuration\n * @param options.config - Path to tailor.config.ts to load SecretManager values into mock\n * @returns Vite plugin\n */\nexport function createEnvironmentPlugin(options?: { config?: string }): Plugin {\n const currentDir = dirname(fileURLToPath(import.meta.url));\n const environmentPath = resolve(currentDir, \"environment.mjs\");\n const setupPath = resolve(currentDir, \"setup.mjs\");\n\n return {\n name: \"tailor-runtime-environment\",\n\n config(config) {\n const testConfig = config.test as\n | (Record<string, unknown> & {\n projects?: Record<string, unknown>[];\n setupFiles?: string | string[];\n })\n | undefined;\n\n // Rewrite environment name to absolute path at top-level\n let usesTailorRuntime = false;\n if (testConfig?.environment === ENVIRONMENT_NAME) {\n testConfig.environment = environmentPath;\n usesTailorRuntime = true;\n }\n\n // Rewrite in each project config\n if (testConfig?.projects) {\n for (const project of testConfig.projects) {\n const projectTest = project.test as Record<string, unknown> | undefined;\n if (projectTest?.environment === ENVIRONMENT_NAME) {\n projectTest.environment = environmentPath;\n usesTailorRuntime = true;\n }\n }\n }\n\n // Pass config path to setup.ts via env var (cross-process compatible).\n // Always clear first, then set only when tailor-runtime is actually\n // selected. This makes the env var deterministic across Vite config\n // reloads (watch mode, programmatic re-init): a stale value from a\n // prior iteration cannot make setup.ts load secrets from an old config.\n // The leading `__` marks this as plugin-private, so deleting any\n // pre-existing value is safe.\n delete process.env.__TAILOR_RUNTIME_CONFIG;\n if (options?.config && usesTailorRuntime) {\n // Resolve against the user-provided Vite root when present (falling\n // back to cwd). Vitest projects with a non-cwd `root` would otherwise\n // resolve a relative options.config against the wrong directory.\n const configRoot = (config.root as string | undefined) ?? process.cwd();\n const configAbsPath = resolve(configRoot, options.config);\n process.env.__TAILOR_RUNTIME_CONFIG = configAbsPath;\n }\n\n // Normalize a user-provided string `setupFiles` into an array so Vite's\n // array-concat merge sees both sides as arrays (the string form would\n // otherwise be replaced rather than concatenated by some merge paths).\n // Vite then concatenates the user's array with our [setupPath].\n if (testConfig && typeof testConfig.setupFiles === \"string\") {\n testConfig.setupFiles = [testConfig.setupFiles];\n }\n\n return {\n test: {\n setupFiles: [setupPath],\n },\n };\n },\n };\n}\n","/**\n * Kysely-layer mock for unit testing.\n *\n * Builds a real Kysely instance backed by a mock driver: queries compile and\n * type-check normally, but execution returns staged rows and records every\n * query for assertions.\n */\n\nimport {\n ColumnNode,\n type CompiledQuery,\n type DatabaseConnection,\n type Dialect,\n type Driver,\n InsertQueryNode,\n Kysely,\n type OperationNode,\n type OperationNodeKind,\n PostgresAdapter,\n PostgresIntrospector,\n PostgresQueryCompiler,\n PrimitiveValueListNode,\n type QueryResult,\n ReferenceNode,\n type Transaction,\n UpdateQueryNode,\n ValueListNode,\n ValueNode,\n ValuesNode,\n} from \"kysely\";\nimport { assertDefined } from \"#/utils/assert\";\n\nfunction unwrapValue(node: OperationNode): unknown {\n return ValueNode.is(node) ? node.value : node;\n}\n\nfunction insertRows(node: OperationNode): Record<string, unknown>[] {\n if (!InsertQueryNode.is(node)) {\n throw new Error(`insertRows: expected InsertQueryNode, got ${node.kind}`);\n }\n const columns = node.columns;\n const valuesNode = node.values;\n if (columns === undefined || valuesNode === undefined || !ValuesNode.is(valuesNode)) {\n throw new Error(\"insertRows: unsupported insert shape; inspect query.node instead\");\n }\n return valuesNode.values.map((row) => {\n if (!PrimitiveValueListNode.is(row) && !ValueListNode.is(row)) {\n throw new Error(\"insertRows: unsupported insert shape; inspect query.node instead\");\n }\n const values = PrimitiveValueListNode.is(row) ? row.values : row.values.map(unwrapValue);\n const result: Record<string, unknown> = {};\n columns.forEach((col, i) => {\n result[col.column.name] = values[i];\n });\n return result;\n });\n}\n\nfunction insertValues(node: OperationNode): Record<string, unknown> {\n const rows = insertRows(node);\n if (rows.length !== 1) {\n throw new Error(\n `insertValues: query inserts ${rows.length} rows; use insertRows() for multi-row inserts`,\n );\n }\n return assertDefined(rows[0], \"insertValues: first row missing\");\n}\n\nfunction updateValues(node: OperationNode): Record<string, unknown> {\n if (!UpdateQueryNode.is(node)) {\n throw new Error(`updateValues: expected UpdateQueryNode, got ${node.kind}`);\n }\n if (node.updates === undefined) {\n throw new Error(\"updateValues: unsupported update shape; inspect query.node instead\");\n }\n const result: Record<string, unknown> = {};\n for (const update of node.updates) {\n const col = update.column;\n const name = ColumnNode.is(col)\n ? col.column.name\n : ReferenceNode.is(col) && ColumnNode.is(col.column)\n ? col.column.column.name\n : undefined;\n if (name === undefined) {\n throw new Error(\"updateValues: unsupported update shape; inspect query.node instead\");\n }\n result[name] = unwrapValue(update.value);\n }\n return result;\n}\n\n/** A single statement executed against the mock, captured in order. */\nexport interface ExecutedQuery {\n /** The Kysely operation node kind, e.g. `\"SelectQueryNode\"`. */\n kind: OperationNodeKind;\n /** The compiled SQL string. */\n sql: string;\n /** The bound parameter values, in positional order. */\n parameters: readonly unknown[];\n /** The compiled Kysely operation node. */\n node: OperationNode;\n /** One `{ column: value }` map per row written by an insert. */\n insertRows: () => Record<string, unknown>[];\n /** The `{ column: value }` map written by a single-row insert. */\n insertValues: () => Record<string, unknown>;\n /** The `{ column: value }` map written by an update's SET clause. */\n updateValues: () => Record<string, unknown>;\n}\n\nfunction toExecutedQuery(compiledQuery: CompiledQuery): ExecutedQuery {\n const node = compiledQuery.query;\n return {\n kind: node.kind,\n sql: compiledQuery.sql,\n parameters: compiledQuery.parameters,\n node,\n insertRows: () => insertRows(node),\n insertValues: () => insertValues(node),\n updateValues: () => updateValues(node),\n };\n}\n\ntype MockRow = Record<string, unknown>;\ntype MockResult = MockRow[] | { rows?: MockRow[]; numAffectedRows?: number | bigint };\ntype QueryResolver = (query: ExecutedQuery) => MockResult | undefined;\n\ninterface StagedResult {\n rows: MockRow[];\n numAffectedRows: bigint | undefined;\n}\n\nfunction toStagedResult(result: MockResult): StagedResult {\n if (Array.isArray(result)) return { rows: result, numAffectedRows: undefined };\n return {\n rows: result.rows ?? [],\n numAffectedRows:\n result.numAffectedRows === undefined ? undefined : BigInt(result.numAffectedRows),\n };\n}\n\n/** Controls and assertions for a {@link createKyselyMock} instance. */\nexport interface KyselyMock<DB> {\n /** The mock Kysely instance to run queries against. */\n db: Kysely<DB>;\n /** Every recorded query, in execution order. */\n executedQueries: ExecutedQuery[];\n /** Recorded SELECT queries. */\n selects: ExecutedQuery[];\n /** Recorded INSERT queries. */\n inserts: ExecutedQuery[];\n /** Recorded UPDATE queries. */\n updates: ExecutedQuery[];\n /** Recorded DELETE queries. */\n deletes: ExecutedQuery[];\n /** Stage the rows the next query returns. */\n enqueueResult: (result: MockResult) => void;\n /** Stage the rows for several upcoming queries, consumed in order. */\n enqueueResults: (...results: MockResult[]) => void;\n /** Set a resolver that returns rows by inspecting each query. */\n setQueryResolver: (resolver: QueryResolver) => void;\n /** Run `fn` inside a real transaction and return its result. */\n withTx: <R>(fn: (trx: Transaction<DB>) => Promise<R>) => Promise<R>;\n /** Clear recorded queries and staged results. */\n reset: () => void;\n /** Same as {@link KyselyMock.reset}; enables `using` disposal. */\n [Symbol.dispose]: () => void;\n}\n\nclass MockState {\n readonly executed: ExecutedQuery[] = [];\n private readonly queue: MockResult[] = [];\n private resolver: QueryResolver | undefined;\n\n enqueue(...results: MockResult[]): void {\n this.queue.push(...results);\n }\n\n setResolver(resolver: QueryResolver): void {\n this.resolver = resolver;\n }\n\n next(query: ExecutedQuery): StagedResult {\n const resolved = this.resolver?.(query);\n if (resolved !== undefined) return toStagedResult(resolved);\n const queued = this.queue.shift();\n return queued === undefined ? { rows: [], numAffectedRows: undefined } : toStagedResult(queued);\n }\n\n reset(): void {\n this.executed.length = 0;\n this.queue.length = 0;\n this.resolver = undefined;\n }\n}\n\nclass MockConnection implements DatabaseConnection {\n constructor(private readonly state: MockState) {}\n\n async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {\n const query = toExecutedQuery(compiledQuery);\n this.state.executed.push(query);\n const { rows, numAffectedRows } = this.state.next(query);\n return {\n rows: rows as R[],\n numAffectedRows: numAffectedRows ?? BigInt(rows.length),\n };\n }\n\n streamQuery<R>(): AsyncIterableIterator<QueryResult<R>> {\n throw new Error(\"createKyselyMock: streaming is not supported\");\n }\n}\n\nclass MockDriver implements Driver {\n constructor(private readonly state: MockState) {}\n\n async init(): Promise<void> {}\n\n async acquireConnection(): Promise<DatabaseConnection> {\n return new MockConnection(this.state);\n }\n\n // No-ops so begin/commit/rollback never enter `executed` and pollute counts.\n async beginTransaction(): Promise<void> {}\n async commitTransaction(): Promise<void> {}\n async rollbackTransaction(): Promise<void> {}\n\n async releaseConnection(): Promise<void> {}\n async destroy(): Promise<void> {}\n}\n\nfunction byKind(state: MockState, kind: OperationNodeKind): ExecutedQuery[] {\n return state.executed.filter((query) => query.kind === kind);\n}\n\n/**\n * Create a mock Kysely instance for unit-testing code that runs Kysely queries.\n * Pass the namespace schema as the type argument, e.g.\n * `createKyselyMock<Namespace[\"main-db\"]>()`.\n * @returns A {@link KyselyMock} with the mock `db`, recorded queries, and result staging.\n */\nexport function createKyselyMock<DB = Record<string, never>>(): KyselyMock<DB> {\n const state = new MockState();\n const dialect: Dialect = {\n createDriver: () => new MockDriver(state),\n createQueryCompiler: () => new PostgresQueryCompiler(),\n createAdapter: () => new PostgresAdapter(),\n createIntrospector: (db) => new PostgresIntrospector(db),\n };\n const kysely = new Kysely<DB>({ dialect });\n\n return {\n db: kysely,\n get executedQueries() {\n return state.executed;\n },\n get selects() {\n return byKind(state, \"SelectQueryNode\");\n },\n get inserts() {\n return byKind(state, \"InsertQueryNode\");\n },\n get updates() {\n return byKind(state, \"UpdateQueryNode\");\n },\n get deletes() {\n return byKind(state, \"DeleteQueryNode\");\n },\n enqueueResult: (result) => state.enqueue(result),\n enqueueResults: (...results) => state.enqueue(...results),\n setQueryResolver: (resolver) => state.setResolver(resolver),\n withTx: (fn) => kysely.transaction().execute(fn),\n reset: () => state.reset(),\n [Symbol.dispose]: () => state.reset(),\n };\n}\n","import { createBlockPlugin, createEnvironmentPlugin } from \"./plugin\";\nimport type { Plugin } from \"vitest/config\";\n\n/**\n * Creates Vitest plugins that emulate the Tailor Platform function runtime environment.\n *\n * **Beta:** This API may change in future releases.\n *\n * ## What it does\n *\n * 1. **Node.js module blocking** (transform hook) — Imports of `node:*` modules\n * (and bare builtins like `crypto`, `fs`) in non-test source files are replaced\n * with code that throws an error with a suggestion for the Web Standard API alternative.\n * Test files are exempt and can use `node:*` freely. Test file patterns are read\n * from the resolved Vitest config (`test.include`).\n *\n * 2. **Node.js globals removal** (environment + setup) — Only globals available in the\n * Tailor Platform runtime are kept (whitelist: ECMAScript standard, Web Standard APIs\n * from bootstrap.js, platform mocks). All others (`Buffer`, `global`, `setImmediate`,\n * `__dirname`, `__filename`, etc.) are removed. `performance` is removed per-test\n * via beforeEach/afterEach since Vitest needs it during initialization.\n *\n * 3. **Platform API mocks** (environment) — All platform APIs are auto-injected with\n * control objects: `mockTailordb`, `mockWorkflow`, `mockSecretmanager`,\n * `mockAuthconnection`, `mockIdp`, `mockFile`, `mockIconv`, `mockAigateway`. Each\n * provides response configuration, call recording, and reset.\n *\n * 4. **Environment resolution** — Rewrites `environment: \"tailor-runtime\"` to the\n * absolute path of the bundled environment module via the config hook.\n *\n * ## Known limitations\n *\n * - **`process`** and **`require`** are NOT removed or blocked. Vitest's internal\n * runner depends on them. On the real Tailor Platform runtime, they do not exist.\n * - **Dynamic `import()`** of bundled files (via `createImportMain()`) bypasses\n * the transform hook since those files are loaded through Node.js native loader.\n * ## Options\n *\n * - **`config`** — Path to `tailor.config.ts`. Loads `defineSecretManager()` values\n * into `mockSecretmanager` so `getSecret()` returns the configured values.\n * @example\n * ```typescript\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { tailorRuntime } from \"@tailor-platform/sdk/vitest\";\n *\n * export default defineConfig({\n * plugins: [tailorRuntime({ config: \"./tailor.config.ts\" })],\n * test: {\n * environment: \"tailor-runtime\",\n * },\n * });\n * ```\n * @param options - Optional configuration\n * @param options.config - Path to tailor.config.ts to load SecretManager values into mock\n * @returns Array of Vite plugins\n */\nexport function tailorRuntime(options?: { config?: string }): Plugin[] {\n return [createBlockPlugin(), createEnvironmentPlugin(options)];\n}\n\nexport {\n mockTailordb,\n mockWorkflow,\n mockSecretmanager,\n mockAuthconnection,\n mockIdp,\n mockFile,\n mockIconv,\n mockAigateway,\n} from \"./mock\";\n\nexport { createKyselyMock, type KyselyMock, type ExecutedQuery } from \"./mock-kysely\";\n"],"mappings":";;;;;;;;;;;;;;;AAUA,MAAM,cAAsC;CAC1C,QAAQ;CACR,QAAQ;CACR,IAAI;CACJ,eAAe;CACf,MAAM;CACN,MAAM;CACN,OAAO;CACP,KAAK;CACL,MAAM;CACN,QAAQ;CACR,cAAc;CACd,QAAQ;CACR,MAAM;CACN,aAAa;CACb,gBAAgB;AAClB;AAEA,MAAM,kCAAkB,IAAI,IAAY;AACxC,KAAK,MAAM,OAAO,gBAAgB;CAChC,gBAAgB,IAAI,GAAG;CACvB,gBAAgB,IAAI,QAAQ,KAAK;AACnC;;;;;;AAOA,SAAgB,gBAAgB,WAA4B;CAC1D,OAAO,gBAAgB,IAAI,SAAS;AACtC;;;;;;AAOA,SAAgB,kBAAkB,WAA2B;CAE3D,MAAM,aAAa,YADN,UAAU,WAAW,OAAO,IAAI,UAAU,MAAM,CAAC,IAAI;CAElE,MAAM,OAAO,IAAI,UAAU;CAC3B,OAAO,aAAa,GAAG,KAAK,GAAG,eAAe;AAChD;;;;AChDA,MAAM,uBAAuB,CAAC,kDAAkD;AAgBhF,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;AACF,CAAC;AAQD,MAAM,u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,MAA0C;CAC1E,OAAO,MAAM,SAAS,QAAQ,UAAU,MAAM,SAAS,IAAI;AAC7D;;;;;;;AAQA,SAAgB,mBAA+D;CAC7E,MAAM,QAAQ,IAAI,UAAU;CAO5B,MAAM,SAAS,IAAI,OAAW,EAAE;EAL9B,oBAAoB,IAAI,WAAW,KAAK;EACxC,2BAA2B,IAAI,sBAAsB;EACrD,qBAAqB,IAAI,gBAAgB;EACzC,qBAAqB,OAAO,IAAI,qBAAqB,EAAE;CAEnB,EAAE,CAAC;CAEzC,OAAO;EACL,IAAI;EACJ,IAAI,kBAAkB;GACpB,OAAO,MAAM;EACf;EACA,IAAI,UAAU;GACZ,OAAO,OAAO,OAAO,iBAAiB;EACxC;EACA,IAAI,UAAU;GACZ,OAAO,OAAO,OAAO,iBAAiB;EACxC;EACA,IAAI,UAAU;GACZ,OAAO,OAAO,OAAO,iBAAiB;EACxC;EACA,IAAI,UAAU;GACZ,OAAO,OAAO,OAAO,iBAAiB;EACxC;EACA,gBAAgB,WAAW,MAAM,QAAQ,MAAM;EAC/C,iBAAiB,GAAG,YAAY,MAAM,QAAQ,GAAG,OAAO;EACxD,mBAAmB,aAAa,MAAM,YAAY,QAAQ;EAC1D,SAAS,OAAO,OAAO,YAAY,CAAC,CAAC,QAAQ,EAAE;EAC/C,aAAa,MAAM,MAAM;GACxB,OAAO,gBAAgB,MAAM,MAAM;CACtC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1NA,SAAgB,cAAc,SAAyC;CACrE,OAAO,CAAC,kBAAkB,GAAG,wBAAwB,OAAO,CAAC;AAC/D"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/vitest/blocked-modules.ts","../../src/vitest/plugin.ts","../../src/vitest/mock-kysely.ts","../../src/vitest/index.ts"],"sourcesContent":["/**\n * Blocked Node.js built-in modules and their Web Standard API alternatives.\n *\n * The Tailor Platform runtime only provides Web Standard APIs.\n * These Node.js modules are not available and should be replaced with\n * the suggested alternatives.\n */\nimport { builtinModules } from \"node:module\";\n\n// Suggestions keyed by bare specifier. Lookup also checks with \"node:\" prefix stripped.\nconst SUGGESTIONS: Record<string, string> = {\n crypto: \"Use the Web Crypto API (globalThis.crypto) instead.\",\n buffer: \"Use Uint8Array or ArrayBuffer instead.\",\n fs: \"File system access is not available in the Tailor Platform runtime.\",\n \"fs/promises\": \"File system access is not available in the Tailor Platform runtime.\",\n path: \"Use URL or URLPattern for path manipulation.\",\n http: \"Use the Fetch API (globalThis.fetch) for HTTP requests instead.\",\n https: \"Use the Fetch API (globalThis.fetch) for HTTPS requests instead.\",\n url: \"Use the URL and URLSearchParams Web APIs instead.\",\n util: \"Use Web Standard APIs instead.\",\n stream: \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n \"stream/web\": \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n events: \"Use EventTarget instead.\",\n zlib: \"Use CompressionStream and DecompressionStream Web APIs instead.\",\n querystring: \"Use URLSearchParams instead.\",\n string_decoder: \"Use TextDecoder instead.\",\n};\n\nconst BLOCKED_MODULES = new Set<string>();\nfor (const mod of builtinModules) {\n BLOCKED_MODULES.add(mod);\n BLOCKED_MODULES.add(`node:${mod}`);\n}\n\n/**\n * Check if a module specifier is a blocked Node.js built-in.\n * @param specifier - Module specifier to check (e.g. \"node:crypto\", \"fs\")\n * @returns Whether the specifier is blocked\n */\nexport function isBlockedModule(specifier: string): boolean {\n return BLOCKED_MODULES.has(specifier);\n}\n\n/**\n * Get the error message for a blocked module import.\n * @param specifier - Module specifier that was blocked\n * @returns Error message with optional suggestion for the Web Standard API alternative\n */\nexport function getBlockedMessage(specifier: string): string {\n const bare = specifier.startsWith(\"node:\") ? specifier.slice(5) : specifier;\n const suggestion = SUGGESTIONS[bare];\n const base = `\"${specifier}\" is not available in the Tailor Platform runtime.`;\n return suggestion ? `${base} ${suggestion}` : base;\n}\n","import { dirname, isAbsolute, matchesGlob, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { isBlockedModule, getBlockedMessage } from \"./blocked-modules\";\nimport type { Plugin } from \"vitest/config\";\n\nconst DEFAULT_TEST_INCLUDE = [\"**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}\"];\n\ninterface ExportSpecifierNode {\n type?: string;\n exported?: { name?: unknown } | null;\n}\n\ninterface ImportLikeNode {\n type: string;\n start: number;\n end: number;\n source?: { value?: unknown } | null;\n specifiers?: ExportSpecifierNode[] | null;\n exported?: { name?: unknown } | null;\n}\n\nconst IMPORT_LIKE_TYPES = new Set([\n \"ImportDeclaration\",\n \"ExportNamedDeclaration\",\n \"ExportAllDeclaration\",\n]);\n\n// Re-export specifiers (`export { x as Y } from \"...\"`) accept any\n// `IdentifierName` for `Y` — including reserved words like `delete`. But\n// `export const Y = ...` requires a `BindingIdentifier`, which forbids\n// reserved words and the strict-mode-banned `arguments` / `eval`. Synthesizing\n// `export const delete = ...` would yield a syntax error, so we fall back to\n// plain `throw` for unsafe names.\nconst UNSAFE_BINDING_NAMES = new Set([\n // ReservedWord (ES2022+)\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"enum\",\n \"export\",\n \"extends\",\n \"false\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"new\",\n \"null\",\n \"return\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"true\",\n \"try\",\n \"typeof\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n // Strict-mode reserved (ESM is always strict)\n \"let\",\n \"static\",\n \"implements\",\n \"interface\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n // Module-specific reserved\n \"await\",\n // Banned as binding names in strict mode\n \"arguments\",\n \"eval\",\n]);\n\nconst ID_START = /^[A-Za-z_$]/;\nconst ID_CONT = /^[A-Za-z0-9_$]*$/;\n\nfunction isSafeBindingName(name: string): boolean {\n if (UNSAFE_BINDING_NAMES.has(name)) return false;\n if (name.length === 0) return false;\n // Restrict to ASCII identifiers — Unicode bindings are valid JS but rare\n // for re-exports of node:* modules, and a regex over the full\n // ID_Start/ID_Continue sets adds substantial weight for marginal gain.\n const firstChar = name[0];\n if (firstChar === undefined) return false;\n return ID_START.test(firstChar) && ID_CONT.test(name.slice(1));\n}\n\nfunction buildBlockedReplacement(node: ImportLikeNode, message: string): string {\n // JSON.stringify yields a fully-escaped string literal (including the\n // surrounding quotes), so we don't need to manually handle backslashes,\n // newlines, or other control characters that may appear in the message.\n const literal = JSON.stringify(message);\n const throwStmt = `throw new Error(${literal});`;\n const throwExpr = `(() => { throw new Error(${literal}); })()`;\n\n if (node.type === \"ExportNamedDeclaration\") {\n const specs = node.specifiers ?? [];\n const stubs: string[] = [];\n for (const spec of specs) {\n const exportedName = spec.exported?.name;\n if (typeof exportedName !== \"string\") continue;\n if (exportedName === \"default\") {\n stubs.push(`export default ${throwExpr};`);\n continue;\n }\n // Reserved words can be re-export names but not binding names.\n // Bail to a plain throw rather than emit invalid syntax.\n if (!isSafeBindingName(exportedName)) return throwStmt;\n stubs.push(`export const ${exportedName} = ${throwExpr};`);\n }\n return stubs.length > 0 ? stubs.join(\" \") : throwStmt;\n }\n\n if (node.type === \"ExportAllDeclaration\") {\n const exportedName = node.exported?.name;\n if (typeof exportedName === \"string\" && isSafeBindingName(exportedName)) {\n return `export const ${exportedName} = ${throwExpr};`;\n }\n return throwStmt;\n }\n\n return throwStmt;\n}\n\n/**\n * Vite plugin that blocks Node.js built-in module imports from production code.\n *\n * Uses the `transform` hook to walk the Rollup-provided AST of non-test source\n * files for static `node:*` imports and re-exports.\n * `ImportDeclaration` and bare `export * from \"...\"` are replaced with a\n * `throw new Error(...)` statement so the failure surfaces at evaluation time.\n * `ExportNamedDeclaration` (`export { x, y as z } from \"...\"`) and namespaced\n * `export * as ns from \"...\"` are rewritten to per-binding stub exports\n * (`export const x = (() => { throw new Error(...) })();`). The IIFE throws\n * eagerly during module evaluation (same timing as a top-level `throw`), but\n * preserving the declared export bindings ensures the surfaced error is the\n * actual \"node:* not available\" message rather than an opaque\n * \"missing export\" raised by the loader.\n * Vitest treats `node:*` as external SSR modules (skipping `resolveId`), so\n * source-level transformation is the only reliable interception point.\n * Runs in the default phase (no `enforce: \"pre\"`) so esbuild's TypeScript\n * transform strips `import type` first; only runtime imports reach this hook.\n * Node.js globals not in the platform runtime are removed by the environment (whitelist-based).\n * Test file patterns are read from the resolved Vitest config (`test.include`).\n * Vitest setup files (`test.setupFiles`) and global-setup files\n * (`test.globalSetup`) are also exempted: they run in the test runner host,\n * not in the emulated platform runtime, so they may freely use `node:*`\n * modules (e.g. `node:url` for `pathToFileURL`).\n * @returns Vite plugin\n */\nexport function createBlockPlugin(): Plugin {\n let isTestFile: (id: string) => boolean = () => false;\n let isUserSourceFile: (id: string) => boolean = () => false;\n\n return {\n name: \"tailor-runtime-block-node\",\n\n configResolved(config) {\n type HostFileTestConfig = {\n include?: string[];\n setupFiles?: string | string[];\n globalSetup?: string | string[];\n root?: string;\n };\n const testConfig = (\n config as typeof config & {\n test?: HostFileTestConfig & {\n projects?: { test?: HostFileTestConfig }[];\n };\n }\n ).test;\n const root = testConfig?.root ?? config.root;\n // Setup files and global-setup files run in the Vitest host (not the\n // emulated runtime), so they may freely import node:* modules. Collect\n // them from the top-level config AND from each `test.projects[i]` —\n // per-project setup files run in the host too and would otherwise be\n // transformed as production code, breaking node:* imports inside them.\n const toAbsolutePaths = (value: string | string[] | undefined, baseRoot: string) =>\n (Array.isArray(value) ? value : value ? [value] : []).map((f) => resolve(baseRoot, f));\n const exemptHostFiles = new Set<string>([\n ...toAbsolutePaths(testConfig?.setupFiles, root),\n ...toAbsolutePaths(testConfig?.globalSetup, root),\n ]);\n // Vitest projects can each define their own `test.include` (and root).\n // A project that uses non-default patterns (e.g. `tests/**/*.spec.ts`)\n // must also be considered when classifying test files — otherwise its\n // tests would be treated as production code and have node:* imports\n // rewritten. Build a list of (root, patterns) pairs covering top-level\n // + every project, and accept a file if any pair matches.\n const includePairs: { root: string; patterns: string[] }[] = [\n { root, patterns: testConfig?.include ?? DEFAULT_TEST_INCLUDE },\n ];\n for (const project of testConfig?.projects ?? []) {\n const projectTest = project.test;\n if (!projectTest) continue;\n const projectRoot = projectTest.root ?? root;\n for (const f of toAbsolutePaths(projectTest.setupFiles, projectRoot)) {\n exemptHostFiles.add(f);\n }\n for (const f of toAbsolutePaths(projectTest.globalSetup, projectRoot)) {\n exemptHostFiles.add(f);\n }\n includePairs.push({\n root: projectRoot,\n patterns: projectTest.include ?? DEFAULT_TEST_INCLUDE,\n });\n }\n isTestFile = (id: string) => {\n if (exemptHostFiles.has(id)) return true;\n return includePairs.some(({ root: r, patterns }) => {\n const candidate = isAbsolute(id) ? relative(r, id) : id;\n return patterns.some((pattern) => matchesGlob(candidate, pattern));\n });\n };\n // Only transform files inside the project root. With pnpm workspaces,\n // dependencies are symlinked and Vite resolves them to absolute paths\n // outside `node_modules`, so the substring check alone is insufficient.\n // Non-absolute ids are Vite-internal: virtual modules (`\\0...`,\n // `virtual:...`), bare specifiers, etc. Those are never user source\n // files and must not be parsed/transformed.\n isUserSourceFile = (id: string) => {\n if (!isAbsolute(id)) return false;\n const rel = relative(root, id);\n return rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel);\n };\n },\n\n transform(code, id) {\n // Vite can pass ids with query/hash suffixes (e.g. `file.ts?import`,\n // `file.ts?v=hash`). Strip them so exact-path lookups (Set membership,\n // glob matching, absolute-path checks) match what callers configured.\n const queryIdx = id.search(/[?#]/);\n const cleanId = queryIdx === -1 ? id : id.slice(0, queryIdx);\n\n if (isTestFile(cleanId)) return undefined;\n if (cleanId.includes(\"node_modules\")) return undefined;\n if (!isUserSourceFile(cleanId)) return undefined;\n\n let ast: { body: ImportLikeNode[] };\n try {\n ast = this.parse(code) as unknown as { body: ImportLikeNode[] };\n } catch {\n // Not parseable as ESM (e.g. JSON, asset). Let other plugins handle it.\n return undefined;\n }\n\n const replacements: { start: number; end: number; replacement: string }[] = [];\n for (const node of ast.body) {\n if (!IMPORT_LIKE_TYPES.has(node.type)) continue;\n const specifier = node.source?.value;\n if (typeof specifier !== \"string\") continue;\n if (isBlockedModule(specifier)) {\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: buildBlockedReplacement(node, getBlockedMessage(specifier)),\n });\n }\n }\n\n if (replacements.length === 0) return undefined;\n\n let transformed = code;\n for (const r of replacements.toSorted((a, b) => b.start - a.start)) {\n transformed = transformed.slice(0, r.start) + r.replacement + transformed.slice(r.end);\n }\n\n return { code: transformed, map: null };\n },\n };\n}\n\nconst ENVIRONMENT_NAME = \"tailor-runtime\";\n\n/**\n * Vite plugin that resolves the tailor-runtime environment and injects setup files.\n *\n * Vitest resolves environments starting with \".\" or \"/\" as file paths.\n * This plugin rewrites `environment: \"tailor-runtime\"` to the absolute path\n * of the bundled environment module, both at the top-level and per-project.\n * It also injects the setup file that removes Vitest-dependent globals\n * (like `performance`) per-test via beforeEach/afterEach hooks.\n * @param options - Optional configuration\n * @param options.config - Path to tailor.config.ts to load SecretManager values into mock\n * @returns Vite plugin\n */\nexport function createEnvironmentPlugin(options?: { config?: string }): Plugin {\n const currentDir = dirname(fileURLToPath(import.meta.url));\n const environmentPath = resolve(currentDir, \"environment.mjs\");\n const setupPath = resolve(currentDir, \"setup.mjs\");\n\n return {\n name: \"tailor-runtime-environment\",\n\n config(config) {\n const testConfig = config.test as\n | (Record<string, unknown> & {\n projects?: Record<string, unknown>[];\n setupFiles?: string | string[];\n })\n | undefined;\n\n // Rewrite environment name to absolute path at top-level\n let usesTailorRuntime = false;\n if (testConfig?.environment === ENVIRONMENT_NAME) {\n testConfig.environment = environmentPath;\n usesTailorRuntime = true;\n }\n\n // Rewrite in each project config\n if (testConfig?.projects) {\n for (const project of testConfig.projects) {\n const projectTest = project.test as Record<string, unknown> | undefined;\n if (projectTest?.environment === ENVIRONMENT_NAME) {\n projectTest.environment = environmentPath;\n usesTailorRuntime = true;\n }\n }\n }\n\n // Pass config path to setup.ts via env var (cross-process compatible).\n // Always clear first, then set only when tailor-runtime is actually\n // selected. This makes the env var deterministic across Vite config\n // reloads (watch mode, programmatic re-init): a stale value from a\n // prior iteration cannot make setup.ts load secrets from an old config.\n // The leading `__` marks this as plugin-private, so deleting any\n // pre-existing value is safe.\n delete process.env.__TAILOR_RUNTIME_CONFIG;\n if (options?.config && usesTailorRuntime) {\n // Resolve against the user-provided Vite root when present (falling\n // back to cwd). Vitest projects with a non-cwd `root` would otherwise\n // resolve a relative options.config against the wrong directory.\n const configRoot = (config.root as string | undefined) ?? process.cwd();\n const configAbsPath = resolve(configRoot, options.config);\n process.env.__TAILOR_RUNTIME_CONFIG = configAbsPath;\n }\n\n // Normalize a user-provided string `setupFiles` into an array so Vite's\n // array-concat merge sees both sides as arrays (the string form would\n // otherwise be replaced rather than concatenated by some merge paths).\n // Vite then concatenates the user's array with our [setupPath].\n if (testConfig && typeof testConfig.setupFiles === \"string\") {\n testConfig.setupFiles = [testConfig.setupFiles];\n }\n\n return {\n test: {\n setupFiles: [setupPath],\n },\n };\n },\n };\n}\n","/**\n * Kysely-layer mock for unit testing.\n *\n * Builds a real Kysely instance backed by a mock driver: queries compile and\n * type-check normally, but execution returns staged rows and records every\n * query for assertions.\n */\n\nimport {\n ColumnNode,\n type CompiledQuery,\n type DatabaseConnection,\n type Dialect,\n type Driver,\n InsertQueryNode,\n Kysely,\n type OperationNode,\n type OperationNodeKind,\n PostgresAdapter,\n PostgresIntrospector,\n PostgresQueryCompiler,\n PrimitiveValueListNode,\n type QueryResult,\n ReferenceNode,\n type Transaction,\n UpdateQueryNode,\n ValueListNode,\n ValueNode,\n ValuesNode,\n} from \"kysely\";\nimport { assertDefined } from \"#/utils/assert\";\n\nfunction unwrapValue(node: OperationNode): unknown {\n return ValueNode.is(node) ? node.value : node;\n}\n\nfunction insertRows(node: OperationNode): Record<string, unknown>[] {\n if (!InsertQueryNode.is(node)) {\n throw new Error(`insertRows: expected InsertQueryNode, got ${node.kind}`);\n }\n const columns = node.columns;\n const valuesNode = node.values;\n if (columns === undefined || valuesNode === undefined || !ValuesNode.is(valuesNode)) {\n throw new Error(\"insertRows: unsupported insert shape; inspect query.node instead\");\n }\n return valuesNode.values.map((row) => {\n if (!PrimitiveValueListNode.is(row) && !ValueListNode.is(row)) {\n throw new Error(\"insertRows: unsupported insert shape; inspect query.node instead\");\n }\n const values = PrimitiveValueListNode.is(row) ? row.values : row.values.map(unwrapValue);\n const result: Record<string, unknown> = {};\n columns.forEach((col, i) => {\n result[col.column.name] = values[i];\n });\n return result;\n });\n}\n\nfunction insertValues(node: OperationNode): Record<string, unknown> {\n const rows = insertRows(node);\n if (rows.length !== 1) {\n throw new Error(\n `insertValues: query inserts ${rows.length} rows; use insertRows() for multi-row inserts`,\n );\n }\n return assertDefined(rows[0], \"insertValues: first row missing\");\n}\n\nfunction updateValues(node: OperationNode): Record<string, unknown> {\n if (!UpdateQueryNode.is(node)) {\n throw new Error(`updateValues: expected UpdateQueryNode, got ${node.kind}`);\n }\n if (node.updates === undefined) {\n throw new Error(\"updateValues: unsupported update shape; inspect query.node instead\");\n }\n const result: Record<string, unknown> = {};\n for (const update of node.updates) {\n const col = update.column;\n const name = ColumnNode.is(col)\n ? col.column.name\n : ReferenceNode.is(col) && ColumnNode.is(col.column)\n ? col.column.column.name\n : undefined;\n if (name === undefined) {\n throw new Error(\"updateValues: unsupported update shape; inspect query.node instead\");\n }\n result[name] = unwrapValue(update.value);\n }\n return result;\n}\n\n/** A single statement executed against the mock, captured in order. */\nexport interface ExecutedQuery {\n /** The Kysely operation node kind, e.g. `\"SelectQueryNode\"`. */\n kind: OperationNodeKind;\n /** The compiled SQL string. */\n sql: string;\n /** The bound parameter values, in positional order. */\n parameters: readonly unknown[];\n /** The compiled Kysely operation node. */\n node: OperationNode;\n /** One `{ column: value }` map per row written by an insert. */\n insertRows: () => Record<string, unknown>[];\n /** The `{ column: value }` map written by a single-row insert. */\n insertValues: () => Record<string, unknown>;\n /** The `{ column: value }` map written by an update's SET clause. */\n updateValues: () => Record<string, unknown>;\n}\n\nfunction toExecutedQuery(compiledQuery: CompiledQuery): ExecutedQuery {\n const node = compiledQuery.query;\n return {\n kind: node.kind,\n sql: compiledQuery.sql,\n parameters: compiledQuery.parameters,\n node,\n insertRows: () => insertRows(node),\n insertValues: () => insertValues(node),\n updateValues: () => updateValues(node),\n };\n}\n\ntype MockRow = Record<string, unknown>;\ntype MockResult = MockRow[] | { rows?: MockRow[]; numAffectedRows?: number | bigint };\ntype QueryResolver = (query: ExecutedQuery) => MockResult | undefined;\n\ninterface StagedResult {\n rows: MockRow[];\n numAffectedRows: bigint | undefined;\n}\n\nfunction toStagedResult(result: MockResult): StagedResult {\n if (Array.isArray(result)) return { rows: result, numAffectedRows: undefined };\n return {\n rows: result.rows ?? [],\n numAffectedRows:\n result.numAffectedRows === undefined ? undefined : BigInt(result.numAffectedRows),\n };\n}\n\n/** Controls and assertions for a {@link createKyselyMock} instance. */\nexport interface KyselyMock<DB> {\n /** The mock Kysely instance to run queries against. */\n db: Kysely<DB>;\n /** Every recorded query, in execution order. */\n executedQueries: ExecutedQuery[];\n /** Recorded SELECT queries. */\n selects: ExecutedQuery[];\n /** Recorded INSERT queries. */\n inserts: ExecutedQuery[];\n /** Recorded UPDATE queries. */\n updates: ExecutedQuery[];\n /** Recorded DELETE queries. */\n deletes: ExecutedQuery[];\n /** Stage the rows the next query returns. */\n enqueueResult: (result: MockResult) => void;\n /** Stage the rows for several upcoming queries, consumed in order. */\n enqueueResults: (...results: MockResult[]) => void;\n /** Set a resolver that returns rows by inspecting each query. */\n setQueryResolver: (resolver: QueryResolver) => void;\n /** Run `fn` inside a real transaction and return its result. */\n withTx: <R>(fn: (trx: Transaction<DB>) => Promise<R>) => Promise<R>;\n /** Clear recorded queries and staged results. */\n reset: () => void;\n /** Same as {@link KyselyMock.reset}; enables `using` disposal. */\n [Symbol.dispose]: () => void;\n}\n\nclass MockState {\n readonly executed: ExecutedQuery[] = [];\n private readonly queue: MockResult[] = [];\n private resolver: QueryResolver | undefined;\n\n enqueue(...results: MockResult[]): void {\n this.queue.push(...results);\n }\n\n setResolver(resolver: QueryResolver): void {\n this.resolver = resolver;\n }\n\n next(query: ExecutedQuery): StagedResult {\n const resolved = this.resolver?.(query);\n if (resolved !== undefined) return toStagedResult(resolved);\n const queued = this.queue.shift();\n return queued === undefined ? { rows: [], numAffectedRows: undefined } : toStagedResult(queued);\n }\n\n reset(): void {\n this.executed.length = 0;\n this.queue.length = 0;\n this.resolver = undefined;\n }\n}\n\nclass MockConnection implements DatabaseConnection {\n constructor(private readonly state: MockState) {}\n\n async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {\n const query = toExecutedQuery(compiledQuery);\n this.state.executed.push(query);\n const { rows, numAffectedRows } = this.state.next(query);\n return {\n rows: rows as R[],\n numAffectedRows: numAffectedRows ?? BigInt(rows.length),\n };\n }\n\n streamQuery<R>(): AsyncIterableIterator<QueryResult<R>> {\n throw new Error(\"createKyselyMock: streaming is not supported\");\n }\n}\n\nclass MockDriver implements Driver {\n constructor(private readonly state: MockState) {}\n\n async init(): Promise<void> {}\n\n async acquireConnection(): Promise<DatabaseConnection> {\n return new MockConnection(this.state);\n }\n\n // No-ops so begin/commit/rollback never enter `executed` and pollute counts.\n async beginTransaction(): Promise<void> {}\n async commitTransaction(): Promise<void> {}\n async rollbackTransaction(): Promise<void> {}\n\n async releaseConnection(): Promise<void> {}\n async destroy(): Promise<void> {}\n}\n\nfunction byKind(state: MockState, kind: OperationNodeKind): ExecutedQuery[] {\n return state.executed.filter((query) => query.kind === kind);\n}\n\n/**\n * Create a mock Kysely instance for unit-testing code that runs Kysely queries.\n * Pass the namespace schema as the type argument, e.g.\n * `createKyselyMock<Namespace[\"main-db\"]>()`.\n * @returns A {@link KyselyMock} with the mock `db`, recorded queries, and result staging.\n */\nexport function createKyselyMock<DB = Record<string, never>>(): KyselyMock<DB> {\n const state = new MockState();\n const dialect: Dialect = {\n createDriver: () => new MockDriver(state),\n createQueryCompiler: () => new PostgresQueryCompiler(),\n createAdapter: () => new PostgresAdapter(),\n createIntrospector: (db) => new PostgresIntrospector(db),\n };\n const kysely = new Kysely<DB>({ dialect });\n\n return {\n db: kysely,\n get executedQueries() {\n return state.executed;\n },\n get selects() {\n return byKind(state, \"SelectQueryNode\");\n },\n get inserts() {\n return byKind(state, \"InsertQueryNode\");\n },\n get updates() {\n return byKind(state, \"UpdateQueryNode\");\n },\n get deletes() {\n return byKind(state, \"DeleteQueryNode\");\n },\n enqueueResult: (result) => state.enqueue(result),\n enqueueResults: (...results) => state.enqueue(...results),\n setQueryResolver: (resolver) => state.setResolver(resolver),\n withTx: (fn) => kysely.transaction().execute(fn),\n reset: () => state.reset(),\n [Symbol.dispose]: () => state.reset(),\n };\n}\n","import { createBlockPlugin, createEnvironmentPlugin } from \"./plugin\";\nimport type { Plugin } from \"vitest/config\";\n\n/**\n * Creates Vitest plugins that emulate the Tailor Platform function runtime environment.\n *\n * **Beta:** This API may change in future releases.\n *\n * ## What it does\n *\n * 1. **Node.js module blocking** (transform hook) — Imports of `node:*` modules\n * (and bare builtins like `crypto`, `fs`) in non-test source files are replaced\n * with code that throws an error with a suggestion for the Web Standard API alternative.\n * Test files are exempt and can use `node:*` freely. Test file patterns are read\n * from the resolved Vitest config (`test.include`).\n *\n * 2. **Node.js globals removal** (environment + setup) — Only globals available in the\n * Tailor Platform runtime are kept (whitelist: ECMAScript standard, Web Standard APIs\n * from bootstrap.js, platform mocks). All others (`Buffer`, `global`, `setImmediate`,\n * `__dirname`, `__filename`, etc.) are removed. `performance` is removed per-test\n * via beforeEach/afterEach since Vitest needs it during initialization.\n *\n * 3. **Platform API mocks** (environment) — All platform APIs are auto-injected with\n * control objects: `mockTailordb`, `mockWorkflow`, `mockSecretmanager`,\n * `mockAuthconnection`, `mockIdp`, `mockFile`, `mockIconv`, `mockAigateway`. Each\n * provides response configuration, call recording, and reset.\n *\n * 4. **Environment resolution** — Rewrites `environment: \"tailor-runtime\"` to the\n * absolute path of the bundled environment module via the config hook.\n *\n * ## Known limitations\n *\n * - **`process`** and **`require`** are NOT removed or blocked. Vitest's internal\n * runner depends on them. On the real Tailor Platform runtime, they do not exist.\n * - **Dynamic `import()`** of bundled files (via `createImportMain()`) bypasses\n * the transform hook since those files are loaded through Node.js native loader.\n * ## Options\n *\n * - **`config`** — Path to `tailor.config.ts`. Loads `defineSecretManager()` values\n * into `mockSecretmanager` so `getSecret()` returns the configured values.\n * @example\n * ```typescript\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { tailorRuntime } from \"@tailor-platform/sdk/vitest\";\n *\n * export default defineConfig({\n * plugins: [tailorRuntime({ config: \"./tailor.config.ts\" })],\n * test: {\n * environment: \"tailor-runtime\",\n * },\n * });\n * ```\n * @param options - Optional configuration\n * @param options.config - Path to tailor.config.ts to load SecretManager values into mock\n * @returns Array of Vite plugins\n */\nexport function tailorRuntime(options?: { config?: string }): Plugin[] {\n return [createBlockPlugin(), createEnvironmentPlugin(options)];\n}\n\nexport {\n mockTailordb,\n mockWorkflow,\n mockSecretmanager,\n mockAuthconnection,\n mockIdp,\n mockFile,\n mockIconv,\n mockAigateway,\n} from \"./mock\";\n\nexport { createKyselyMock, type KyselyMock, type ExecutedQuery } from \"./mock-kysely\";\n"],"mappings":";;;;;;;;;;;;;;;AAUA,MAAM,cAAsC;CAC1C,QAAQ;CACR,QAAQ;CACR,IAAI;CACJ,eAAe;CACf,MAAM;CACN,MAAM;CACN,OAAO;CACP,KAAK;CACL,MAAM;CACN,QAAQ;CACR,cAAc;CACd,QAAQ;CACR,MAAM;CACN,aAAa;CACb,gBAAgB;AAClB;AAEA,MAAM,kCAAkB,IAAI,IAAY;AACxC,KAAK,MAAM,OAAO,gBAAgB;CAChC,gBAAgB,IAAI,GAAG;CACvB,g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,aAAa,MAAM,MAAM;GACxB,OAAO,gBAAgB,MAAM,MAAM;CACtC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1NA,SAAgB,cAAc,SAAyC;CACrE,OAAO,CAAC,kBAAkB,GAAG,wBAAwB,OAAO,CAAC;AAC/D"}
@@ -59,23 +59,33 @@ tailor-sdk deploy [options]
59
59
 
60
60
  **Options**
61
61
 
62
- | Option | Alias | Description | Required | Default | Env |
63
- | ------------------------------- | ----- | ----------------------------------------------------------------- | -------- | -------------------- | --------------------------------- |
64
- | `--workspace-id <WORKSPACE_ID>` | `-w` | Workspace ID | No | - | `TAILOR_PLATFORM_WORKSPACE_ID` |
65
- | `--profile <PROFILE>` | `-p` | Workspace profile | No | - | `TAILOR_PLATFORM_PROFILE` |
66
- | `--config <CONFIG>` | `-c` | Path to SDK config file | No | `"tailor.config.ts"` | `TAILOR_PLATFORM_SDK_CONFIG_PATH` |
67
- | `--yes` | `-y` | Skip confirmation prompts | No | `false` | - |
68
- | `--dry-run` | `-d` | Run the command without making any changes | No | - | - |
69
- | `--no-schema-check` | - | Skip schema diff check against migration snapshots | No | - | - |
70
- | `--no-validate` | - | Skip client-side validation against platform resource constraints | No | - | - |
71
- | `--no-cache` | - | Disable bundle caching for this run | No | - | - |
72
- | `--clean-cache` | - | Clean the bundle cache before building | No | - | - |
62
+ | Option | Alias | Description | Required | Default | Env |
63
+ | ------------------------------- | ----- | ------------------------------------------------------------------------------------ | -------- | -------------------- | --------------------------------- |
64
+ | `--workspace-id <WORKSPACE_ID>` | `-w` | Workspace ID | No | - | `TAILOR_PLATFORM_WORKSPACE_ID` |
65
+ | `--profile <PROFILE>` | `-p` | Workspace profile | No | - | `TAILOR_PLATFORM_PROFILE` |
66
+ | `--config <CONFIG>` | `-c` | Path to SDK config file. Use comma-separated paths to deploy multiple apps together. | No | `"tailor.config.ts"` | `TAILOR_PLATFORM_SDK_CONFIG_PATH` |
67
+ | `--yes` | `-y` | Skip confirmation prompts | No | `false` | - |
68
+ | `--dry-run` | `-d` | Run the command without making any changes | No | - | - |
69
+ | `--no-schema-check` | - | Skip schema diff check against migration snapshots | No | - | - |
70
+ | `--no-validate` | - | Skip client-side validation against platform resource constraints | No | - | - |
71
+ | `--no-cache` | - | Disable bundle caching for this run | No | - | - |
72
+ | `--clean-cache` | - | Clean the bundle cache before building | No | - | - |
73
73
 
74
74
  See [Global Options](../cli-reference.md#global-options) for options available to all commands.
75
75
  **Config File Modification:**
76
76
 
77
77
  On first run, `deploy` automatically injects a stable `id: "<uuid>"` field into your `defineConfig({...})` call in `tailor.config.ts`. This UUID is used to track your application across renames so the SDK can recognize ownership across renames. Commit the generated id to version control. See [Configuration](../configuration.md#application-settings) for details.
78
78
 
79
+ **Multiple Config Deploys:**
80
+
81
+ To deploy interdependent applications to the same workspace in one run, pass comma-separated config paths:
82
+
83
+ ```bash
84
+ tailor-sdk deploy --config apps/buyer/tailor.config.ts,apps/supplier/tailor.config.ts
85
+ ```
86
+
87
+ When multiple configs are provided, `deploy` creates or updates all configured services first, then updates the applications. This lets one application reference resources owned by another config with `external: true` during the same deploy.
88
+
79
89
  **Migration Handling:**
80
90
 
81
91
  When migrations are configured (`db.tailordb.migration` in config), the `deploy` command automatically:
package/docs/cli/setup.md CHANGED
@@ -24,6 +24,7 @@ See [Global Options](../cli-reference.md#global-options) for options available t
24
24
  | [`setup action`](#setup-action) | Generate a per-app composite action for use with setup coordinate (monorepo multi-app deploys). |
25
25
  | [`setup coordinate`](#setup-coordinate) | Generate a coordinator workflow that orchestrates multiple --action-generated composite actions. |
26
26
  | [`setup check`](#setup-check) | Audit generated workflows for drift against the current config/repo (read-only). |
27
+ | [`setup delete`](#setup-delete) | Delete managed workflow/action file(s) and their .github/tailor-sdk.lock entries. |
27
28
 
28
29
  ### setup action
29
30
 
@@ -110,6 +111,30 @@ tailor-sdk setup coordinate [options]
110
111
 
111
112
  See [Global Options](../cli-reference.md#global-options) for options available to all commands.
112
113
 
114
+ ### setup delete
115
+
116
+ Delete managed workflow/action file(s) and their .github/tailor-sdk.lock entries.
117
+
118
+ **Usage**
119
+
120
+ ```
121
+ tailor-sdk setup delete [options] <files>
122
+ ```
123
+
124
+ **Arguments**
125
+
126
+ | Argument | Description | Required |
127
+ | -------- | ------------------------------------------------------------------------------------------ | -------- |
128
+ | `files` | Workflow/action file(s) to delete, as generated under .github/workflows or .github/actions | Yes |
129
+
130
+ **Options**
131
+
132
+ | Option | Alias | Description | Required | Default |
133
+ | ------- | ----- | ------------------------- | -------- | ------- |
134
+ | `--yes` | `-y` | Skip confirmation prompts | No | `false` |
135
+
136
+ See [Global Options](../cli-reference.md#global-options) for options available to all commands.
137
+
113
138
  ### setup preview
114
139
 
115
140
  Generate a preview workflow (PR open/sync triggers deploy to a per-PR workspace).
@@ -320,6 +320,7 @@ Commands for setting up project infrastructure.
320
320
  | [setup branch](./cli/setup.md#setup-branch) | Generate a branch-target deploy workflow (push to branch triggers deploy). |
321
321
  | [setup check](./cli/setup.md#setup-check) | Audit generated workflows for drift against the current config/repo (read-only). |
322
322
  | [setup coordinate](./cli/setup.md#setup-coordinate) | Generate a coordinator workflow that orchestrates multiple --action-generated composite actions. |
323
+ | [setup delete](./cli/setup.md#setup-delete) | Delete managed workflow/action file(s) and their .github/tailor-sdk.lock entries. |
323
324
  | [setup preview](./cli/setup.md#setup-preview) | Generate a preview workflow (PR open/sync triggers deploy to a per-PR workspace). |
324
325
  | [setup tag](./cli/setup.md#setup-tag) | Generate a tag-target deploy workflow (tag push triggers deploy). |
325
326
 
@@ -254,6 +254,29 @@ type User {
254
254
  - `toward.as` - Customizes the field name for accessing the related type from this type
255
255
  - `backward` - Customizes the field name for accessing this type from the related type
256
256
 
257
+ Relation names share the same GraphQL field namespace as fields, files, and other relations on
258
+ the type. The SDK rejects duplicate or empty relation names. Use `toward.as` when multiple fields
259
+ on the same type point to the same target type, because their default forward names are derived
260
+ from the target type name:
261
+
262
+ ```typescript
263
+ const post = db.type("Post", {
264
+ authorID: db.uuid().relation({
265
+ type: "n-1",
266
+ toward: { type: user, as: "author" },
267
+ backward: "authoredPosts",
268
+ }),
269
+ reviewerID: db.uuid().relation({
270
+ type: "n-1",
271
+ toward: { type: user, as: "reviewer" },
272
+ backward: "reviewedPosts",
273
+ }),
274
+ });
275
+ ```
276
+
277
+ Use `toward.as` or `backward` when a generated relation name would conflict with an existing
278
+ field, files entry, or relation on the same type.
279
+
257
280
  ### Hooks
258
281
 
259
282
  Add hooks to execute functions during data creation or update. Hooks receive three arguments:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tailor-platform/sdk",
3
- "version": "1.73.2",
3
+ "version": "1.74.0",
4
4
  "description": "Tailor Platform SDK - The SDK to work with Tailor Platform",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -159,7 +159,7 @@
159
159
  "@opentelemetry/resources": "2.8.0",
160
160
  "@opentelemetry/sdk-trace-node": "2.8.0",
161
161
  "@opentelemetry/semantic-conventions": "1.41.1",
162
- "@oxc-project/types": "0.137.0",
162
+ "@oxc-project/types": "0.138.0",
163
163
  "@standard-schema/spec": "1.1.0",
164
164
  "@tailor-platform/function-kysely-tailordb": "0.1.3",
165
165
  "@toiroakr/lines-db": "0.10.0",
@@ -178,13 +178,13 @@
178
178
  "madge": "8.0.0",
179
179
  "mime-types": "3.0.2",
180
180
  "open": "11.0.0",
181
- "oxc-parser": "0.137.0",
181
+ "oxc-parser": "0.138.0",
182
182
  "p-limit": "7.3.0",
183
183
  "pathe": "2.0.3",
184
184
  "pgsql-ast-parser": "12.0.2",
185
185
  "pkg-types": "2.3.1",
186
- "politty": "0.10.1",
187
- "rolldown": "1.1.3",
186
+ "politty": "0.11.0",
187
+ "rolldown": "1.1.4",
188
188
  "semver": "7.8.5",
189
189
  "sql-highlight": "6.1.0",
190
190
  "std-env": "4.1.0",
@@ -204,9 +204,9 @@
204
204
  "@types/semver": "7.7.1",
205
205
  "@typescript/native-preview": "7.0.0-dev.20260621.1",
206
206
  "@vitest/coverage-v8": "4.1.9",
207
- "oxfmt": "0.56.0",
208
- "oxlint": "1.71.0",
209
- "oxlint-tsgolint": "0.23.0",
207
+ "oxfmt": "0.57.0",
208
+ "oxlint": "1.72.0",
209
+ "oxlint-tsgolint": "0.24.0",
210
210
  "sonda": "0.13.1",
211
211
  "tsdown": "0.22.3",
212
212
  "typescript": "6.0.3",
@@ -1,3 +0,0 @@
1
- import { n as generatePluginFilesIfNeeded, r as loadApplication, t as defineApplication } from "./application-Bb9NNp5m.mjs";
2
-
3
- export { defineApplication, generatePluginFilesIfNeeded };