@tailor-platform/sdk 1.14.2 → 1.15.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.
@@ -1,6 +1,6 @@
1
1
  /// <reference path="./user-defined.d.ts" />
2
- import { $ as ArrayFieldOutput, Ct as AllowedValues, F as Plugin, M as TailorDBType, T as UserAttributeMap, _t as TailorEnv, a as AuthInvoker$1, at as TailorAnyField, et as DefinedFieldMetadata, ht as output$1, it as TailorFieldType, j as TailorDBInstance, l as DefinedAuth, mt as JsonCompatible, nt as FieldOptions, ot as TailorField, pt as InferFieldsOutput, rt as FieldOutput, s as AuthServiceInput, tt as FieldMetadata, ut as ResolverInput, vt as TailorActor, w as UserAttributeListKey, wt as AllowedValuesOutput, xt as TailorUser } from "./types-DbvONSS-.mjs";
3
- import { C as ScheduleTriggerInput, S as ResolverExecutedTrigger$1, T as WorkflowOperation$1, _ as FunctionOperation$1, b as IncomingWebhookTrigger$1, f as AuthAccessTokenTrigger$1, m as ExecutorInput, n as GeneratorConfig, o as IdPInput, r as AppConfig, s as IdpDefinitionBrand, v as GqlOperation$1, w as WebhookOperation$1, x as RecordTrigger$1, y as IdpUserTrigger$1 } from "./index-YzESrtj0.mjs";
2
+ import { F as Plugin, M as TailorDBType, St as TailorUser, T as UserAttributeMap, Tt as AllowedValuesOutput, a as AuthInvoker$1, at as TailorFieldType, dt as ResolverInput, et as ArrayFieldOutput, gt as output$1, ht as JsonCompatible, it as FieldOutput, j as TailorDBInstance, l as DefinedAuth, mt as InferFieldsOutput, nt as FieldMetadata, ot as TailorAnyField, rt as FieldOptions, s as AuthServiceInput, st as TailorField, tt as DefinedFieldMetadata, vt as TailorEnv, w as UserAttributeListKey, wt as AllowedValues, yt as TailorActor } from "./types-Db1oxr0U.mjs";
3
+ import { C as ScheduleTriggerInput, S as ResolverExecutedTrigger$1, T as WorkflowOperation$1, _ as FunctionOperation$1, b as IncomingWebhookTrigger$1, f as AuthAccessTokenTrigger$1, m as ExecutorInput, n as GeneratorConfig, o as IdPInput, r as AppConfig, s as IdpDefinitionBrand, v as GqlOperation$1, w as WebhookOperation$1, x as RecordTrigger$1, y as IdpUserTrigger$1 } from "./index-DomkP6gz.mjs";
4
4
  import * as zod0 from "zod";
5
5
  import { JsonPrimitive, Jsonifiable, Jsonify } from "type-fest";
6
6
  import * as zod_v4_core0 from "zod/v4/core";
@@ -404,29 +404,45 @@ type Trigger<Args> = RecordTrigger<Args> | ResolverExecutedTrigger<Args> | Sched
404
404
  * Extract mainJob's Input type from Workflow.
405
405
  */
406
406
  type WorkflowInput<W$1 extends Workflow> = Parameters<W$1["trigger"]>[0];
