import { I as ISymbolType, C as Config, T as Token, S as SymbolMetadata } from '../config-Bsd6DPFy.js';
import '@tokens-studio/schema-validation';

type InterpreterResult = ISymbolType | string | null;

declare const defaultObjectParsers: ObjectParser[];

/**
 * Matches objects with shape { value: number, unit: string }.
 */
declare const numberWithUnitParser: ObjectParser;

/**
 * ObjectParser allows custom transformation of structured values into interpreter symbols.
 * This is useful for parsing complex nested structures like { value: 1, unit: "rem" } into NumberWithUnitSymbol.
 *
 * @example
 * const numberWithUnitParser: ObjectParser = {
 *   predicate: (value) => isObject(value) && 'value' in value && 'unit' in value,
 *   toSymbol: ({ value, unit }, config) => new NumberWithUnitSymbol(value, unit, config)
 * }
 */
type ObjectParser = {
    /**
     * Check if this parser should handle the given value
     */
    predicate: (value: unknown) => boolean;
    /**
     * Convert the matched value to an interpreter symbol
     */
    toSymbol: (value: any, config?: Config) => ISymbolType;
};

declare class DependencyGraph<N = string> {
    private nodes;
    addNode(node: N, dependencies?: N[] | Set<N>): void;
    removeNode(node: N): void;
    getNodes(): Map<N, Set<N>>;
    entryNodes(): N[];
    private findCycle;
    topologicalSort(): N[];
}

declare enum ProcessorErrorCode {
    TOKEN_NOT_FOUND = "PROC_TOKEN_NOT_FOUND",
    TOKEN_ALREADY_EXISTS = "PROC_TOKEN_ALREADY_EXISTS",
    CIRCULAR_DEPENDENCY = "PROC_CIRCULAR_DEPENDENCY",
    SUB_FIELD_NOT_RESOLVED = "PROC_SUB_FIELD_NOT_RESOLVED",
    DEPENDENCY_ERROR = "PROC_DEPENDENCY_ERROR",
    NO_THEMES_FOUND = "PROC_NO_THEMES_FOUND",
    THEME_NOT_FOUND = "PROC_THEME_NOT_FOUND",
    TOKEN_SET_NOT_FOUND = "PROC_TOKEN_SET_NOT_FOUND",
    TOKEN_SET_INVALID = "PROC_TOKEN_SET_INVALID",
    NO_SETS_TO_PROCESS = "PROC_NO_SETS_TO_PROCESS",
    MULTIPLE_SETS_NO_SELECTION = "PROC_MULTIPLE_SETS_NO_SELECTION",
    UNKNOWN_PARSING_ERROR = "PROC_UNKNOWN_PARSING_ERROR",
    RESOLVER_NOT_INITIALIZED = "PROC_RESOLVER_NOT_INITIALIZED"
}

interface ErrorOptions {
    token?: Token;
    line?: number;
    data?: Record<string, unknown>;
    cause?: unknown;
}
declare class LanguageError extends Error {
    readonly code: string;
    readonly data: Record<string, unknown>;
    readonly line?: number;
    readonly token?: Token;
    readonly originalMessage: string;
    constructor(code: string, options?: ErrorOptions);
    private formatMessage;
}
declare class ProcessorError extends LanguageError {
    readonly code: ProcessorErrorCode;
    constructor(code: ProcessorErrorCode, options?: ErrorOptions);
}

/**
 * Structured token data containing value and optional type information
 */
interface TokenData {
    $value: unknown;
    $type?: string;
    /**
     * Optional metadata attached to the token.
     * This is passed through to the TokenSymbol and preserved during cloning.
     * Not accessible to the tokenscript language.
     */
    $metadata?: SymbolMetadata;
}

declare enum ValidationSeverity {
    ERROR = "error",
    WARNING = "warning",
    INFO = "info"
}
/**
 * A validation issue found during token type validation.
 *
 * @property code - Unique error code for this specific issue type
 * @property severity - Severity level (ERROR, WARNING, INFO)
 * @property message - Human-readable description of the issue
 * @property tokenName - The token where the issue was found
 * @property path - Path to the specific field within a structured token (e.g., ["fontSize"] or [0, "blur"] for arrays)
 * @property line - Optional line number in the source
 * @property data - Additional structured data for debugging
 */
