@tailor-platform/sdk 2.16.0 → 2.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -0
- package/dist/{application-wYQ-ivDg.mjs → application-DEkgf2w1.mjs} +18 -18
- package/dist/application-DEkgf2w1.mjs.map +1 -0
- package/dist/application-Dl94fzpm.mjs +1 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-files.d.mts +5 -1
- package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +2 -2
- package/dist/cli/lib.d.mts +4 -3
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +43 -43
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/shared/error-diagnostics.d.mts +10 -0
- package/dist/cli/shared/error-json.d.mts +19 -0
- package/dist/cli/shared/github-actions.d.mts +11 -0
- package/dist/cli/shared/logger.d.mts +18 -0
- package/dist/completion/zsh-worker.zsh +2 -2
- package/dist/configure/index.mjs +1 -1
- package/dist/configure/index.mjs.map +1 -1
- package/dist/crashreport-CgymxQDu.mjs +1 -0
- package/dist/crashreport-Cyuz1qiu.mjs +42 -0
- package/dist/crashreport-Cyuz1qiu.mjs.map +1 -0
- package/dist/{errors-BtTxkzgy.mjs → errors-BjJnpXkK.mjs} +2 -2
- package/dist/{errors-BtTxkzgy.mjs.map → errors-BjJnpXkK.mjs.map} +1 -1
- package/dist/field-parse-CzlKC4b7.mjs +2 -0
- package/dist/field-parse-CzlKC4b7.mjs.map +1 -0
- package/dist/kysely-type-B_oA8D1k.mjs +43 -0
- package/dist/kysely-type-B_oA8D1k.mjs.map +1 -0
- package/dist/{logger-CEAxByN5.mjs → logger-72hM4JWZ.mjs} +4 -4
- package/dist/logger-72hM4JWZ.mjs.map +1 -0
- package/dist/{manager-E3ffRcCt.mjs → manager-C26Gi1bX.mjs} +2 -2
- package/dist/{manager-E3ffRcCt.mjs.map → manager-C26Gi1bX.mjs.map} +1 -1
- package/dist/plugin/builtin/kysely-type/index.d.mts +2 -0
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
- package/dist/plugin/index.mjs +1 -1
- package/dist/{register-ts-hook-DrHS-J1k.mjs → register-ts-hook-BD3ArLqY.mjs} +111 -72
- package/dist/register-ts-hook-BD3ArLqY.mjs.map +1 -0
- package/dist/schema-DRyQEabV.mjs +2 -0
- package/dist/schema-DRyQEabV.mjs.map +1 -0
- package/dist/seed/index.d.mts +5 -0
- package/dist/seed/index.mjs +3 -2
- package/dist/seed/index.mjs.map +1 -1
- package/dist/service-B3OiWCYg.mjs +1 -0
- package/dist/{service-Cw7hb5HK.mjs → service-B4Gh_bbL.mjs} +2 -2
- package/dist/{service-Cw7hb5HK.mjs.map → service-B4Gh_bbL.mjs.map} +1 -1
- package/dist/{service-DaoW0kzo.mjs → service-eM7Fd8zS.mjs} +3 -3
- package/dist/{service-DaoW0kzo.mjs.map → service-eM7Fd8zS.mjs.map} +1 -1
- package/dist/tailordb-ddl-Fgm2cNvT.mjs +7 -0
- package/dist/tailordb-ddl-Fgm2cNvT.mjs.map +1 -0
- package/dist/utils/test/index.mjs +1 -1
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mocks/tailordb-pglite.d.mts +5 -4
- package/docs/cli/tailordb.md +8 -8
- package/docs/cli-reference.md +18 -5
- package/docs/services/tailordb-migration.md +29 -24
- package/docs/testing.md +23 -21
- package/package.json +16 -15
- package/dist/application-Dw3t9p2f.mjs +0 -1
- package/dist/application-wYQ-ivDg.mjs.map +0 -1
- package/dist/crashreport-DF8YMIE5.mjs +0 -1
- package/dist/crashreport-Doz2Kuuq.mjs +0 -42
- package/dist/crashreport-Doz2Kuuq.mjs.map +0 -1
- package/dist/field-column-type-QMtF6lUp.mjs +0 -2
- package/dist/field-column-type-QMtF6lUp.mjs.map +0 -1
- package/dist/kysely-type-B-BOlXH7.mjs +0 -43
- package/dist/kysely-type-B-BOlXH7.mjs.map +0 -1
- package/dist/logger-CEAxByN5.mjs.map +0 -1
- package/dist/register-ts-hook-DrHS-J1k.mjs.map +0 -1
- package/dist/schema-BTioi2dP.mjs +0 -2
- package/dist/schema-BTioi2dP.mjs.map +0 -1
- package/dist/service-dn9jxC8c.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager-E3ffRcCt.mjs","names":[],"sources":["../src/plugin/manager.ts"],"sourcesContent":["import { db, type TailorAnyDBType } from \"#/configure/services/tailordb/index\";\nimport {\n getPluginGenerationDependencies,\n getRawPluginTableName,\n hasGenerationHooks,\n} from \"#/plugin/guards\";\nimport { assertDefined } from \"#/utils/assert\";\nimport type {\n TailorTypePermission,\n TailorTypeGqlPermission,\n} from \"#/configure/services/tailordb/permission\";\nimport type {\n TailorAnyDBField,\n TypeHook,\n TypeValidateFn,\n} from \"#/configure/services/tailordb/types\";\nimport type {\n DependencyKind,\n Plugin,\n PluginAttachment,\n PluginGeneratedExecutor,\n PluginGeneratedTable,\n PluginNamespaceProcessContext,\n PluginOutput,\n TablePluginOutput,\n} from \"#/plugin/types\";\nimport type { TailorDBTypeRaw } from \"#/types/tailordb.generated\";\n\n/**\n * Context for processing a single plugin attachment on a raw TailorDBType\n */\nexport interface ProcessAttachmentContext {\n table: TailorAnyDBType;\n tableConfig: unknown;\n namespace: string;\n pluginId: string;\n}\n\n/**\n * Information about a plugin-generated table (for table file generation)\n */\nexport interface PluginGeneratedTableInfo {\n /** Plugin ID that generated this table */\n pluginId: string;\n /** Plugin import path for resolving executor files */\n pluginImportPath: string;\n /** Source table name that triggered the plugin */\n sourceTableName: string;\n /** Kind identifier for this generated table */\n kind: string;\n /** The generated TailorDB table object */\n table: PluginGeneratedTable;\n /** Namespace where this table was generated */\n namespace: string;\n /** Plugin config used to generate this table */\n pluginConfig?: unknown;\n}\n\n/**\n * Extended executor info with plugin import path\n */\nexport interface PluginExecutorInfoExtended extends PluginExecutorInfo {\n /** Plugin's import path for resolving executor files */\n pluginImportPath: string;\n}\n\n/**\n * Result of processing a table-attached plugin\n */\nexport type ProcessAttachmentResult =\n | { success: true; output: TablePluginOutput }\n | { success: false; error: string };\n\n/**\n * Result of processing a namespace plugin\n */\nexport type ProcessNamespaceResult =\n | { success: true; output: PluginOutput }\n | { success: false; error: string };\n\n/**\n * Parameters for processing all plugin attachments of a TailorDB table.\n */\nexport interface ProcessAttachmentsForTableParams {\n rawTable: TailorDBTypeRaw;\n attachments: PluginAttachment[];\n namespace: string;\n}\n\n/**\n * Progress event emitted while processing plugin attachments for a TailorDB table.\n * Plain data so the caller (typically the cli) can format and output it.\n */\ntype ProcessAttachmentEvent =\n | { kind: \"extended\"; tableName: string; fieldCount: number; pluginId: string }\n | { kind: \"generated\"; tableName: string; pluginId: string };\n\n/**\n * Generated table produced by a plugin during attachment processing.\n * `table` is raw plugin output; the caller must validate it before use.\n */\ninterface ProcessAttachmentsGeneratedTable {\n tableName: string;\n table: unknown;\n kind: string;\n pluginId: string;\n pluginImportPath: string;\n pluginConfig?: unknown;\n}\n\n/**\n * Result of {@link PluginManager.processAttachmentsForTable}.\n */\nexport interface ProcessAttachmentsForTableResult {\n /**\n * Final table after all extends are applied; undefined if no plugin extended the table.\n * Raw builder output; the caller must validate it before use.\n */\n extendedTable?: unknown;\n /** Tables newly generated by plugins for this attachment chain. */\n generatedTables: ProcessAttachmentsGeneratedTable[];\n /** Events for the caller to render. */\n events: ProcessAttachmentEvent[];\n}\n\n/**\n * Information about a plugin-generated executor\n */\nexport interface PluginExecutorInfo {\n /** The executor definition */\n executor: PluginGeneratedExecutor;\n /** Plugin ID that generated this executor */\n pluginId: string;\n /** Namespace where the executor was generated */\n namespace: string;\n /** Source table name (for table-attached executors, undefined for namespace) */\n sourceTableName?: string;\n}\n\n/**\n * Manages plugin registration and processing\n */\nexport class PluginManager {\n private plugins: Map<string, Plugin> = new Map();\n private generatedExecutors: PluginExecutorInfo[] = [];\n private generatedTables: PluginGeneratedTableInfo[] = [];\n private namespaceGeneratedTableKeys: Set<string> = new Set();\n private namespaceGeneratedExecutorKeys: Set<string> = new Set();\n\n /** Generated plugin executor file paths */\n private pluginExecutorFiles: string[] = [];\n\n constructor(plugins: Plugin[] = []) {\n for (const plugin of plugins) {\n if (this.plugins.has(plugin.id)) {\n throw new Error(\n `Duplicate plugin ID \"${plugin.id}\" detected. Each plugin must have a unique ID.`,\n );\n }\n this.plugins.set(plugin.id, plugin);\n }\n }\n\n /**\n * Process a single plugin attachment on a raw TailorDBType.\n * This method is called during table loading before parsing.\n * @param context - Context containing the raw table, config, namespace, and plugin ID\n * @returns Result with plugin output on success, or error message on failure\n */\n async processAttachment(context: ProcessAttachmentContext): Promise<ProcessAttachmentResult> {\n const plugin = this.plugins.get(context.pluginId);\n if (!plugin) {\n return {\n success: false,\n error: `Plugin \"${context.pluginId}\" not found`,\n };\n }\n\n const tableConfigRequired = plugin.tableConfigRequired;\n const resolvedRequired =\n typeof tableConfigRequired === \"function\"\n ? tableConfigRequired(plugin.pluginConfig)\n : tableConfigRequired === true;\n if (resolvedRequired && (context.tableConfig === undefined || context.tableConfig === null)) {\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" requires tableConfig, but none was provided for table \"${context.table.name}\".`,\n };\n }\n\n // Check if plugin supports table-attached processing\n if (!plugin.onTableLoaded) {\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" does not support table-attached processing (missing onTableLoaded method). Use onNamespaceLoaded via definePlugins() instead.`,\n };\n }\n\n // Execute plugin onTableLoaded with the raw TailorDB table\n let output: TablePluginOutput;\n try {\n output = await plugin.onTableLoaded({\n table: context.table,\n tableConfig: context.tableConfig,\n pluginConfig: plugin.pluginConfig,\n namespace: context.namespace,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" threw an error while processing table \"${context.table.name}\": ${message}`,\n };\n }\n\n // Collect generated tables\n if (output.tables && Object.keys(output.tables).length > 0) {\n // importPath is guaranteed by schema validation for plugins with definition-time hooks\n const importPath = assertDefined(\n plugin.importPath,\n `plugin \"${plugin.id}\" missing importPath`,\n );\n for (const [kind, table] of Object.entries(output.tables)) {\n this.generatedTables.push({\n pluginId: context.pluginId,\n pluginImportPath: importPath,\n sourceTableName: context.table.name,\n kind,\n table,\n namespace: context.namespace,\n pluginConfig: plugin.pluginConfig,\n });\n }\n }\n\n // Collect generated executors\n if (output.executors && output.executors.length > 0) {\n for (const executor of output.executors) {\n this.generatedExecutors.push({\n executor,\n pluginId: context.pluginId,\n namespace: context.namespace,\n sourceTableName: context.table.name,\n });\n }\n }\n\n return { success: true, output };\n }\n\n /**\n * Process namespace plugins that don't require a source table.\n * This method is called once per namespace for plugins with onNamespaceLoaded method.\n * @param namespace - The target namespace for generated tables\n * @returns Array of results with plugin outputs and configs\n */\n async processNamespacePlugins(\n namespace: string,\n ): Promise<Array<{ pluginId: string; config: unknown; result: ProcessNamespaceResult }>> {\n const results: Array<{ pluginId: string; config: unknown; result: ProcessNamespaceResult }> =\n [];\n\n for (const [pluginId, plugin] of this.plugins) {\n // Skip plugins without onNamespaceLoaded method\n if (!plugin.onNamespaceLoaded) {\n continue;\n }\n\n // Use stored plugin config (from definePlugins)\n const config = plugin.pluginConfig;\n\n // Execute plugin onNamespaceLoaded\n const context: PluginNamespaceProcessContext = {\n pluginConfig: config,\n namespace,\n };\n\n let output: Awaited<ReturnType<NonNullable<Plugin[\"onNamespaceLoaded\"]>>>;\n try {\n output = await plugin.onNamespaceLoaded(context);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n results.push({\n pluginId,\n config,\n result: {\n success: false,\n error: `Plugin \"${plugin.id}\" threw an error during namespace processing for \"${namespace}\": ${message}`,\n },\n });\n continue;\n }\n\n // Collect generated executors (namespace - no source table)\n if (output.executors && output.executors.length > 0) {\n for (const executor of output.executors) {\n const executorKey = `${pluginId}:${executor.name}`;\n if (this.namespaceGeneratedExecutorKeys.has(executorKey)) {\n continue;\n }\n this.namespaceGeneratedExecutorKeys.add(executorKey);\n this.generatedExecutors.push({\n executor,\n pluginId,\n namespace,\n });\n }\n }\n\n // Collect generated tables (namespace - no source table)\n if (output.tables && Object.keys(output.tables).length > 0) {\n // importPath is guaranteed by schema validation for plugins with definition-time hooks\n const importPath = assertDefined(\n plugin.importPath,\n `plugin \"${plugin.id}\" missing importPath`,\n );\n for (const [kind, table] of Object.entries(output.tables)) {\n const tableKey = `${pluginId}:${kind}:${getRawPluginTableName(table) ?? \"\"}`;\n if (this.namespaceGeneratedTableKeys.has(tableKey)) {\n continue;\n }\n this.namespaceGeneratedTableKeys.add(tableKey);\n this.generatedTables.push({\n pluginId,\n pluginImportPath: importPath,\n sourceTableName: \"(namespace)\",\n kind,\n table,\n namespace,\n pluginConfig: plugin.pluginConfig,\n });\n }\n }\n\n results.push({\n pluginId,\n config,\n result: { success: true, output },\n });\n }\n\n return results;\n }\n\n /**\n * Run every plugin attachment for a single TailorDB table in order, threading the\n * extended table through the chain. Returns plain data (no logging, no shared state)\n * so the caller decides how to apply updates and render progress.\n * @param params - The raw table, its attachments, and the target namespace\n * @returns Final extended table (if any), generated tables, and render events\n */\n async processAttachmentsForTable(\n params: ProcessAttachmentsForTableParams,\n ): Promise<ProcessAttachmentsForTableResult> {\n const { rawTable, attachments, namespace } = params;\n // The runtime value is a configure-layer builder instance; we accept the structural\n // TailorDBTypeRaw at the boundary so callers (cli) don't need to depend on TailorAnyDBType.\n let currentTable: TailorAnyDBType = rawTable as unknown as TailorAnyDBType;\n let extendedTable: TailorAnyDBType | undefined;\n const generatedTables: ProcessAttachmentsGeneratedTable[] = [];\n const events: ProcessAttachmentEvent[] = [];\n\n for (const attachment of attachments) {\n const result = await this.processAttachment({\n table: currentTable,\n tableConfig: attachment.config,\n namespace,\n pluginId: attachment.pluginId,\n });\n if (!result.success) {\n throw new Error(result.error);\n }\n\n const output = result.output;\n const extendFields = output.extends?.fields;\n if (extendFields && Object.keys(extendFields).length > 0) {\n currentTable = this.extendTable({\n originalTable: currentTable,\n extendFields,\n pluginId: attachment.pluginId,\n });\n extendedTable = currentTable;\n events.push({\n kind: \"extended\",\n tableName: currentTable.name,\n fieldCount: Object.keys(extendFields).length,\n pluginId: attachment.pluginId,\n });\n }\n\n const plugin = this.getPlugin(attachment.pluginId);\n for (const [kind, table] of Object.entries(output.tables ?? {})) {\n const tableName = getRawPluginTableName(table) ?? \"\";\n generatedTables.push({\n tableName,\n table,\n kind,\n pluginId: attachment.pluginId,\n pluginImportPath: this.getPluginImportPath(attachment.pluginId) ?? \"\",\n pluginConfig: plugin?.pluginConfig,\n });\n events.push({ kind: \"generated\", tableName, pluginId: attachment.pluginId });\n }\n }\n\n return { extendedTable, generatedTables, events };\n }\n\n /**\n * Get plugins that have onNamespaceLoaded method\n * @returns Array of plugin IDs that support namespace processing\n */\n getNamespacePluginIds(): string[] {\n return Array.from(this.plugins.entries())\n .filter(([, plugin]) => plugin.onNamespaceLoaded !== undefined)\n .map(([id]) => id);\n }\n\n /**\n * Get the count of registered plugins\n * @returns Number of registered plugins\n */\n get pluginCount(): number {\n return this.plugins.size;\n }\n\n /**\n * Get a plugin by its ID\n * @param pluginId - The plugin ID to look up\n * @returns The plugin instance, or undefined if not found\n */\n getPlugin(pluginId: string): Plugin | undefined {\n return this.plugins.get(pluginId);\n }\n\n /**\n * Get the import path for a plugin\n * @param pluginId - The plugin ID to look up\n * @returns The plugin's import path, or undefined if not found\n */\n getPluginImportPath(pluginId: string): string | undefined {\n return this.plugins.get(pluginId)?.importPath;\n }\n\n /**\n * Get all plugin-generated executors\n * @returns Array of plugin-generated executor info\n */\n getPluginGeneratedExecutors(): ReadonlyArray<PluginExecutorInfo> {\n return this.generatedExecutors;\n }\n\n /**\n * Get all plugin-generated executors with import paths\n * @returns Array of plugin-generated executor info with import paths\n */\n getPluginGeneratedExecutorsWithImportPath(): ReadonlyArray<PluginExecutorInfoExtended> {\n return this.generatedExecutors.map((info) => ({\n ...info,\n pluginImportPath: this.getPluginImportPath(info.pluginId) ?? \"\",\n }));\n }\n\n /**\n * Get all plugin-generated tables\n * @returns Array of plugin-generated table info\n */\n getPluginGeneratedTables(): ReadonlyArray<PluginGeneratedTableInfo> {\n return this.generatedTables;\n }\n\n /**\n * Get plugin-generated executors for a specific namespace\n * @param namespace - The namespace to filter by\n * @returns Array of plugin-generated executor info for the namespace\n */\n getPluginGeneratedExecutorsForNamespace(namespace: string): ReadonlyArray<PluginExecutorInfo> {\n return this.generatedExecutors.filter((info) => info.namespace === namespace);\n }\n\n /**\n * Get plugins that have any generation-time hooks.\n * @returns Array of plugins with generation hooks\n */\n getPluginsWithGenerationHooks(): Plugin[] {\n return Array.from(this.plugins.values()).filter((plugin) => hasGenerationHooks(plugin));\n }\n\n /**\n * Get the generation-time dependencies for a specific plugin.\n * @param pluginId - The plugin ID to look up\n * @returns Set of dependency kinds, or empty set if plugin not found\n */\n getPluginGenerationDependencies(pluginId: string): Set<DependencyKind> {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) return new Set();\n return getPluginGenerationDependencies(plugin);\n }\n\n /**\n * Generate plugin files (tables and executors) and store the executor file paths.\n * @param params - Parameters for file generation\n * @returns Generated executor file paths\n */\n generatePluginFiles(params: GeneratePluginFilesParams): string[] {\n const { outputDir, sourceTableInfoMap, configPath, tableGenerator, executorGenerator } = params;\n\n // Generate table files\n const tableGenerationResult = tableGenerator(this.generatedTables, outputDir);\n\n // Generate executor files\n const pluginExecutors = this.getPluginGeneratedExecutorsWithImportPath();\n this.pluginExecutorFiles = executorGenerator(\n pluginExecutors,\n outputDir,\n tableGenerationResult,\n sourceTableInfoMap,\n configPath,\n );\n\n return this.pluginExecutorFiles;\n }\n\n /**\n * Extend a TailorDB table with new fields.\n * This method handles the `db.table()` call and metadata copying internally.\n * @param params - Parameters for table extension\n * @returns The extended TailorDB table\n */\n extendTable(params: ExtendTableParams): TailorAnyDBType {\n const { originalTable, extendFields, pluginId } = params;\n const existingFieldNames = Object.keys(originalTable.fields);\n const existingFileNames = Object.keys(originalTable.metadata.files);\n const newFieldNames = Object.keys(extendFields);\n const duplicateFields = newFieldNames.filter((name) => existingFieldNames.includes(name));\n const duplicateFiles = newFieldNames.filter((name) => existingFileNames.includes(name));\n\n if (duplicateFields.length > 0) {\n throw new Error(\n `Plugin \"${pluginId}\" attempted to add fields that already exist in table \"${originalTable.name}\": ${duplicateFields.join(\", \")}. ` +\n `extendFields cannot overwrite existing fields.`,\n );\n }\n\n if (duplicateFiles.length > 0) {\n throw new Error(\n `Plugin \"${pluginId}\" attempted to add fields that collide with file keys already declared via .files() on table \"${originalTable.name}\": ${duplicateFiles.join(\", \")}.`,\n );\n }\n\n const mergedFields = {\n ...originalTable.fields,\n ...extendFields,\n };\n\n const { id: _id, ...fieldsWithoutId } = mergedFields;\n const pluralForm = originalTable.metadata.settings?.pluralForm;\n const tableName = pluralForm\n ? ([originalTable.name, pluralForm] as [string, string])\n : originalTable.name;\n const extendedTable = db.table(tableName, fieldsWithoutId);\n return copyMetadataToExtendedTable(originalTable, extendedTable);\n }\n}\n\n/**\n * Source info for user-defined tables\n */\nexport type SourceTableInfo = {\n filePath: string;\n exportName: string;\n};\n\n/**\n * Result of generating plugin table files\n */\nexport interface PluginTableGenerationResult {\n /** Map of table name to generated file path (relative to outputDir) */\n tableFilePaths: Map<string, string>;\n /** List of all generated file paths (absolute) */\n generatedFiles: string[];\n}\n\n/**\n * Parameters for generating plugin files\n */\nexport interface GeneratePluginFilesParams {\n /** Base output directory (e.g., .tailor/plugin) */\n outputDir: string;\n /** Map of source table names to their source info */\n sourceTableInfoMap: Map<string, SourceTableInfo>;\n /** Path to tailor.config.ts (used for resolving plugin import paths) */\n configPath: string;\n /** Function to generate table files */\n tableGenerator: (\n tables: ReadonlyArray<PluginGeneratedTableInfo>,\n outputDir: string,\n ) => PluginTableGenerationResult;\n /** Function to generate executor files */\n executorGenerator: (\n executors: ReadonlyArray<PluginExecutorInfoExtended>,\n outputDir: string,\n tableGenerationResult: PluginTableGenerationResult,\n sourceTableInfoMap: Map<string, SourceTableInfo>,\n configPath: string,\n ) => string[];\n}\n\n/**\n * Parameters for extending a TailorDB table\n */\nexport interface ExtendTableParams {\n /** The original TailorDB table to extend */\n originalTable: TailorAnyDBType;\n /** New fields to add to the table */\n extendFields: Record<string, unknown>;\n /** The ID of the plugin extending the table */\n pluginId: string;\n}\n\n/**\n * Copy metadata from original table to extended table.\n * Preserves files, settings, permissions, indexes, and plugins.\n * @param original - The original TailorDB table with metadata\n * @param extended - The newly created extended table\n * @returns The extended table with copied metadata\n */\nfunction copyMetadataToExtendedTable(\n original: TailorAnyDBType,\n extended: TailorAnyDBType,\n): TailorAnyDBType {\n let result = extended;\n\n // Copy description\n if (original._description) {\n result = result.description(original._description);\n }\n\n // Copy files metadata\n const metadata = original.metadata;\n if (Object.keys(metadata.files).length > 0) {\n result = result.files(metadata.files);\n }\n\n // Copy settings/features (excluding pluralForm which is set during construction)\n if (metadata.settings) {\n const { pluralForm: _pluralForm, ...features } = metadata.settings;\n if (Object.keys(features).length > 0) {\n result = result.features(\n features as typeof features & { aggregation?: true; bulkUpsert?: true },\n );\n }\n }\n\n // Copy permissions from metadata\n // Zod schema operand types are wider unions than the configure layer's discriminated PermissionCondition,\n // so type assertions are needed here.\n if (metadata.permissions.record) {\n result = result.permission(metadata.permissions.record as TailorTypePermission);\n }\n if (metadata.permissions.gql) {\n result = result.gqlPermission(metadata.permissions.gql as TailorTypeGqlPermission);\n }\n\n // Copy indexes from metadata (indexes are stored in metadata, not as a direct property)\n if (metadata.indexes && Object.keys(metadata.indexes).length > 0) {\n const indexDefs = Object.entries(metadata.indexes).map(([name, def]) => ({\n name,\n // Cast fields array to tuple type (IndexDef expects [T, T, ...T[]])\n fields: def.fields as [string, string, ...string[]],\n unique: def.unique,\n }));\n result = result.indexes(...indexDefs);\n }\n\n if (metadata.typeHook) {\n result = result.hooks(metadata.typeHook as TypeHook<Record<string, TailorAnyDBField>>);\n }\n if (metadata.typeValidate) {\n result = result.validate(\n metadata.typeValidate as TypeValidateFn<Record<string, TailorAnyDBField>>,\n );\n }\n\n // Copy plugins (but don't re-process them)\n if (original.plugins.length > 0) {\n for (const plugin of original.plugins) {\n // Use type assertion as plugin ID is dynamic at runtime\n result = result.plugin({\n [plugin.pluginId]: plugin.config,\n });\n }\n }\n\n return result;\n}\n"],"mappings":"6HA8IA,IAAa,cAAb,KAA2B,CACzB,QAAuC,IAAI,IAC3C,mBAAmD,CAAC,EACpD,gBAAsD,CAAC,EACvD,4BAAmD,IAAI,IACvD,+BAAsD,IAAI,IAG1D,oBAAwC,CAAC,EAEzC,YAAY,EAAoB,CAAC,EAAG,CAClC,IAAK,IAAM,KAAU,EAAS,CAC5B,GAAI,KAAK,QAAQ,IAAI,EAAO,EAAE,EAC5B,MAAU,MACR,wBAAwB,EAAO,GAAG,+CACpC,EAEF,KAAK,QAAQ,IAAI,EAAO,GAAI,CAAM,CACpC,CACF,CAQA,MAAM,kBAAkB,EAAqE,CAC3F,IAAM,EAAS,KAAK,QAAQ,IAAI,EAAQ,QAAQ,EAChD,GAAI,CAAC,EACH,MAAO,CACL,QAAS,GACT,MAAO,WAAW,EAAQ,SAAS,YACrC,EAGF,IAAM,EAAsB,EAAO,oBAKnC,IAHE,OAAO,GAAwB,WAC3B,EAAoB,EAAO,YAAY,EACvC,IAAwB,MACL,EAAQ,cAAgB,IAAA,IAAa,EAAQ,cAAgB,MACpF,MAAO,CACL,QAAS,GACT,MAAO,WAAW,EAAO,GAAG,2DAA2D,EAAQ,MAAM,KAAK,GAC5G,EAIF,GAAI,CAAC,EAAO,cACV,MAAO,CACL,QAAS,GACT,MAAO,WAAW,EAAO,GAAG,gIAC9B,EAIF,IAAI,EACJ,GAAI,CACF,EAAS,MAAM,EAAO,cAAc,CAClC,MAAO,EAAQ,MACf,YAAa,EAAQ,YACrB,aAAc,EAAO,aACrB,UAAW,EAAQ,SACrB,CAAC,CACH,OAAS,EAAO,CACd,IAAM,EAAU,aAAiB,MAAQ,EA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SAM1B,GALI,OAAO,KAAK,EAAS,KAAK,CAAC,CAAC,OAAS,IACvC,EAAS,EAAO,MAAM,EAAS,KAAK,GAIlC,EAAS,SAAU,CACrB,GAAM,CAAE,WAAY,EAAa,GAAG,GAAa,EAAS,SACtD,OAAO,KAAK,CAAQ,CAAC,CAAC,OAAS,IACjC,EAAS,EAAO,SACd,CACF,EAEJ,CAaA,GARI,EAAS,YAAY,SACvB,EAAS,EAAO,WAAW,EAAS,YAAY,MAA8B,GAE5E,EAAS,YAAY,MACvB,EAAS,EAAO,cAAc,EAAS,YAAY,GAA8B,GAI/E,EAAS,SAAW,OAAO,KAAK,EAAS,OAAO,CAAC,CAAC,OAAS,EAAG,CAChE,IAAM,EAAY,OAAO,QAAQ,EAAS,OAAO,CAAC,CAAC,KAAK,CAAC,EAAM,MAAU,CACvE,OAEA,OAAQ,EAAI,OACZ,OAAQ,EAAI,MACd,EAAE,EACF,EAAS,EAAO,QAAQ,GAAG,CAAS,CACtC,CAYA,GAVI,EAAS,WACX,EAAS,EAAO,MAAM,EAAS,QAAsD,GAEnF,EAAS,eACX,EAAS,EAAO,SACd,EAAS,YACX,GAIE,EAAS,QAAQ,OAAS,EAC5B,IAAK,IAAM,KAAU,EAAS,QAE5B,EAAS,EAAO,OAAO,EACpB,EAAO,UAAW,EAAO,MAC5B,CAAC,EAIL,OAAO,CACT"}
|
|
1
|
+
{"version":3,"file":"manager-C26Gi1bX.mjs","names":[],"sources":["../src/plugin/manager.ts"],"sourcesContent":["import { db, type TailorAnyDBType } from \"#/configure/services/tailordb/index\";\nimport {\n getPluginGenerationDependencies,\n getRawPluginTableName,\n hasGenerationHooks,\n} from \"#/plugin/guards\";\nimport { assertDefined } from \"#/utils/assert\";\nimport type {\n TailorTypePermission,\n TailorTypeGqlPermission,\n} from \"#/configure/services/tailordb/permission\";\nimport type {\n TailorAnyDBField,\n TypeHook,\n TypeValidateFn,\n} from \"#/configure/services/tailordb/types\";\nimport type {\n DependencyKind,\n Plugin,\n PluginAttachment,\n PluginGeneratedExecutor,\n PluginGeneratedTable,\n PluginNamespaceProcessContext,\n PluginOutput,\n TablePluginOutput,\n} from \"#/plugin/types\";\nimport type { TailorDBTypeRaw } from \"#/types/tailordb.generated\";\n\n/**\n * Context for processing a single plugin attachment on a raw TailorDBType\n */\nexport interface ProcessAttachmentContext {\n table: TailorAnyDBType;\n tableConfig: unknown;\n namespace: string;\n pluginId: string;\n}\n\n/**\n * Information about a plugin-generated table (for table file generation)\n */\nexport interface PluginGeneratedTableInfo {\n /** Plugin ID that generated this table */\n pluginId: string;\n /** Plugin import path for resolving executor files */\n pluginImportPath: string;\n /** Source table name that triggered the plugin */\n sourceTableName: string;\n /** Kind identifier for this generated table */\n kind: string;\n /** The generated TailorDB table object */\n table: PluginGeneratedTable;\n /** Namespace where this table was generated */\n namespace: string;\n /** Plugin config used to generate this table */\n pluginConfig?: unknown;\n}\n\n/**\n * Extended executor info with plugin import path\n */\nexport interface PluginExecutorInfoExtended extends PluginExecutorInfo {\n /** Plugin's import path for resolving executor files */\n pluginImportPath: string;\n}\n\n/**\n * Result of processing a table-attached plugin\n */\nexport type ProcessAttachmentResult =\n | { success: true; output: TablePluginOutput }\n | { success: false; error: string };\n\n/**\n * Result of processing a namespace plugin\n */\nexport type ProcessNamespaceResult =\n | { success: true; output: PluginOutput }\n | { success: false; error: string };\n\n/**\n * Parameters for processing all plugin attachments of a TailorDB table.\n */\nexport interface ProcessAttachmentsForTableParams {\n rawTable: TailorDBTypeRaw;\n attachments: PluginAttachment[];\n namespace: string;\n}\n\n/**\n * Progress event emitted while processing plugin attachments for a TailorDB table.\n * Plain data so the caller (typically the cli) can format and output it.\n */\ntype ProcessAttachmentEvent =\n | { kind: \"extended\"; tableName: string; fieldCount: number; pluginId: string }\n | { kind: \"generated\"; tableName: string; pluginId: string };\n\n/**\n * Generated table produced by a plugin during attachment processing.\n * `table` is raw plugin output; the caller must validate it before use.\n */\ninterface ProcessAttachmentsGeneratedTable {\n tableName: string;\n table: unknown;\n kind: string;\n pluginId: string;\n pluginImportPath: string;\n pluginConfig?: unknown;\n}\n\n/**\n * Result of {@link PluginManager.processAttachmentsForTable}.\n */\nexport interface ProcessAttachmentsForTableResult {\n /**\n * Final table after all extends are applied; undefined if no plugin extended the table.\n * Raw builder output; the caller must validate it before use.\n */\n extendedTable?: unknown;\n /** Tables newly generated by plugins for this attachment chain. */\n generatedTables: ProcessAttachmentsGeneratedTable[];\n /** Events for the caller to render. */\n events: ProcessAttachmentEvent[];\n}\n\n/**\n * Information about a plugin-generated executor\n */\nexport interface PluginExecutorInfo {\n /** The executor definition */\n executor: PluginGeneratedExecutor;\n /** Plugin ID that generated this executor */\n pluginId: string;\n /** Namespace where the executor was generated */\n namespace: string;\n /** Source table name (for table-attached executors, undefined for namespace) */\n sourceTableName?: string;\n}\n\n/**\n * Manages plugin registration and processing\n */\nexport class PluginManager {\n private plugins: Map<string, Plugin> = new Map();\n private generatedExecutors: PluginExecutorInfo[] = [];\n private generatedTables: PluginGeneratedTableInfo[] = [];\n private namespaceGeneratedTableKeys: Set<string> = new Set();\n private namespaceGeneratedExecutorKeys: Set<string> = new Set();\n\n /** Generated plugin executor file paths */\n private pluginExecutorFiles: string[] = [];\n\n constructor(plugins: Plugin[] = []) {\n for (const plugin of plugins) {\n if (this.plugins.has(plugin.id)) {\n throw new Error(\n `Duplicate plugin ID \"${plugin.id}\" detected. Each plugin must have a unique ID.`,\n );\n }\n this.plugins.set(plugin.id, plugin);\n }\n }\n\n /**\n * Process a single plugin attachment on a raw TailorDBType.\n * This method is called during table loading before parsing.\n * @param context - Context containing the raw table, config, namespace, and plugin ID\n * @returns Result with plugin output on success, or error message on failure\n */\n async processAttachment(context: ProcessAttachmentContext): Promise<ProcessAttachmentResult> {\n const plugin = this.plugins.get(context.pluginId);\n if (!plugin) {\n return {\n success: false,\n error: `Plugin \"${context.pluginId}\" not found`,\n };\n }\n\n const tableConfigRequired = plugin.tableConfigRequired;\n const resolvedRequired =\n typeof tableConfigRequired === \"function\"\n ? tableConfigRequired(plugin.pluginConfig)\n : tableConfigRequired === true;\n if (resolvedRequired && (context.tableConfig === undefined || context.tableConfig === null)) {\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" requires tableConfig, but none was provided for table \"${context.table.name}\".`,\n };\n }\n\n // Check if plugin supports table-attached processing\n if (!plugin.onTableLoaded) {\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" does not support table-attached processing (missing onTableLoaded method). Use onNamespaceLoaded via definePlugins() instead.`,\n };\n }\n\n // Execute plugin onTableLoaded with the raw TailorDB table\n let output: TablePluginOutput;\n try {\n output = await plugin.onTableLoaded({\n table: context.table,\n tableConfig: context.tableConfig,\n pluginConfig: plugin.pluginConfig,\n namespace: context.namespace,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" threw an error while processing table \"${context.table.name}\": ${message}`,\n };\n }\n\n // Collect generated tables\n if (output.tables && Object.keys(output.tables).length > 0) {\n // importPath is guaranteed by schema validation for plugins with definition-time hooks\n const importPath = assertDefined(\n plugin.importPath,\n `plugin \"${plugin.id}\" missing importPath`,\n );\n for (const [kind, table] of Object.entries(output.tables)) {\n this.generatedTables.push({\n pluginId: context.pluginId,\n pluginImportPath: importPath,\n sourceTableName: context.table.name,\n kind,\n table,\n namespace: context.namespace,\n pluginConfig: plugin.pluginConfig,\n });\n }\n }\n\n // Collect generated executors\n if (output.executors && output.executors.length > 0) {\n for (const executor of output.executors) {\n this.generatedExecutors.push({\n executor,\n pluginId: context.pluginId,\n namespace: context.namespace,\n sourceTableName: context.table.name,\n });\n }\n }\n\n return { success: true, output };\n }\n\n /**\n * Process namespace plugins that don't require a source table.\n * This method is called once per namespace for plugins with onNamespaceLoaded method.\n * @param namespace - The target namespace for generated tables\n * @returns Array of results with plugin outputs and configs\n */\n async processNamespacePlugins(\n namespace: string,\n ): Promise<Array<{ pluginId: string; config: unknown; result: ProcessNamespaceResult }>> {\n const results: Array<{ pluginId: string; config: unknown; result: ProcessNamespaceResult }> =\n [];\n\n for (const [pluginId, plugin] of this.plugins) {\n // Skip plugins without onNamespaceLoaded method\n if (!plugin.onNamespaceLoaded) {\n continue;\n }\n\n // Use stored plugin config (from definePlugins)\n const config = plugin.pluginConfig;\n\n // Execute plugin onNamespaceLoaded\n const context: PluginNamespaceProcessContext = {\n pluginConfig: config,\n namespace,\n };\n\n let output: Awaited<ReturnType<NonNullable<Plugin[\"onNamespaceLoaded\"]>>>;\n try {\n output = await plugin.onNamespaceLoaded(context);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n results.push({\n pluginId,\n config,\n result: {\n success: false,\n error: `Plugin \"${plugin.id}\" threw an error during namespace processing for \"${namespace}\": ${message}`,\n },\n });\n continue;\n }\n\n // Collect generated executors (namespace - no source table)\n if (output.executors && output.executors.length > 0) {\n for (const executor of output.executors) {\n const executorKey = `${pluginId}:${executor.name}`;\n if (this.namespaceGeneratedExecutorKeys.has(executorKey)) {\n continue;\n }\n this.namespaceGeneratedExecutorKeys.add(executorKey);\n this.generatedExecutors.push({\n executor,\n pluginId,\n namespace,\n });\n }\n }\n\n // Collect generated tables (namespace - no source table)\n if (output.tables && Object.keys(output.tables).length > 0) {\n // importPath is guaranteed by schema validation for plugins with definition-time hooks\n const importPath = assertDefined(\n plugin.importPath,\n `plugin \"${plugin.id}\" missing importPath`,\n );\n for (const [kind, table] of Object.entries(output.tables)) {\n const tableKey = `${pluginId}:${kind}:${getRawPluginTableName(table) ?? \"\"}`;\n if (this.namespaceGeneratedTableKeys.has(tableKey)) {\n continue;\n }\n this.namespaceGeneratedTableKeys.add(tableKey);\n this.generatedTables.push({\n pluginId,\n pluginImportPath: importPath,\n sourceTableName: \"(namespace)\",\n kind,\n table,\n namespace,\n pluginConfig: plugin.pluginConfig,\n });\n }\n }\n\n results.push({\n pluginId,\n config,\n result: { success: true, output },\n });\n }\n\n return results;\n }\n\n /**\n * Run every plugin attachment for a single TailorDB table in order, threading the\n * extended table through the chain. Returns plain data (no logging, no shared state)\n * so the caller decides how to apply updates and render progress.\n * @param params - The raw table, its attachments, and the target namespace\n * @returns Final extended table (if any), generated tables, and render events\n */\n async processAttachmentsForTable(\n params: ProcessAttachmentsForTableParams,\n ): Promise<ProcessAttachmentsForTableResult> {\n const { rawTable, attachments, namespace } = params;\n // The runtime value is a configure-layer builder instance; we accept the structural\n // TailorDBTypeRaw at the boundary so callers (cli) don't need to depend on TailorAnyDBType.\n let currentTable: TailorAnyDBType = rawTable as unknown as TailorAnyDBType;\n let extendedTable: TailorAnyDBType | undefined;\n const generatedTables: ProcessAttachmentsGeneratedTable[] = [];\n const events: ProcessAttachmentEvent[] = [];\n\n for (const attachment of attachments) {\n const result = await this.processAttachment({\n table: currentTable,\n tableConfig: attachment.config,\n namespace,\n pluginId: attachment.pluginId,\n });\n if (!result.success) {\n throw new Error(result.error);\n }\n\n const output = result.output;\n const extendFields = output.extends?.fields;\n if (extendFields && Object.keys(extendFields).length > 0) {\n currentTable = this.extendTable({\n originalTable: currentTable,\n extendFields,\n pluginId: attachment.pluginId,\n });\n extendedTable = currentTable;\n events.push({\n kind: \"extended\",\n tableName: currentTable.name,\n fieldCount: Object.keys(extendFields).length,\n pluginId: attachment.pluginId,\n });\n }\n\n const plugin = this.getPlugin(attachment.pluginId);\n for (const [kind, table] of Object.entries(output.tables ?? {})) {\n const tableName = getRawPluginTableName(table) ?? \"\";\n generatedTables.push({\n tableName,\n table,\n kind,\n pluginId: attachment.pluginId,\n pluginImportPath: this.getPluginImportPath(attachment.pluginId) ?? \"\",\n pluginConfig: plugin?.pluginConfig,\n });\n events.push({ kind: \"generated\", tableName, pluginId: attachment.pluginId });\n }\n }\n\n return { extendedTable, generatedTables, events };\n }\n\n /**\n * Get plugins that have onNamespaceLoaded method\n * @returns Array of plugin IDs that support namespace processing\n */\n getNamespacePluginIds(): string[] {\n return Array.from(this.plugins.entries())\n .filter(([, plugin]) => plugin.onNamespaceLoaded !== undefined)\n .map(([id]) => id);\n }\n\n /**\n * Get the count of registered plugins\n * @returns Number of registered plugins\n */\n get pluginCount(): number {\n return this.plugins.size;\n }\n\n /**\n * Get a plugin by its ID\n * @param pluginId - The plugin ID to look up\n * @returns The plugin instance, or undefined if not found\n */\n getPlugin(pluginId: string): Plugin | undefined {\n return this.plugins.get(pluginId);\n }\n\n /**\n * Get the import path for a plugin\n * @param pluginId - The plugin ID to look up\n * @returns The plugin's import path, or undefined if not found\n */\n getPluginImportPath(pluginId: string): string | undefined {\n return this.plugins.get(pluginId)?.importPath;\n }\n\n /**\n * Get all plugin-generated executors\n * @returns Array of plugin-generated executor info\n */\n getPluginGeneratedExecutors(): ReadonlyArray<PluginExecutorInfo> {\n return this.generatedExecutors;\n }\n\n /**\n * Get all plugin-generated executors with import paths\n * @returns Array of plugin-generated executor info with import paths\n */\n getPluginGeneratedExecutorsWithImportPath(): ReadonlyArray<PluginExecutorInfoExtended> {\n return this.generatedExecutors.map((info) => ({\n ...info,\n pluginImportPath: this.getPluginImportPath(info.pluginId) ?? \"\",\n }));\n }\n\n /**\n * Get all plugin-generated tables\n * @returns Array of plugin-generated table info\n */\n getPluginGeneratedTables(): ReadonlyArray<PluginGeneratedTableInfo> {\n return this.generatedTables;\n }\n\n /**\n * Get plugin-generated executors for a specific namespace\n * @param namespace - The namespace to filter by\n * @returns Array of plugin-generated executor info for the namespace\n */\n getPluginGeneratedExecutorsForNamespace(namespace: string): ReadonlyArray<PluginExecutorInfo> {\n return this.generatedExecutors.filter((info) => info.namespace === namespace);\n }\n\n /**\n * Get plugins that have any generation-time hooks.\n * @returns Array of plugins with generation hooks\n */\n getPluginsWithGenerationHooks(): Plugin[] {\n return Array.from(this.plugins.values()).filter((plugin) => hasGenerationHooks(plugin));\n }\n\n /**\n * Get the generation-time dependencies for a specific plugin.\n * @param pluginId - The plugin ID to look up\n * @returns Set of dependency kinds, or empty set if plugin not found\n */\n getPluginGenerationDependencies(pluginId: string): Set<DependencyKind> {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) return new Set();\n return getPluginGenerationDependencies(plugin);\n }\n\n /**\n * Generate plugin files (tables and executors) and store the executor file paths.\n * @param params - Parameters for file generation\n * @returns Generated executor file paths\n */\n generatePluginFiles(params: GeneratePluginFilesParams): string[] {\n const { outputDir, sourceTableInfoMap, configPath, tableGenerator, executorGenerator } = params;\n\n // Generate table files\n const tableGenerationResult = tableGenerator(this.generatedTables, outputDir);\n\n // Generate executor files\n const pluginExecutors = this.getPluginGeneratedExecutorsWithImportPath();\n this.pluginExecutorFiles = executorGenerator(\n pluginExecutors,\n outputDir,\n tableGenerationResult,\n sourceTableInfoMap,\n configPath,\n );\n\n return this.pluginExecutorFiles;\n }\n\n /**\n * Extend a TailorDB table with new fields.\n * This method handles the `db.table()` call and metadata copying internally.\n * @param params - Parameters for table extension\n * @returns The extended TailorDB table\n */\n extendTable(params: ExtendTableParams): TailorAnyDBType {\n const { originalTable, extendFields, pluginId } = params;\n const existingFieldNames = Object.keys(originalTable.fields);\n const existingFileNames = Object.keys(originalTable.metadata.files);\n const newFieldNames = Object.keys(extendFields);\n const duplicateFields = newFieldNames.filter((name) => existingFieldNames.includes(name));\n const duplicateFiles = newFieldNames.filter((name) => existingFileNames.includes(name));\n\n if (duplicateFields.length > 0) {\n throw new Error(\n `Plugin \"${pluginId}\" attempted to add fields that already exist in table \"${originalTable.name}\": ${duplicateFields.join(\", \")}. ` +\n `extendFields cannot overwrite existing fields.`,\n );\n }\n\n if (duplicateFiles.length > 0) {\n throw new Error(\n `Plugin \"${pluginId}\" attempted to add fields that collide with file keys already declared via .files() on table \"${originalTable.name}\": ${duplicateFiles.join(\", \")}.`,\n );\n }\n\n const mergedFields = {\n ...originalTable.fields,\n ...extendFields,\n };\n\n const { id: _id, ...fieldsWithoutId } = mergedFields;\n const pluralForm = originalTable.metadata.settings?.pluralForm;\n const tableName = pluralForm\n ? ([originalTable.name, pluralForm] as [string, string])\n : originalTable.name;\n const extendedTable = db.table(tableName, fieldsWithoutId);\n return copyMetadataToExtendedTable(originalTable, extendedTable);\n }\n}\n\n/**\n * Source info for user-defined tables\n */\nexport type SourceTableInfo = {\n filePath: string;\n exportName: string;\n};\n\n/**\n * Result of generating plugin table files\n */\nexport interface PluginTableGenerationResult {\n /** Map of table name to generated file path (relative to outputDir) */\n tableFilePaths: Map<string, string>;\n /** List of all generated file paths (absolute) */\n generatedFiles: string[];\n}\n\n/**\n * Parameters for generating plugin files\n */\nexport interface GeneratePluginFilesParams {\n /** Base output directory (e.g., .tailor/plugin) */\n outputDir: string;\n /** Map of source table names to their source info */\n sourceTableInfoMap: Map<string, SourceTableInfo>;\n /** Path to tailor.config.ts (used for resolving plugin import paths) */\n configPath: string;\n /** Function to generate table files */\n tableGenerator: (\n tables: ReadonlyArray<PluginGeneratedTableInfo>,\n outputDir: string,\n ) => PluginTableGenerationResult;\n /** Function to generate executor files */\n executorGenerator: (\n executors: ReadonlyArray<PluginExecutorInfoExtended>,\n outputDir: string,\n tableGenerationResult: PluginTableGenerationResult,\n sourceTableInfoMap: Map<string, SourceTableInfo>,\n configPath: string,\n ) => string[];\n}\n\n/**\n * Parameters for extending a TailorDB table\n */\nexport interface ExtendTableParams {\n /** The original TailorDB table to extend */\n originalTable: TailorAnyDBType;\n /** New fields to add to the table */\n extendFields: Record<string, unknown>;\n /** The ID of the plugin extending the table */\n pluginId: string;\n}\n\n/**\n * Copy metadata from original table to extended table.\n * Preserves files, settings, permissions, indexes, and plugins.\n * @param original - The original TailorDB table with metadata\n * @param extended - The newly created extended table\n * @returns The extended table with copied metadata\n */\nfunction copyMetadataToExtendedTable(\n original: TailorAnyDBType,\n extended: TailorAnyDBType,\n): TailorAnyDBType {\n let result = extended;\n\n // Copy description\n if (original._description) {\n result = result.description(original._description);\n }\n\n // Copy files metadata\n const metadata = original.metadata;\n if (Object.keys(metadata.files).length > 0) {\n result = result.files(metadata.files);\n }\n\n // Copy settings/features (excluding pluralForm which is set during construction)\n if (metadata.settings) {\n const { pluralForm: _pluralForm, ...features } = metadata.settings;\n if (Object.keys(features).length > 0) {\n result = result.features(\n features as typeof features & { aggregation?: true; bulkUpsert?: true },\n );\n }\n }\n\n // Copy permissions from metadata\n // Zod schema operand types are wider unions than the configure layer's discriminated PermissionCondition,\n // so type assertions are needed here.\n if (metadata.permissions.record) {\n result = result.permission(metadata.permissions.record as TailorTypePermission);\n }\n if (metadata.permissions.gql) {\n result = result.gqlPermission(metadata.permissions.gql as TailorTypeGqlPermission);\n }\n\n // Copy indexes from metadata (indexes are stored in metadata, not as a direct property)\n if (metadata.indexes && Object.keys(metadata.indexes).length > 0) {\n const indexDefs = Object.entries(metadata.indexes).map(([name, def]) => ({\n name,\n // Cast fields array to tuple type (IndexDef expects [T, T, ...T[]])\n fields: def.fields as [string, string, ...string[]],\n unique: def.unique,\n }));\n result = result.indexes(...indexDefs);\n }\n\n if (metadata.typeHook) {\n result = result.hooks(metadata.typeHook as TypeHook<Record<string, TailorAnyDBField>>);\n }\n if (metadata.typeValidate) {\n result = result.validate(\n metadata.typeValidate as TypeValidateFn<Record<string, TailorAnyDBField>>,\n );\n }\n\n // Copy plugins (but don't re-process them)\n if (original.plugins.length > 0) {\n for (const plugin of original.plugins) {\n // Use type assertion as plugin ID is dynamic at runtime\n result = result.plugin({\n [plugin.pluginId]: plugin.config,\n });\n }\n }\n\n return result;\n}\n"],"mappings":"6HA8IA,IAAa,cAAb,KAA2B,CACzB,QAAuC,IAAI,IAC3C,mBAAmD,CAAC,EACpD,gBAAsD,CAAC,EACvD,4BAAmD,IAAI,IACvD,+BAAsD,IAAI,IAG1D,oBAAwC,CAAC,EAEzC,YAAY,EAAoB,CAAC,EAAG,CAClC,IAAK,IAAM,KAAU,EAAS,CAC5B,GAAI,KAAK,QAAQ,IAAI,EAAO,EAAE,EAC5B,MAAU,MACR,wBAAwB,EAAO,GAAG,+CACpC,EAEF,KAAK,QAAQ,IAAI,EAAO,GAAI,CAAM,CACpC,CACF,CAQA,MAAM,kBAAkB,EAAqE,CAC3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AYA,GAVI,EAAS,WACX,EAAS,EAAO,MAAM,EAAS,QAAsD,GAEnF,EAAS,eACX,EAAS,EAAO,SACd,EAAS,YACX,GAIE,EAAS,QAAQ,OAAS,EAC5B,IAAK,IAAM,KAAU,EAAS,QAE5B,EAAS,EAAO,OAAO,EACpB,EAAO,UAAW,EAAO,MAC5B,CAAC,EAIL,OAAO,CACT"}
|
|
@@ -4,6 +4,7 @@ import { Plugin } from "../../types.mjs";
|
|
|
4
4
|
export declare const KyselyGeneratorID = "@tailor-platform/kysely-type";
|
|
5
5
|
type KyselyTypePluginOptions = {
|
|
6
6
|
distPath: string;
|
|
7
|
+
pgliteSchemaPath?: string;
|
|
7
8
|
};
|
|
8
9
|
declare module "@tailor-platform/sdk/plugin" {
|
|
9
10
|
interface PluginConfigRegistry {
|
|
@@ -16,6 +17,7 @@ export declare const DEFAULT_KYSELY_TYPES_DIST_PATH = "./generated/tailordb.ts";
|
|
|
16
17
|
* Plugin that generates Kysely type definitions for TailorDB tables.
|
|
17
18
|
* @param options - Plugin options
|
|
18
19
|
* @param options.distPath - Output file path for generated types
|
|
20
|
+
* @param options.pgliteSchemaPath - Output file path for the PGlite `CREATE TABLE` script module; omit to skip it
|
|
19
21
|
* @returns Plugin instance with onTailorDBReady hook
|
|
20
22
|
*/
|
|
21
23
|
export declare function kyselyTypePlugin(options: KyselyTypePluginOptions): Plugin<unknown, KyselyTypePluginOptions>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"../../../kysely-type-
|
|
1
|
+
import{n as e,r as t,t as n}from"../../../kysely-type-B_oA8D1k.mjs";export{n as DEFAULT_KYSELY_TYPES_DIST_PATH,e as KyselyGeneratorID,t as kyselyTypePlugin};
|
package/dist/plugin/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e}from"../guards-ForsrxnH.mjs";import{t}from"../manager-
|
|
1
|
+
import{a as e}from"../guards-ForsrxnH.mjs";import{t}from"../manager-C26Gi1bX.mjs";import*as n from"pathe";import*as r from"node:fs";import{pathToFileURL as i}from"node:url";function withPluginContext(e){return e}const a=new Map;async function loadAndCacheConfig(t){let o=n.resolve(t),s=a.get(o);if(s)return s;if(!r.existsSync(o))return null;let c=await import(i(o).href);if(!c?.default)throw Error(`Invalid config module at "${o}": default export not found`);let l=c.default,u=n.dirname(o),d=new Map;for(let t of e(c))for(let e of t){let t=e;d.set(t.id,{plugin:t,pluginConfig:t.pluginConfig})}let f={config:l,plugins:d,configDir:u};return a.set(o,f),f}async function resolveNamespaceForTable(e,t,a){if(!e.db)throw Error(`No db configuration found in config`);for(let[o,s]of Object.entries(e.db)){let e=s;if(!e.external&&e.files)for(let s of e.files){let e=n.resolve(t,s),c;try{c=r.globSync(e)}catch{continue}for(let e of c){let t=await import(i(e).href);for(let e of Object.values(t))if(e===a)return o}}}throw Error(`Could not resolve namespace for table "${a.name}". Ensure the table file is included in a db namespace's files pattern.`)}async function resolveNamespaceForNamespacePlugin(e,t,n,r){if(!e.db)throw Error(`No db configuration found in config`);if(!t.onNamespaceLoaded)throw Error(`Plugin "${t.id}" does not have a onNamespaceLoaded() method`);for(let i of Object.keys(e.db)){if(e.db[i].external)continue;let a=await t.onNamespaceLoaded({pluginConfig:r,namespace:i});if(a.tables?.[n])return{namespace:i,output:a}}throw Error(`Could not resolve namespace for plugin "${t.id}" with kind "${n}". No namespace produced a table with that kind.`)}const o=new WeakMap,s=new WeakMap;function getCacheKey(e,t){if(t===void 0)return e;try{return`${e}:${JSON.stringify(t)}`}catch{throw Error(`pluginConfig must be JSON-serializable for caching. Received non-serializable value.`)}}async function getGeneratedTable(e,t,n,r){let i=await loadAndCacheConfig(e);if(!i)return{name:`__placeholder_${r}__`,fields:{}};let{config:a,configDir:o,plugins:s}=i,c=s.get(t);if(!c)throw Error(`Plugin "${t}" not found in config at "${e}". Ensure the plugin is registered via definePlugins().`);let{plugin:l,pluginConfig:u}=c;return n===null?getGeneratedTableForNamespacePlugin(a,l,r,u):getGeneratedTableForTableAttachedPlugin(l,n,r,u,await resolveNamespaceForTable(a,o,n))}async function getGeneratedTableForTableAttachedPlugin(e,t,n,r,i){if(!e.onTableLoaded)throw Error(`Plugin "${e.id}" does not have an onTableLoaded() method`);let a=o.get(e);a||(a=new Map,o.set(e,a));let s=getCacheKey(`${t.name}:ns=${i}`,r),c=a.get(s);if(!c){let n=t.plugins.find(t=>t.pluginId===e.id)?.config;c=await e.onTableLoaded({table:t,tableConfig:n??{},pluginConfig:r,namespace:i}),a.set(s,c)}let l=c.tables?.[n];if(!l)throw Error(`Generated table not found: plugin=${e.id}, sourceTable=${t.name}, kind=${n}`);return l}async function getGeneratedTableForNamespacePlugin(e,t,n,r){if(!t.onNamespaceLoaded)throw Error(`Plugin "${t.id}" does not have a onNamespaceLoaded() method`);let i=s.get(t);if(i||(i=new Map,s.set(t,i)),e.db)for(let t of Object.keys(e.db)){if(e.db[t].external)continue;let a=getCacheKey(`namespace:ns=${t}`,r),o=i.get(a);if(o?.tables?.[n])return o.tables[n]}let{namespace:a,output:o}=await resolveNamespaceForNamespacePlugin(e,t,n,r),c=getCacheKey(`namespace:ns=${a}`,r);i.set(c,o);let l=o.tables?.[n];if(!l)throw Error(`Generated table not found: plugin=${t.id}, kind=${n}`);return l}const c=new Map;async function getExtendedTable(e,t){if(t.plugins.length===0)return t;let r=n.resolve(e),i=c.get(r);i||(i=new WeakMap,c.set(r,i));let a=i.get(t);if(a)return a;let o=applyPluginExtensions(r,t);return i.set(t,o),o.catch(()=>i.delete(t)),o}async function applyPluginExtensions(e,n){let r=await loadAndCacheConfig(e);if(!r)return n;let{config:i,configDir:a,plugins:o}=r,s=await resolveNamespaceForTable(i,a,n),{extendedTable:c}=await new t([...o.values()].map(e=>e.plugin)).processAttachmentsForTable({rawTable:n,attachments:[...n.plugins],namespace:s});return c??n}export{getExtendedTable,getGeneratedTable,withPluginContext};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|