407
- type ExecutorBase<Args> = Omit<ExecutorInput, "trigger" | "operation"> & {
408
- trigger: Trigger<Args>;
407
+ type TriggerArgs<T extends Trigger<unknown>> = T extends {
408
+ __args: infer Args;
409
+ } ? Args : never;
410
+ type ExecutorBase<T extends Trigger<unknown>> = Omit<ExecutorInput, "trigger" | "operation"> & {
411
+ trigger: T;
409
412
  };
410
413
  /**
411
414
  * Executor type with conditional inference for workflow operations.
412
415
  * When operation.kind is "workflow", infers W from the workflow property
413
416
  * to ensure args type matches the workflow's mainJob input type.
414
417
  */
415
- type Executor<Args, O> = O extends {
418
+ type Executor<T extends Trigger<unknown>, O> = O extends {
416
419
  kind: "workflow";
417
420
  workflow: infer W extends Workflow;
418
- } ? ExecutorBase<Args> & {
421
+ } ? ExecutorBase<T> & {
419
422
  operation: {
420
423
  kind: "workflow";
421
424
  workflow: W;
422
- args?: WorkflowInput<W> | ((args: Args) => WorkflowInput<W>);
425
+ args?: WorkflowInput<W> | ((args: TriggerArgs<T>) => WorkflowInput<W>);
423
426
  authInvoker?: AuthInvoker<string>;
424
427
  };
425
- } : ExecutorBase<Args> & {
428
+ } : ExecutorBase<T> & {
426
429
  operation: O;
427
430
  };
428
431
  /**
429
432
  * Create an executor configuration for the Tailor SDK.
433
+ * @template T
434
+ * @template O
435
+ * @param config - Executor configuration
436
+ * @returns The same executor configuration
437
+ */
438
+ declare function createExecutor<T extends Trigger<unknown>, O extends Operation<TriggerArgs<T>> | {
439
+ kind: "workflow";
440
+ workflow: Workflow;
441
+ }>(config: Executor<T, O>): Executor<T, O>;
442
+ /**
443
+ * Create an executor configuration for the Tailor SDK.
444
+ * This overload preserves source compatibility for legacy explicit generic calls,
445
+ * where the first generic argument represents trigger args.
430
446
  * @template Args
431
447
  * @template O
432
448
  * @param config - Executor configuration
@@ -435,7 +451,7 @@ type Executor<Args, O> = O extends {
435
451
  declare function createExecutor<Args, O extends Operation<Args> | {
436
452
  kind: "workflow";
437
453
  workflow: Workflow;
438
- }>(config: Executor<Args, O>): Executor<Args, O>;
454
+ }>(config: Executor<Trigger<Args>, O>): Executor<Trigger<Args>, O>;
439
455
  //#endregion
440
456
  //#region src/configure/services/idp/index.d.ts
441
457
  /**
@@ -515,7 +531,7 @@ declare function defineGenerators(...configs: GeneratorConfig[]): (["@tailor-pla
515
531
  * @param configs - Plugin configurations
516
532
  * @returns Plugin configurations as given
517
533
  */
518
- declare function definePlugins(...configs: Plugin[]): Plugin[];
534
+ declare function definePlugins(...configs: Plugin[]): Plugin<unknown, unknown>[];
519
535
  //#endregion
520
536
  //#region src/configure/index.d.ts
521
537
  type TailorOutput<T> = output$1<T>;
@@ -589,4 +605,4 @@ declare namespace t {
589
605
  }
590
606
  //#endregion
591
607
  export { defineAuth as $, idpUserCreatedTrigger as A, WebhookOperation as B, RecordTrigger as C, authAccessTokenIssuedTrigger as D, ResolverExecutedTrigger as E, recordUpdatedTrigger as F, WORKFLOW_TEST_ENV_KEY as G, Workflow as H, resolverExecutedTrigger as I, WorkflowJobInput as J, WorkflowJob as K, FunctionOperation as L, idpUserUpdatedTrigger as M, recordCreatedTrigger as N, authAccessTokenRefreshedTrigger as O, recordDeletedTrigger as P, AuthInvoker as Q, GqlOperation as R, RecordDeletedArgs as S, ResolverExecutedArgs as T, WorkflowConfig as U, WorkflowOperation as V, createWorkflow as W, createWorkflowJob as X, WorkflowJobOutput as Y, createResolver as Z, AuthAccessTokenArgs as _, defineGenerators as a, IdpUserTrigger as b, createExecutor as c, IncomingWebhookRequest as d, IncomingWebhookTrigger as f, scheduleTrigger as g, ScheduleTrigger as h, defineConfig as i, idpUserDeletedTrigger as j, authAccessTokenRevokedTrigger as k, Trigger as l, ScheduleArgs as m, output as n, definePlugins as o, incomingWebhookTrigger as p, WorkflowJobContext as q, t as r, defineIdp as s, infer as t, IncomingWebhookArgs as u, AuthAccessTokenTrigger as v, RecordUpdatedArgs as w, RecordCreatedArgs as x, IdpUserArgs as y, Operation as z };
592
- //# sourceMappingURL=index-q3n7wQOs.d.mts.map
608
+ //# sourceMappingURL=index-Bs9AsQb2.d.mts.map
@@ -1,5 +1,5 @@
1
1
  /// <reference path="./user-defined.d.ts" />
2
- import { Tt as TailorDBServiceInput, c as BuiltinIdP, ft as ResolverServiceInput, r as AuthConfig } from "./types-DbvONSS-.mjs";
2
+ import { Et as TailorDBServiceInput, c as BuiltinIdP, pt as ResolverServiceInput, r as AuthConfig } from "./types-Db1oxr0U.mjs";
3
3
  import { z } from "zod";
4
4
 
5
5
  //#region src/parser/service/executor/schema.d.ts
@@ -393,4 +393,4 @@ type GeneratorConfigSchemaType = ReturnType<typeof createGeneratorConfigSchema>;
393
393
  type Generator = z.output<GeneratorConfigSchemaType>;
394
394
  //#endregion
395
395
  export { ScheduleTriggerInput as C, ResolverExecutedTrigger as S, WorkflowOperation as T, FunctionOperation as _, IdPExternalConfig as a, IncomingWebhookTrigger as b, WorkflowServiceConfig as c, defineStaticWebSite as d, AuthAccessTokenTrigger as f, ExecutorServiceInput as g, ExecutorServiceConfig as h, IdPConfig as i, WorkflowServiceInput as l, ExecutorInput as m, GeneratorConfig as n, IdPInput as o, Executor as p, AppConfig as r, IdpDefinitionBrand as s, Generator as t, StaticWebsiteConfig as u, GqlOperation as v, WebhookOperation as w, RecordTrigger as x, IdpUserTrigger as y };
396
- //# sourceMappingURL=index-YzESrtj0.d.mts.map
396
+ //# sourceMappingURL=index-DomkP6gz.d.mts.map
@@ -1,5 +1,5 @@
1
1
  /// <reference path="./../user-defined.d.ts" />
2
- import { _t as TailorEnv, k as TailorAnyDBType, vt as TailorActor } from "../types-DbvONSS-.mjs";
2
+ import { k as TailorAnyDBType, vt as TailorEnv, yt as TailorActor } from "../types-Db1oxr0U.mjs";
3
3
 
4
4
  //#region src/plugin/with-context.d.ts
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["fs","namespace","cacheKey"],"sources":["../../src/plugin/with-context.ts","../../src/plugin/get-generated-type.ts"],"sourcesContent":["/**\n * Plugin executor context support for defining plugin executors in separate files.\n * This module provides utilities for creating type-safe plugin executors that receive\n * context (like type references and namespace) at runtime.\n */\n\nimport type { TailorActor, TailorEnv } from \"@/parser/types\";\n\n/**\n * Plugin executor factory function type.\n * Takes context and returns an executor configuration.\n * Returns unknown since the exact return type depends on createExecutor's generic params.\n */\nexport type PluginExecutorFactory<Ctx> = (ctx: Ctx) => unknown;\n\n// ============================================================================\n// Plugin Executor Args Types\n// ============================================================================\n\n/**\n * Base args for plugin executor function operations.\n * Provides typed access to runtime context without requiring specific record types.\n */\nexport interface PluginFunctionArgs {\n /** Workspace ID where the executor runs */\n workspaceId: string;\n /** Application namespace */\n appNamespace: string;\n /** Environment variables */\n env: TailorEnv;\n /** Actor (user) who triggered the event, null for system events */\n actor: TailorActor | null;\n /** Name of the TailorDB type */\n typeName: string;\n /** TailorDB connections by namespace */\n tailordb: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record creation.\n */\nexport interface PluginRecordCreatedArgs extends PluginFunctionArgs {\n /** The newly created record */\n newRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record update.\n */\nexport interface PluginRecordUpdatedArgs extends PluginFunctionArgs {\n /** The record after update */\n newRecord: Record<string, unknown>;\n /** The record before update */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record deletion.\n */\nexport interface PluginRecordDeletedArgs extends PluginFunctionArgs {\n /** The deleted record */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Database schema type for plugins.\n * Since plugins work with dynamic types, the schema uses Record types.\n */\nexport type PluginDBSchema = Record<string, Record<string, unknown>>;\n\n/**\n * Base record type for TailorDB records.\n * All records have an id field.\n */\nexport type PluginRecord = { id: string } & Record<string, unknown>;\n\n/**\n * Define a plugin executor that receives context at runtime.\n * This allows executor definitions to be in separate files while\n * still receiving dynamic values like typeName, generated types, and namespace.\n * @param factory - Function that takes context and returns executor configuration\n * @returns The same factory function (for type inference)\n * @example\n * ```typescript\n * // executors/on-create.ts\n * import { withPluginContext } from \"@tailor-platform/sdk/plugin\";\n * import { createExecutor, recordCreatedTrigger } from \"@tailor-platform/sdk\";\n * import { getDB } from \"@tailor-platform/function-kysely-tailordb\";\n *\n * interface MyContext {\n * sourceType: TailorAnyDBType;\n * historyType: TailorAnyDBType;\n * namespace: string;\n * }\n *\n * export default withPluginContext<MyContext>((ctx) =>\n * createExecutor({\n * name: `${ctx.sourceType.name.toLowerCase()}-on-create`,\n * trigger: recordCreatedTrigger({ type: ctx.sourceType }),\n * operation: {\n * kind: \"function\",\n * body: async (args) => {\n * const db = getDB(ctx.namespace);\n * await db.insertInto(ctx.historyType.name).values({\n * recordId: args.newRecord.id,\n * // ...\n * }).execute();\n * },\n * },\n * })\n * );\n * ```\n */\nexport function withPluginContext<Ctx>(\n factory: PluginExecutorFactory<Ctx>,\n): PluginExecutorFactory<Ctx> {\n return factory;\n}\n","import * as fs from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport type { NamespacePluginOutput, Plugin, PluginOutput } from \"@/parser/plugin-config/types\";\nimport type { TailorAnyDBType } from \"@/parser/service/tailordb/types\";\n\n// ========================================\n// Config loading and caching\n// ========================================\n\ninterface PluginEntry {\n plugin: Plugin;\n pluginConfig: unknown;\n}\n\ninterface ConfigCache {\n config: { db?: Record<string, unknown> };\n plugins: Map<string, PluginEntry>;\n configDir: string;\n}\n\n/** Cache: resolved config path -> loaded config data */\nconst configCacheMap = new Map<string, ConfigCache>();\n\n/**\n * Check if a value is a Plugin instance.\n * @param value - Value to check\n * @returns True if value has the shape of Plugin\n */\nfunction isPlugin(value: unknown): value is Plugin {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Record<string, unknown>).id === \"string\" &&\n typeof (value as Record<string, unknown>).importPath === \"string\"\n );\n}\n\n/**\n * Load and cache config module from the given path.\n * Extracts plugins from all array exports using definePlugins() format.\n * Returns null if the config file does not exist (e.g., in bundled executor on platform server).\n * @param configPath - Absolute or relative path to tailor.config.ts\n * @returns Cached config data with plugins map, or null if config file is not available\n */\nasync function loadAndCacheConfig(configPath: string): Promise<ConfigCache | null> {\n const resolvedPath = path.resolve(configPath);\n\n const cached = configCacheMap.get(resolvedPath);\n if (cached) return cached;\n\n // Config file may not exist in bundled environments (e.g., platform server)\n if (!fs.existsSync(resolvedPath)) {\n return null;\n }\n\n const configModule = await import(pathToFileURL(resolvedPath).href);\n if (!configModule?.default) {\n throw new Error(`Invalid config module at \"${resolvedPath}\": default export not found`);\n }\n\n const config = configModule.default as { db?: Record<string, unknown> };\n const configDir = path.dirname(resolvedPath);\n const plugins = new Map<string, PluginEntry>();\n\n // Find plugin arrays from exports (definePlugins returns PluginConfig[])\n for (const value of Object.values(configModule)) {\n if (!Array.isArray(value)) continue;\n\n for (const item of value) {\n if (isPlugin(item)) {\n plugins.set(item.id, { plugin: item, pluginConfig: item.pluginConfig });\n }\n }\n }\n\n const result: ConfigCache = { config, plugins, configDir };\n configCacheMap.set(resolvedPath, result);\n return result;\n}\n\n// ========================================\n// Namespace resolution\n// ========================================\n\ninterface DbNamespaceConfig {\n files?: string[];\n external?: boolean;\n}\n\n/**\n * Resolve the namespace for a type-attached sourceType by checking config.db file patterns.\n * Uses ESM module cache identity: same file path yields same object references.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param configDir - Directory containing the config file\n * @param sourceType - The TailorDB type to look up\n * @returns The namespace name\n */\nasync function resolveNamespaceForType(\n config: { db?: Record<string, unknown> },\n configDir: string,\n sourceType: TailorAnyDBType,\n): Promise<string> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n for (const [namespace, nsConfig] of Object.entries(config.db)) {\n const dbConfig = nsConfig as DbNamespaceConfig;\n // Skip external namespaces (no files to resolve)\n if (dbConfig.external || !dbConfig.files) continue;\n\n for (const pattern of dbConfig.files) {\n const absolutePattern = path.resolve(configDir, pattern);\n let matchedFiles: string[];\n try {\n matchedFiles = fs.globSync(absolutePattern);\n } catch {\n continue;\n }\n\n for (const file of matchedFiles) {\n const mod = await import(pathToFileURL(file).href);\n for (const exported of Object.values(mod)) {\n if (exported === sourceType) {\n return namespace;\n }\n }\n }\n }\n }\n\n throw new Error(\n `Could not resolve namespace for type \"${sourceType.name}\". ` +\n `Ensure the type file is included in a db namespace's files pattern.`,\n );\n}\n\n/**\n * Resolve the namespace for a namespace plugin by trying each namespace.\n * Calls processNamespace() for each and returns the first whose output contains the requested kind.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - Plugin instance\n * @param kind - The generated type kind to look for\n * @param pluginConfig - Plugin-level configuration\n * @returns The namespace name\n */\nasync function resolveNamespaceForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<{ namespace: string; output: NamespacePluginOutput }> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n if (!plugin.processNamespace) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a processNamespace() method`);\n }\n\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const output = await plugin.processNamespace({\n pluginConfig,\n namespace,\n });\n\n if (output.types?.[kind]) {\n return { namespace, output };\n }\n }\n\n throw new Error(\n `Could not resolve namespace for plugin \"${plugin.id}\" with kind \"${kind}\". ` +\n `No namespace produced a type with that kind.`,\n );\n}\n\n// ========================================\n// Process caching\n// ========================================\n\n// Cache: plugin -> cacheKey -> PluginOutput\nconst processCache = new WeakMap<Plugin, Map<string, PluginOutput>>();\n\n// Cache for namespace plugins: plugin -> cacheKey -> NamespacePluginOutput\nconst namespaceProcessCache = new WeakMap<Plugin, Map<string, NamespacePluginOutput>>();\n\n/**\n * Generate a cache key that includes pluginConfig.\n * @param baseKey - Base key for the cache\n * @param pluginConfig - Plugin configuration to include in the key\n * @returns Cache key string\n */\nfunction getCacheKey(baseKey: string, pluginConfig: unknown): string {\n if (pluginConfig === undefined) {\n return baseKey;\n }\n try {\n return `${baseKey}:${JSON.stringify(pluginConfig)}`;\n } catch {\n throw new Error(\n `pluginConfig must be JSON-serializable for caching. Received non-serializable value.`,\n );\n }\n}\n\n// ========================================\n// Main API\n// ========================================\n\n/**\n * Get a generated type from a plugin by loading the config and resolving everything automatically.\n * For type-attached plugins, calls processType() with the sourceType.\n * For namespace plugins, calls processNamespace() with auto-resolved namespace.\n * Results are cached per config path, plugin, namespace, and pluginConfig to avoid redundant processing.\n * @param configPath - Path to tailor.config.ts (absolute or relative to cwd)\n * @param pluginId - The plugin's unique identifier\n * @param sourceType - The source TailorDB type (null for namespace plugins)\n * @param kind - The generated type kind (e.g., \"request\", \"step\")\n * @returns The generated TailorDB type\n */\nexport async function getGeneratedType(\n configPath: string,\n pluginId: string,\n sourceType: TailorAnyDBType | null,\n kind: string,\n): Promise<TailorAnyDBType> {\n const cache = await loadAndCacheConfig(configPath);\n\n if (!cache) {\n // Config not available (e.g., running in bundled executor on platform server).\n // Return a placeholder. The actual type is resolved at generate/apply time.\n return { name: `__placeholder_${kind}__`, fields: {} } as TailorAnyDBType;\n }\n\n const { config, configDir, plugins } = cache;\n\n const pluginEntry = plugins.get(pluginId);\n if (!pluginEntry) {\n throw new Error(\n `Plugin \"${pluginId}\" not found in config at \"${configPath}\". ` +\n `Ensure the plugin is registered via definePlugins().`,\n );\n }\n\n const { plugin, pluginConfig } = pluginEntry;\n\n if (sourceType === null) {\n return getGeneratedTypeForNamespacePlugin(config, plugin, kind, pluginConfig);\n }\n\n const namespace = await resolveNamespaceForType(config, configDir, sourceType);\n return getGeneratedTypeForTypeAttachedPlugin(plugin, sourceType, kind, pluginConfig, namespace);\n}\n\n/**\n * Get a generated type from a type-attached plugin.\n * @param plugin - The plugin instance (must have processType() method)\n * @param sourceType - The source TailorDB type\n * @param kind - The generated type kind\n * @param pluginConfig - Plugin-level configuration\n * @param namespace - Resolved namespace\n * @returns The generated TailorDB type\n */\nasync function getGeneratedTypeForTypeAttachedPlugin(\n plugin: Plugin,\n sourceType: TailorAnyDBType,\n kind: string,\n pluginConfig: unknown,\n namespace: string,\n): Promise<TailorAnyDBType> {\n if (!plugin.processType) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a processType() method`);\n }\n\n // Check cache first\n let pluginCache = processCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n processCache.set(plugin, pluginCache);\n }\n\n const cacheKey = getCacheKey(`${sourceType.name}:ns=${namespace}`, pluginConfig);\n let output = pluginCache.get(cacheKey);\n\n if (!output) {\n const typeConfig = sourceType.plugins?.find((p) => p.pluginId === plugin.id)?.config;\n output = await plugin.processType({\n type: sourceType,\n typeConfig: typeConfig ?? {},\n pluginConfig,\n namespace,\n });\n pluginCache.set(cacheKey, output);\n }\n\n const generatedType = output.types?.[kind];\n if (!generatedType) {\n throw new Error(\n `Generated type not found: plugin=${plugin.id}, sourceType=${sourceType.name}, kind=${kind}`,\n );\n }\n\n return generatedType as TailorAnyDBType;\n}\n\n/**\n * Get a generated type from a namespace plugin.\n * Auto-resolves the namespace by trying each one.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - The plugin instance (must have processNamespace() method)\n * @param kind - The generated type kind\n * @param pluginConfig - Plugin-level configuration\n * @returns The generated TailorDB type\n */\nasync function getGeneratedTypeForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<TailorAnyDBType> {\n if (!plugin.processNamespace) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a processNamespace() method`);\n }\n\n // Check cache first - try all namespaces\n let pluginCache = namespaceProcessCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n namespaceProcessCache.set(plugin, pluginCache);\n }\n\n // Try cached results first\n if (config.db) {\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n const cached = pluginCache.get(cacheKey);\n if (cached?.types?.[kind]) {\n return cached.types[kind] as TailorAnyDBType;\n }\n }\n }\n\n // Not in cache - resolve namespace and process\n const { namespace, output } = await resolveNamespaceForNamespacePlugin(\n config,\n plugin,\n kind,\n pluginConfig,\n );\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n pluginCache.set(cacheKey, output);\n\n const generatedType = output.types?.[kind];\n if (!generatedType) {\n throw new Error(`Generated type not found: plugin=${plugin.id}, kind=${kind}`);\n }\n\n return generatedType as TailorAnyDBType;\n}\n\n/**\n * Clear all internal caches. For testing only.\n * @lintignore\n */\nexport function _clearCacheForTesting(): void {\n configCacheMap.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA,SAAgB,kBACd,SAC4B;AAC5B,QAAO;;;;;;AC9FT,MAAM,iCAAiB,IAAI,KAA0B;;;;;;AAOrD,SAAS,SAAS,OAAiC;AACjD,QACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAkC,OAAO,YACjD,OAAQ,MAAkC,eAAe;;;;;;;;;AAW7D,eAAe,mBAAmB,YAAiD;CACjF,MAAM,eAAe,KAAK,QAAQ,WAAW;CAE7C,MAAM,SAAS,eAAe,IAAI,aAAa;AA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WAAW,YAAY,gBAAgB,aAAa,aAAa;AACvE,aAAY,IAAI,UAAU,OAAO;CAEjC,MAAM,gBAAgB,OAAO,QAAQ;AACrC,KAAI,CAAC,cACH,OAAM,IAAI,MAAM,oCAAoC,OAAO,GAAG,SAAS,OAAO;AAGhF,QAAO"}
1
+ {"version":3,"file":"index.mjs","names":["fs","namespace","cacheKey"],"sources":["../../src/plugin/with-context.ts","../../src/plugin/get-generated-type.ts"],"sourcesContent":["/**\n * Plugin executor context support for defining plugin executors in separate files.\n * This module provides utilities for creating type-safe plugin executors that receive\n * context (like type references and namespace) at runtime.\n */\n\nimport type { TailorActor, TailorEnv } from \"@/parser/types\";\n\n/**\n * Plugin executor factory function type.\n * Takes context and returns an executor configuration.\n * Returns unknown since the exact return type depends on createExecutor's generic params.\n */\nexport type PluginExecutorFactory<Ctx> = (ctx: Ctx) => unknown;\n\n// ============================================================================\n// Plugin Executor Args Types\n// ============================================================================\n\n/**\n * Base args for plugin executor function operations.\n * Provides typed access to runtime context without requiring specific record types.\n */\nexport interface PluginFunctionArgs {\n /** Workspace ID where the executor runs */\n workspaceId: string;\n /** Application namespace */\n appNamespace: string;\n /** Environment variables */\n env: TailorEnv;\n /** Actor (user) who triggered the event, null for system events */\n actor: TailorActor | null;\n /** Name of the TailorDB type */\n typeName: string;\n /** TailorDB connections by namespace */\n tailordb: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record creation.\n */\nexport interface PluginRecordCreatedArgs extends PluginFunctionArgs {\n /** The newly created record */\n newRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record update.\n */\nexport interface PluginRecordUpdatedArgs extends PluginFunctionArgs {\n /** The record after update */\n newRecord: Record<string, unknown>;\n /** The record before update */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record deletion.\n */\nexport interface PluginRecordDeletedArgs extends PluginFunctionArgs {\n /** The deleted record */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Database schema type for plugins.\n * Since plugins work with dynamic types, the schema uses Record types.\n */\nexport type PluginDBSchema = Record<string, Record<string, unknown>>;\n\n/**\n * Base record type for TailorDB records.\n * All records have an id field.\n */\nexport type PluginRecord = { id: string } & Record<string, unknown>;\n\n/**\n * Define a plugin executor that receives context at runtime.\n * This allows executor definitions to be in separate files while\n * still receiving dynamic values like typeName, generated types, and namespace.\n * @param factory - Function that takes context and returns executor configuration\n * @returns The same factory function (for type inference)\n * @example\n * ```typescript\n * // executors/on-create.ts\n * import { withPluginContext } from \"@tailor-platform/sdk/plugin\";\n * import { createExecutor, recordCreatedTrigger } from \"@tailor-platform/sdk\";\n * import { getDB } from \"@tailor-platform/function-kysely-tailordb\";\n *\n * interface MyContext {\n * sourceType: TailorAnyDBType;\n * historyType: TailorAnyDBType;\n * namespace: string;\n * }\n *\n * export default withPluginContext<MyContext>((ctx) =>\n * createExecutor({\n * name: `${ctx.sourceType.name.toLowerCase()}-on-create`,\n * trigger: recordCreatedTrigger({ type: ctx.sourceType }),\n * operation: {\n * kind: \"function\",\n * body: async (args) => {\n * const db = getDB(ctx.namespace);\n * await db.insertInto(ctx.historyType.name).values({\n * recordId: args.newRecord.id,\n * // ...\n * }).execute();\n * },\n * },\n * })\n * );\n * ```\n */\nexport function withPluginContext<Ctx>(\n factory: PluginExecutorFactory<Ctx>,\n): PluginExecutorFactory<Ctx> {\n return factory;\n}\n","import * as fs from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport type { Plugin, PluginOutput, TypePluginOutput } from \"@/parser/plugin-config/types\";\nimport type { TailorAnyDBType } from \"@/parser/service/tailordb/types\";\n\n// ========================================\n// Config loading and caching\n// ========================================\n\ninterface PluginEntry {\n plugin: Plugin;\n pluginConfig: unknown;\n}\n\ninterface ConfigCache {\n config: { db?: Record<string, unknown> };\n plugins: Map<string, PluginEntry>;\n configDir: string;\n}\n\n/** Cache: resolved config path -> loaded config data */\nconst configCacheMap = new Map<string, ConfigCache>();\n\n/**\n * Check if a value is a Plugin instance.\n * @param value - Value to check\n * @returns True if value has the shape of Plugin\n */\nfunction isPlugin(value: unknown): value is Plugin {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Record<string, unknown>).id === \"string\" &&\n typeof (value as Record<string, unknown>).importPath === \"string\"\n );\n}\n\n/**\n * Load and cache config module from the given path.\n * Extracts plugins from all array exports using definePlugins() format.\n * Returns null if the config file does not exist (e.g., in bundled executor on platform server).\n * @param configPath - Absolute or relative path to tailor.config.ts\n * @returns Cached config data with plugins map, or null if config file is not available\n */\nasync function loadAndCacheConfig(configPath: string): Promise<ConfigCache | null> {\n const resolvedPath = path.resolve(configPath);\n\n const cached = configCacheMap.get(resolvedPath);\n if (cached) return cached;\n\n // Config file may not exist in bundled environments (e.g., platform server)\n if (!fs.existsSync(resolvedPath)) {\n return null;\n }\n\n const configModule = await import(pathToFileURL(resolvedPath).href);\n if (!configModule?.default) {\n throw new Error(`Invalid config module at \"${resolvedPath}\": default export not found`);\n }\n\n const config = configModule.default as { db?: Record<string, unknown> };\n const configDir = path.dirname(resolvedPath);\n const plugins = new Map<string, PluginEntry>();\n\n // Find plugin arrays from exports (definePlugins returns PluginConfig[])\n for (const value of Object.values(configModule)) {\n if (!Array.isArray(value)) continue;\n\n for (const item of value) {\n if (isPlugin(item)) {\n plugins.set(item.id, { plugin: item, pluginConfig: item.pluginConfig });\n }\n }\n }\n\n const result: ConfigCache = { config, plugins, configDir };\n configCacheMap.set(resolvedPath, result);\n return result;\n}\n\n// ========================================\n// Namespace resolution\n// ========================================\n\ninterface DbNamespaceConfig {\n files?: string[];\n external?: boolean;\n}\n\n/**\n * Resolve the namespace for a type-attached sourceType by checking config.db file patterns.\n * Uses ESM module cache identity: same file path yields same object references.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param configDir - Directory containing the config file\n * @param sourceType - The TailorDB type to look up\n * @returns The namespace name\n */\nasync function resolveNamespaceForType(\n config: { db?: Record<string, unknown> },\n configDir: string,\n sourceType: TailorAnyDBType,\n): Promise<string> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n for (const [namespace, nsConfig] of Object.entries(config.db)) {\n const dbConfig = nsConfig as DbNamespaceConfig;\n // Skip external namespaces (no files to resolve)\n if (dbConfig.external || !dbConfig.files) continue;\n\n for (const pattern of dbConfig.files) {\n const absolutePattern = path.resolve(configDir, pattern);\n let matchedFiles: string[];\n try {\n matchedFiles = fs.globSync(absolutePattern);\n } catch {\n continue;\n }\n\n for (const file of matchedFiles) {\n const mod = await import(pathToFileURL(file).href);\n for (const exported of Object.values(mod)) {\n if (exported === sourceType) {\n return namespace;\n }\n }\n }\n }\n }\n\n throw new Error(\n `Could not resolve namespace for type \"${sourceType.name}\". ` +\n `Ensure the type file is included in a db namespace's files pattern.`,\n );\n}\n\n/**\n * Resolve the namespace for a namespace plugin by trying each namespace.\n * Calls processNamespace() for each and returns the first whose output contains the requested kind.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - Plugin instance\n * @param kind - The generated type kind to look for\n * @param pluginConfig - Plugin-level configuration\n * @returns The namespace name\n */\nasync function resolveNamespaceForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<{ namespace: string; output: PluginOutput }> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n if (!plugin.processNamespace) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a processNamespace() method`);\n }\n\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const output = await plugin.processNamespace({\n pluginConfig,\n namespace,\n });\n\n if (output.types?.[kind]) {\n return { namespace, output };\n }\n }\n\n throw new Error(\n `Could not resolve namespace for plugin \"${plugin.id}\" with kind \"${kind}\". ` +\n `No namespace produced a type with that kind.`,\n );\n}\n\n// ========================================\n// Process caching\n// ========================================\n\n// Cache: plugin -> cacheKey -> TypePluginOutput\nconst processCache = new WeakMap<Plugin, Map<string, TypePluginOutput>>();\n\n// Cache for namespace plugins: plugin -> cacheKey -> PluginOutput\nconst namespaceProcessCache = new WeakMap<Plugin, Map<string, PluginOutput>>();\n\n/**\n * Generate a cache key that includes pluginConfig.\n * @param baseKey - Base key for the cache\n * @param pluginConfig - Plugin configuration to include in the key\n * @returns Cache key string\n */\nfunction getCacheKey(baseKey: string, pluginConfig: unknown): string {\n if (pluginConfig === undefined) {\n return baseKey;\n }\n try {\n return `${baseKey}:${JSON.stringify(pluginConfig)}`;\n } catch {\n throw new Error(\n `pluginConfig must be JSON-serializable for caching. Received non-serializable value.`,\n );\n }\n}\n\n// ========================================\n// Main API\n// ========================================\n\n/**\n * Get a generated type from a plugin by loading the config and resolving everything automatically.\n * For type-attached plugins, calls processType() with the sourceType.\n * For namespace plugins, calls processNamespace() with auto-resolved namespace.\n * Results are cached per config path, plugin, namespace, and pluginConfig to avoid redundant processing.\n * @param configPath - Path to tailor.config.ts (absolute or relative to cwd)\n * @param pluginId - The plugin's unique identifier\n * @param sourceType - The source TailorDB type (null for namespace plugins)\n * @param kind - The generated type kind (e.g., \"request\", \"step\")\n * @returns The generated TailorDB type\n */\nexport async function getGeneratedType(\n configPath: string,\n pluginId: string,\n sourceType: TailorAnyDBType | null,\n kind: string,\n): Promise<TailorAnyDBType> {\n const cache = await loadAndCacheConfig(configPath);\n\n if (!cache) {\n // Config not available (e.g., running in bundled executor on platform server).\n // Return a placeholder. The actual type is resolved at generate/apply time.\n return { name: `__placeholder_${kind}__`, fields: {} } as TailorAnyDBType;\n }\n\n const { config, configDir, plugins } = cache;\n\n const pluginEntry = plugins.get(pluginId);\n if (!pluginEntry) {\n throw new Error(\n `Plugin \"${pluginId}\" not found in config at \"${configPath}\". ` +\n `Ensure the plugin is registered via definePlugins().`,\n );\n }\n\n const { plugin, pluginConfig } = pluginEntry;\n\n if (sourceType === null) {\n return getGeneratedTypeForNamespacePlugin(config, plugin, kind, pluginConfig);\n }\n\n const namespace = await resolveNamespaceForType(config, configDir, sourceType);\n return getGeneratedTypeForTypeAttachedPlugin(plugin, sourceType, kind, pluginConfig, namespace);\n}\n\n/**\n * Get a generated type from a type-attached plugin.\n * @param plugin - The plugin instance (must have processType() method)\n * @param sourceType - The source TailorDB type\n * @param kind - The generated type kind\n * @param pluginConfig - Plugin-level configuration\n * @param namespace - Resolved namespace\n * @returns The generated TailorDB type\n */\nasync function getGeneratedTypeForTypeAttachedPlugin(\n plugin: Plugin,\n sourceType: TailorAnyDBType,\n kind: string,\n pluginConfig: unknown,\n namespace: string,\n): Promise<TailorAnyDBType> {\n if (!plugin.processType) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a processType() method`);\n }\n\n // Check cache first\n let pluginCache = processCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n processCache.set(plugin, pluginCache);\n }\n\n const cacheKey = getCacheKey(`${sourceType.name}:ns=${namespace}`, pluginConfig);\n let output = pluginCache.get(cacheKey);\n\n if (!output) {\n const typeConfig = sourceType.plugins?.find((p) => p.pluginId === plugin.id)?.config;\n output = await plugin.processType({\n type: sourceType,\n typeConfig: typeConfig ?? {},\n pluginConfig,\n namespace,\n });\n pluginCache.set(cacheKey, output);\n }\n\n const generatedType = output.types?.[kind];\n if (!generatedType) {\n throw new Error(\n `Generated type not found: plugin=${plugin.id}, sourceType=${sourceType.name}, kind=${kind}`,\n );\n }\n\n return generatedType as TailorAnyDBType;\n}\n\n/**\n * Get a generated type from a namespace plugin.\n * Auto-resolves the namespace by trying each one.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - The plugin instance (must have processNamespace() method)\n * @param kind - The generated type kind\n * @param pluginConfig - Plugin-level configuration\n * @returns The generated TailorDB type\n */\nasync function getGeneratedTypeForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<TailorAnyDBType> {\n if (!plugin.processNamespace) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a processNamespace() method`);\n }\n\n // Check cache first - try all namespaces\n let pluginCache = namespaceProcessCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n namespaceProcessCache.set(plugin, pluginCache);\n }\n\n // Try cached results first\n if (config.db) {\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n const cached = pluginCache.get(cacheKey);\n if (cached?.types?.[kind]) {\n return cached.types[kind] as TailorAnyDBType;\n }\n }\n }\n\n // Not in cache - resolve namespace and process\n const { namespace, output } = await resolveNamespaceForNamespacePlugin(\n config,\n plugin,\n kind,\n pluginConfig,\n );\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n pluginCache.set(cacheKey, output);\n\n const generatedType = output.types?.[kind];\n if (!generatedType) {\n throw new Error(`Generated type not found: plugin=${plugin.id}, kind=${kind}`);\n }\n\n return generatedType as TailorAnyDBType;\n}\n\n/**\n * Clear all internal caches. For testing only.\n * @lintignore\n */\nexport function _clearCacheForTesting(): void {\n configCacheMap.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA,SAAgB,kBACd,SAC4B;AAC5B,QAAO;;;;;;AC9FT,MAAM,iCAAiB,IAAI,KAA0B;;;;;;AAOrD,SAAS,SAAS,OAAiC;AACjD,QACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAkC,OAAO,YACjD,OAAQ,MAAkC,eAAe;;;;;;;;;AAW7D,eAAe,mBAAmB,YAAiD;CACjF,MAAM,eAAe,KAAK,QAAQ,WAAW;CAE7C,MAAM,SAAS,eAAe,IAAI,aAAa;AAC/C,KAAI,OAAQ,QAAO;AAGnB,KAAI,CAACA,KAAG,WAAW,aAAa,CAC9B,QAAO;CAGT,MAAM,eAAe,MAAM,OAAO,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AI,CAAC,cACH,OAAM,IAAI,MAAM,oCAAoC,OAAO,GAAG,SAAS,OAAO;AAGhF,QAAO"}
@@ -492,8 +492,8 @@ declare const RawPermissionsSchema: z.ZodObject<{
492
492
  }, z.core.$strip>, z.ZodString, z.ZodBoolean, z.ZodArray<z.ZodString>, z.ZodArray<z.ZodBoolean>]>], null>>>>;
493
493
  actions: z.ZodUnion<readonly [z.ZodLiteral<"all">, z.ZodReadonly<z.ZodArray<z.ZodEnum<{
494
494
  create: "create";
495
- update: "update";
496
495
  delete: "delete";
496
+ update: "update";
497
497
  aggregate: "aggregate";
498
498
  bulkUpsert: "bulkUpsert";
499
499
  read: "read";
@@ -635,11 +635,11 @@ declare const TailorFieldSchema: z.ZodObject<{
635
635
  type: z.ZodEnum<{
636
636
  string: "string";
637
637
  boolean: "boolean";
638
+ date: "date";
639
+ enum: "enum";
638
640
  uuid: "uuid";
639
641
  integer: "integer";
640
642
  float: "float";
641
- enum: "enum";
642
- date: "date";
643
643
  datetime: "datetime";
644
644
  time: "time";
645
645
  nested: "nested";
@@ -668,11 +668,11 @@ declare const ResolverSchema: z.ZodObject<{
668
668
  type: z.ZodEnum<{
669
669
  string: "string";
670
670
  boolean: "boolean";
671
+ date: "date";
672
+ enum: "enum";
671
673
  uuid: "uuid";
672
674
  integer: "integer";
673
675
  float: "float";
674
- enum: "enum";
675
- date: "date";
676
676
  datetime: "datetime";
677
677
  time: "time";
678
678
  nested: "nested";
@@ -698,11 +698,11 @@ declare const ResolverSchema: z.ZodObject<{
698
698
  type: z.ZodEnum<{
699
699
  string: "string";
700
700
  boolean: "boolean";
701
+ date: "date";
702
+ enum: "enum";
701
703
  uuid: "uuid";
702
704
  integer: "integer";
703
705
  float: "float";
704
- enum: "enum";
705
- date: "date";
706
706
  datetime: "datetime";
707
707
  time: "time";
708
708
  nested: "nested";
@@ -1342,10 +1342,11 @@ interface PluginExtends {
1342
1342
  * These fields will be merged into the original type's fields.
1343
1343
  * Existing fields (from original definition or earlier plugins) take precedence.
1344
1344
  */
1345
- fields?: Record<string, unknown>;
1345
+ fields?: Record<string, TailorAnyDBField>;
1346
1346
  }
1347
1347
  /**
1348
- * Output returned by a plugin's process method
1348
+ * Base output returned by a plugin's process method.
1349
+ * Used by both processType and processNamespace.
1349
1350
  */
1350
1351
  interface PluginOutput {
1351
1352
  /**
@@ -1358,20 +1359,26 @@ interface PluginOutput {
1358
1359
  resolvers?: PluginGeneratedResolver[];
1359
1360
  /** Additional executors to generate */
1360
1361
  executors?: PluginGeneratedExecutor[];
1362
+ }
1363
+ /**
1364
+ * Output returned by a plugin's processType method.
1365
+ * Extends PluginOutput with the ability to add fields to the source type.
1366
+ */
1367
+ interface TypePluginOutput extends PluginOutput {
1361
1368
  /** Extensions to apply to the source type */
1362
1369
  extends?: PluginExtends;
1363
1370
  }
1364
1371
  /**
1365
1372
  * Output returned by a plugin's processNamespace method.
1366
- * Namespace plugins cannot extend a source type.
1373
+ * Alias for PluginOutput (namespace plugins cannot extend a source type).
1367
1374
  */
1368
- type NamespacePluginOutput = Omit<PluginOutput, "extends"> & {
1369
- extends?: never;
1370
- };
1375
+ type NamespacePluginOutput = PluginOutput;
1371
1376
  /**
1372
- * Base plugin interface that all plugins must implement
1377
+ * Plugin interface that all plugins must implement.
1378
+ * @template TypeConfig - Type for per-type configuration passed via .plugin() method
1379
+ * @template PluginConfig - Type for plugin-level configuration passed via definePlugins()
1373
1380
  */
1374
- interface PluginCommon<PluginConfig = unknown> {
1381
+ interface Plugin<TypeConfig = unknown, PluginConfig = unknown> {
1375
1382
  /** Unique identifier for the plugin */
1376
1383
  readonly id: string;
1377
1384
  /** Human-readable description of the plugin */
@@ -1382,19 +1389,6 @@ interface PluginCommon<PluginConfig = unknown> {
1382
1389
  * (e.g., plugin executors and seed schema generation).
1383
1390
  */
1384
1391
  readonly importPath: string;
1385
- /**
1386
- * Schema defining the expected plugin-level configuration.
1387
- * Used to validate the `pluginConfig` property on the plugin object.
1388
- * If not provided, pluginConfig validation is skipped.
1389
- * @example
1390
- * ```typescript
1391
- * pluginConfigSchema: t.object({
1392
- * archiveTablePrefix: t.string({ optional: true }),
1393
- * defaultRetentionDays: t.int({ optional: true }),
1394
- * })
1395
- * ```
1396
- */
1397
- readonly pluginConfigSchema?: TailorAnyField;
1398
1392
  /**
1399
1393
  * Controls whether per-type plugin config is required when attaching via .plugin().
1400
1394
  * If a function is provided, it receives pluginConfig from definePlugins().
@@ -1407,24 +1401,13 @@ interface PluginCommon<PluginConfig = unknown> {
1407
1401
  * to both processType() and processNamespace() methods.
1408
1402
  */
1409
1403
  readonly pluginConfig?: PluginConfig;
1410
- /**
1411
- * TypeScript type template for generating type-safe plugin configuration.
1412
- * Use `Fields` to reference the field names of the type being configured.
1413
- * If not provided, the type is generated from configSchema.
1414
- * @example
1415
- * ```typescript
1416
- * // For field-aware configs:
1417
- * configTypeTemplate: "{ labels: Partial<Record<Fields, FieldLabel>>; typeLabel?: FieldLabel }"
1418
- * ```
1419
- */
1420
- readonly configTypeTemplate?: string;
1421
1404
  /**
1422
1405
  * Process a single TailorDB type and generate outputs.
1423
1406
  * This method is called for each type that has this plugin attached via .plugin().
1424
1407
  * @param context - Context containing the type, config, pluginConfig, and namespace
1425
1408
  * @returns Plugin output with generated types, resolvers, and executors
1426
1409
  */
1427
- processType?(context: PluginProcessContext): PluginOutput | Promise<PluginOutput>;
1410
+ processType?(context: PluginProcessContext<TypeConfig, PluginConfig>): TypePluginOutput | Promise<TypePluginOutput>;
1428
1411
  /**
1429
1412
  * Process plugin for a namespace without requiring a source type.
1430
1413
  * This method is called once per namespace for plugins configured via definePlugins().
@@ -1432,32 +1415,8 @@ interface PluginCommon<PluginConfig = unknown> {
1432
1415
  * @param context - Context containing the plugin config, namespace, and types
1433
1416
  * @returns Plugin output with generated types, resolvers, and executors
1434
1417
  */
1435
- processNamespace?(context: PluginNamespaceProcessContext): NamespacePluginOutput | Promise<NamespacePluginOutput>;
1436
- }
1437
- interface PluginWithConfig<PluginConfig = unknown> extends PluginCommon<PluginConfig> {
1438
- /**
1439
- * Schema defining the expected per-type configuration for this plugin.
1440
- * Used to validate config passed via `.plugin({ pluginId: config })`.
1441
- * Uses the same field types as createResolver's input (t.string(), t.number(), etc.).
1442
- * @example
1443
- * ```typescript
1444
- * configSchema: t.object({
1445
- * archiveReason: t.bool({ optional: true }),
1446
- * })
1447
- * ```
1448
- */
1449
- readonly configSchema: TailorAnyField;
1418
+ processNamespace?(context: PluginNamespaceProcessContext<PluginConfig>): NamespacePluginOutput | Promise<NamespacePluginOutput>;
1450
1419
  }
1451
- interface PluginNamespaceOnly<PluginConfig = unknown> extends PluginCommon<PluginConfig> {
1452
- /** Namespace-only plugins do not accept per-type config. */
1453
- readonly configSchema?: undefined;
1454
- /** Namespace-only plugins cannot define processType(). */
1455
- processType?: never;
1456
- }
1457
- /**
1458
- * Plugin interface that all plugins must implement
1459
- */
1460
- type Plugin<PluginConfig = unknown> = PluginWithConfig<PluginConfig> | PluginNamespaceOnly<PluginConfig>;
1461
1420
  //#endregion
1462
1421
  //#region src/configure/services/tailordb/schema.d.ts
1463
1422
  interface RelationConfig<S extends RelationType, T extends TailorDBType$1> {
@@ -2277,5 +2236,5 @@ interface TailorDBType {
2277
2236
  files?: TailorDBTypeMetadata["files"];
2278
2237
  }
2279
2238
  //#endregion
2280
- export { ArrayFieldOutput as $, TailorDBField as A, PluginGeneratedExecutor as B, UserAttributeKey as C, AllowedValues as Ct, ValueOperand as D, UsernameFieldKey as E, Plugin as F, PluginOutput as G, PluginGeneratedResolver as H, PluginAttachment as I, PermissionCondition as J, PluginProcessContext as K, PluginConfigs as L, TailorDBType$1 as M, db as N, TailorAnyDBField as O, NamespacePluginOutput as P, unsafeAllowAllTypePermission as Q, PluginExecutorContext as R, TenantProviderConfig as S, unauthenticatedTailorUser as St, UserAttributeMap as T, TailorDBServiceInput as Tt, PluginGeneratedType as U, PluginGeneratedExecutorWithFile as V, PluginNamespaceProcessContext as W, TailorTypePermission as X, TailorTypeGqlPermission as Y, unsafeAllowAllGqlPermission as Z, SCIMAttributeMapping as _, TailorEnv as _t, AuthInvoker as a, TailorAnyField as at, SCIMConfig as b, AttributeMap as bt, BuiltinIdP as c, Resolver as ct, IdProviderConfig as d, ResolverServiceConfig as dt, DefinedFieldMetadata as et, OAuth2ClientGrantType as f, ResolverServiceInput as ft, SCIMAttribute as g, Env as gt, SAML as h, output as ht, AuthExternalConfig as i, TailorFieldType as it, TailorDBInstance as j, TailorAnyDBType as k, DefinedAuth as l, ResolverExternalConfig as lt, OIDC as m, JsonCompatible as mt, TypeSourceInfoEntry as n, FieldOptions as nt, AuthOwnConfig as o, TailorField as ot, OAuth2ClientInput as p, InferFieldsOutput as pt, TailorDBTypeForPlugin as q, AuthConfig as r, FieldOutput$1 as rt, AuthServiceInput as s, QueryType as st, TailorDBType as t, FieldMetadata as tt, IDToken as u, ResolverInput as ut, SCIMAttributeType as v, TailorActor as vt, UserAttributeListKey as w, AllowedValuesOutput as wt, SCIMResource as x, TailorUser as xt, SCIMAuthorization as y, AttributeList as yt, PluginExecutorContextBase as z };
2281
- //# sourceMappingURL=types-DbvONSS-.d.mts.map
2239
+ export { unsafeAllowAllTypePermission as $, TailorDBField as A, PluginGeneratedExecutor as B, UserAttributeKey as C, unauthenticatedTailorUser as Ct, ValueOperand as D, UsernameFieldKey as E, TailorDBServiceInput as Et, Plugin as F, PluginOutput as G, PluginGeneratedResolver as H, PluginAttachment as I, TypePluginOutput as J, PluginProcessContext as K, PluginConfigs as L, TailorDBType$1 as M, db as N, TailorAnyDBField as O, NamespacePluginOutput as P, unsafeAllowAllGqlPermission as Q, PluginExecutorContext as R, TenantProviderConfig as S, TailorUser as St, UserAttributeMap as T, AllowedValuesOutput as Tt, PluginGeneratedType as U, PluginGeneratedExecutorWithFile as V, PluginNamespaceProcessContext as W, TailorTypeGqlPermission as X, PermissionCondition as Y, TailorTypePermission as Z, SCIMAttributeMapping as _, Env as _t, AuthInvoker as a, TailorFieldType as at, SCIMConfig as b, AttributeList as bt, BuiltinIdP as c, QueryType as ct, IdProviderConfig as d, ResolverInput as dt, ArrayFieldOutput as et, OAuth2ClientGrantType as f, ResolverServiceConfig as ft, SCIMAttribute as g, output as gt, SAML as h, JsonCompatible as ht, AuthExternalConfig as i, FieldOutput$1 as it, TailorDBInstance as j, TailorAnyDBType as k, DefinedAuth as l, Resolver as lt, OIDC as m, InferFieldsOutput as mt, TypeSourceInfoEntry as n, FieldMetadata as nt, AuthOwnConfig as o, TailorAnyField as ot, OAuth2ClientInput as p, ResolverServiceInput as pt, TailorDBTypeForPlugin as q, AuthConfig as r, FieldOptions as rt, AuthServiceInput as s, TailorField as st, TailorDBType as t, DefinedFieldMetadata as tt, IDToken as u, ResolverExternalConfig as ut, SCIMAttributeType as v, TailorEnv as vt, UserAttributeListKey as w, AllowedValues as wt, SCIMResource as x, AttributeMap as xt, SCIMAuthorization as y, TailorActor as yt, PluginExecutorContextBase as z };
2240
+ //# sourceMappingURL=types-Db1oxr0U.d.mts.map