interface ValidationIssue {
    code: string;
    severity: ValidationSeverity;
    message: string;
    tokenName: RefPath;
    path?: (string | number)[];
    line?: number;
    data?: Record<string, unknown>;
}

/**
 * Reference path (token name delimited by `.`)
 */
type RefPath = string;
type TokenInputMap = Map<RefPath, string | TokenData>;
type TokenDataMap$1 = Map<RefPath, TokenData>;
type ResolvedValueMap = Map<RefPath, InterpreterResult>;
type TokenResult = InterpreterResult | Error;
type TokenResultMap = Map<RefPath, TokenResult>;
/**
 * An issue found during token resolution.
 * Can be a validation issue or a language error (lexer/parser/interpreter/processor).
 */
type ResolveIssue = ValidationIssue | LanguageError;
type IssuesMap = Map<RefPath, ResolveIssue[]>;
type TokenOperationBase = {
    tokenPath: RefPath;
};
type CreateTokenParams = TokenOperationBase & {
    tokenData: TokenData;
};
type UpdateTokenParams = TokenOperationBase & {
    tokenData?: TokenData;
    tokenPathRenamed?: RefPath;
    updateReferences?: boolean;
};
type DeleteTokenParams = TokenOperationBase;
type TokenOperationResult = {
    tokens: ResolvedValueMap;
    resolved?: InterpreterResult;
    issues?: IssuesMap;
    dependants?: {
        graph: DependencyGraph<RefPath>;
    };
};
type CreateTokenResult = TokenOperationResult & {
    created: boolean;
};
type UpdateTokenResult = TokenOperationResult & {
    updated: boolean;
};
type DeleteTokenResult = TokenOperationResult;
type ResolveValueParams = {
    /** The raw token value expression to resolve (e.g. "{baseColors.red}", "16 * 2", "#ff0000") */
    value: unknown;
    /** Token type used for validation (e.g. "color", "dimension"). Only used when `validate` is true. */
    type?: string;
    /** When true, validate the resolved value against the token `type`. Defaults to false. */
    validate?: boolean;
};
type ResolveValueResult = {
    /** The resolved value (ISymbolType, string, Error, etc.) */
    resolved: InterpreterResult;
    /** Resolution issues (parse errors, missing references, etc.) */
    issues: ResolveIssue[];
};

type ProcessorResult = {
    graph: DependencyGraph<RefPath>;
    resolved: TokenResultMap;
    issues?: IssuesMap;
};
type ProcessorCallbacks = {
    onResolve?: (tokenName: RefPath, value: InterpreterResult) => void;
    onError?: (tokenName: RefPath, error: Error, originalValue: string | unknown, metadata?: {
        isSubField: boolean;
        parentToken?: string;
        fieldPath?: string;
    }) => void;
};
type ProcessorOutput = ProcessorResult & {
    tokens: ResolvedValueMap;
    resolver: TokenResolver;
    issues?: IssuesMap;
};
/**
 * TokenResolver - Resolves tokens with dependencies using prefix-aware resolution
 *
 * @example
 * const processor = new TokenResolver();
 * const tokens = new Map([
 *   ["a", { $value: "10" }],
 *   ["b", { $value: "{a} * 2" }],
 * ]);
 * const result = processor.build(tokens);
 */
