@tailor-platform/sdk 1.79.0 → 1.80.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/{application-fjqb-Gh8.mjs → application-C1d52JP9.mjs} +241 -222
  3. package/dist/application-C1d52JP9.mjs.map +1 -0
  4. package/dist/application-Nlh9BHQf.mjs +3 -0
  5. package/dist/cli/commands/tailordb/migrate/bundler.d.mts +3 -2
  6. package/dist/cli/index.mjs +17 -21
  7. package/dist/cli/index.mjs.map +1 -1
  8. package/dist/cli/lib.mjs +3 -6
  9. package/dist/cli/lib.mjs.map +1 -1
  10. package/dist/cli/tsconfig-paths-hook.d.mts +1 -0
  11. package/dist/cli/tsconfig-paths-hook.mjs +153 -0
  12. package/dist/completion/zsh-worker.zsh +1 -1
  13. package/dist/configure/config/types.d.mts +5 -1
  14. package/dist/configure/index.d.mts +1 -1
  15. package/dist/configure/services/auth/types.d.mts +18 -23
  16. package/dist/configure/services/idp/index.d.mts +1 -1
  17. package/dist/configure/services/idp/types.d.mts +5 -1
  18. package/dist/configure/services/index.d.mts +1 -1
  19. package/dist/{globals-B-n_3uYu.mjs → globals-DVJ8RVvm.mjs} +8 -1
  20. package/dist/{globals-B-n_3uYu.mjs.map → globals-DVJ8RVvm.mjs.map} +1 -1
  21. package/dist/{runtime-CjMeYuPA.mjs → register-typescript-runtime-Bd4bcLbW.mjs} +398 -123
  22. package/dist/register-typescript-runtime-Bd4bcLbW.mjs.map +1 -0
  23. package/dist/{service-D12iQGcS.mjs → service-CDPatibu.mjs} +31 -17
  24. package/dist/service-CDPatibu.mjs.map +1 -0
  25. package/dist/service-Cg7Qibit.mjs +3 -0
  26. package/dist/vitest/environment.mjs +1 -1
  27. package/dist/vitest/setup.mjs +1 -1
  28. package/docs/cli/application.md +6 -0
  29. package/docs/cli-reference.md +21 -21
  30. package/docs/configuration.md +2 -0
  31. package/docs/services/auth.md +2 -2
  32. package/docs/testing.md +10 -4
  33. package/package.json +8 -7
  34. package/dist/application-BB6BlUfk.mjs +0 -3
  35. package/dist/application-fjqb-Gh8.mjs.map +0 -1
  36. package/dist/runtime-CjMeYuPA.mjs.map +0 -1
  37. package/dist/service-CghpdV-9.mjs +0 -3
  38. package/dist/service-D12iQGcS.mjs.map +0 -1
package/dist/cli/lib.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as assertDefined } from "../assert-DBxo8jPo.mjs";
2
- import { $ as listFolders, A as generate$1, An as generateUserTypes, B as remove, Bt as deploy, C as waitWorkflowExecution, Cn as formatDiffSummary, D as listWorkflows, En as getNamespacesWithMigrations, Et as getExecutorWaitFailureMessage, Ft as getWorkflowExecution, Gt as createWorkspace, I as show, It as listWorkflowExecutions, Mn as apiCall, Nt as getWorkflow, O as truncate, Ot as listExecutorJobs, Pn as loadConfig, Qt as MIGRATION_LABEL_KEY, St as triggerExecutor, T as resumeWorkflow, Tn as hasChanges, Tt as getExecutorJob, U as updateOrganization, Un as loadWorkspaceId, Ut as listWorkspaces, W as organizationTree, Xt as waitForExecution, Y as getOrganization, Yt as executeScript, Z as updateFolder, Zt as bundleMigrationScript, _ as deleteWorkspace, _n as getNextMigrationNumber, a as updateUser, an as DIFF_FILE_NAME, at as createFolder, b as getAppHealth, bn as reconstructSnapshotFromMigrations, cn as SCHEMA_FILE_NAME, d as inviteUser, dn as compareSnapshots, fn as createSnapshotFromLocalTypes, gn as getMigrationFiles, gt as listFunctionRegistries, h as getWorkspace, hn as getMigrationFilePath, in as DB_TYPES_FILE_NAME, jt as startWorkflow, kt as watchExecutorJob, l as listUsers, lt as getOAuth2Client, mn as getMigrationDirPath, mt as generate, n as query, on as INITIAL_SCHEMA_NUMBER, p as restoreWorkspace, pn as getLatestMigrationNumber, pt as listMachineUsers, q as listOrganizations, rt as deleteFolder, s as removeUser, sn as MIGRATE_FILE_NAME, st as listOAuth2Clients, t as isNativeTypeScriptRuntime, tt as getFolder, un as compareLocalTypesWithSnapshot, ut as getMachineUserToken, v as listApps, vt as getFunctionRegistry, wn as formatMigrationDiff, wt as listExecutors, yt as listWebhookExecutors, zn as loadAccessToken, zt as getExecutor } from "../runtime-CjMeYuPA.mjs";
3
- import { B as initOperatorClient, _ as platformBundleDefinePlugin, w as getDistDir } from "../application-fjqb-Gh8.mjs";
2
+ import { $ as listFolders, A as generate$1, An as generateUserTypes, B as remove, Bt as deploy, C as waitWorkflowExecution, Cn as formatDiffSummary, D as listWorkflows, En as getNamespacesWithMigrations, Et as getExecutorWaitFailureMessage, Ft as getWorkflowExecution, Gt as createWorkspace, I as show, It as listWorkflowExecutions, Mn as apiCall, Nt as getWorkflow, O as truncate, Ot as listExecutorJobs, Pn as loadConfig, Qt as MIGRATION_LABEL_KEY, St as triggerExecutor, T as resumeWorkflow, Tn as hasChanges, Tt as getExecutorJob, U as updateOrganization, Un as loadWorkspaceId, Ut as listWorkspaces, W as organizationTree, Xt as waitForExecution, Y as getOrganization, Yt as executeScript, Z as updateFolder, Zt as bundleMigrationScript, _ as deleteWorkspace, _n as getNextMigrationNumber, a as updateUser, an as DIFF_FILE_NAME, at as createFolder, b as getAppHealth, bn as reconstructSnapshotFromMigrations, cn as SCHEMA_FILE_NAME, d as inviteUser, dn as compareSnapshots, fn as createSnapshotFromLocalTypes, gn as getMigrationFiles, gt as listFunctionRegistries, h as getWorkspace, hn as getMigrationFilePath, in as DB_TYPES_FILE_NAME, jt as startWorkflow, kt as watchExecutorJob, l as listUsers, lt as getOAuth2Client, mn as getMigrationDirPath, mt as generate, n as query, on as INITIAL_SCHEMA_NUMBER, p as restoreWorkspace, pn as getLatestMigrationNumber, pt as listMachineUsers, q as listOrganizations, rt as deleteFolder, s as removeUser, sn as MIGRATE_FILE_NAME, st as listOAuth2Clients, t as registerTypeScriptRuntime, tt as getFolder, un as compareLocalTypesWithSnapshot, ut as getMachineUserToken, v as listApps, vt as getFunctionRegistry, wn as formatMigrationDiff, wt as listExecutors, yt as listWebhookExecutors, zn as loadAccessToken, zt as getExecutor } from "../register-typescript-runtime-Bd4bcLbW.mjs";
3
+ import { T as getDistDir, V as initOperatorClient, v as platformBundleDefinePlugin } from "../application-C1d52JP9.mjs";
4
4
  import { n as enumConstantsPlugin } from "../enum-constants-j9QBF0cB.mjs";
5
5
  import { t as multiline } from "../multiline-sfHpTZZK.mjs";
6
6
  import { n as fileUtilsPlugin } from "../file-utils-DcyIPFQh.mjs";
