@uiwwsw/react-query-helper 1.3.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,109 +1,121 @@
1
1
  // src/core/generator.ts
2
- var DEFAULT_IMPORT_NAMES = {
2
+ import ts from "typescript";
3
+ var imports = {
3
4
  query: "queryOption",
4
5
  mutation: "mutationOption",
5
6
  infinite: "infiniteOption"
6
7
  };
7
- var DEFAULT_OUTPUT_NAMES = {
8
+ var suffixes = {
8
9
  query: "QueryOption",
9
10
  mutation: "MutationOption",
10
11
  infinite: "InfiniteQueryOption"
11
12
  };
12
- var MUTATION_NAME_PATTERN = /^(create|post|add|update|put|patch|delete|remove|set|send|upload|signIn|signOut|login|logout|mutate)/i;
13
- var QUERY_NAME_PATTERN = /^(get|list|fetch|find|read|load|search|retrieve|detail|details)/i;
14
- function isSimpleParameterName(name) {
15
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
13
+ var mutationPattern = /^(create|post|add|update|put|patch|delete|remove|set|send|upload|signIn|signOut|login|logout|mutate)(?=[A-Z_\d]|$)/;
14
+ var queryPattern = /^(get|list|fetch|find|read|load|search|retrieve|detail|details)(?=[A-Z_\d]|$)/;
15
+ function validIdentifier(name) {
16
+ const scanner = ts.createScanner(
17
+ ts.ScriptTarget.Latest,
18
+ false,
19
+ ts.LanguageVariant.Standard,
20
+ name
21
+ );
22
+ const token = scanner.scan();
23
+ return (token === ts.SyntaxKind.Identifier || token >= ts.SyntaxKind.AbstractKeyword && token <= ts.SyntaxKind.OfKeyword && token !== ts.SyntaxKind.AwaitKeyword) && scanner.getTokenText() === name && scanner.scan() === ts.SyntaxKind.EndOfFileToken;
16
24
  }
17
- function getMutationVariablesTypeName(functionName) {
18
- return `${functionName}MutationVariables`;
19
- }
20
- function buildMutationVariablesType(info) {
21
- if (info.parameters.length <= 1 || !info.parameters.every(isSimpleParameterName)) {
22
- return null;
23
- }
24
- const lines = info.parameters.map((parameterName, index) => ` ${parameterName}: Parameters<typeof ${info.name}>[${index}];`);
25
- return `export type ${getMutationVariablesTypeName(info.name)} = {
26
- ${lines.join(`
27
- `)}
28
- };
29
- `;
30
- }
31
- function buildMutationOptionExpression(info, importName, keyName) {
32
- if (info.parameters.length <= 1 || !info.parameters.every(isSimpleParameterName)) {
33
- return `${importName}(${keyName}, ${info.name})`;
34
- }
35
- const variablesTypeName = getMutationVariablesTypeName(info.name);
36
- const argumentMapping = info.parameters.map((parameterName) => `variables.${parameterName}`).join(", ");
37
- return `${importName}<Parameters<typeof ${info.name}>, Awaited<ReturnType<typeof ${info.name}>>, ${variablesTypeName}>(${keyName}, ${info.name}, { mapVariablesToArgs: (variables) => [${argumentMapping}] })`;
38
- }
39
- function resolveArtifacts(info, enabledArtifacts, strategy) {
40
- if (strategy === "all") {
41
- return enabledArtifacts;
42
- }
43
- if (MUTATION_NAME_PATTERN.test(info.name)) {
44
- return enabledArtifacts.filter((artifact) => artifact === "mutation");
25
+ function generateOptionsCode(functionInfos, importPath, {
26
+ keySegments,
27
+ fileName,
28
+ templateImportPath,
29
+ template = {}
30
+ }) {
31
+ const enabled = template.enabledArtifacts ?? [
32
+ "query",
33
+ "mutation",
34
+ "infinite"
35
+ ];
36
+ const strategy = template.artifactStrategy ?? "smart";
37
+ const rows = functionInfos.map((info) => {
38
+ let artifacts = template.artifactsByName?.[info.name] ?? enabled;
39
+ if (!template.artifactsByName?.[info.name] && strategy === "smart") {
40
+ artifacts = artifacts.filter(
41
+ (a) => mutationPattern.test(info.name) ? a === "mutation" : queryPattern.test(info.name) ? a !== "mutation" : a !== "infinite"
42
+ );
43
+ }
44
+ return {
45
+ info,
46
+ artifacts: [...new Set(artifacts.filter((a) => enabled.includes(a)))]
47
+ };
48
+ }).filter((row) => row.artifacts.length);
49
+ if (!rows.length) return "";
50
+ const occupied = /* @__PURE__ */ new Set();
51
+ function reserve(name) {
52
+ if (!validIdentifier(name) || occupied.has(name))
53
+ throw new Error(`Invalid or duplicate generated identifier: ${name}`);
54
+ occupied.add(name);
55
+ return name;
45
56
  }
46
- if (QUERY_NAME_PATTERN.test(info.name)) {
47
- return enabledArtifacts.filter((artifact) => artifact === "query" || artifact === "infinite");
57
+ for (const { info } of rows) {
58
+ if (!info.isExported)
59
+ throw new Error(
60
+ `Cannot import private function ${info.name}. Export it or use a custom template.`
61
+ );
62
+ reserve(info.name);
48
63
  }
49
- return enabledArtifacts.filter((artifact) => artifact !== "infinite");
50
- }
51
- function getKeySegments(info, fileName, keySegments, keyStyle) {
52
- switch (keyStyle) {
53
- case "function-only":
54
- return [info.name];
55
- case "file-only":
56
- return [fileName, info.name];
57
- case "path":
58
- default:
59
- return [...keySegments, info.name];
64
+ for (const { info, artifacts } of rows) {
65
+ reserve(`${info.name}Key`);
66
+ for (const a of artifacts)
67
+ reserve(`${info.name}${template.outputNames?.[a] ?? suffixes[a]}`);
60
68
  }
61
- }
62
- function generateOptionsCode(functionInfos, importPath, { keySegments, fileName, templateImportPath, template }) {
63
- if (functionInfos.length === 0) {
64
- return "";
69
+ const helpers = /* @__PURE__ */ new Map();
70
+ const helperImports = [];
71
+ for (const a of new Set(rows.flatMap((row) => row.artifacts))) {
72
+ const name = template.importNames?.[a] ?? imports[a];
73
+ if (!validIdentifier(name))
74
+ throw new Error(`Invalid helper import: ${name}`);
75
+ let alias = `__rqh_${a}`;
76
+ while (occupied.has(alias)) alias += "_";
77
+ reserve(alias);
78
+ helpers.set(a, alias);
79
+ helperImports.push(`${name} as ${alias}`);
65
80
  }
66
- const enabledArtifacts = template?.enabledArtifacts?.length ? template.enabledArtifacts : ["query", "mutation", "infinite"];
67
- const importNames = {
68
- ...DEFAULT_IMPORT_NAMES,
69
- ...template?.importNames
70
- };
71
- const outputNames = {
72
- ...DEFAULT_OUTPUT_NAMES,
73
- ...template?.outputNames
74
- };
75
- const artifactStrategy = template?.artifactStrategy ?? "smart";
76
- const helperImports = [...new Set(enabledArtifacts.map((artifact) => importNames[artifact]))];
77
- const functionNames = functionInfos.map((info) => info.name);
78
- const keyStyle = template?.keyStyle ?? "path";
79
- let newContent = `import { ${functionNames.join(", ")} } from "${importPath}";
81
+ let code = `import { ${rows.map(
82
+ ({ info }) => info.importName && info.importName !== info.name ? `${info.importName === "default" ? "default" : JSON.stringify(info.importName)} as ${info.name}` : info.name
83
+ ).join(", ")} } from ${JSON.stringify(importPath)};
80
84
  `;
81
- newContent += `import { ${helperImports.join(", ")} } from "${templateImportPath}";
85
+ code += `import { ${helperImports.join(", ")} } from ${JSON.stringify(templateImportPath)};
82
86
 
83
87
  `;
84
- functionInfos.forEach((info) => {
85
- const resolvedArtifacts = resolveArtifacts(info, enabledArtifacts, artifactStrategy);
86
- if (resolvedArtifacts.length === 0) {
87
- return;
88
- }
89
- const keyArray = JSON.stringify(getKeySegments(info, fileName, keySegments, keyStyle));
88
+ for (const { info, artifacts } of rows) {
89
+ const base = template.keyStyle === "function-only" ? [] : template.keyStyle === "file-only" ? [fileName] : [...keySegments, fileName];
90
90
  const keyName = `${info.name}Key`;
91
- const mutationVariablesType = buildMutationVariablesType(info);
92
- if (mutationVariablesType && resolvedArtifacts.includes("mutation")) {
93
- newContent += mutationVariablesType;
94
- }
95
- newContent += `export const ${keyName} = ${keyArray} as const;
91
+ code += `export const ${keyName} = ${JSON.stringify([...base, info.name])} as const;
96
92
  `;
97
- resolvedArtifacts.forEach((artifact) => {
98
- const optionExpression = artifact === "mutation" ? buildMutationOptionExpression(info, importNames[artifact], keyName) : `${importNames[artifact]}(${keyName}, ${info.name})`;
99
- newContent += `export const ${info.name}${outputNames[artifact]} = ${optionExpression};
93
+ for (const artifact of artifacts) {
94
+ const helper = helpers.get(artifact);
95
+ let expression = `${helper}(${keyName}, ${info.name})`;
96
+ if (artifact === "mutation") {
97
+ const hasRest = info.restParameterIndex !== void 0 && info.restParameterIndex >= 0;
98
+ if (info.parameters.length > 1 && !hasRest && info.parameters.every(validIdentifier)) {
99
+ const typeName = reserve(`${info.name}MutationVariables`);
100
+ code += `export type ${typeName} = {
101
+ ${info.parameters.map(
102
+ (p, i) => ` ${p}${info.optionalParameters?.[i] ? "?" : ""}: Parameters<typeof ${info.name}>[${i}];`
103
+ ).join("\n")}
104
+ };
100
105
  `;
101
- });
102
- newContent += `
106
+ expression = `${helper}<Parameters<typeof ${info.name}>, Awaited<ReturnType<typeof ${info.name}>>, ${typeName}>(${keyName}, ${info.name}, { mapVariablesToArgs: (variables) => [${info.parameters.map((p) => `variables.${p}`).join(", ")}] })`;
107
+ } else if (info.parameters.length > 1 || hasRest) {
108
+ expression = `${helper}(${keyName}, ${info.name}, { variablesMode: "tuple" })`;
109
+ }
110
+ }
111
+ code += `export const ${info.name}${template.outputNames?.[artifact] ?? suffixes[artifact]} = ${expression};
103
112
  `;
104
- });
105
- return newContent;
113
+ }
114
+ code += "\n";
115
+ }
116
+ return code;
106
117
  }
107
118
  export {
108
- generateOptionsCode
119
+ generateOptionsCode,
120
+ validIdentifier
109
121
  };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
- export * from './utils/query';
2
- export type { AutoQueryConfig } from './config';
3
- //# sourceMappingURL=index.d.ts.map
1
+ export * from "./utils/query.js";
2
+ export type { AutoQueryConfig } from "./config.js";
package/dist/index.js CHANGED
@@ -1,111 +1,118 @@
1
1
  // src/utils/query.ts
2
+ import {
3
+ infiniteQueryOptions,
4
+ mutationOptions,
5
+ queryOptions
6
+ } from "@tanstack/react-query";
2
7
  function resolveArgs(payload, overrides) {
3
- const baseArgs = overrides?.args ?? payload;
4
- return overrides?.mapArgs ? overrides.mapArgs(baseArgs) : baseArgs;
8
+ const args = [...overrides.args ?? payload];
9
+ return overrides.mapArgs ? overrides.mapArgs(args) : args;
5
10
  }
6
- function resolveKey(baseKey, appendKey, overrideKey) {
7
- if (overrideKey) {
8
- return [...overrideKey];
9
- }
10
- return [...baseKey, ...appendKey ?? []];
11
+ function resolveKey(base, args, append, override) {
12
+ return override ?? [...base, ...args, ...append ?? []];
11
13
  }
12
- function toArgs(variables) {
13
- if (Array.isArray(variables)) {
14
- return variables;
15
- }
16
- if (typeof variables === "undefined") {
17
- return [];
18
- }
19
- return [variables];
20
- }
21
- var queryOption = (key, fn) => {
22
- const buildOptions = (payload, overrides) => {
14
+ function queryOption(key, fn) {
15
+ function build(payload, overrides = {}) {
23
16
  const args = resolveArgs(payload, overrides);
24
- const queryKey = resolveKey([...key, ...args], overrides?.appendQueryKey, overrides?.queryKey);
25
- const { appendQueryKey: _appendQueryKey, args: _args, mapArgs: _mapArgs, queryFn: overrideQueryFn, queryKey: _queryKey, ...restOverrides } = overrides ?? {};
17
+ const {
18
+ queryKey: customKey,
19
+ appendQueryKey,
20
+ args: _args,
21
+ mapArgs: _mapArgs,
22
+ queryFn: customFn,
23
+ ...options
24
+ } = overrides;
25
+ const queryKey = resolveKey(
26
+ key,
27
+ ["query", args],
28
+ appendQueryKey,
29
+ customKey
30
+ );
31
+ const queryFn = async (context) => customFn ? customFn({ ...context, args }) : fn(...args);
26
32
  return {
27
- queryKey,
28
- queryFn: (context) => {
29
- if (overrideQueryFn) {
30
- return Promise.resolve(overrideQueryFn({
31
- queryKey: context.queryKey,
32
- signal: context.signal,
33
- meta: context.meta,
34
- args
35
- }));
36
- }
37
- return Promise.resolve(fn(...args));
38
- },
39
- gcTime: Infinity,
40
- refetchOnWindowFocus: false,
41
- ...restOverrides
33
+ ...queryOptions({
34
+ ...options,
35
+ queryKey,
36
+ queryFn
37
+ }),
38
+ queryFn
42
39
  };
43
- };
44
- const factory = (...payload) => buildOptions(payload);
45
- factory.withOptions = (overrides, ...payload) => buildOptions(payload, overrides);
40
+ }
41
+ const factory = (...payload) => build(payload);
42
+ function withOptions(overrides, ...payload) {
43
+ return build(payload, overrides);
44
+ }
45
+ factory.withOptions = withOptions;
46
46
  return factory;
47
- };
48
- var mutationOption = (key, fn, config) => {
49
- const buildOptions = (overrides) => {
47
+ }
48
+ function mutationOption(key, fn, ...configuration) {
49
+ const config = configuration[0];
50
+ function build(overrides = {}) {
50
51
  const {
51
- appendMutationKey: _appendMutationKey,
52
- mutationKey: overrideMutationKey,
52
+ mutationKey,
53
+ appendMutationKey,
53
54
  mapVariablesToArgs,
54
- mutationFn: overrideMutationFn,
55
- ...restOverrides
56
- } = overrides ?? {};
55
+ mutationFn: customFn,
56
+ ...options
57
+ } = overrides;
58
+ const mapper = mapVariablesToArgs ?? config?.mapVariablesToArgs;
59
+ const mutationFn = async (variables, context) => {
60
+ const args = mapper ? mapper(variables) : config?.variablesMode === "tuple" ? variables : variables === void 0 ? [] : [variables];
61
+ if (!Array.isArray(args))
62
+ throw new TypeError("Mutation argument mapping must return an array.");
63
+ return customFn ? customFn({ ...context, variables, args }) : fn(...args);
64
+ };
57
65
  return {
58
- mutationKey: resolveKey(key, _appendMutationKey, overrideMutationKey),
59
- mutationFn: (variables) => {
60
- const args = mapVariablesToArgs ? mapVariablesToArgs(variables) : config?.mapVariablesToArgs ? config.mapVariablesToArgs(variables) : toArgs(variables);
61
- if (overrideMutationFn) {
62
- return Promise.resolve(overrideMutationFn({ variables, args }));
63
- }
64
- return Promise.resolve(fn(...args));
65
- },
66
- ...restOverrides
66
+ ...mutationOptions({
67
+ ...options,
68
+ mutationKey: mutationKey ?? [...key, ...appendMutationKey ?? []],
69
+ mutationFn
70
+ }),
71
+ mutationFn
67
72
  };
68
- };
69
- const factory = () => buildOptions();
70
- factory.withOptions = (overrides) => buildOptions(overrides);
73
+ }
74
+ const factory = () => build();
75
+ factory.withOptions = build;
71
76
  return factory;
72
- };
73
- var infiniteOption = (key, fn) => {
74
- const buildOptions = (payload, overrides) => {
77
+ }
78
+ function infiniteOption(key, fn) {
79
+ function build(payload, overrides) {
75
80
  const args = resolveArgs(payload, overrides);
76
- const queryKey = resolveKey([...key, ...args], overrides?.appendQueryKey, overrides?.queryKey);
77
- const { appendQueryKey: _appendQueryKey, args: _args, mapArgs: _mapArgs, pageParamToArgs, queryFn: overrideQueryFn, queryKey: _queryKey, ...restOverrides } = overrides ?? {};
81
+ const {
82
+ queryKey: customKey,
83
+ appendQueryKey,
84
+ args: _args,
85
+ mapArgs: _mapArgs,
86
+ pageParamToArgs,
87
+ queryFn: customFn,
88
+ ...options
89
+ } = overrides;
90
+ const queryKey = resolveKey(
91
+ key,
92
+ ["infinite", args],
93
+ appendQueryKey,
94
+ customKey
95
+ );
96
+ const queryFn = async (context) => {
97
+ if (customFn) return customFn({ ...context, args });
98
+ return fn(
99
+ ...pageParamToArgs ? pageParamToArgs(context.pageParam, [...args]) : args
100
+ );
101
+ };
78
102
  return {
79
- queryKey,
80
- queryFn: (context) => {
81
- if (overrideQueryFn) {
82
- return Promise.resolve(overrideQueryFn({
83
- queryKey: context.queryKey,
84
- signal: context.signal,
85
- meta: context.meta,
86
- pageParam: context.pageParam,
87
- direction: context.direction,
88
- args
89
- }));
90
- }
91
- const resolvedArgs = pageParamToArgs ? pageParamToArgs(context.pageParam, args) : args;
92
- return Promise.resolve(fn(...resolvedArgs));
93
- },
94
- getNextPageParam: () => {
95
- return;
96
- },
97
- initialPageParam: undefined,
98
- staleTime: Infinity,
99
- refetchOnWindowFocus: false,
100
- ...restOverrides
103
+ ...infiniteQueryOptions({ ...options, queryKey, queryFn }),
104
+ queryFn
101
105
  };
102
- };
103
- const factory = (...payload) => buildOptions(payload);
104
- factory.withOptions = (overrides, ...payload) => buildOptions(payload, overrides);
106
+ }
107
+ const factory = (...payload) => build(payload, {
108
+ initialPageParam: void 0,
109
+ getNextPageParam: () => void 0
110
+ });
111
+ factory.withOptions = (overrides, ...payload) => build(payload, overrides);
105
112
  return factory;
106
- };
113
+ }
107
114
  export {
108
- queryOption,
115
+ infiniteOption,
109
116
  mutationOption,
110
- infiniteOption
117
+ queryOption
111
118
  };
@@ -1,64 +1,73 @@
1
- import type { QueryKey, UseInfiniteQueryOptions, UseMutationOptions, UseQueryOptions } from "@tanstack/react-query";
2
- type MaybePromise<T> = T | Promise<T>;
3
- type AnyFn<TArgs extends unknown[] = unknown[], TResult = unknown> = (...payload: TArgs) => MaybePromise<TResult>;
4
- type MutationVariables<TArgs extends unknown[]> = TArgs extends [] ? void : TArgs extends [infer Only] ? Only : TArgs;
5
- type BaseQueryKey = readonly unknown[];
6
- type QueryOptionOverrides<TArgs extends unknown[], TResult> = Omit<UseQueryOptions<TResult, unknown, TResult, BaseQueryKey>, "queryKey" | "queryFn"> & {
7
- queryKey?: QueryKey;
8
- appendQueryKey?: readonly unknown[];
1
+ import { type DataTag, type DefaultError, type InfiniteData, type MutationFunctionContext, type MutationKey, type QueryFunctionContext, type QueryKey, type UseInfiniteQueryOptions, type UseMutationOptions, type UseQueryOptions } from "@tanstack/react-query";
2
+ type MaybePromise<T> = T | PromiseLike<T>;
3
+ type Api<TArgs extends unknown[], TResult> = (...args: TArgs) => MaybePromise<TResult>;
4
+ export type MutationVariables<TArgs extends unknown[]> = TArgs extends [] ? void : TArgs extends [unknown?] ? TArgs[0] : TArgs;
5
+ type ArgumentOptions<TArgs extends unknown[]> = {
9
6
  args?: TArgs;
10
7
  mapArgs?: (args: TArgs) => TArgs;
11
- queryFn?: (context: {
12
- queryKey: BaseQueryKey;
13
- signal: AbortSignal;
14
- meta: Record<string, unknown> | undefined;
15
- args: TArgs;
16
- }) => MaybePromise<TResult>;
17
8
  };
18
- type MutationOptionOverrides<TArgs extends unknown[], TResult, TVariables = MutationVariables<TArgs>> = Omit<UseMutationOptions<TResult, unknown, TVariables, unknown>, "mutationKey" | "mutationFn"> & {
19
- mutationKey?: QueryKey;
20
- appendMutationKey?: readonly unknown[];
21
- mapVariablesToArgs?: (variables: TVariables) => TArgs;
22
- mutationFn?: (context: {
23
- variables: TVariables;
9
+ export type QueryResult<TResult, TData = TResult> = Omit<UseQueryOptions<TResult, DefaultError, TData>, "queryFn" | "queryKey"> & {
10
+ queryKey: DataTag<QueryKey, TResult, DefaultError>;
11
+ queryFn: (context: QueryFunctionContext) => Promise<TResult>;
12
+ };
13
+ type InitialValue<T> = Exclude<T, undefined> | (() => Exclude<T, undefined>);
14
+ export type DefinedQueryResult<TResult, TData = TResult> = QueryResult<TResult, TData> & {
15
+ initialData: InitialValue<TResult>;
16
+ };
17
+ export type InfiniteResult<TResult, TPageParam, TData = InfiniteData<TResult, TPageParam>> = Omit<UseInfiniteQueryOptions<TResult, DefaultError, TData, QueryKey, TPageParam>, "queryFn" | "queryKey"> & {
18
+ queryKey: DataTag<QueryKey, InfiniteData<TResult>, DefaultError>;
19
+ queryFn: (context: QueryFunctionContext<QueryKey, TPageParam>) => Promise<TResult>;
20
+ };
21
+ export type MutationResult<TResult, TVariables, TOnMutateResult> = UseMutationOptions<TResult, DefaultError, TVariables, TOnMutateResult> & {
22
+ mutationKey: MutationKey;
23
+ mutationFn: (variables: TVariables, context: MutationFunctionContext) => Promise<TResult>;
24
+ };
25
+ export type QueryOptionOverrides<TArgs extends unknown[], TResult, TData = TResult> = Omit<UseQueryOptions<TResult, DefaultError, TData>, "queryKey" | "queryFn"> & ArgumentOptions<TArgs> & {
26
+ queryKey?: QueryKey;
27
+ appendQueryKey?: readonly unknown[];
28
+ queryFn?: (context: QueryFunctionContext & {
24
29
  args: TArgs;
25
30
  }) => MaybePromise<TResult>;
26
31
  };
27
- type InfiniteOptionOverrides<TArgs extends unknown[], TResult, TPageParam = unknown> = Omit<UseInfiniteQueryOptions<TResult, unknown, TResult, BaseQueryKey, TPageParam>, "queryKey" | "queryFn"> & {
32
+ export type InfiniteOptionOverrides<TArgs extends unknown[], TResult, TPageParam, TData = InfiniteData<TResult, TPageParam>> = Omit<UseInfiniteQueryOptions<TResult, DefaultError, TData, QueryKey, TPageParam>, "queryKey" | "queryFn"> & ArgumentOptions<TArgs> & {
28
33
  queryKey?: QueryKey;
29
34
  appendQueryKey?: readonly unknown[];
30
- args?: TArgs;
31
- mapArgs?: (args: TArgs) => TArgs;
32
35
  pageParamToArgs?: (pageParam: TPageParam, args: TArgs) => TArgs;
33
- queryFn?: (context: {
34
- queryKey: BaseQueryKey;
35
- signal: AbortSignal;
36
- meta: Record<string, unknown> | undefined;
37
- pageParam: TPageParam;
38
- direction: unknown;
36
+ queryFn?: (context: QueryFunctionContext<QueryKey, TPageParam> & {
39
37
  args: TArgs;
40
38
  }) => MaybePromise<TResult>;
41
39
  };
42
- interface QueryOptionFactory<TArgs extends unknown[], TResult> {
43
- (...payload: TArgs): UseQueryOptions<TResult, unknown, TResult, BaseQueryKey>;
44
- withOptions: (overrides: QueryOptionOverrides<TArgs, TResult>, ...payload: TArgs) => UseQueryOptions<TResult, unknown, TResult, BaseQueryKey>;
45
- }
46
- interface MutationOptionFactory<TArgs extends unknown[], TResult, TVariables = MutationVariables<TArgs>> {
47
- (): UseMutationOptions<TResult, unknown, TVariables, unknown>;
48
- withOptions: (overrides?: MutationOptionOverrides<TArgs, TResult, TVariables>) => UseMutationOptions<TResult, unknown, TVariables, unknown>;
49
- }
50
- interface MutationOptionConfig<TArgs extends unknown[], TVariables = MutationVariables<TArgs>> {
40
+ export type MutationOptionConfig<TArgs extends unknown[], TVariables> = {
41
+ mapVariablesToArgs: (variables: TVariables) => TArgs;
42
+ variablesMode?: never;
43
+ } | (TArgs extends [unknown?] ? never : TVariables extends TArgs ? {
44
+ variablesMode: "tuple";
45
+ mapVariablesToArgs?: never;
46
+ } : never);
47
+ export type MutationOptionOverrides<TArgs extends unknown[], TResult, TVariables, TOnMutateResult = unknown> = Omit<UseMutationOptions<TResult, DefaultError, TVariables, TOnMutateResult>, "mutationKey" | "mutationFn"> & {
48
+ mutationKey?: MutationKey;
49
+ appendMutationKey?: readonly unknown[];
51
50
  mapVariablesToArgs?: (variables: TVariables) => TArgs;
52
- }
53
- interface InfiniteOptionFactory<TArgs extends unknown[], TResult, TPageParam = unknown> {
54
- (...payload: TArgs): UseInfiniteQueryOptions<TResult, unknown, TResult, BaseQueryKey, TPageParam>;
55
- withOptions: (overrides: InfiniteOptionOverrides<TArgs, TResult, TPageParam>, ...payload: TArgs) => UseInfiniteQueryOptions<TResult, unknown, TResult, BaseQueryKey, TPageParam>;
56
- }
57
- type QueryOptionType = <T extends unknown[], J>(key: readonly unknown[], fn: AnyFn<T, J>) => QueryOptionFactory<T, J>;
58
- type MutationOptionType = <TArgs extends unknown[], TResult, TVariables = MutationVariables<TArgs>>(key: readonly unknown[], fn: AnyFn<TArgs, TResult>, config?: MutationOptionConfig<TArgs, TVariables>) => MutationOptionFactory<TArgs, TResult, TVariables>;
59
- type InfiniteOptionType = <T extends unknown[], K>(key: readonly unknown[], fn: AnyFn<T, K>) => InfiniteOptionFactory<T, K>;
60
- export declare const queryOption: QueryOptionType;
61
- export declare const mutationOption: MutationOptionType;
62
- export declare const infiniteOption: InfiniteOptionType;
51
+ mutationFn?: (context: MutationFunctionContext & {
52
+ variables: TVariables;
53
+ args: TArgs;
54
+ }) => MaybePromise<TResult>;
55
+ };
56
+ export declare function queryOption<TArgs extends unknown[], TResult>(key: QueryKey, fn: Api<TArgs, TResult>): {
57
+ (...payload: TArgs): QueryResult<TResult, TResult>;
58
+ withOptions: {
59
+ <TData = TResult>(overrides: QueryOptionOverrides<TArgs, TResult, TData> & {
60
+ initialData: InitialValue<TResult>;
61
+ }, ...payload: TArgs): DefinedQueryResult<TResult, TData>;
62
+ <TData = TResult>(overrides: QueryOptionOverrides<TArgs, TResult, TData>, ...payload: TArgs): QueryResult<TResult, TData>;
63
+ };
64
+ };
65
+ export declare function mutationOption<TArgs extends unknown[], TResult, TVariables = MutationVariables<TArgs>>(key: MutationKey, fn: Api<TArgs, TResult>, ...configuration: TArgs extends [unknown?] ? [config?: MutationOptionConfig<TArgs, TVariables>] : [config: MutationOptionConfig<TArgs, TVariables>]): {
66
+ (): MutationResult<TResult, TVariables, unknown>;
67
+ withOptions: <TOnMutateResult = unknown>(overrides?: MutationOptionOverrides<TArgs, TResult, TVariables, TOnMutateResult>) => MutationResult<TResult, TVariables, TOnMutateResult>;
68
+ };
69
+ export declare function infiniteOption<TArgs extends unknown[], TResult>(key: QueryKey, fn: Api<TArgs, TResult>): {
70
+ (...payload: TArgs): InfiniteResult<TResult, undefined, InfiniteData<TResult, undefined>>;
71
+ withOptions<TPageParam, TData = InfiniteData<TResult, TPageParam>>(overrides: InfiniteOptionOverrides<TArgs, TResult, TPageParam, TData>, ...payload: TArgs): InfiniteResult<TResult, TPageParam, TData>;
72
+ };
63
73
  export {};
64
- //# sourceMappingURL=query.d.ts.map
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@uiwwsw/react-query-helper",
3
- "version": "1.3.0",
3
+ "version": "2.0.1",
4
4
  "module": "dist/index.js",
5
5
  "type": "module",
6
6
  "types": "dist/index.d.ts",
7
7
  "main": "dist/index.js",
8
8
  "license": "MIT",
9
- "description": "React Query Helper is a CLI tool that automatically generates React Query hooks and option objects from TypeScript API functions.",
9
+ "description": "Generate type-safe TanStack Query v5 option factories from TypeScript API functions.",
10
10
  "keywords": [
11
11
  "react",
12
12
  "react-query",
@@ -28,7 +28,9 @@
28
28
  },
29
29
  "author": "uiwwsw",
30
30
  "files": [
31
- "dist"
31
+ "dist",
32
+ "README_EN.md",
33
+ "CHANGELOG.md"
32
34
  ],
33
35
  "bin": {
34
36
  "react-query-helper": "dist/cli.js"
@@ -38,42 +40,48 @@
38
40
  },
39
41
  "exports": {
40
42
  ".": {
41
- "import": "./dist/index.js",
42
- "types": "./dist/index.d.ts"
43
+ "types": "./dist/index.d.ts",
44
+ "import": "./dist/index.js"
43
45
  },
44
46
  "./config": {
45
- "import": "./dist/config.js",
46
- "types": "./dist/config.d.ts"
47
+ "types": "./dist/config.d.ts",
48
+ "import": "./dist/config.js"
47
49
  },
48
50
  "./core/analyzer": {
49
- "import": "./dist/core/analyzer.js",
50
- "types": "./dist/core/analyzer.d.ts"
51
+ "types": "./dist/core/analyzer.d.ts",
52
+ "import": "./dist/core/analyzer.js"
51
53
  },
52
54
  "./core/generator": {
53
- "import": "./dist/core/generator.js",
54
- "types": "./dist/core/generator.d.ts"
55
+ "types": "./dist/core/generator.d.ts",
56
+ "import": "./dist/core/generator.js"
55
57
  }
56
58
  },
57
59
  "sideEffects": false,
58
60
  "scripts": {
59
- "start": "bun run src/index.ts",
60
- "build": "tsc && bun build src/cli.ts --outdir dist --target node --external typescript --external prettier && bun build src/index.ts --outdir dist --target node --external typescript --external prettier && bun build src/config.ts --outdir dist --target node --external typescript --external prettier && bun build src/core/analyzer.ts --outdir dist/core --target node --external typescript --external prettier && bun build src/core/generator.ts --outdir dist/core --target node --external typescript --external prettier && node scripts/prepend-shebang.cjs dist/cli.js",
61
- "dev": "bun run src/cli.ts --watch",
62
- "generate": "bun run src/cli.ts --generate",
63
- "test": "npm run build && node --test test/**/*.test.mjs"
61
+ "build": "node scripts/build.mjs",
62
+ "dev": "npm run build && node dist/cli.js watch",
63
+ "generate": "npm run build && node dist/cli.js generate",
64
+ "test": "npm run build && node --test test/*.test.mjs && tsc -p test/tsconfig.json && tsc -p test/tsconfig.register.json",
65
+ "prepack": "npm run build",
66
+ "smoke": "node scripts/smoke.mjs"
64
67
  },
65
68
  "devDependencies": {
66
- "@types/bun": "latest",
69
+ "@tanstack/react-query": "^5.102.8",
67
70
  "@types/node": "^24.1.0",
68
- "chokidar": "^4.0.3"
71
+ "@types/picomatch": "^4.0.3",
72
+ "@types/react": "^19.2.18",
73
+ "esbuild": "^0.28.2",
74
+ "react": "^19.2.8"
69
75
  },
70
76
  "peerDependencies": {
71
- "@tanstack/react-query": "^5.83.0"
77
+ "@tanstack/react-query": "^5.102.8"
72
78
  },
73
79
  "dependencies": {
74
- "fs": "^0.0.1-security",
80
+ "jiti": "^2.7.0",
81
+ "picomatch": "^4.0.7",
75
82
  "prettier": "^3.6.2",
76
- "typescript": "^5.8.3"
83
+ "typescript": "^5.8.3",
84
+ "chokidar": "^4.0.3"
77
85
  },
78
86
  "engines": {
79
87
  "node": ">=22"