declare class TokenResolver {
    private prefixResolver?;
    private tokens?;
    private config?;
    private objectParsers?;
    processTokens(tokens: TokenInputMap, callbacks?: ProcessorCallbacks, config?: Config, objectParsers?: ObjectParser[]): ProcessorResult;
    /**
     * Find all tokens affected by a change to the given token.
     *
     * Uses BFS traversal on the reverse dependency graph to identify
     * the changed token plus all tokens that transitively depend on it.
     *
     * @param tokenName - The token that changed
     * @returns Object containing affected tokens and a subgraph showing their relationships
     *
     * @example
     * const { resolver } = new TokenResolver().build(tokens);
     * const { tokens, subgraph } = resolver.getTokenDependencyGraph("color.primary");
     * console.log(tokens); // Set(['color.primary', 'button.background', ...])
     */
    getTokenDependencyGraph(tokenName: RefPath): {
        tokens: Set<RefPath>;
        subgraph: DependencyGraph<RefPath>;
    };
    build(tokens: TokenDataMap$1, config?: Config, objectParsers?: ObjectParser[]): ProcessorOutput;
    private ensureInitialized;
    private normalizeTokenPath;
    private createOutputCallbacks;
    private rebuildResolver;
    updateToken(params: UpdateTokenParams): UpdateTokenResult;
    createToken(params: CreateTokenParams): CreateTokenResult;
    deleteToken(params: DeleteTokenParams): DeleteTokenResult;
    /**
     * Resolve a single value expression against the existing warm cache.
     * No cloning, no graph rebuild, no re-parsing of other tokens.
     * Use this for lightweight preview resolution (e.g. live form input).
     *
     * **Important:** This method reads from the resolver's current cache and
     * shares its interpreter instance. It is intended for development-time
     * previews only. Callers that need isolation (e.g. speculative resolution
     * that must not observe or affect other operations) should clone the
     * `TokenResolver` first via `build()` on a copy of the token map.
     *
     * Must not be called concurrently with `updateToken`, `createToken`,
     * or `deleteToken` — those methods rebuild the internal resolver and
     * the shared interpreter state would conflict.
     */
    resolveValue(params: ResolveValueParams): ResolveValueResult;
}

interface TokenBuilder<T = unknown> {
    onResolve(tokenName: string, value: InterpreterResult): void;
    onError(tokenName: string, error: Error, originalValue: string | unknown): void;
    getResult(): T;
    readonly name: string;
}
type BuilderFormat = "nested" | "flat" | "map";

type TokenDataMap = Map<string, TokenData>;
interface BuildTokensOptions<T> {
    builder?: TokenBuilder<T>;
    config?: Config;
    objectParsers?: ObjectParser[];
}
/**
 * Builds tokens from a normalized TokenDataMap.
 *
 * This is the core token processing function. For most use cases, call this directly
 * rather than using the higher-level processTokens/processTokenSets wrappers.
 *
 * @param tokens - Map of token names to TokenData. Must be pre-normalized to TokenData format.
 * @param options - Build options (all optional):
 *   - builder: Custom token builder (default: MapBuilder)
 *   - config: Interpreter config
 *   - objectParsers: Array of object parsers
 *   - linter: Lint runner
 * @returns ProcessorOutput with resolved tokens, output, and optional lint results.
 *
 * @remarks
 * Consumers must normalize input to Map<string, TokenData> before calling this function.
 * Use processTokens/processTokenSets for automatic normalization of Records and Maps.
 */
declare function buildTokens<T = Map<string, InterpreterResult>>(tokens: TokenDataMap, options?: BuildTokensOptions<T>): ProcessorOutput & {
    output: T;
    issues?: IssuesMap;
};

type FlattenCallback<T> = (key: string, value: InterpreterResult) => T;
/**
 * Flatten a DictionarySymbol into key-value pairs
 *
 * @param result - The InterpreterResult to flatten (only DictionarySymbol will be flattened)
 * @param prefix - The prefix to prepend to keys
 * @param callback - Callback function that receives each flattened key-value pair
 *
 * @example
 * const result: Record<string, unknown> = {};
 * flattenChildrenObject(dictionarySymbol, "root", (key, value) => {
 *   result[key] = value;
 * });
 */
declare function flattenChildrenObject<T>(result: InterpreterResult, prefix: string, callback: FlattenCallback<T>): void;
/**
 * Flatten a Map structure into key-value pairs
 *
 * @param map - The map to flatten (from Dictionary.value)
 * @param prefix - The prefix to prepend to keys
 * @param callback - Callback function that receives each flattened key-value pair
 *
 * @example
 * const result = new Map<string, unknown>();
 * flattenChildrenMap(dictionarySymbol.value, "root", (key, value) => {
 *   result.set(key, value);
 * });
 */