@@ -279,10 +279,7 @@ async function bundleSeedScript(namespace, typeNames) {
279
279
 
280
280
  //#endregion
281
281
  //#region src/cli/lib.ts
282
- if (!isNativeTypeScriptRuntime()) {
283
- const { register } = await import("tsx/esm/api");
284
- register();
285
- }
282
+ await registerTypeScriptRuntime(new URL("./tsconfig-paths-hook.mjs", import.meta.url));
286
283
 
287
284
  //#endregion
288
285
  export { DB_TYPES_FILE_NAME, DIFF_FILE_NAME, INITIAL_SCHEMA_NUMBER, MIGRATE_FILE_NAME, MIGRATION_LABEL_KEY, SCHEMA_FILE_NAME, apiCall, deploy as apply, deploy, bundleMigrationScript, bundleSeedScript, chunkSeedData, compareLocalTypesWithSnapshot, compareSnapshots, createFolder, createSnapshotFromLocalTypes, createWorkspace, deleteFolder, deleteWorkspace, enumConstantsPlugin, executeScript, fileUtilsPlugin, formatDiffSummary, formatMigrationDiff, generate, generateUserTypes, getAppHealth, getExecutor, getExecutorJob, getExecutorWaitFailureMessage, getFolder, getFunctionRegistry, getLatestMigrationNumber, getMachineUserToken, getMigrationDirPath, getMigrationFilePath, getMigrationFiles, getNamespacesWithMigrations, getNextMigrationNumber, getOAuth2Client, getOrganization, getWorkflow, getWorkflowExecution, getWorkspace, hasChanges, initOperatorClient, inviteUser, kyselyTypePlugin, listApps, listExecutorJobs, listExecutors, listFolders, listFunctionRegistries, listMachineUsers, listOAuth2Clients, listOrganizations, listUsers, listWebhookExecutors, listWorkflowExecutions, listWorkflows, listWorkspaces, loadAccessToken, loadConfig, loadWorkspaceId, generate$1 as migrateGenerate, organizationTree, query, reconstructSnapshotFromMigrations, remove, removeUser, restoreWorkspace, resumeWorkflow, seedPlugin, show, startWorkflow, triggerExecutor, truncate, updateFolder, updateOrganization, updateUser, waitForExecution, waitWorkflowExecution, watchExecutorJob };
@@ -1 +1 @@
1
- {"version":3,"file":"lib.mjs","names":[],"sources":["../../src/cli/shared/seed-chunker.ts","../../src/cli/commands/generate/seed/bundler.ts","../../src/cli/lib.ts"],"sourcesContent":["/**\n * Seed data chunker for splitting large seed data into manageable message sizes.\n *\n * When seed data exceeds the gRPC message size limit, this module splits the data\n * into multiple chunks at type boundaries (or record boundaries for large types).\n */\n\nimport { assertDefined } from \"#/utils/assert\";\n\n/**\n * Seed data keyed by type name, with an array of records per type.\n */\nexport type SeedData = Record<string, Record<string, unknown>[]>;\n\n/**\n * A single chunk of seed data with metadata for ordered execution.\n */\nexport type SeedChunk = {\n data: SeedData;\n order: string[];\n index: number;\n total: number;\n};\n\n/**\n * Options for chunking seed data.\n */\nexport type ChunkSeedDataOptions = {\n /** Seed data keyed by type name */\n data: SeedData;\n /** Ordered list of type names (dependency order) */\n order: string[];\n /** Byte size of the bundled seed script code */\n codeByteSize: number;\n /** Maximum gRPC message size in bytes (default: 3.5MB) */\n maxMessageSize?: number;\n};\n\n/** Default maximum message size: 3.5MB (conservative limit for gRPC) */\nexport const DEFAULT_MAX_MESSAGE_SIZE = 3.5 * 1024 * 1024;\n\n/** Reserved bytes for message metadata overhead */\nconst METADATA_OVERHEAD = 1024;\n\n/**\n * Split seed data into chunks that fit within the gRPC message size limit.\n *\n * Algorithm:\n * 1. Calculate the available budget for the arg field (maxMessageSize - codeByteSize - overhead)\n * 2. If all data fits in one message, return a single chunk\n * 3. Otherwise, iterate through types in dependency order:\n * - If a type fits in the current chunk, add it\n * - If adding a type would exceed the budget, finalize the current chunk and start a new one\n * - If a single type exceeds the budget, split its records across multiple chunks\n * - If a single record exceeds the budget, throw an error\n * @param options - Chunking options\n * @returns Array of seed chunks\n */\nexport function chunkSeedData(options: ChunkSeedDataOptions): SeedChunk[] {\n const { data, order, codeByteSize, maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE } = options;\n\n const argBudget = maxMessageSize - codeByteSize - METADATA_OVERHEAD;\n if (argBudget <= 0) {\n throw new Error(\n `Code size (${codeByteSize} bytes) exceeds the message size limit (${maxMessageSize} bytes). ` +\n `No space left for seed data.`,\n );\n }\n\n // Filter to types that have data\n const typesWithData = order.filter((type) => (data[type]?.length ?? 0) > 0);\n\n if (typesWithData.length === 0) {\n return [];\n }\n\n // Check if all data fits in a single message\n const fullArg = JSON.stringify({ data, order });\n if (byteSize(fullArg) <= argBudget) {\n return [{ data, order, index: 0, total: 1 }];\n }\n\n // Split into multiple chunks\n const chunks: Omit<SeedChunk, \"total\">[] = [];\n let currentData: SeedData = {};\n let currentOrder: string[] = [];\n\n for (const type of typesWithData) {\n const typeRecords = assertDefined(data[type], `seed data missing for type: ${type}`);\n\n // Check if the type fits in the current chunk\n if (currentOrder.length > 0) {\n const testData = { ...currentData, [type]: typeRecords };\n const testOrder = [...currentOrder, type];\n if (byteSize(JSON.stringify({ data: testData, order: testOrder })) > argBudget) {\n // Finalize the current chunk\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n }\n }\n\n // Check if the entire type fits in an empty chunk\n if (byteSize(JSON.stringify({ data: { [type]: typeRecords }, order: [type] })) <= argBudget) {\n currentData[type] = typeRecords;\n currentOrder.push(type);\n continue;\n }\n\n // Type is too large — split by records\n if (currentOrder.length > 0) {\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n }\n\n let recordBatch: Record<string, unknown>[] = [];\n for (const record of typeRecords) {\n if (byteSize(JSON.stringify({ data: { [type]: [record] }, order: [type] })) > argBudget) {\n const singleRecordSize = byteSize(JSON.stringify(record));\n throw new Error(\n `A single record in type \"${type}\" (${singleRecordSize} bytes) exceeds the message size budget ` +\n `(${argBudget} bytes). Consider increasing maxMessageSize or reducing the record size.`,\n );\n }\n\n const testBatch = [...recordBatch, record];\n const testData = { ...currentData, [type]: testBatch };\n const testOrder = currentOrder.includes(type) ? currentOrder : [...currentOrder, type];\n const testSize = byteSize(JSON.stringify({ data: testData, order: testOrder }));\n\n if (testSize > argBudget && recordBatch.length > 0) {\n // Finalize current chunk with accumulated records\n currentData[type] = recordBatch;\n if (!currentOrder.includes(type)) {\n currentOrder.push(type);\n }\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n recordBatch = [record];\n } else {\n recordBatch = testBatch;\n }\n }\n\n // Add remaining records\n if (recordBatch.length > 0) {\n currentData[type] = recordBatch;\n if (!currentOrder.includes(type)) {\n currentOrder.push(type);\n }\n }\n }\n\n // Finalize the last chunk\n if (currentOrder.length > 0) {\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n }\n\n const total = chunks.length;\n return chunks.map((chunk) => ({ ...chunk, total }));\n}\n\nfunction byteSize(str: string): number {\n return new TextEncoder().encode(str).length;\n}\n","/**\n * Seed script bundler for TailorDB seed data\n *\n * Bundles seed scripts to be executed via TestExecScript API\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { resolveTSConfig } from \"pkg-types\";\nimport * as rolldown from \"rolldown\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport ml from \"#/utils/multiline\";\n\nexport type SeedBundleResult = {\n namespace: string;\n bundledCode: string;\n typesIncluded: string[];\n};\n\nconst BATCH_SIZE = 100;\n\n/**\n * Generate seed script content for server-side execution\n * @param namespace - TailorDB namespace\n * @returns Generated seed script content\n */\nfunction generateSeedScriptContent(namespace: string): string {\n return ml /* ts */ `\n import { Kysely, TailordbDialect } from \"@tailor-platform/sdk/kysely\";\n\n type SeedInput = {\n data: Record<string, Record<string, unknown>[]>;\n order: string[];\n selfRefTypes: string[];\n };\n\n type SeedResult = {\n success: boolean;\n processed: Record<string, number>;\n errors: string[];\n };\n\n function getDB(namespace: string) {\n const client = new tailordb.Client({ namespace });\n return new Kysely<Record<string, Record<string, unknown>>>({\n dialect: new TailordbDialect(client),\n });\n }\n\n export async function main(input: SeedInput): Promise<SeedResult> {\n const db = getDB(\"${namespace}\");\n const processed: Record<string, number> = {};\n const errors: string[] = [];\n const BATCH_SIZE = ${String(BATCH_SIZE)};\n\n for (const typeName of input.order) {\n const records = input.data[typeName];\n if (!records || records.length === 0) {\n console.log(\\`[${namespace}] \\${typeName}: skipped (no data)\\`);\n continue;\n }\n\n processed[typeName] = 0;\n const hasSelfRef = (input.selfRefTypes || []).includes(typeName);\n\n try {\n if (hasSelfRef) {\n // Insert one-by-one to respect self-referencing foreign key order\n for (const record of records) {\n await db.insertInto(typeName).values(record).execute();\n processed[typeName] += 1;\n }\n console.log(\\`[${namespace}] \\${typeName}: \\${processed[typeName]}/\\${records.length} (one-by-one)\\`);\n } else {\n for (let i = 0; i < records.length; i += BATCH_SIZE) {\n const batch = records.slice(i, i + BATCH_SIZE);\n await db.insertInto(typeName).values(batch).execute();\n processed[typeName] += batch.length;\n console.log(\\`[${namespace}] \\${typeName}: \\${processed[typeName]}/\\${records.length}\\`);\n }\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(\\`\\${typeName}: \\${message}\\`);\n console.error(\\`[${namespace}] \\${typeName}: failed - \\${message}\\`);\n }\n }\n\n return {\n success: errors.length === 0,\n processed,\n errors,\n };\n }\n `;\n}\n\n/**\n * Bundle a seed script for server-side execution\n *\n * Creates an entry that:\n * 1. Defines getDB() function inline\n * 2. Processes data in batches using Kysely\n * 3. Reports progress via console.log\n * 4. Exports as main() for TestExecScript\n * @param namespace - TailorDB namespace\n * @param typeNames - List of type names to include in the seed\n * @returns Bundled seed script result\n */\nexport async function bundleSeedScript(\n namespace: string,\n typeNames: string[],\n): Promise<SeedBundleResult> {\n // Output directory in .tailor-sdk (relative to project root)\n const outputDir = path.resolve(getDistDir(), \"seed\");\n fs.mkdirSync(outputDir, { recursive: true });\n\n // Entry file in output directory\n const entryPath = path.join(outputDir, `seed_${namespace}.entry.ts`);\n\n // Generate seed script content\n const entryContent = generateSeedScriptContent(namespace);\n fs.writeFileSync(entryPath, entryContent);\n\n let tsconfig: string | undefined;\n try {\n tsconfig = await resolveTSConfig();\n } catch {\n tsconfig = undefined;\n }\n\n // Bundle with tree-shaking (write: false to avoid unnecessary disk I/O)\n const result = await rolldown.build({\n plugins: [platformBundleDefinePlugin],\n input: entryPath,\n write: false,\n output: {\n format: \"esm\",\n sourcemap: false,\n minify: false,\n codeSplitting: false,\n globals: {\n tailordb: \"tailordb\",\n },\n },\n external: [\"tailordb\"],\n resolve: {\n conditionNames: [\"node\", \"import\"],\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 = result.output[0].code;\n\n return {\n namespace,\n bundledCode,\n typesIncluded: typeNames,\n };\n}\n","// CLI API exports for programmatic usage\nimport { isNativeTypeScriptRuntime } from \"./shared/runtime\";\n\n// Register tsx to handle TypeScript files when using CLI API programmatically.\n// Bun and Deno handle TypeScript natively, so registration is skipped.\n// tsx's own register() picks `module.registerHooks` on Node ≥ 24.11.1 / 25.1 / 26\n// (avoiding the DEP0205 deprecation) and falls back to `module.register` on older runtimes.\nif (!isNativeTypeScriptRuntime()) {\n const { register } = await import(\"tsx/esm/api\");\n register();\n}\n\nexport { deploy, deploy as apply } from \"./commands/deploy/deploy\";\nexport type { DeployOptions, DeployOptions as ApplyOptions } from \"./commands/deploy/deploy\";\nexport type { BundledScripts } from \"./commands/deploy/function-registry\";\nexport { generate } from \"./commands/generate/service\";\nexport type { GenerateOptions } from \"./commands/generate/options\";\nexport { loadConfig, type LoadedConfig } from \"./shared/config-loader\";\nexport { generateUserTypes } from \"./shared/type-generator\";\nexport type {\n CodeGenerator,\n TailorDBGenerator,\n ResolverGenerator,\n ExecutorGenerator,\n TailorDBResolverGenerator,\n FullCodeGenerator,\n TailorDBInput,\n ResolverInput,\n ExecutorInput,\n FullInput,\n AggregateArgs,\n GeneratorResult,\n DependencyKind,\n PluginAttachment,\n TypeSourceInfoEntry,\n} from \"./commands/generate/types\";\nexport type { TailorDBType } from \"#/parser/service/tailordb/types\";\nexport type { Resolver } from \"#/types/resolver.generated\";\nexport type { Executor } from \"#/types/executor.generated\";\n\n/** @deprecated Import from '@tailor-platform/sdk/plugin/kysely-type' instead */\nexport { kyselyTypePlugin } from \"#/plugin/builtin/kysely-type/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/enum-constants' instead */\nexport { enumConstantsPlugin } from \"#/plugin/builtin/enum-constants/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/file-utils' instead */\nexport { fileUtilsPlugin } from \"#/plugin/builtin/file-utils/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/seed' instead */\nexport { seedPlugin } from \"#/plugin/builtin/seed/index\";\n\nexport {\n show,\n type ShowOptions,\n type ApplicationInfo,\n type ShowInfo,\n type AIGatewayInfo,\n} from \"./commands/show\";\nexport { remove, type RemoveOptions } from \"./commands/remove\";\nexport { createWorkspace, type CreateWorkspaceOptions } from \"./commands/workspace/create\";\nexport { listWorkspaces, type ListWorkspacesOptions } from \"./commands/workspace/list\";\nexport { deleteWorkspace, type DeleteWorkspaceOptions } from \"./commands/workspace/delete\";\nexport { getWorkspace, type GetWorkspaceOptions } from \"./commands/workspace/get\";\nexport { restoreWorkspace, type RestoreWorkspaceOptions } from \"./commands/workspace/restore\";\nexport type { WorkspaceInfo, WorkspaceDetails } from \"./commands/workspace/transform\";\nexport { listUsers, type ListUsersOptions } from \"./commands/workspace/user/list\";\nexport { inviteUser, type InviteUserOptions } from \"./commands/workspace/user/invite\";\nexport { updateUser, type UpdateUserOptions } from \"./commands/workspace/user/update\";\nexport { removeUser, type RemoveUserOptions } from \"./commands/workspace/user/remove\";\nexport type { UserInfo } from \"./commands/workspace/user/transform\";\nexport { listApps, type ListAppsOptions } from \"./commands/workspace/app/list\";\nexport {\n getAppHealth,\n type HealthOptions as GetAppHealthOptions,\n} from \"./commands/workspace/app/health\";\nexport type { AppInfo, AppHealthInfo } from \"./commands/workspace/app/transform\";\nexport { getFunctionRegistry, type GetFunctionRegistryOptions } from \"./commands/function/get\";\nexport {\n listFunctionRegistries,\n type ListFunctionRegistriesOptions,\n} from \"./commands/function/list\";\nexport type { FunctionRegistryInfo } from \"./commands/function/transform\";\nexport {\n listMachineUsers,\n type ListMachineUsersOptions,\n type MachineUserInfo,\n} from \"./commands/machineuser/list\";\nexport {\n getMachineUserToken,\n type GetMachineUserTokenOptions,\n type MachineUserTokenInfo,\n} from \"./commands/machineuser/token\";\nexport { getOAuth2Client, type GetOAuth2ClientOptions } from \"./commands/oauth2client/get\";\nexport { listOAuth2Clients, type ListOAuth2ClientsOptions } from \"./commands/oauth2client/list\";\nexport type { OAuth2ClientInfo, OAuth2ClientCredentials } from \"./commands/oauth2client/transform\";\nexport { listWorkflows, type ListWorkflowsOptions } from \"./commands/workflow/list\";\nexport {\n getWorkflow,\n type GetWorkflowOptions,\n type GetWorkflowTypedOptions,\n} from \"./commands/workflow/get\";\nexport {\n startWorkflow,\n type StartWorkflowOptions,\n type StartWorkflowTypedOptions,\n type StartWorkflowResultWithWait,\n type WaitOptions,\n} from \"./commands/workflow/start\";\nexport {\n listWorkflowExecutions,\n getWorkflowExecution,\n type ListWorkflowExecutionsOptions,\n type ListWorkflowExecutionsTypedOptions,\n type GetWorkflowExecutionOptions,\n type GetWorkflowExecutionResult,\n type WorkflowExecutionWaitInfo,\n} from \"./commands/workflow/executions\";\nexport { waitWorkflowExecution, type WorkflowWaitOutput } from \"./commands/workflow/wait\";\nexport type { WaitWorkflowExecutionOptions, WorkflowWaitResult } from \"./commands/workflow/waiter\";\nexport {\n resumeWorkflow,\n type ResumeWorkflowOptions,\n type ResumeWorkflowResultWithWait,\n} from \"./commands/workflow/resume\";\nexport type {\n WorkflowListInfo,\n WorkflowInfo,\n WorkflowExecutionInfo,\n WorkflowJobExecutionInfo,\n} from \"./commands/workflow/transform\";\nexport {\n triggerExecutor,\n type TriggerExecutorOptions,\n type TriggerExecutorTypedOptions,\n type TriggerExecutorResult,\n} from \"./commands/executor/trigger\";\nexport {\n listExecutorJobs,\n getExecutorJob,\n getExecutorWaitFailureMessage,\n watchExecutorJob,\n type ListExecutorJobsOptions,\n type ListExecutorJobsTypedOptions,\n type GetExecutorJobOptions,\n type GetExecutorJobTypedOptions,\n type WatchExecutorJobOptions,\n type WatchExecutorJobTypedOptions,\n type ExecutorJobDetailInfo,\n type WatchExecutorJobResult,\n} from \"./commands/executor/jobs\";\nexport { listExecutors, type ListExecutorsOptions } from \"./commands/executor/list\";\nexport {\n getExecutor,\n type GetExecutorOptions,\n type GetExecutorTypedOptions,\n} from \"./commands/executor/get\";\nexport {\n listWebhookExecutors,\n type ListWebhookExecutorsOptions,\n type WebhookExecutorInfo,\n} from \"./commands/executor/webhook\";\nexport type {\n ExecutorJobListInfo,\n ExecutorJobInfo,\n ExecutorJobAttemptInfo,\n ExecutorListInfo,\n ExecutorInfo,\n} from \"./commands/executor/transform\";\nexport { listOrganizations, type ListOrganizationsOptions } from \"./commands/organization/list\";\nexport { getOrganization, type GetOrganizationOptions } from \"./commands/organization/get\";\nexport { updateOrganization, type UpdateOrganizationOptions } from \"./commands/organization/update\";\nexport { organizationTree, type OrganizationTreeOptions } from \"./commands/organization/tree\";\nexport type {\n UserOrganizationInfo,\n OrganizationInfo,\n FolderListInfo,\n FolderInfo,\n} from \"./commands/organization/transform\";\nexport { listFolders, type ListFoldersOptions } from \"./commands/organization/folder/list\";\nexport { getFolder, type GetFolderOptions } from \"./commands/organization/folder/get\";\nexport { createFolder, type CreateFolderOptions } from \"./commands/organization/folder/create\";\nexport { updateFolder, type UpdateFolderOptions } from \"./commands/organization/folder/update\";\nexport { deleteFolder, type DeleteFolderOptions } from \"./commands/organization/folder/delete\";\nexport { loadAccessToken, loadWorkspaceId } from \"./shared/context\";\nexport { apiCall, type ApiCallOptions, type ApiCallResult } from \"./commands/api\";\nexport { query } from \"./query\";\nexport { truncate, type TruncateOptions } from \"./commands/tailordb/truncate\";\n\n// Migration exports\nexport {\n generate as migrateGenerate,\n type GenerateOptions as MigrateGenerateOptions,\n} from \"./commands/tailordb/migrate/generate\";\nexport {\n createSnapshotFromLocalTypes,\n reconstructSnapshotFromMigrations,\n compareSnapshots,\n getNextMigrationNumber,\n getLatestMigrationNumber,\n getMigrationFiles,\n compareLocalTypesWithSnapshot,\n} from \"./commands/tailordb/migrate/snapshot\";\nexport {\n getNamespacesWithMigrations,\n type NamespaceWithMigrations,\n} from \"./commands/tailordb/migrate/config\";\nexport {\n hasChanges,\n formatMigrationDiff,\n formatDiffSummary,\n type MigrationDiff,\n type BreakingChangeInfo,\n} from \"./commands/tailordb/migrate/diff-calculator\";\nexport {\n SCHEMA_FILE_NAME,\n DIFF_FILE_NAME,\n MIGRATE_FILE_NAME,\n DB_TYPES_FILE_NAME,\n INITIAL_SCHEMA_NUMBER,\n getMigrationDirPath,\n getMigrationFilePath,\n type SchemaSnapshot,\n type NormalizedSchemaSnapshot,\n type TailorDBSnapshotType,\n type SnapshotFieldConfig,\n} from \"./commands/tailordb/migrate/snapshot\";\nexport { MIGRATION_LABEL_KEY } from \"./commands/tailordb/migrate/types\";\n\n// Seed exports\nexport { chunkSeedData, type SeedChunk, type ChunkSeedDataOptions } from \"./shared/seed-chunker\";\nexport { bundleSeedScript, type SeedBundleResult } from \"./commands/generate/seed/bundler\";\nexport {\n bundleMigrationScript,\n type MigrationBundleResult,\n} from \"./commands/tailordb/migrate/bundler\";\nexport {\n executeScript,\n waitForExecution,\n type ScriptExecutionOptions,\n type ScriptExecutionResult,\n type ExecutionWaitResult,\n} from \"./shared/script-executor\";\nexport { initOperatorClient, type OperatorClient } from \"./shared/client\";\nexport type { AuthInvoker } from \"@t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"}
1
+ {"version":3,"file":"lib.mjs","names":[],"sources":["../../src/cli/shared/seed-chunker.ts","../../src/cli/commands/generate/seed/bundler.ts","../../src/cli/lib.ts"],"sourcesContent":["/**\n * Seed data chunker for splitting large seed data into manageable message sizes.\n *\n * When seed data exceeds the gRPC message size limit, this module splits the data\n * into multiple chunks at type boundaries (or record boundaries for large types).\n */\n\nimport { assertDefined } from \"#/utils/assert\";\n\n/**\n * Seed data keyed by type name, with an array of records per type.\n */\nexport type SeedData = Record<string, Record<string, unknown>[]>;\n\n/**\n * A single chunk of seed data with metadata for ordered execution.\n */\nexport type SeedChunk = {\n data: SeedData;\n order: string[];\n index: number;\n total: number;\n};\n\n/**\n * Options for chunking seed data.\n */\nexport type ChunkSeedDataOptions = {\n /** Seed data keyed by type name */\n data: SeedData;\n /** Ordered list of type names (dependency order) */\n order: string[];\n /** Byte size of the bundled seed script code */\n codeByteSize: number;\n /** Maximum gRPC message size in bytes (default: 3.5MB) */\n maxMessageSize?: number;\n};\n\n/** Default maximum message size: 3.5MB (conservative limit for gRPC) */\nexport const DEFAULT_MAX_MESSAGE_SIZE = 3.5 * 1024 * 1024;\n\n/** Reserved bytes for message metadata overhead */\nconst METADATA_OVERHEAD = 1024;\n\n/**\n * Split seed data into chunks that fit within the gRPC message size limit.\n *\n * Algorithm:\n * 1. Calculate the available budget for the arg field (maxMessageSize - codeByteSize - overhead)\n * 2. If all data fits in one message, return a single chunk\n * 3. Otherwise, iterate through types in dependency order:\n * - If a type fits in the current chunk, add it\n * - If adding a type would exceed the budget, finalize the current chunk and start a new one\n * - If a single type exceeds the budget, split its records across multiple chunks\n * - If a single record exceeds the budget, throw an error\n * @param options - Chunking options\n * @returns Array of seed chunks\n */\nexport function chunkSeedData(options: ChunkSeedDataOptions): SeedChunk[] {\n const { data, order, codeByteSize, maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE } = options;\n\n const argBudget = maxMessageSize - codeByteSize - METADATA_OVERHEAD;\n if (argBudget <= 0) {\n throw new Error(\n `Code size (${codeByteSize} bytes) exceeds the message size limit (${maxMessageSize} bytes). ` +\n `No space left for seed data.`,\n );\n }\n\n // Filter to types that have data\n const typesWithData = order.filter((type) => (data[type]?.length ?? 0) > 0);\n\n if (typesWithData.length === 0) {\n return [];\n }\n\n // Check if all data fits in a single message\n const fullArg = JSON.stringify({ data, order });\n if (byteSize(fullArg) <= argBudget) {\n return [{ data, order, index: 0, total: 1 }];\n }\n\n // Split into multiple chunks\n const chunks: Omit<SeedChunk, \"total\">[] = [];\n let currentData: SeedData = {};\n let currentOrder: string[] = [];\n\n for (const type of typesWithData) {\n const typeRecords = assertDefined(data[type], `seed data missing for type: ${type}`);\n\n // Check if the type fits in the current chunk\n if (currentOrder.length > 0) {\n const testData = { ...currentData, [type]: typeRecords };\n const testOrder = [...currentOrder, type];\n if (byteSize(JSON.stringify({ data: testData, order: testOrder })) > argBudget) {\n // Finalize the current chunk\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n }\n }\n\n // Check if the entire type fits in an empty chunk\n if (byteSize(JSON.stringify({ data: { [type]: typeRecords }, order: [type] })) <= argBudget) {\n currentData[type] = typeRecords;\n currentOrder.push(type);\n continue;\n }\n\n // Type is too large — split by records\n if (currentOrder.length > 0) {\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n }\n\n let recordBatch: Record<string, unknown>[] = [];\n for (const record of typeRecords) {\n if (byteSize(JSON.stringify({ data: { [type]: [record] }, order: [type] })) > argBudget) {\n const singleRecordSize = byteSize(JSON.stringify(record));\n throw new Error(\n `A single record in type \"${type}\" (${singleRecordSize} bytes) exceeds the message size budget ` +\n `(${argBudget} bytes). Consider increasing maxMessageSize or reducing the record size.`,\n );\n }\n\n const testBatch = [...recordBatch, record];\n const testData = { ...currentData, [type]: testBatch };\n const testOrder = currentOrder.includes(type) ? currentOrder : [...currentOrder, type];\n const testSize = byteSize(JSON.stringify({ data: testData, order: testOrder }));\n\n if (testSize > argBudget && recordBatch.length > 0) {\n // Finalize current chunk with accumulated records\n currentData[type] = recordBatch;\n if (!currentOrder.includes(type)) {\n currentOrder.push(type);\n }\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n recordBatch = [record];\n } else {\n recordBatch = testBatch;\n }\n }\n\n // Add remaining records\n if (recordBatch.length > 0) {\n currentData[type] = recordBatch;\n if (!currentOrder.includes(type)) {\n currentOrder.push(type);\n }\n }\n }\n\n // Finalize the last chunk\n if (currentOrder.length > 0) {\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n }\n\n const total = chunks.length;\n return chunks.map((chunk) => ({ ...chunk, total }));\n}\n\nfunction byteSize(str: string): number {\n return new TextEncoder().encode(str).length;\n}\n","/**\n * Seed script bundler for TailorDB seed data\n *\n * Bundles seed scripts to be executed via TestExecScript API\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { resolveTSConfig } from \"pkg-types\";\nimport * as rolldown from \"rolldown\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport ml from \"#/utils/multiline\";\n\nexport type SeedBundleResult = {\n namespace: string;\n bundledCode: string;\n typesIncluded: string[];\n};\n\nconst BATCH_SIZE = 100;\n\n/**\n * Generate seed script content for server-side execution\n * @param namespace - TailorDB namespace\n * @returns Generated seed script content\n */\nfunction generateSeedScriptContent(namespace: string): string {\n return ml /* ts */ `\n import { Kysely, TailordbDialect } from \"@tailor-platform/sdk/kysely\";\n\n type SeedInput = {\n data: Record<string, Record<string, unknown>[]>;\n order: string[];\n selfRefTypes: string[];\n };\n\n type SeedResult = {\n success: boolean;\n processed: Record<string, number>;\n errors: string[];\n };\n\n function getDB(namespace: string) {\n const client = new tailordb.Client({ namespace });\n return new Kysely<Record<string, Record<string, unknown>>>({\n dialect: new TailordbDialect(client),\n });\n }\n\n export async function main(input: SeedInput): Promise<SeedResult> {\n const db = getDB(\"${namespace}\");\n const processed: Record<string, number> = {};\n const errors: string[] = [];\n const BATCH_SIZE = ${String(BATCH_SIZE)};\n\n for (const typeName of input.order) {\n const records = input.data[typeName];\n if (!records || records.length === 0) {\n console.log(\\`[${namespace}] \\${typeName}: skipped (no data)\\`);\n continue;\n }\n\n processed[typeName] = 0;\n const hasSelfRef = (input.selfRefTypes || []).includes(typeName);\n\n try {\n if (hasSelfRef) {\n // Insert one-by-one to respect self-referencing foreign key order\n for (const record of records) {\n await db.insertInto(typeName).values(record).execute();\n processed[typeName] += 1;\n }\n console.log(\\`[${namespace}] \\${typeName}: \\${processed[typeName]}/\\${records.length} (one-by-one)\\`);\n } else {\n for (let i = 0; i < records.length; i += BATCH_SIZE) {\n const batch = records.slice(i, i + BATCH_SIZE);\n await db.insertInto(typeName).values(batch).execute();\n processed[typeName] += batch.length;\n console.log(\\`[${namespace}] \\${typeName}: \\${processed[typeName]}/\\${records.length}\\`);\n }\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(\\`\\${typeName}: \\${message}\\`);\n console.error(\\`[${namespace}] \\${typeName}: failed - \\${message}\\`);\n }\n }\n\n return {\n success: errors.length === 0,\n processed,\n errors,\n };\n }\n `;\n}\n\n/**\n * Bundle a seed script for server-side execution\n *\n * Creates an entry that:\n * 1. Defines getDB() function inline\n * 2. Processes data in batches using Kysely\n * 3. Reports progress via console.log\n * 4. Exports as main() for TestExecScript\n * @param namespace - TailorDB namespace\n * @param typeNames - List of type names to include in the seed\n * @returns Bundled seed script result\n */\nexport async function bundleSeedScript(\n namespace: string,\n typeNames: string[],\n): Promise<SeedBundleResult> {\n // Output directory in .tailor-sdk (relative to project root)\n const outputDir = path.resolve(getDistDir(), \"seed\");\n fs.mkdirSync(outputDir, { recursive: true });\n\n // Entry file in output directory\n const entryPath = path.join(outputDir, `seed_${namespace}.entry.ts`);\n\n // Generate seed script content\n const entryContent = generateSeedScriptContent(namespace);\n fs.writeFileSync(entryPath, entryContent);\n\n let tsconfig: string | undefined;\n try {\n tsconfig = await resolveTSConfig();\n } catch {\n tsconfig = undefined;\n }\n\n // Bundle with tree-shaking (write: false to avoid unnecessary disk I/O)\n const result = await rolldown.build({\n plugins: [platformBundleDefinePlugin],\n input: entryPath,\n write: false,\n output: {\n format: \"esm\",\n sourcemap: false,\n minify: false,\n codeSplitting: false,\n globals: {\n tailordb: \"tailordb\",\n },\n },\n external: [\"tailordb\"],\n resolve: {\n conditionNames: [\"node\", \"import\"],\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 = result.output[0].code;\n\n return {\n namespace,\n bundledCode,\n typesIncluded: typeNames,\n };\n}\n","// CLI API exports for programmatic usage\nimport { registerTypeScriptRuntime } from \"./shared/register-typescript-runtime\";\n\nawait registerTypeScriptRuntime(new URL(\"./tsconfig-paths-hook.mjs\", import.meta.url));\n\nexport { deploy, deploy as apply } from \"./commands/deploy/deploy\";\nexport type { DeployOptions, DeployOptions as ApplyOptions } from \"./commands/deploy/deploy\";\nexport type { BundledScripts } from \"./commands/deploy/function-registry\";\nexport { generate } from \"./commands/generate/service\";\nexport type { GenerateOptions } from \"./commands/generate/options\";\nexport { loadConfig, type LoadedConfig } from \"./shared/config-loader\";\nexport { generateUserTypes } from \"./shared/type-generator\";\nexport type {\n CodeGenerator,\n TailorDBGenerator,\n ResolverGenerator,\n ExecutorGenerator,\n TailorDBResolverGenerator,\n FullCodeGenerator,\n TailorDBInput,\n ResolverInput,\n ExecutorInput,\n FullInput,\n AggregateArgs,\n GeneratorResult,\n DependencyKind,\n PluginAttachment,\n TypeSourceInfoEntry,\n} from \"./commands/generate/types\";\nexport type { TailorDBType } from \"#/parser/service/tailordb/types\";\nexport type { Resolver } from \"#/types/resolver.generated\";\nexport type { Executor } from \"#/types/executor.generated\";\n\n/** @deprecated Import from '@tailor-platform/sdk/plugin/kysely-type' instead */\nexport { kyselyTypePlugin } from \"#/plugin/builtin/kysely-type/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/enum-constants' instead */\nexport { enumConstantsPlugin } from \"#/plugin/builtin/enum-constants/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/file-utils' instead */\nexport { fileUtilsPlugin } from \"#/plugin/builtin/file-utils/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/seed' instead */\nexport { seedPlugin } from \"#/plugin/builtin/seed/index\";\n\nexport {\n show,\n type ShowOptions,\n type ApplicationInfo,\n type ShowInfo,\n type AIGatewayInfo,\n} from \"./commands/show\";\nexport { remove, type RemoveOptions } from \"./commands/remove\";\nexport { createWorkspace, type CreateWorkspaceOptions } from \"./commands/workspace/create\";\nexport { listWorkspaces, type ListWorkspacesOptions } from \"./commands/workspace/list\";\nexport { deleteWorkspace, type DeleteWorkspaceOptions } from \"./commands/workspace/delete\";\nexport { getWorkspace, type GetWorkspaceOptions } from \"./commands/workspace/get\";\nexport { restoreWorkspace, type RestoreWorkspaceOptions } from \"./commands/workspace/restore\";\nexport type { WorkspaceInfo, WorkspaceDetails } from \"./commands/workspace/transform\";\nexport { listUsers, type ListUsersOptions } from \"./commands/workspace/user/list\";\nexport { inviteUser, type InviteUserOptions } from \"./commands/workspace/user/invite\";\nexport { updateUser, type UpdateUserOptions } from \"./commands/workspace/user/update\";\nexport { removeUser, type RemoveUserOptions } from \"./commands/workspace/user/remove\";\nexport type { UserInfo } from \"./commands/workspace/user/transform\";\nexport { listApps, type ListAppsOptions } from \"./commands/workspace/app/list\";\nexport {\n getAppHealth,\n type HealthOptions as GetAppHealthOptions,\n} from \"./commands/workspace/app/health\";\nexport type { AppInfo, AppHealthInfo } from \"./commands/workspace/app/transform\";\nexport { getFunctionRegistry, type GetFunctionRegistryOptions } from \"./commands/function/get\";\nexport {\n listFunctionRegistries,\n type ListFunctionRegistriesOptions,\n} from \"./commands/function/list\";\nexport type { FunctionRegistryInfo } from \"./commands/function/transform\";\nexport {\n listMachineUsers,\n type ListMachineUsersOptions,\n type MachineUserInfo,\n} from \"./commands/machineuser/list\";\nexport {\n getMachineUserToken,\n type GetMachineUserTokenOptions,\n type MachineUserTokenInfo,\n} from \"./commands/machineuser/token\";\nexport { getOAuth2Client, type GetOAuth2ClientOptions } from \"./commands/oauth2client/get\";\nexport { listOAuth2Clients, type ListOAuth2ClientsOptions } from \"./commands/oauth2client/list\";\nexport type { OAuth2ClientInfo, OAuth2ClientCredentials } from \"./commands/oauth2client/transform\";\nexport { listWorkflows, type ListWorkflowsOptions } from \"./commands/workflow/list\";\nexport {\n getWorkflow,\n type GetWorkflowOptions,\n type GetWorkflowTypedOptions,\n} from \"./commands/workflow/get\";\nexport {\n startWorkflow,\n type StartWorkflowOptions,\n type StartWorkflowTypedOptions,\n type StartWorkflowResultWithWait,\n type WaitOptions,\n} from \"./commands/workflow/start\";\nexport {\n listWorkflowExecutions,\n getWorkflowExecution,\n type ListWorkflowExecutionsOptions,\n type ListWorkflowExecutionsTypedOptions,\n type GetWorkflowExecutionOptions,\n type GetWorkflowExecutionResult,\n type WorkflowExecutionWaitInfo,\n} from \"./commands/workflow/executions\";\nexport { waitWorkflowExecution, type WorkflowWaitOutput } from \"./commands/workflow/wait\";\nexport type { WaitWorkflowExecutionOptions, WorkflowWaitResult } from \"./commands/workflow/waiter\";\nexport {\n resumeWorkflow,\n type ResumeWorkflowOptions,\n type ResumeWorkflowResultWithWait,\n} from \"./commands/workflow/resume\";\nexport type {\n WorkflowListInfo,\n WorkflowInfo,\n WorkflowExecutionInfo,\n WorkflowJobExecutionInfo,\n} from \"./commands/workflow/transform\";\nexport {\n triggerExecutor,\n type TriggerExecutorOptions,\n type TriggerExecutorTypedOptions,\n type TriggerExecutorResult,\n} from \"./commands/executor/trigger\";\nexport {\n listExecutorJobs,\n getExecutorJob,\n getExecutorWaitFailureMessage,\n watchExecutorJob,\n type ListExecutorJobsOptions,\n type ListExecutorJobsTypedOptions,\n type GetExecutorJobOptions,\n type GetExecutorJobTypedOptions,\n type WatchExecutorJobOptions,\n type WatchExecutorJobTypedOptions,\n type ExecutorJobDetailInfo,\n type WatchExecutorJobResult,\n} from \"./commands/executor/jobs\";\nexport { listExecutors, type ListExecutorsOptions } from \"./commands/executor/list\";\nexport {\n getExecutor,\n type GetExecutorOptions,\n type GetExecutorTypedOptions,\n} from \"./commands/executor/get\";\nexport {\n listWebhookExecutors,\n type ListWebhookExecutorsOptions,\n type WebhookExecutorInfo,\n} from \"./commands/executor/webhook\";\nexport type {\n ExecutorJobListInfo,\n ExecutorJobInfo,\n ExecutorJobAttemptInfo,\n ExecutorListInfo,\n ExecutorInfo,\n} from \"./commands/executor/transform\";\nexport { listOrganizations, type ListOrganizationsOptions } from \"./commands/organization/list\";\nexport { getOrganization, type GetOrganizationOptions } from \"./commands/organization/get\";\nexport { updateOrganization, type UpdateOrganizationOptions } from \"./commands/organization/update\";\nexport { organizationTree, type OrganizationTreeOptions } from \"./commands/organization/tree\";\nexport type {\n UserOrganizationInfo,\n OrganizationInfo,\n FolderListInfo,\n FolderInfo,\n} from \"./commands/organization/transform\";\nexport { listFolders, type ListFoldersOptions } from \"./commands/organization/folder/list\";\nexport { getFolder, type GetFolderOptions } from \"./commands/organization/folder/get\";\nexport { createFolder, type CreateFolderOptions } from \"./commands/organization/folder/create\";\nexport { updateFolder, type UpdateFolderOptions } from \"./commands/organization/folder/update\";\nexport { deleteFolder, type DeleteFolderOptions } from \"./commands/organization/folder/delete\";\nexport { loadAccessToken, loadWorkspaceId } from \"./shared/context\";\nexport { apiCall, type ApiCallOptions, type ApiCallResult } from \"./commands/api\";\nexport { query } from \"./query\";\nexport { truncate, type TruncateOptions } from \"./commands/tailordb/truncate\";\n\n// Migration exports\nexport {\n generate as migrateGenerate,\n type GenerateOptions as MigrateGenerateOptions,\n} from \"./commands/tailordb/migrate/generate\";\nexport {\n createSnapshotFromLocalTypes,\n reconstructSnapshotFromMigrations,\n compareSnapshots,\n getNextMigrationNumber,\n getLatestMigrationNumber,\n getMigrationFiles,\n compareLocalTypesWithSnapshot,\n} from \"./commands/tailordb/migrate/snapshot\";\nexport {\n getNamespacesWithMigrations,\n type NamespaceWithMigrations,\n} from \"./commands/tailordb/migrate/config\";\nexport {\n hasChanges,\n formatMigrationDiff,\n formatDiffSummary,\n type MigrationDiff,\n type BreakingChangeInfo,\n} from \"./commands/tailordb/migrate/diff-calculator\";\nexport {\n SCHEMA_FILE_NAME,\n DIFF_FILE_NAME,\n MIGRATE_FILE_NAME,\n DB_TYPES_FILE_NAME,\n INITIAL_SCHEMA_NUMBER,\n getMigrationDirPath,\n getMigrationFilePath,\n type SchemaSnapshot,\n type NormalizedSchemaSnapshot,\n type TailorDBSnapshotType,\n type SnapshotFieldConfig,\n} from \"./commands/tailordb/migrate/snapshot\";\nexport { MIGRATION_LABEL_KEY } from \"./commands/tailordb/migrate/types\";\n\n// Seed exports\nexport { chunkSeedData, type SeedChunk, type ChunkSeedDataOptions } from \"./shared/seed-chunker\";\nexport { bundleSeedScript, type SeedBundleResult } from \"./commands/generate/seed/bundler\";\nexport {\n bundleMigrationScript,\n type MigrationBundleResult,\n} from \"./commands/tailordb/migrate/bundler\";\nexport {\n executeScript,\n waitForExecution,\n type ScriptExecutionOptions,\n type ScriptExecutionResult,\n type ExecutionWaitResult,\n} from \"./shared/script-executor\";\nexport { initOperatorClient, type OperatorClient } from \"./shared/client\";\nexport type { AuthInvoker } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,2BAA2B,MAAM,OAAO;;AAGrD,MAAM,oBAAoB;;;;;;;;;;;;;;;AAgB1B,SAAgB,cAAc,SAA4C;CACxE,MAAM,EAAE,MAAM,OAAO,cAAc,iBAAiB,6BAA6B;CAEjF,MAAM,YAAY,iBAAiB,eAAe;CAClD,IAAI,aAAa,GACf,MAAM,IAAI,MACR,cAAc,aAAa,0CAA0C,eAAe,sCA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;6BAcR,UAAU;;;;;;+BAMR,UAAU;;;;;;6BAMZ,UAAU;;;;;;;;;;;AAWvC;;;;;;;;;;;;;AAcA,eAAsB,iBACpB,WACA,WAC2B;CAE3B,MAAM,YAAY,KAAK,QAAQ,WAAW,GAAG,MAAM;CACnD,GAAG,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;CAG3C,MAAM,YAAY,KAAK,KAAK,WAAW,QAAQ,UAAU,UAAU;CAGnE,MAAM,eAAe,0BAA0B,SAAS;CACxD,GAAG,cAAc,WAAW,YAAY;CAExC,IAAI;CACJ,IAAI;EACF,WAAW,MAAM,gBAAgB;CACnC,QAAQ;EACN,WAAW;CACb;CA+BA,OAAO;EACL;EACA,cAJkB,MA1BC,SAAS,MAAM;GAClC,SAAS,CAAC,0BAA0B;GACpC,OAAO;GACP,OAAO;GACP,QAAQ;IACN,QAAQ;IACR,WAAW;IACX,QAAQ;IACR,eAAe;IACf,SAAS,EACP,UAAU,WACZ;GACF;GACA,UAAU,CAAC,UAAU;GACrB,SAAS,EACP,gBAAgB,CAAC,QAAQ,QAAQ,EACnC;GACA;GACA,WAAW;IACT,mBAAmB;IACnB,aAAa;IACb,0BAA0B;GAC5B;GACA,UAAU;EACZ,CAA0B,EAEA,CAAC,OAAO,EAAE,CAAC;EAKnC,eAAe;CACjB;AACF;;;;ACnKA,MAAM,0BAA0B,IAAI,IAAI,6BAA6B,OAAO,KAAK,GAAG,CAAC"}
@@ -0,0 +1 @@
1
+ export declare function resolve(...args: unknown[]): Promise<unknown>;
@@ -0,0 +1,153 @@
1
+ import { dirname } from "node:path";
2
+ import { fileURLToPath, pathToFileURL } from "node:url";
3
+ import { createPathsMatcher, getTsconfig } from "get-tsconfig";
4
+
5
+ // Resolve-only Node.js module hook: fixes tsconfig `paths` alias resolution
6
+ // for dynamically-imported user files (resolvers, executors, workflows,
7
+ // TailorDB types). tsx's own tsconfig-paths support is scoped to the
8
+ // tsconfig discovered relative to where tsx itself was registered, so an
9
+ // alias declared in a project-local tsconfig.json can fail to resolve when
10
+ // the imported file lives in a different directory. This hook activates
11
+ // only when tsx's own resolution throws (a fallback, not an override): it
12
+ // then re-derives the effective `paths` matcher from the importing file's
13
+ // own directory, so the fallback resolves against each file's own
14
+ // project's tsconfig regardless of process cwd or which other
15
+ // tsconfig-bearing projects have already been loaded in the same process.
16
+ //
17
+ // Known limitation: if tsx's cwd-scoped tsconfig happens to define the
18
+ // same alias pattern as the importing file's own tsconfig (e.g. both share
19
+ // a `@/*` convention) and a file exists at the guessed target, tsx's own
20
+ // resolution succeeds — incorrectly — before this fallback ever runs.
21
+ // Winning that race would require this hook to run ahead of tsx's own
22
+ // resolution, which was investigated and found to depend on undocumented,
23
+ // inconsistent Node.js module-hook composition behavior between tsx's two
24
+ // internal registration APIs; not attempted here.
25
+ //
26
+ // Registered via module.register() (not module.registerHooks()): chaining
27
+ // another register()-based loader after tsx's composes correctly regardless
28
+ // of which of the two internal registration APIs tsx itself picks (it
29
+ // varies by Node.js version).
30
+ //
31
+ // TypeScript transformation itself is left to tsx's already-registered load
32
+ // hook; this only supplies the resolve fallback tsx's cwd-scoped resolver
33
+ // misses.
34
+
35
+ const TS_EXTENSIONS = [".ts", ".tsx", ".mts"];
36
+ const JS_EXTENSIONS = [".js", ".jsx", ".mjs"];
37
+
38
+ // A specifier ending in one of these already names a JS-style output
39
+ // extension (the pattern TypeScript's NodeNext/bundler resolution expects
40
+ // for relative-looking specifiers): it must map to the corresponding TS
41
+ // source extension, not be treated as extensionless and have a TS
42
+ // extension appended after it (which would guess e.g. `utils.js.ts`).
43
+ const JS_TO_TS_EXT = new Map([
44
+ [".js", ".ts"],
45
+ [".jsx", ".tsx"],
46
+ [".mjs", ".mts"],
47
+ ]);
48
+
49
+ // Cached per directory for the lifetime of this process. `generate --watch`
50
+ // restarts its own child process on config/service-file changes (clearing
51
+ // this cache along with it), but it does not currently watch tsconfig.json
52
+ // itself, so edits to `paths` there won't be picked up until the next
53
+ // restart — a pre-existing limitation of watch mode, not new here.
54
+ const tsconfigCache = new Map();
55
+ const matcherCache = new Map();
56
+
57
+ function getResolutionContext(startDir) {
58
+ if (matcherCache.has(startDir)) return matcherCache.get(startDir);
59
+
60
+ const tsconfig = getTsconfig(startDir, "tsconfig.json", tsconfigCache);
61
+ const matcher = tsconfig ? createPathsMatcher(tsconfig) : null;
62
+ const result = matcher
63
+ ? { matcher, allowJs: tsconfig.config.compilerOptions?.allowJs ?? false }
64
+ : null;
65
+
66
+ matcherCache.set(startDir, result);
67
+ return result;
68
+ }
69
+
70
+ async function tryResolveWithExtensions(base, context, nextResolve, allowJs) {
71
+ for (const [jsExt, tsExt] of JS_TO_TS_EXT) {
72
+ if (base.endsWith(jsExt)) {
73
+ try {
74
+ return await nextResolve(base.slice(0, -jsExt.length) + tsExt, context);
75
+ } catch (e) {
76
+ if (e?.code !== "ERR_MODULE_NOT_FOUND") throw e;
77
+ }
78
+ return null;
79
+ }
80
+ }
81
+
82
+ if (!TS_EXTENSIONS.some((ext) => base.endsWith(ext))) {
83
+ // TypeScript resolves a file at this path before falling back to a
84
+ // directory's index file, so file extensions are tried (across every
85
+ // suffix-less candidate) before any `/index` candidate.
86
+ const extensions = allowJs ? [...TS_EXTENSIONS, ...JS_EXTENSIONS] : TS_EXTENSIONS;
87
+ for (const suffix of ["", "/index"]) {
88
+ for (const ext of extensions) {
89
+ try {
90
+ return await nextResolve(base + suffix + ext, context);
91
+ } catch (e) {
92
+ if (e?.code !== "ERR_MODULE_NOT_FOUND") throw e;
93
+ }
94
+ }
95
+ }
96
+ }
97
+ try {
98
+ return await nextResolve(base, context);
99
+ } catch (e) {
100
+ const code = e?.code;
101
+ if (code !== "ERR_MODULE_NOT_FOUND" && code !== "ERR_UNSUPPORTED_DIR_IMPORT") throw e;
102
+ }
103
+ return null;
104
+ }
105
+
106
+ // Hook for module.register(). Only handles the case default resolution
107
+ // (including tsx's own tsconfig-paths support) already failed on: a
108
+ // non-relative bare specifier that maps to a tsconfig `paths` alias declared
109
+ // by a tsconfig.json above the importing file's own directory. Relative
110
+ // imports and anything tsx/Node already resolves are left alone.
111
+ //
112
+ // A `#`-prefixed specifier (Node's subpath imports syntax, also usable as a
113
+ // tsconfig `paths` alias pattern) fails with ERR_PACKAGE_IMPORT_NOT_DEFINED
114
+ // or ERR_INVALID_MODULE_SPECIFIER rather than ERR_MODULE_NOT_FOUND, so those
115
+ // codes are treated as recoverable for `#`-prefixed specifiers only —
116
+ // narrow enough to avoid masking genuinely malformed specifiers elsewhere.
117
+ export async function resolve(specifier, context, nextResolve) {
118
+ try {
119
+ return await nextResolve(specifier, context);
120
+ } catch (err) {
121
+ const code = err?.code;
122
+ const isSubpathImport = specifier.startsWith("#");
123
+ const recoverable =
124
+ code === "ERR_MODULE_NOT_FOUND" ||
125
+ code === "ERR_UNSUPPORTED_DIR_IMPORT" ||
126
+ (isSubpathImport &&
127
+ (code === "ERR_PACKAGE_IMPORT_NOT_DEFINED" || code === "ERR_INVALID_MODULE_SPECIFIER"));
128
+ if (!recoverable) throw err;
129
+ if (specifier.startsWith(".") || specifier.startsWith("/")) throw err;
130
+ if (!context.parentURL?.startsWith("file://")) throw err;
131
+
132
+ const parentParsed = new URL(context.parentURL);
133
+ parentParsed.search = "";
134
+ parentParsed.hash = "";
135
+ const parentDir = dirname(fileURLToPath(parentParsed));
136
+
137
+ const resolutionContext = getResolutionContext(parentDir);
138
+ if (!resolutionContext) throw err;
139
+ const candidates = resolutionContext.matcher(specifier);
140
+ if (!candidates || candidates.length === 0) throw err;
141
+
142
+ for (const candidatePath of candidates) {
143
+ const result = await tryResolveWithExtensions(
144
+ pathToFileURL(candidatePath).href,
145
+ context,
146
+ nextResolve,
147
+ resolutionContext.allowJs,
148
+ );
149
+ if (result) return result;
150
+ }
151
+ throw err;
152
+ }
153
+ }
@@ -1,5 +1,5 @@
1
1
  # politty-completion-version: 1
2
- # politty-bin-sig: 1784179615
2
+ # politty-bin-sig: 1784677832
3
3
  # politty-bin-path: /home/runner/work/sdk/sdk/node_modules/.bin/tailor-sdk
4
4
  # program: tailor-sdk
5
5
  # shell: zsh
@@ -9,15 +9,18 @@ import { LogLevelEnum } from "../../types/app-config.generated.mjs";
9
9
  //#region src/configure/config/types.d.ts
10
10
  type LogLevel = LogLevelEnum;
11
11
  type LogLevelInput = LogLevel | (string & {});
12
+ /** `files`/`ignores` patterns are resolved relative to this config's own directory, not the invocation directory. */
12
13
  type ExecutorServiceConfig = {
13
14
  files: string[];
14
15
  ignores?: string[];
15
16
  };
16
17
  type ExecutorServiceInput = ExecutorServiceConfig;
18
+ /** `files`/`ignores` patterns are resolved relative to this config's own directory, not the invocation directory. */
17
19
  type HttpAdapterServiceInput = {
18
20
  files: string[];
19
21
  ignores?: string[];
20
22
  };
23
+ /** `files`/`ignores` patterns are resolved relative to this config's own directory, not the invocation directory. */
21
24
  type ResolverServiceConfig = {
22
25
  files: string[];
23
26
  ignores?: string[];
@@ -29,6 +32,7 @@ type ResolverServiceInput = {
29
32
  [namespace: string]: ResolverServiceConfig | ResolverExternalConfig;
30
33
  };
31
34
  type WorkflowServiceConfig = {
35
+ /** Resolved relative to this config's own directory, not the invocation directory. */
32
36
  files: string[];
33
37
  job_files?: string[];
34
38
  ignores?: string[];
@@ -47,7 +51,7 @@ type WorkflowServiceInput = WorkflowServiceConfig;
47
51
  * - `idp`: Array of IdP configs, e.g. `[myIdp]`
48
52
  * - `staticWebsites`: Array of static website configs, e.g. `[website]`
49
53
  * - `aiGateways`: Array of AI Gateway configs, e.g. `[gateway]`
50
- * - `db`, `resolver`, `executor`, `workflow`: Service configs with file globs
54
+ * - `db`, `resolver`, `executor`, `workflow`, `httpAdapter`: Service configs with file globs (resolved relative to this config file's own directory, not the invocation directory)
51
55
  */
52
56
  interface AppConfig<Auth extends AuthConfig = AuthConfig, Idp extends IdPConfig[] = IdPConfig[], StaticWebsites extends StaticWebsiteConfig[] = StaticWebsiteConfig[], AIGateways extends AIGatewayConfig[] = AIGatewayConfig[], Env extends Record<string, string | number | boolean> = Record<string, string | number | boolean>> {
53
57
  /** Application name (required). */
@@ -12,6 +12,7 @@ import { ExecutorReadyContext, GeneratorResult, NamespacePluginOutput, Plugin, P
12
12
  import { PermissionCondition, TailorTypeGqlPermission, TailorTypePermission, unsafeAllowAllGqlPermission, unsafeAllowAllTypePermission } from "./services/tailordb/permission.mjs";
13
13
  import { TailorAnyDBField, TailorAnyDBType, TailorDBField, TailorDBInstance, TailorDBType, db } from "./services/tailordb/schema.mjs";
14
14
  import { AIGatewayConfig } from "./services/aigateway/types.mjs";
15
+ import { IdPPermission, IdPPermissionCondition, unsafeAllowAllIdPPermission } from "./services/idp/permission.mjs";
15
16
  import { IdPEmailConfig, IdPGqlOperations, IdPGqlOperationsInput } from "../types/idp.generated.mjs";
16
17
  import { IdPConfig, IdPExternalConfig } from "./services/idp/types.mjs";
17
18
  import { SecretsConfig } from "./services/secrets/types.mjs";
@@ -42,7 +43,6 @@ import { defineWorkflowExecutionPolicies, defineWorkflowExecutionPolicy } from "
42
43
  import { WaitPointInstance, defineWaitPoint, defineWaitPoints } from "./services/workflow/wait-point.mjs";
43
44
  import { defineStaticWebSite } from "./services/staticwebsite/index.mjs";
44
45
  import { defineAIGateway } from "./services/aigateway/index.mjs";
45
- import { IdPPermission, IdPPermissionCondition, unsafeAllowAllIdPPermission } from "./services/idp/permission.mjs";
46
46
  import { defineIdp } from "./services/idp/index.mjs";
47
47
  import { defineSecretManager } from "./services/secrets/index.mjs";
48
48
  import { HttpAdapter, HttpAdapterGraphQLQuery, HttpAdapterGraphQLRequest, HttpAdapterGraphQLResponse, HttpAdapterInput, HttpAdapterInputFn, HttpAdapterOutputFn, HttpAdapterRequest, HttpAdapterResponse, HttpAdapterTypedDocumentNode, createHttpAdapter } from "./services/http-adapter/http-adapter.mjs";
@@ -1,5 +1,5 @@
1
1
  import { TailorEnv } from "../../../runtime/types.mjs";
2
- import { output } from "../../../types/helpers.mjs";
2
+ import { NullableToOptional, output } from "../../../types/helpers.mjs";
3
3
  import { DefinedFieldMetadata, FieldMetadata, TailorField, TailorFieldType } from "../../types/field.types.mjs";
4
4
  import { TailorDBInstance } from "../tailordb/types.mjs";
5
5
  import { AuthConnectionConfig } from "../../../types/auth-connection.generated.mjs";
@@ -56,37 +56,32 @@ type UserProfile<User extends TailorDBInstance, AttributeMap extends UserAttribu
56
56
  };
57
57
  type MachineUserAttributeFields = Record<string, TailorField<DefinedFieldMetadata, unknown, FieldMetadata, TailorFieldType>>;
58
58
  type TailorFieldOutputValue<Field> = Field extends TailorField<DefinedFieldMetadata, infer Output, FieldMetadata, TailorFieldType> ? Output : never;
59
- type MachineUserAttributeValues<Fields extends MachineUserAttributeFields> = { [K in keyof Fields]: TailorFieldOutputValue<Fields[K]> extends ValueOperand | null | undefined ? TailorFieldOutputValue<Fields[K]> : never; };
60
- type MachineUserFromAttributes<Fields extends MachineUserAttributeFields> = (keyof Fields extends never ? {
61
- attributes?: never;
59
+ type MachineUserAttributeValues<Fields extends MachineUserAttributeFields> = NullableToOptional<{ [K in keyof Fields]: TailorFieldOutputValue<Fields[K]> extends ValueOperand | null | undefined ? TailorFieldOutputValue<Fields[K]> : never; }>;
60
+ type OptionalIfNoRequiredKeys<Attributes> = Record<never, never> extends Attributes ? {
61
+ attributes?: Attributes;
62
62
  } : {
63
- attributes: DisallowExtraKeys<MachineUserAttributeValues<Fields>, keyof Fields>;
64
- }) & {
65
- attributeList?: string[];
63
+ attributes: Attributes;
66
64
  };
67
- type MachineUser<User extends TailorDBInstance, AttributeMap extends UserAttributeMap<User> = UserAttributeMap<User>, AttributeList extends UserAttributeListKey<User>[] = [], MachineUserAttributes extends MachineUserAttributeFields | undefined = undefined> = IsAny<MachineUserAttributes> extends true ? IsAny<User> extends true ? {
68
- attributes: Record<string, AuthAttributeValue>;
69
- attributeList?: string[];
70
- } : (AttributeMapSelectedKeys<User, AttributeMap> extends never ? {
65
+ type MachineUserFromAttributes<Fields extends MachineUserAttributeFields> = (keyof Fields extends never ? {
71
66
  attributes?: never;
72
- } : {
73
- attributes: { [K in AttributeMapSelectedKeys<User, AttributeMap>]: K extends keyof output<User> ? output<User>[K] : never; } & { [K in Exclude<keyof output<User>, AttributeMapSelectedKeys<User, AttributeMap>>]?: never; };
74
- }) & ([] extends AttributeList ? {
75
- attributeList?: never;
76
- } : {
77
- attributeList: AttributeListToTuple<User, AttributeList>;
78
- }) : [MachineUserAttributes] extends [MachineUserAttributeFields] ? MachineUserFromAttributes<MachineUserAttributes> : IsAny<User> extends true ? {
79
- attributes: Record<string, AuthAttributeValue>;
67
+ } : OptionalIfNoRequiredKeys<DisallowExtraKeys<MachineUserAttributeValues<Fields>, keyof Fields>>) & {
80
68
  attributeList?: string[];
81
- } : (AttributeMapSelectedKeys<User, AttributeMap> extends never ? {
69
+ };
70
+ type MachineUserProfileAttributes<User extends TailorDBInstance, AttributeMap extends UserAttributeMap<User>> = NullableToOptional<{ [K in AttributeMapSelectedKeys<User, AttributeMap>]: K extends keyof output<User> ? output<User>[K] : never; }> & { [K in Exclude<keyof output<User>, AttributeMapSelectedKeys<User, AttributeMap>>]?: never; };
71
+ type MachineUserFromUserProfile<User extends TailorDBInstance, AttributeMap extends UserAttributeMap<User>, AttributeList extends UserAttributeListKey<User>[]> = (AttributeMapSelectedKeys<User, AttributeMap> extends never ? {
82
72
  attributes?: never;
83
- } : {
84
- attributes: { [K in AttributeMapSelectedKeys<User, AttributeMap>]: K extends keyof output<User> ? output<User>[K] : never; } & { [K in Exclude<keyof output<User>, AttributeMapSelectedKeys<User, AttributeMap>>]?: never; };
85
- }) & ([] extends AttributeList ? {
73
+ } : OptionalIfNoRequiredKeys<MachineUserProfileAttributes<User, AttributeMap>>) & ([] extends AttributeList ? {
86
74
  attributeList?: never;
87
75
  } : {
88
76
  attributeList: AttributeListToTuple<User, AttributeList>;
89
77
  });
78
+ type MachineUser<User extends TailorDBInstance, AttributeMap extends UserAttributeMap<User> = UserAttributeMap<User>, AttributeList extends UserAttributeListKey<User>[] = [], MachineUserAttributes extends MachineUserAttributeFields | undefined = undefined> = IsAny<MachineUserAttributes> extends true ? IsAny<User> extends true ? {
79
+ attributes?: Record<string, AuthAttributeValue>;
80
+ attributeList?: string[];
81
+ } : MachineUserFromUserProfile<User, AttributeMap, AttributeList> : [MachineUserAttributes] extends [MachineUserAttributeFields] ? MachineUserFromAttributes<MachineUserAttributes> : IsAny<User> extends true ? {
82
+ attributes?: Record<string, AuthAttributeValue>;
83
+ attributeList?: string[];
84
+ } : MachineUserFromUserProfile<User, AttributeMap, AttributeList>;
90
85
  /** Upstream OAuth provider that federated a login through the Built-in IdP. */
91
86
  type FederatedIdentityProvider = "google" | "microsoft";
92
87
  /**
@@ -1,6 +1,6 @@
1
+ import { IdPPermission, IdPPermissionCondition, unsafeAllowAllIdPPermission } from "./permission.mjs";
1
2
  import { IdPEmailConfig, IdPGqlOperations, IdPGqlOperationsInput, IdPInput } from "../../../types/idp.generated.mjs";
2
3
  import { IdPConfig, IdPExternalConfig, IdpDefinitionBrand } from "./types.mjs";
3
- import { IdPPermission, IdPPermissionCondition, unsafeAllowAllIdPPermission } from "./permission.mjs";
4
4
  //#region src/configure/services/idp/index.d.ts
5
5
  /**
6
6
  * Define an IdP service configuration for the Tailor SDK.
@@ -1,4 +1,5 @@
1
1
  import { BuiltinIdP } from "../../../types/auth.generated.mjs";
2
+ import { IdPPermission } from "./permission.mjs";
2
3
  import { IdPInput } from "../../../types/idp.generated.mjs";
3
4
  //#region src/configure/services/idp/types.d.ts
4
5
  declare const idpDefinitionBrand: unique symbol;
@@ -13,7 +14,10 @@ type IdPExternalConfig = {
13
14
  name: string;
14
15
  external: true;
15
16
  };
16
- type IdPOwnConfig = Omit<DefinedIdp<string, IdPInput, string>, "provider">;
17
+ type IdPOwnConfigInput = Omit<IdPInput, "permission"> & {
18
+ permission?: IdPPermission;
19
+ };
20
+ type IdPOwnConfig = Omit<DefinedIdp<string, IdPOwnConfigInput, string>, "provider">;
17
21
  type IdPConfig = IdPOwnConfig | IdPExternalConfig;
18
22
  //#endregion
19
23
  export { DefinedIdp, IdPConfig, IdPExternalConfig, IdPOwnConfig, IdpDefinitionBrand };
@@ -6,6 +6,7 @@ import { PermissionCondition, TailorTypeGqlPermission, TailorTypePermission, uns
6
6
  import { TailorAnyDBField, TailorAnyDBType, TailorDBField, TailorDBInstance, TailorDBType, db } from "./tailordb/schema.mjs";
7
7
  import "./tailordb/index.mjs";
8
8
  import { AIGatewayConfig } from "./aigateway/types.mjs";
9
+ import { IdPPermission, IdPPermissionCondition, unsafeAllowAllIdPPermission } from "./idp/permission.mjs";
9
10
  import { IdPEmailConfig, IdPGqlOperations, IdPGqlOperationsInput } from "../../types/idp.generated.mjs";
10
11
  import { IdPConfig, IdPExternalConfig } from "./idp/types.mjs";
11
12
  import { SecretsConfig } from "./secrets/types.mjs";
@@ -32,7 +33,6 @@ import { WaitPointInstance, defineWaitPoint, defineWaitPoints } from "./workflow
32
33
  import "./workflow/index.mjs";
33
34
  import { defineStaticWebSite } from "./staticwebsite/index.mjs";
34
35
  import { defineAIGateway } from "./aigateway/index.mjs";
35
- import { IdPPermission, IdPPermissionCondition, unsafeAllowAllIdPPermission } from "./idp/permission.mjs";
36
36
  import { defineIdp } from "./idp/index.mjs";
37
37
  import { defineSecretManager } from "./secrets/index.mjs";
38
38
  import { HttpAdapter, HttpAdapterGraphQLQuery, HttpAdapterGraphQLRequest, HttpAdapterGraphQLResponse, HttpAdapterInput, HttpAdapterInputFn, HttpAdapterOutputFn, HttpAdapterRequest, HttpAdapterResponse, HttpAdapterTypedDocumentNode, createHttpAdapter } from "./http-adapter/http-adapter.mjs";
@@ -81,7 +81,11 @@ function defaultGetInvoker() {
81
81
  * Install the always-present base platform globals (containers, context stub,
82
82
  * error classes, runtime flag). Per-namespace mocks are layered on top by the
83
83
  * `xMock()` factories in `./mock`.
84
+ *
85
+ * Acquire with a `using` declaration and the globals are removed when the
86
+ * scope exits; alternatively call `cleanupPlatformGlobals` yourself.
84
87
  * @param global - The global object to install into (typically `globalThis`)
88
+ * @returns A `Disposable` that removes the installed globals
85
89
  */
86
90
  function installPlatformGlobals(global) {
87
91
  const g = global;
@@ -94,6 +98,9 @@ function installPlatformGlobals(global) {
94
98
  g.TailorErrors = TailorErrorsMock;
95
99
  g.TailorErrorMessage = TailorErrorMessageMock;
96
100
  g.TailorDBFileError = TailorDBFileErrorMock;
101
+ return { [Symbol.dispose]() {
102
+ cleanupPlatformGlobals(global);
103
+ } };
97
104
  }
98
105
  /**
99
106
  * Remove the base platform globals (and anything the namespace mocks layered on
@@ -112,4 +119,4 @@ function cleanupPlatformGlobals(global) {
112
119
 
113
120
  //#endregion
114
121
  export { cleanupPlatformGlobals as n, installPlatformGlobals as r, RUNTIME_FLAG_KEY as t };
115
- //# sourceMappingURL=globals-B-n_3uYu.mjs.map
122
+ //# sourceMappingURL=globals-DVJ8RVvm.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"globals-B-n_3uYu.mjs","names":[],"sources":["../src/vitest/workflow-runtime.ts","../src/vitest/globals.ts"],"sourcesContent":["// Default `tailor.workflow` runner installed by the `tailor-runtime` environment.\n// Must stay free of `vitest` (`vi`): it loads via `./globals` in the environment\n// realm where `vi` is unavailable, hence relative imports only (no `@/` alias).\nimport { runRegisteredJob, runRegisteredWorkflow } from \"../configure/services/workflow/registry\";\nimport type { StartJobFunctionOptions, StartWorkflowOptions } from \"../runtime/workflow\";\n\nexport interface DefaultWorkflowRuntime {\n startJobFunction: (name: string, args?: unknown, options?: StartJobFunctionOptions) => unknown;\n triggerJobFunction: (name: string, args?: unknown, options?: StartJobFunctionOptions) => unknown;\n startWorkflow: (name: string, args?: unknown, options?: StartWorkflowOptions) => Promise<string>;\n triggerWorkflow: (\n name: string,\n args?: unknown,\n options?: StartWorkflowOptions,\n ) => Promise<string>;\n resumeWorkflowExecution: (executionId: string) => Promise<string>;\n resumeWorkflow: (executionId: string) => Promise<string>;\n wait: (key: string, payload?: unknown) => unknown;\n resolve: (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n ) => Promise<void>;\n}\n\nexport function createDefaultWorkflowRuntime(): DefaultWorkflowRuntime {\n const startJobFunction: DefaultWorkflowRuntime[\"startJobFunction\"] = (name, args) =>\n runRegisteredJob(name, args);\n const startWorkflow: DefaultWorkflowRuntime[\"startWorkflow\"] = (name, args) =>\n runRegisteredWorkflow(name, args);\n const resumeWorkflowExecution: DefaultWorkflowRuntime[\"resumeWorkflowExecution\"] = async (\n executionId,\n ) => executionId;\n return {\n startJobFunction,\n triggerJobFunction: startJobFunction,\n startWorkflow,\n triggerWorkflow: startWorkflow,\n resumeWorkflowExecution,\n resumeWorkflow: resumeWorkflowExecution,\n wait: (key: string): unknown => {\n throw new Error(\n `No wait handler for \"${key}\". Acquire mockWorkflow() and call setWaitHandler(...).`,\n );\n },\n resolve: async (): Promise<void> => {\n throw new Error(\n \"No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).\",\n );\n },\n };\n}\n","/**\n * Base platform globals for the tailor-runtime test environment.\n *\n * This module is intentionally free of any `vitest` (`vi`) dependency so it can\n * be imported from the Vitest *environment* module (which runs in a realm where\n * `vi` is not available). It installs only the always-present structural pieces:\n *\n * - `globalThis.tailor` / `globalThis.tailordb` container objects\n * - `globalThis.tailor.context.getInvoker` default stub\n * - the platform error classes (`TailorErrors`, `TailorErrorMessage`,\n * `TailorDBFileError`)\n * - the `__tailorRuntimeActive` sentinel flag\n *\n * The per-namespace mock behavior (TailorDB client, workflow, secretmanager, …)\n * is installed on demand by the `xMock()` factories in `./mock`, which run in\n * test context where `vi` *is* available.\n */\n\nimport { createDefaultWorkflowRuntime } from \"./workflow-runtime\";\nimport type { ContextInvoker } from \"../runtime/context\";\nimport type { TailorDBFileErrorCode } from \"../runtime/file\";\n\n// Sentinel set when the tailor-runtime environment is active. setup.ts reads it\n// to decide whether to run its blocked-globals lifecycle and config-secret\n// loading.\nexport const RUNTIME_FLAG_KEY = \"__tailorRuntimeActive\";\n\n// ---------------------------------------------------------------------------\n// Error class mocks\n// ---------------------------------------------------------------------------\n\ninterface TailorErrorItem {\n message: string;\n path: (string | number)[];\n}\n\nclass TailorErrorsMock extends Error {\n errors: TailorErrorItem[];\n\n constructor(errors: TailorErrorItem[]) {\n if (!Array.isArray(errors)) {\n throw new TypeError(\"TailorErrors: errors must be an array\");\n }\n const validated = errors.map((e, i) => {\n if (typeof e.message !== \"string\") {\n throw new TypeError(`TailorErrors: errors[${i}].message must be a string`);\n }\n if (!Array.isArray(e.path)) {\n throw new TypeError(`TailorErrors: errors[${i}].path must be an array`);\n }\n return { message: e.message, path: e.path };\n });\n // Match the PF runtime's TailorErrors serialization, which prefixes the\n // JSON payload with \"TailorErrors: \". Other SDK code (e.g. apply\n // integration fixtures) strips this prefix before JSON.parse.\n super(`TailorErrors: ${JSON.stringify({ errors: validated })}`);\n this.name = \"TailorErrors\";\n this.errors = validated;\n }\n}\n\nclass TailorErrorMessageMock extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TailorErrorMessage\";\n }\n}\n\nclass TailorDBFileErrorMock extends Error {\n code?: TailorDBFileErrorCode;\n override cause: unknown;\n\n constructor(message: string, code?: TailorDBFileErrorCode, cause?: unknown) {\n super(message);\n this.name = \"TailorDBFileError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Base install / cleanup\n// ---------------------------------------------------------------------------\n\n// Stub-only injection. SDK consumers configure invokers at the body level\n// (resolver/executor/workflow `.body()` `invoker` arg) or, for bundled tests,\n// via `vi.spyOn(globalThis.tailor.context, \"getInvoker\")`.\nfunction defaultGetInvoker(): ContextInvoker | null {\n return null;\n}\n\n/**\n * Install the always-present base platform globals (containers, context stub,\n * error classes, runtime flag). Per-namespace mocks are layered on top by the\n * `xMock()` factories in `./mock`.\n * @param global - The global object to install into (typically `globalThis`)\n */\nexport function installPlatformGlobals(global: typeof globalThis): void {\n const g = global as Record<string, unknown>;\n\n g[RUNTIME_FLAG_KEY] = true;\n\n // Containers. Namespace mocks (secretmanager, …) are added to these by the\n // corresponding `xMock()` on acquisition. `workflow` carries a default runner\n // so `.trigger()` runs the real job chain locally without `mockWorkflow()`;\n // `mockWorkflow()` overlays and restores it.\n g.tailor = {\n context: { getInvoker: defaultGetInvoker },\n workflow: createDefaultWorkflowRuntime(),\n };\n g.tailordb = {};\n\n g.TailorErrors = TailorErrorsMock;\n g.TailorErrorMessage = TailorErrorMessageMock;\n g.TailorDBFileError = TailorDBFileErrorMock;\n}\n\n/**\n * Remove the base platform globals (and anything the namespace mocks layered on\n * top, since they live under the same containers).\n * @param global - The global object to clean up (typically `globalThis`)\n */\nexport function cleanupPlatformGlobals(global: typeof globalThis): void {\n const g = global as Record<string, unknown>;\n delete g.tailordb;\n delete g.tailor;\n delete g.TailorErrors;\n delete g.TailorErrorMessage;\n delete g.TailorDBFileError;\n delete g[RUNTIME_FLAG_KEY];\n}\n"],"mappings":";;;AAyBA,SAAgB,+BAAuD;CACrE,MAAM,oBAAgE,MAAM,SAC1E,iBAAiB,MAAM,IAAI;CAC7B,MAAM,iBAA0D,MAAM,SACpE,sBAAsB,MAAM,IAAI;CAClC,MAAM,0BAA6E,OACjF,gBACG;CACL,OAAO;EACL;EACA,oBAAoB;EACpB;EACA,iBAAiB;EACjB;EACA,gBAAgB;EAChB,OAAO,QAAyB;GAC9B,MAAM,IAAI,MACR,wBAAwB,IAAI,wDAC9B;EACF;EACA,SAAS,YAA2B;GAClC,MAAM,IAAI,MACR,6EACF;EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;AC1BA,MAAa,mBAAmB;AAWhC,IAAM,mBAAN,cAA+B,MAAM;CACnC;CAEA,YAAY,QAA2B;EACrC,IAAI,CAAC,MAAM,QAAQ,MAAM,GACvB,MAAM,IAAI,UAAU,uCAAuC;EAE7D,MAAM,YAAY,OAAO,KAAK,GAAG,MAAM;GACrC,IAAI,OAAO,EAAE,YAAY,UACvB,MAAM,IAAI,UAAU,wBAAwB,EAAE,2BAA2B;GAE3E,IAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,GACvB,MAAM,IAAI,UAAU,wBAAwB,EAAE,wBAAwB;GAExE,OAAO;IAAE,SAAS,EAAE;IAAS,MAAM,EAAE;GAAK;EAC5C,CAAC;EAID,MAAM,iBAAiB,KAAK,UAAU,EAAE,QAAQ,UAAU,CAAC,GAAG;EAC9D,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAEA,IAAM,yBAAN,cAAqC,MAAM;CACzC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,IAAM,wBAAN,cAAoC,MAAM;CACxC;CACA,AAAS;CAET,YAAY,SAAiB,MAA8B,OAAiB;EAC1E,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;AASA,SAAS,oBAA2C;CAClD,OAAO;AACT;;;;;;;AAQA,SAAgB,uBAAuB,QAAiC;CACtE,MAAM,IAAI;CAEV,EAAE,oBAAoB;CAMtB,EAAE,SAAS;EACT,SAAS,EAAE,YAAY,kBAAkB;EACzC,UAAU,6BAA6B;CACzC;CACA,EAAE,WAAW,CAAC;CAEd,EAAE,eAAe;CACjB,EAAE,qBAAqB;CACvB,EAAE,oBAAoB;AACxB;;;;;;AAOA,SAAgB,uBAAuB,QAAiC;CACtE,MAAM,IAAI;CACV,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;AACX"}
1
+ {"version":3,"file":"globals-DVJ8RVvm.mjs","names":[],"sources":["../src/vitest/workflow-runtime.ts","../src/vitest/globals.ts"],"sourcesContent":["// Default `tailor.workflow` runner installed by the `tailor-runtime` environment.\n// Must stay free of `vitest` (`vi`): it loads via `./globals` in the environment\n// realm where `vi` is unavailable, hence relative imports only (no `@/` alias).\nimport { runRegisteredJob, runRegisteredWorkflow } from \"../configure/services/workflow/registry\";\nimport type { StartJobFunctionOptions, StartWorkflowOptions } from \"../runtime/workflow\";\n\nexport interface DefaultWorkflowRuntime {\n startJobFunction: (name: string, args?: unknown, options?: StartJobFunctionOptions) => unknown;\n triggerJobFunction: (name: string, args?: unknown, options?: StartJobFunctionOptions) => unknown;\n startWorkflow: (name: string, args?: unknown, options?: StartWorkflowOptions) => Promise<string>;\n triggerWorkflow: (\n name: string,\n args?: unknown,\n options?: StartWorkflowOptions,\n ) => Promise<string>;\n resumeWorkflowExecution: (executionId: string) => Promise<string>;\n resumeWorkflow: (executionId: string) => Promise<string>;\n wait: (key: string, payload?: unknown) => unknown;\n resolve: (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n ) => Promise<void>;\n}\n\nexport function createDefaultWorkflowRuntime(): DefaultWorkflowRuntime {\n const startJobFunction: DefaultWorkflowRuntime[\"startJobFunction\"] = (name, args) =>\n runRegisteredJob(name, args);\n const startWorkflow: DefaultWorkflowRuntime[\"startWorkflow\"] = (name, args) =>\n runRegisteredWorkflow(name, args);\n const resumeWorkflowExecution: DefaultWorkflowRuntime[\"resumeWorkflowExecution\"] = async (\n executionId,\n ) => executionId;\n return {\n startJobFunction,\n triggerJobFunction: startJobFunction,\n startWorkflow,\n triggerWorkflow: startWorkflow,\n resumeWorkflowExecution,\n resumeWorkflow: resumeWorkflowExecution,\n wait: (key: string): unknown => {\n throw new Error(\n `No wait handler for \"${key}\". Acquire mockWorkflow() and call setWaitHandler(...).`,\n );\n },\n resolve: async (): Promise<void> => {\n throw new Error(\n \"No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).\",\n );\n },\n };\n}\n","/**\n * Base platform globals for the tailor-runtime test environment.\n *\n * This module is intentionally free of any `vitest` (`vi`) dependency so it can\n * be imported from the Vitest *environment* module (which runs in a realm where\n * `vi` is not available). It installs only the always-present structural pieces:\n *\n * - `globalThis.tailor` / `globalThis.tailordb` container objects\n * - `globalThis.tailor.context.getInvoker` default stub\n * - the platform error classes (`TailorErrors`, `TailorErrorMessage`,\n * `TailorDBFileError`)\n * - the `__tailorRuntimeActive` sentinel flag\n *\n * The per-namespace mock behavior (TailorDB client, workflow, secretmanager, …)\n * is installed on demand by the `xMock()` factories in `./mock`, which run in\n * test context where `vi` *is* available.\n */\n\nimport { createDefaultWorkflowRuntime } from \"./workflow-runtime\";\nimport type { ContextInvoker } from \"../runtime/context\";\nimport type { TailorDBFileErrorCode } from \"../runtime/file\";\n\n// Sentinel set when the tailor-runtime environment is active. setup.ts reads it\n// to decide whether to run its blocked-globals lifecycle and config-secret\n// loading.\nexport const RUNTIME_FLAG_KEY = \"__tailorRuntimeActive\";\n\n// ---------------------------------------------------------------------------\n// Error class mocks\n// ---------------------------------------------------------------------------\n\ninterface TailorErrorItem {\n message: string;\n path: (string | number)[];\n}\n\nclass TailorErrorsMock extends Error {\n errors: TailorErrorItem[];\n\n constructor(errors: TailorErrorItem[]) {\n if (!Array.isArray(errors)) {\n throw new TypeError(\"TailorErrors: errors must be an array\");\n }\n const validated = errors.map((e, i) => {\n if (typeof e.message !== \"string\") {\n throw new TypeError(`TailorErrors: errors[${i}].message must be a string`);\n }\n if (!Array.isArray(e.path)) {\n throw new TypeError(`TailorErrors: errors[${i}].path must be an array`);\n }\n return { message: e.message, path: e.path };\n });\n // Match the PF runtime's TailorErrors serialization, which prefixes the\n // JSON payload with \"TailorErrors: \". Other SDK code (e.g. apply\n // integration fixtures) strips this prefix before JSON.parse.\n super(`TailorErrors: ${JSON.stringify({ errors: validated })}`);\n this.name = \"TailorErrors\";\n this.errors = validated;\n }\n}\n\nclass TailorErrorMessageMock extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TailorErrorMessage\";\n }\n}\n\nclass TailorDBFileErrorMock extends Error {\n code?: TailorDBFileErrorCode;\n override cause: unknown;\n\n constructor(message: string, code?: TailorDBFileErrorCode, cause?: unknown) {\n super(message);\n this.name = \"TailorDBFileError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Base install / cleanup\n// ---------------------------------------------------------------------------\n\n// Stub-only injection. SDK consumers configure invokers at the body level\n// (resolver/executor/workflow `.body()` `invoker` arg) or, for bundled tests,\n// via `vi.spyOn(globalThis.tailor.context, \"getInvoker\")`.\nfunction defaultGetInvoker(): ContextInvoker | null {\n return null;\n}\n\n/**\n * Install the always-present base platform globals (containers, context stub,\n * error classes, runtime flag). Per-namespace mocks are layered on top by the\n * `xMock()` factories in `./mock`.\n *\n * Acquire with a `using` declaration and the globals are removed when the\n * scope exits; alternatively call `cleanupPlatformGlobals` yourself.\n * @param global - The global object to install into (typically `globalThis`)\n * @returns A `Disposable` that removes the installed globals\n */\nexport function installPlatformGlobals(global: typeof globalThis): Disposable {\n const g = global as Record<string, unknown>;\n\n g[RUNTIME_FLAG_KEY] = true;\n\n // Containers. Namespace mocks (secretmanager, …) are added to these by the\n // corresponding `xMock()` on acquisition. `workflow` carries a default runner\n // so `.trigger()` runs the real job chain locally without `mockWorkflow()`;\n // `mockWorkflow()` overlays and restores it.\n g.tailor = {\n context: { getInvoker: defaultGetInvoker },\n workflow: createDefaultWorkflowRuntime(),\n };\n g.tailordb = {};\n\n g.TailorErrors = TailorErrorsMock;\n g.TailorErrorMessage = TailorErrorMessageMock;\n g.TailorDBFileError = TailorDBFileErrorMock;\n\n return {\n [Symbol.dispose]() {\n cleanupPlatformGlobals(global);\n },\n };\n}\n\n/**\n * Remove the base platform globals (and anything the namespace mocks layered on\n * top, since they live under the same containers).\n * @param global - The global object to clean up (typically `globalThis`)\n */\nexport function cleanupPlatformGlobals(global: typeof globalThis): void {\n const g = global as Record<string, unknown>;\n delete g.tailordb;\n delete g.tailor;\n delete g.TailorErrors;\n delete g.TailorErrorMessage;\n delete g.TailorDBFileError;\n delete g[RUNTIME_FLAG_KEY];\n}\n"],"mappings":";;;AAyBA,SAAgB,+BAAuD;CACrE,MAAM,oBAAgE,MAAM,SAC1E,iBAAiB,MAAM,IAAI;CAC7B,MAAM,iBAA0D,MAAM,SACpE,sBAAsB,MAAM,IAAI;CAClC,M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