{"version":3,"file":"index.mjs","names":[],"sources":["../src/types.ts","../src/runtime/utils.ts","../src/runtime/precompute.ts","../src/runtime/proxy.ts","../src/index.ts"],"sourcesContent":["/**\n * Represents a key hierarchy for a given object type.\n * Dynamically derived based on a provided {@link KeyHierarchyConfig}.\n */\nexport type KeyHierarchy<T, Path extends readonly unknown[] = []> = {\n  readonly [\n    K in keyof T as K extends InternalKeys ? never : K extends number ? `${K}` : K\n  ]: T[K] extends DynamicExtendedSegment<infer Arg, infer U> // 1) dynamic *extend*: property is a function that accepts Arg and returns a nested hierarchy\n    ? (arg: Arg) => KeyHierarchy<\n        U,\n        readonly [...Path, readonly [K extends number ? `${K}` : K, DeepReadonly<Arg>]]\n      > & {\n        readonly __key: readonly [\n          ...Path,\n          readonly [K extends number ? `${K}` : K, DeepReadonly<Arg>],\n        ]\n      }\n    : // 2) dynamic *leaf*: property is a function that accepts Arg and returns the final tuple\n      T[K] extends DynamicSegment<infer Arg>\n      ? (\n          arg: Arg,\n        ) => readonly [...Path, readonly [K extends number ? `${K}` : K, DeepReadonly<Arg>]]\n      : // 3) nested (normal object) => recurse and expose __key\n        T[K] extends object\n        ? KeyHierarchy<T[K], readonly [...Path, K extends number ? `${K}` : K]> & {\n            readonly __key: readonly [...Path, K extends number ? `${K}` : K]\n          }\n        : // 4) plain leaf (true) => final tuple\n          readonly [...Path, K extends number ? `${K}` : K]\n}\n\nexport const DYNAMIC_SEGMENT: unique symbol = Symbol('DynamicSegment')\n\nexport interface DynamicSegment<T> {\n  readonly [DYNAMIC_SEGMENT]: T\n}\n\nexport const DYNAMIC_EXTENDED_SEGMENT: unique symbol = Symbol('DynamicExtendedSegment')\n\nexport type DynamicExtendedSegment<T, U extends KeyHierarchyConfig<U>> = U & {\n  readonly [DYNAMIC_EXTENDED_SEGMENT]: T\n}\n\nexport type DynamicExtendableSegment<T> = DynamicSegment<T> & {\n  /**\n   * Extends the dynamic segment with a nested configuration.\n   * @param config - The nested configuration to extend the dynamic segment with.\n   * @returns The extended dynamic segment.\n   */\n  extend: <U extends KeyHierarchyConfig<U>>(config: U) => DynamicExtendedSegment<T, U>\n}\n\ntype InternalKeys = '__key' | typeof DYNAMIC_SEGMENT | typeof DYNAMIC_EXTENDED_SEGMENT\n\n/**\n * Declarative configuration of a key hierarchy.\n * @remarks **Note:** May not contain `__key` as a property at any place.\n */\nexport type KeyHierarchyConfig<T> = '__key' extends keyof T\n  ? never\n  : {\n      [K in keyof T as K extends InternalKeys ? never : K]: T[K] extends DynamicSegment<infer Arg>\n        ? DynamicExtendableSegment<Arg>\n        : T[K] extends DynamicExtendedSegment<infer Arg, infer U>\n          ? DynamicExtendedSegment<Arg, U>\n          : T[K] extends Function\n            ? never\n            : T[K] extends object\n              ? KeyHierarchyConfig<T[K]>\n              : true\n    }\n\n/**\n * Options for a key hierarchy.\n */\nexport interface KeyHierarchyOptions {\n  /**\n   * If enabled, all key arrays and their elements will be deeply frozen.\n   * While already present at the type level, due to {@link DeepReadonly}, this ensures true immutability during runtime.\n   * @remarks **Note:** Function arguments will be cloned with {@link structuredClone} to not affect the original values.\n   * @remarks **Warning:** Does not work with values that are not supported by {@link structuredClone}.\n   * @remarks **Warning:** Do not enable this for `queryKey` or `mutationKey` with `@tanstack/vue-query` as it will cause issues with reactivity.\n   * @defaultValue false\n   */\n  freeze?: boolean\n  /**\n   * The method to use for key hierarchy computation.\n   * `proxy` uses a {@link Proxy} to dynamically resolve keys on demand.\n   * `precompute` computes the key hierarchy upfront.\n   * @defaultValue 'proxy'\n   */\n  method?: 'proxy' | 'precompute'\n}\n\n/**\n * Represents a deeply readonly version of a type.\n */\nexport type DeepReadonly<T> = T extends (infer R)[]\n  ? DeepReadonlyArray<R>\n  : T extends Function\n    ? T\n    : T extends object\n      ? DeepReadonlyObject<T>\n      : T\n\n/**\n * Represents a deeply readonly version of an array.\n */\nexport interface DeepReadonlyArray<T> extends ReadonlyArray<DeepReadonly<T>> {}\n\n/**\n * Represents a deeply readonly version of an object.\n */\nexport type DeepReadonlyObject<T> = {\n  readonly [P in keyof T]: DeepReadonly<T[P]>\n}\n","export function deepFreeze(value: any): unknown {\n  if (value === undefined || value === null) {\n    return value\n  }\n  Object.freeze(value)\n  Object.getOwnPropertyNames(value).forEach((prop) => {\n    if (\n      value[prop] !== null &&\n      (typeof value[prop] === 'object' || typeof value[prop] === 'function') &&\n      !Object.isFrozen(value[prop])\n    ) {\n      deepFreeze(value[prop])\n    }\n  })\n  return value\n}\n\nexport function createClone<T>(value: T): T {\n  if (typeof value === 'function' || typeof value === 'symbol') {\n    return value\n  }\n  return structuredClone(value)\n}\n","import type { KeyHierarchyOptions } from '../types'\nimport { DYNAMIC_EXTENDED_SEGMENT, DYNAMIC_SEGMENT } from '../types'\nimport { createClone, deepFreeze } from './utils'\n\nexport function precomputeHierarchy(\n  path: unknown[],\n  currentConfig: any,\n  options: Required<KeyHierarchyOptions>,\n): any {\n  const result: any = {}\n\n  // Iterate over all own properties, including symbols\n  const keys = [\n    ...Object.keys(currentConfig),\n    ...Object.getOwnPropertySymbols(currentConfig),\n  ].filter((key) => key !== DYNAMIC_SEGMENT && key !== DYNAMIC_EXTENDED_SEGMENT) as (\n    | string\n    | symbol\n  )[]\n\n  for (const key of keys) {\n    const value = currentConfig[key]\n    const currentPath = [...path, key]\n\n    if (typeof value === 'boolean') {\n      // Leaf node: return the path\n      result[key] = options.freeze ? deepFreeze(currentPath) : [...currentPath]\n    } else if (typeof value === 'object' && value !== null) {\n      // Check if this is a DynamicExtend object\n      if (DYNAMIC_EXTENDED_SEGMENT in value) {\n        // Extract the extended config (symbols are not enumerable, so spread gets everything else)\n        const extendedConfig = { ...value }\n\n        // Create a function that returns the precomputed hierarchy for the extended config\n        result[key] = (arg: unknown) => {\n          const argPath = options.freeze ? createClone(arg) : arg\n          const functionPath = [...path, [key, argPath]]\n\n          // Precompute the sub-hierarchy with the extended config\n          const nested = precomputeHierarchy(functionPath, extendedConfig, options)\n          nested.__key = options.freeze ? deepFreeze(functionPath) : functionPath\n          return nested\n        }\n      } else if (DYNAMIC_SEGMENT in value) {\n        // Check if this is a DynamicLeaf object\n        // Create a function that returns the final path\n        result[key] = (arg: unknown) => {\n          const argPath = options.freeze ? createClone(arg) : arg\n          const functionPath = [...path, [key, argPath]]\n\n          // Leaf node\n          return options.freeze ? deepFreeze(functionPath) : functionPath\n        }\n      } else {\n        // Regular nested object: recurse\n        const nested = precomputeHierarchy(currentPath, value, options)\n        nested.__key = options.freeze ? deepFreeze(currentPath) : [...currentPath]\n        result[key] = nested\n      }\n    }\n  }\n\n  return result\n}\n","import type { KeyHierarchyOptions } from '../types'\nimport { DYNAMIC_EXTENDED_SEGMENT, DYNAMIC_SEGMENT } from '../types'\nimport { createClone, deepFreeze } from './utils'\n\nexport function createProxy<T>(\n  path: unknown[],\n  currentConfig: unknown,\n  options: Required<KeyHierarchyOptions>,\n): unknown {\n  return new Proxy(\n    {},\n    {\n      get(_, prop: string | number | symbol) {\n        // Return the frozen path for __key\n        if (prop === '__key') {\n          if (options.freeze) {\n            return deepFreeze([...path])\n          }\n          return [...path]\n        }\n\n        const value = (currentConfig as T)[prop as keyof T]\n\n        // Handle DynamicExtend - create a function that returns a proxy to the extended config\n        if (typeof value === 'object' && value !== null && DYNAMIC_EXTENDED_SEGMENT in value) {\n          return (arg: unknown) => {\n            const argPath = options.freeze ? createClone(arg) : arg\n            const functionPath = [...path, [prop, argPath]]\n\n            // Extract the extended config (symbols are not enumerable, so spread gets everything else)\n            const extendedConfig = { ...value }\n\n            // Continue with nested object using the extended config\n            return createProxy(functionPath, extendedConfig, options)\n          }\n        }\n\n        // Handle DynamicLeaf - create a function that returns the final path\n        if (typeof value === 'object' && value !== null && DYNAMIC_SEGMENT in value) {\n          return (arg: unknown) => {\n            const argPath = options.freeze ? createClone(arg) : arg\n            const functionPath = [...path, [prop, argPath]]\n\n            // Leaf node reached\n            if (options.freeze) {\n              return deepFreeze(functionPath)\n            }\n            return functionPath\n          }\n        }\n\n        // Handle object properties (non-dynamic)\n        if (typeof value === 'object' && value !== null) {\n          return createProxy([...path, prop], value, options)\n        }\n\n        if (options.freeze) {\n          return deepFreeze([...path, prop])\n        }\n        // Leaf node - return the path array\n        return [...path, prop]\n      },\n    },\n  )\n}\n","import { precomputeHierarchy } from './runtime/precompute'\nimport { createProxy } from './runtime/proxy'\nimport type {\n  KeyHierarchyConfig,\n  KeyHierarchyOptions,\n  KeyHierarchy,\n  DynamicExtendedSegment,\n  DynamicExtendableSegment,\n} from './types'\nimport { DYNAMIC_EXTENDED_SEGMENT, DYNAMIC_SEGMENT } from './types'\n\nexport type * from './types'\n\n/**\n * Represents a configuration or a builder function for a key hierarchy.\n */\nexport type ConfigOrBuilder<T extends KeyHierarchyConfig<T>> =\n  | T\n  | ((dynamic: typeof dynamicHelper) => T)\n\nfunction resolveConfigOrBuilder<T extends KeyHierarchyConfig<T>>(\n  configOrBuilder: ConfigOrBuilder<T>,\n): T {\n  return typeof configOrBuilder === 'function' ? configOrBuilder(dynamicHelper) : configOrBuilder\n}\n\n/**\n * Defines a key hierarchy based on the provided configuration and options.\n * @remarks **Note:** This function uses {@link Proxy} objects by default. See {@link KeyHierarchyOptions.method} for other options.\n * @param config - The declarative {@link KeyHierarchyConfig} of the key hierarchy.\n * @param options - The {@link KeyHierarchyOptions} for the key hierarchy.\n * @returns The {@link KeyHierarchy} derived from the given config and options.\n * @example\n * ```ts\n * const keys = defineKeyHierarchy((dynamic) => ({\n *   users: {\n *     getAll: true,\n *     create: true,\n *     byId: dynamic<number>().extend({\n *       get: true,\n *       update: true,\n *       delete: true,\n *     }),\n *   },\n *   posts: {\n *     byUserId: dynamic<number>(),\n *     byMonth: dynamic<number>().extend({\n *       byDay: dynamic<number>(),\n *     }),\n *     byAuthorAndYear: dynamic<{ authorId: string, year: number }>(),\n *     byTags: dynamic<{ tags: string[], filter?: PostFilter }>(),\n *   }\n * }))\n * console.log(keys.users.getAll) // readonly ['users', 'getAll']\n * console.log(keys.users.byId(42).update) // readonly ['users', ['byId', 42], 'update']\n * console.log(keys.users.byId(42).__key) // readonly ['users', ['byId', 42]]\n * console.log(keys.posts.byUserId(42)) // readonly ['posts', ['byUserId', 42]]\n * console.log(keys.posts.byMonth(3).byDay(15)) // readonly ['posts', ['byMonth', 3], ['byDay', 15]]\n * console.log(keys.posts.byAuthorAndYear({ authorId: 'id', year: 2023 })) // readonly ['posts', ['byAuthorAndYear', { authorId: 'id', year: 2023 }]]\n * ```\n */\nexport function defineKeyHierarchy<T extends KeyHierarchyConfig<T>>(\n  configOrBuilder: ConfigOrBuilder<T>,\n  options: KeyHierarchyOptions = {},\n): KeyHierarchy<T> {\n  const resolvedOptions: Required<KeyHierarchyOptions> = {\n    freeze: false,\n    method: 'proxy',\n    ...options,\n  }\n\n  const resolvedConfig = defineKeyHierarchyModule(configOrBuilder)\n\n  if (resolvedOptions.method === 'precompute') {\n    return precomputeHierarchy([], resolvedConfig, resolvedOptions) as KeyHierarchy<T>\n  }\n\n  return createProxy([], resolvedConfig, resolvedOptions) as KeyHierarchy<T>\n}\n\n/**\n * Defines a key hierarchy module.\n * @remarks This function is a no-op and is used for type inference only.\n * @param config - The declarative {@link KeyHierarchyConfig} of the key hierarchy module.\n * @returns The {@link KeyHierarchyConfig} of the key hierarchy module.\n * @example\n * ```ts\n * const userKeyModule = defineKeyHierarchyModule((dynamic) => ({\n *   getAll: true,\n *   create: true,\n *   byId: dynamic<number>().extend({\n *     get: true,\n *     update: true,\n *     delete: true,\n *   })\n * }))\n *\n * const postKeyModule = defineKeyHierarchyModule((dynamic) => ({\n *   byUserId: dynamic<number>(),\n *   byMonth: dynamic<number>().extend({\n *     byDay: dynamic<number>(),\n *   })\n * })\n *\n * const keys = defineKeyHierarchy({\n *   users: userKeyModule,\n *   posts: postKeyModule\n * })\n * ```\n */\nexport function defineKeyHierarchyModule<T extends KeyHierarchyConfig<T>>(\n  configOrBuilder: ConfigOrBuilder<T>,\n): T {\n  return resolveConfigOrBuilder(configOrBuilder)\n}\n\n/**\n * Helper function to define dynamic key segments with a single argument.\n * @returns A dynamic key segment that can optionally be extended with a nested configuration.\n * @example\n * ```ts\n * defineKeyHierarchy({\n *   getAll: true,\n *   byGroup: dynamic<{ groupId: string }>(),\n *   byId: dynamic<string>().extend({ get: true, update: true }),\n *   byMonth: dynamic<number>().extend({\n *     byDay: dynamic<number>(),\n *   }),\n *   byAuthorAndYear: dynamic<{ authorId: string, year: number }>(),\n *   byTags: dynamic<{ tags: string[], filter?: PostFilter }>(),\n * })\n * ```\n */\nfunction dynamicHelper<T>(): DynamicExtendableSegment<T> {\n  return {\n    [DYNAMIC_SEGMENT]: undefined as any as T,\n    extend<U extends KeyHierarchyConfig<U>>(config: U): DynamicExtendedSegment<T, U> {\n      return {\n        [DYNAMIC_EXTENDED_SEGMENT]: undefined as any as T,\n        ...config,\n      }\n    },\n  } as DynamicExtendableSegment<T>\n}\n"],"mappings":";AA+BA,MAAa,kBAAiC,OAAO,gBAAgB;AAMrE,MAAa,2BAA0C,OAAO,wBAAwB;;ACrCtF,SAAgB,WAAW,OAAqB;CAC9C,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO;CAET,OAAO,OAAO,KAAK;CACnB,OAAO,oBAAoB,KAAK,CAAC,CAAC,SAAS,SAAS;EAClD,IACE,MAAM,UAAU,SACf,OAAO,MAAM,UAAU,YAAY,OAAO,MAAM,UAAU,eAC3D,CAAC,OAAO,SAAS,MAAM,KAAK,GAE5B,WAAW,MAAM,KAAK;CAE1B,CAAC;CACD,OAAO;AACT;AAEA,SAAgB,YAAe,OAAa;CAC1C,IAAI,OAAO,UAAU,cAAc,OAAO,UAAU,UAClD,OAAO;CAET,OAAO,gBAAgB,KAAK;AAC9B;;AClBA,SAAgB,oBACd,MACA,eACA,SACK;CACL,MAAM,SAAc,CAAC;CAGrB,MAAM,OAAO,CACX,GAAG,OAAO,KAAK,aAAa,GAC5B,GAAG,OAAO,sBAAsB,aAAa,CAC/C,CAAC,CAAC,QAAQ,QAAQ,QAAQ,mBAAmB,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