declare function flattenChildrenMap<T>(map: Map<string, InterpreterResult>, prefix: string, callback: FlattenCallback<T>): void;

declare class MapBuilder implements TokenBuilder<Map<string, string | InterpreterResult>> {
    readonly name = "map";
    protected result: Map<string, string | InterpreterResult>;
    private successfullyResolved;
    onResolve(tokenName: string, value: InterpreterResult): void;
    onError(tokenName: string, _error: Error, originalValue: string | unknown): void;
    getResult(): Map<string, string | InterpreterResult>;
    getResolvedTokens(): Map<string, InterpreterResult>;
}

/**
 * Nested Object Builder
 *
 * Builds a nested object structure incrementally as tokens are resolved.
 * Converts flat token paths to nested structure.
 * Example: "color.primary" -> { color: { primary: value } }
 */
declare class NestedObjectBuilder implements TokenBuilder<Record<string, unknown>> {
    readonly name = "nested";
    private result;
    onResolve(tokenName: string, value: InterpreterResult): void;
    onError(tokenName: string, _error: Error, originalValue: string | unknown): void;
    getResult(): Record<string, unknown>;
}
/**
 * Flat Object Builder
 *
 * Builds a flat key-value object incrementally as tokens are resolved.
 * Example: "color.primary" -> { "color.primary": value }
 */
declare class FlatObjectBuilder implements TokenBuilder<Record<string, unknown>> {
    readonly name = "flat";
    private result;
    onResolve(tokenName: string, value: InterpreterResult): void;
    onError(tokenName: string, _error: Error, originalValue: string | unknown): void;
    getResult(): Record<string, unknown>;
}

declare class StringMapBuilder extends MapBuilder {
    onResolve(tokenName: string, value: InterpreterResult): void;
    getResult(): Map<string, string>;
}

/**
 * Create a ProcessorError for dependency-related failures.
 * Builds the dependency chain and extracts the root cause.
 */
declare function createDependencyError(tokenName: string, dependencyName: string, originalError: Error): ProcessorError;

type ProcessOptions = BuildTokensOptions<any>;
interface ProcessSetsOptions extends ProcessOptions {
    activeSets?: string[];
    activeTheme?: string;
}
interface ProcessResult<T = Map<string, string | InterpreterResult>> extends ProcessorOutput {
    output: T;
    issues?: IssuesMap;
}
type ProcessFilesOptions<T = any> = {
    path: string;
    outputPath?: string;
    schemas?: string[];
    activeSets?: string[];
    activeTheme?: string;
    builder?: TokenBuilder<T>;
    objectParsers?: ObjectParser[];
};

/**
 * Process flat token collection.
 *
 * @param tokens - Token input in various formats (Map or Record)
 * @param options - Processing options
 * @returns Processed tokens with resolved values
 *
 * @note Performance optimization: If you already have a `Map<string, TokenData>`,
 * you can skip this function and call `buildTokens` directly to avoid unnecessary flattening.
 */
declare function processTokens<T = Map<string, string | InterpreterResult>>(tokens: Map<string, TokenData> | Map<string, string> | Record<string, any>, options?: ProcessOptions): ProcessResult<T>;
/**
 * Process token sets with theme or set selection.
 */
declare function processTokenSets<T = Map<string, string | InterpreterResult>>(normalizedFiles: Record<string, unknown>, options?: ProcessSetsOptions): ProcessResult<T>;

/**
 * Get all affected token paths from the dependants graph.
 * Returns the set of all tokens that depend on the changed token.
 */
declare function getAffectedTokens(result: TokenOperationResult): Set<RefPath>;
/**
 * Get broken references from issues.
 * Filters issues for TOKEN_NOT_FOUND or DEPENDENCY_ERROR codes.
 */
declare function getBrokenReferences(result: TokenOperationResult): Set<RefPath>;
/**
 * For rename operations: get tokens whose references were updated.
 * Pass the set of tokens that were modified during rename.
 */
declare function getRenamedReferences(_result: TokenOperationResult, modifiedTokens: Set<RefPath>): Set<RefPath>;
/**
 * Get tokens from the dependants graph whose values actually changed.
 * Compares the old token values with the new result to filter only modified tokens.
 */
declare function getModifiedDependants(oldTokens: Map<RefPath, any>, result: TokenOperationResult): Set<RefPath>;

/**
 * Check if issues map contains an error with the specified code.
 * Useful for checking if any token has a specific type of error.
 *
 * @example
 * ```typescript
 * const result = resolver.updateToken({ ... });
 * if (hasIssueWithCode(result.issues, ProcessorErrorCode.CIRCULAR_DEPENDENCY)) {
 *   console.error("Circular dependency detected");
 * }
 * ```
 */
declare function hasIssueWithCode(issues: IssuesMap | undefined, code: ProcessorErrorCode): boolean;
/**
 * Check if a specific token has an issue with the specified code.
 *
 * @example
 * ```typescript
 * const result = resolver.updateToken({ tokenPath: "foo", ... });
 * if (tokenHasIssueWithCode(result.issues, "foo", ProcessorErrorCode.CIRCULAR_DEPENDENCY)) {
 *   console.error("Token 'foo' has a circular dependency");
 * }
 * ```
 */
declare function tokenHasIssueWithCode(issues: IssuesMap | undefined, tokenName: string, code: ProcessorErrorCode): boolean;
/**
 * Get all tokens that have issues of any kind.
 *
 * @example
 * ```typescript
 * const result = resolver.build(tokens);
 * const tokensWithIssues = getTokensWithIssues(result.issues);
 * console.log(`${tokensWithIssues.size} tokens have issues`);
 * ```
 */
declare function getTokensWithIssues(issues: IssuesMap | undefined): Set<string>;
/**
 * Check if there are any issues at all.
 *
 * @example
 * ```typescript
 * const result = resolver.build(tokens);
 * if (hasAnyIssues(result.issues)) {
 *   console.error("There are issues with the tokens");
 * }
 * ```
 */
declare function hasAnyIssues(issues: IssuesMap | undefined): boolean;

/**
 * Token name validation.
 *
 * Must stay in sync with the Go and Ruby versions. The shared fixture
 * at tokenscript/test-suites/token-name-validation.json proves they agree.
 * Uses explicit whitespace chars (not \s) to ensure identical behavior
 * across Go/JS/Ruby regex engines.
 */
/** Returns true if a single name segment is valid: non-empty and contains no whitespace, braces, or brackets. */
declare function validateTokenName(name: string): boolean;
/** Returns true if every segment of a dot-delimited token path is a valid token name. */
declare function validateTokenPath(path: string): boolean;

export { type BuildTokensOptions, type BuilderFormat, type CreateTokenParams, type CreateTokenResult, type DeleteTokenParams, type DeleteTokenResult, FlatObjectBuilder, type FlattenCallback, type IssuesMap, MapBuilder, NestedObjectBuilder, type ObjectParser, type ProcessFilesOptions, type ProcessOptions, type ProcessResult, type ProcessSetsOptions, type ProcessorOutput, type ProcessorResult, type ResolveIssue, type ResolveValueParams, type ResolveValueResult, StringMapBuilder, type TokenBuilder, type TokenDataMap, type TokenOperationResult, TokenResolver, type UpdateTokenParams, type UpdateTokenResult, type ValidationIssue, ValidationSeverity, buildTokens, createDependencyError, defaultObjectParsers, flattenChildrenMap, flattenChildrenObject, getAffectedTokens, getBrokenReferences, getModifiedDependants, getRenamedReferences, getTokensWithIssues, hasAnyIssues, hasIssueWithCode, numberWithUnitParser, processTokenSets, processTokens, tokenHasIssueWithCode, validateTokenName, validateTokenPath };
