@7nohe/openapi-react-query-codegen 3.2.1 → 4.0.0-beta.3

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.
Files changed (49) hide show
  1. package/AGENTS.md +22 -19
  2. package/README.md +5 -4
  3. package/dist/cli.d.mts +6 -1
  4. package/dist/client/emitSchemas.d.mts +9 -0
  5. package/dist/client/emitSchemas.mjs +130 -0
  6. package/dist/client/emitSdk.d.mts +18 -0
  7. package/dist/client/emitSdk.mjs +253 -0
  8. package/dist/client/emitTransformers.d.mts +19 -0
  9. package/dist/client/emitTransformers.mjs +556 -0
  10. package/dist/client/emitTypes.d.mts +16 -0
  11. package/dist/client/emitTypes.mjs +204 -0
  12. package/dist/client/index.d.mts +44 -0
  13. package/dist/client/index.mjs +126 -0
  14. package/dist/client/naming.d.mts +41 -0
  15. package/dist/client/naming.mjs +175 -0
  16. package/dist/client/operations.d.mts +103 -0
  17. package/dist/client/operations.mjs +352 -0
  18. package/dist/client/runtime/axios.runtime.ts +706 -0
  19. package/dist/client/runtime/fetch.runtime.ts +795 -0
  20. package/dist/client/schema.d.mts +50 -0
  21. package/dist/client/schema.mjs +648 -0
  22. package/dist/client/spec.d.mts +40 -0
  23. package/dist/client/spec.mjs +387 -0
  24. package/dist/client/tsconfig.d.mts +12 -0
  25. package/dist/client/tsconfig.mjs +152 -0
  26. package/dist/common.d.mts +0 -38
  27. package/dist/common.mjs +0 -87
  28. package/dist/constants.d.mts +0 -2
  29. package/dist/constants.mjs +0 -2
  30. package/dist/createSource.d.mts +8 -7
  31. package/dist/createSource.mjs +14 -17
  32. package/dist/format.mjs +0 -1
  33. package/dist/generate.d.mts +9 -9
  34. package/dist/generate.mjs +45 -107
  35. package/dist/runCli.mjs +7 -2
  36. package/dist/tsmorph/buildQueryHooks.mjs +19 -11
  37. package/dist/tsmorph/generateFiles.mjs +105 -161
  38. package/dist/tsmorph/operationNames.d.mts +2 -13
  39. package/dist/tsmorph/operationNames.mjs +4 -24
  40. package/dist/tsmorph/projectFactory.d.mts +7 -2
  41. package/dist/tsmorph/projectFactory.mjs +16 -9
  42. package/dist/types.d.mts +14 -26
  43. package/package.json +7 -8
  44. package/dist/parseOperations.d.mts +0 -10
  45. package/dist/parseOperations.mjs +0 -164
  46. package/dist/service.d.mts +0 -8
  47. package/dist/service.mjs +0 -98
  48. package/dist/util.d.mts +0 -2
  49. package/dist/util.mjs +0 -16
package/dist/common.mjs CHANGED
@@ -1,31 +1,6 @@
1
1
  import { stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { ArrowFunction, } from "ts-morph";
4
- import ts from "typescript";
5
3
  import { queriesOutputPath, requestsOutputPath } from "./constants.mjs";
6
- export const capitalizeFirstLetter = (str) => {
7
- return str.charAt(0).toUpperCase() + str.slice(1);
8
- };
9
- export const lowercaseFirstLetter = (str) => {
10
- return str.charAt(0).toLowerCase() + str.slice(1);
11
- };
12
- export const getVariableArrowFunctionParameters = (variable) => {
13
- const initializer = variable.getInitializer();
14
- if (!initializer) {
15
- throw new Error("Initializer not found");
16
- }
17
- if (!ArrowFunction.isArrowFunction(initializer)) {
18
- throw new Error("Initializer is not an arrow function");
19
- }
20
- return initializer.getParameters();
21
- };
22
- export const getNameFromVariable = (variable) => {
23
- const variableName = variable.getName();
24
- if (!variableName) {
25
- throw new Error("Variable name not found");
26
- }
27
- return variableName;
28
- };
29
4
  export async function exists(f) {
30
5
  try {
31
6
  await stat(f);
@@ -35,16 +10,6 @@ export async function exists(f) {
35
10
  return false;
36
11
  }
37
12
  }
38
- const Common = "Common";
39
- /**
40
- * Build a common type name by prepending the Common namespace.
41
- */
42
- export function BuildCommonTypeName(name) {
43
- if (typeof name === "string") {
44
- return ts.factory.createIdentifier(`${Common}.${name}`);
45
- }
46
- return ts.factory.createIdentifier(`${Common}.${name.text}`);
47
- }
48
13
  /**
49
14
  * Safely parse a value into a number. Checks for NaN and Infinity.
50
15
  * Returns NaN if the string is not a valid number.
@@ -64,58 +29,6 @@ export function safeParseNumber(value) {
64
29
  }
65
30
  return Number.NaN;
66
31
  }
67
- export function extractPropertiesFromObjectParam(param) {
68
- const referenced = param.findReferences()[0];
69
- const def = referenced.getDefinition();
70
- const paramNodes = def
71
- .getNode()
72
- .getType()
73
- .getProperties()
74
- .filter((prop) => prop.getValueDeclaration()?.getType())
75
- .map((prop) => {
76
- return {
77
- name: prop.getName(),
78
- optional: prop.isOptional(),
79
- type: prop.getValueDeclaration()?.getType(),
80
- };
81
- });
82
- return paramNodes;
83
- }
84
- /**
85
- * Replace the import("...") surrounding the type if there is one.
86
- * This can happen when the type is imported from another file, but
87
- * we are already importing all the types from that file.
88
- *
89
- * https://regex101.com/r/3DyHaQ/1
90
- *
91
- * TODO: Replace with a more robust solution.
92
- */
93
- export function getShortType(type) {
94
- return type.replaceAll(/import\(".*?"\)\./g, "");
95
- }
96
- export function getClassesFromService(node) {
97
- const klasses = node.getClasses();
98
- if (!klasses.length) {
99
- throw new Error("No classes found");
100
- }
101
- return klasses.map((klass) => {
102
- const className = klass.getName();
103
- if (!className) {
104
- throw new Error("Class name not found");
105
- }
106
- return {
107
- className,
108
- klass,
109
- };
110
- });
111
- }
112
- export function getClassNameFromClassNode(klass) {
113
- const className = klass.getName();
114
- if (!className) {
115
- throw new Error("Class name not found");
116
- }
117
- return className;
118
- }
119
32
  export function formatOptions(options) {
120
33
  // loop through properties on the options object
121
34
  // if the property is a string of number then convert it to a number
@@ -1,8 +1,6 @@
1
1
  export declare const defaultOutputPath = "openapi";
2
2
  export declare const queriesOutputPath = "queries";
3
3
  export declare const requestsOutputPath = "requests";
4
- export declare const serviceFileName = "sdk.gen";
5
- export declare const modelsFileName = "types.gen";
6
4
  export declare const OpenApiRqFiles: {
7
5
  readonly queries: "queries";
8
6
  readonly queryOptions: "queryOptions";
@@ -1,8 +1,6 @@
1
1
  export const defaultOutputPath = "openapi";
2
2
  export const queriesOutputPath = "queries";
3
3
  export const requestsOutputPath = "requests";
4
- export const serviceFileName = "sdk.gen";
5
- export const modelsFileName = "types.gen";
6
4
  export const OpenApiRqFiles = {
7
5
  queries: "queries",
8
6
  queryOptions: "queryOptions",
@@ -1,15 +1,16 @@
1
+ import type { ClientKind, GeneratedClient } from "./client/index.mjs";
1
2
  import type { GeneratedFile } from "./types.mjs";
2
- type ClientType = "@hey-api/client-fetch" | "@hey-api/client-axios";
3
3
  /**
4
- * Create source files using ts-morph based generation.
4
+ * Create the React Query source files for a generated client.
5
5
  */
6
- export declare const createSource: ({ outputPath, client, version, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, }: {
7
- outputPath: string;
8
- client: ClientType;
6
+ export declare const createSource: ({ generated, client, version, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, importExtension, }: {
7
+ generated: Pick<GeneratedClient, "operations" | "modelNames" | "serviceNames">;
8
+ client: ClientKind;
9
9
  version: string;
10
10
  pageParam: string;
11
11
  nextPageParam: string;
12
12
  initialPageParam: string;
13
13
  omitInitialPageParam: boolean;
14
- }) => Promise<GeneratedFile[]>;
15
- export {};
14
+ /** Extension of the relative imports; see `detectImportExtension`. */
15
+ importExtension?: "" | ".js";
16
+ }) => GeneratedFile[];
@@ -1,21 +1,18 @@
1
- import { resolve } from "node:path";
2
- import { Project } from "ts-morph";
3
- import { buildGenerationContext, parseOperations } from "./parseOperations.mjs";
4
1
  import { generateAllFiles } from "./tsmorph/index.mjs";
5
2
  /**
6
- * Create source files using ts-morph based generation.
3
+ * Create the React Query source files for a generated client.
7
4
  */
8
- export const createSource = async ({ outputPath, client, version, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, }) => {
9
- // Initialize ts-morph project to read the generated OpenAPI client
10
- const project = new Project({
11
- skipAddingFilesFromTsConfig: true,
12
- });
13
- const sourceFiles = resolve(process.cwd(), outputPath);
14
- project.addSourceFilesAtPaths(`${sourceFiles}/**/*`);
15
- // Parse operations from the service file
16
- const operations = await parseOperations(project, pageParam);
17
- // Build generation context
18
- const ctx = buildGenerationContext(project, client, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, version);
19
- // Generate all files using ts-morph
20
- return generateAllFiles(operations, ctx);
5
+ export const createSource = ({ generated, client, version, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, importExtension = "", }) => {
6
+ const ctx = {
7
+ client,
8
+ modelNames: generated.modelNames,
9
+ serviceNames: generated.serviceNames,
10
+ pageParam,
11
+ nextPageParam,
12
+ initialPageParam,
13
+ omitInitialPageParam,
14
+ version,
15
+ importExtension,
16
+ };
17
+ return generateAllFiles(generated.operations, ctx);
21
18
  };
package/dist/format.mjs CHANGED
@@ -14,7 +14,6 @@ export const formatOutput = async (outputPath) => {
14
14
  const sourceFiles = project.addSourceFilesAtPaths(`${outputPath}/**/*`);
15
15
  const tasks = sourceFiles.map((sourceFile) => {
16
16
  sourceFile.formatText();
17
- sourceFile.fixMissingImports();
18
17
  sourceFile.organizeImports();
19
18
  return sourceFile.save();
20
19
  });
@@ -1,19 +1,19 @@
1
- import type { LimitedUserConfig } from "./cli.mjs";
1
+ import type { ClientChoice, LimitedUserConfig } from "./cli.mjs";
2
+ import { type ClientKind, findNearestTsConfigPath } from "./client/index.mjs";
2
3
  import { CodegenError } from "./errors.mjs";
3
- export declare function findNearestTsConfigPath(startDir: string): string | undefined;
4
+ export { findNearestTsConfigPath };
5
+ /** Map a `--client` value (including the v3 `@hey-api/*` aliases) to a kind. */
6
+ export declare function resolveClientKind(client: ClientChoice | undefined): ClientKind;
4
7
  export type GenerateRuntimeOptions = {
5
8
  /**
6
- * Silence @hey-api/openapi-ts logs and stop it from writing crash-report
7
- * files into cwd. Used by `--json` (stderr must carry only our JSON) and
8
- * by `--check` (which must leave nothing behind).
9
+ * Keep the generator's warnings off stderr. Used by `--json` (stderr must
10
+ * carry only our JSON) and by `--check`.
9
11
  */
10
12
  silent?: boolean;
11
13
  };
12
14
  /**
13
- * Translate @hey-api/openapi-ts failures into our stable error codes.
14
- * hey-api's error classes live in a transitive dependency, so they are
15
- * matched by name rather than imported. This is the only place that knows
16
- * about them (see the IR boundary notes in AGENTS.md).
15
+ * Translate a failure of the client generator into our stable error codes.
16
+ * This is the only place that knows how `src/client/` reports them.
17
17
  */
18
18
  export declare function mapClientError(error: unknown, input: unknown): CodegenError;
19
19
  /**
package/dist/generate.mjs CHANGED
@@ -1,29 +1,18 @@
1
- import { readdirSync } from "node:fs";
2
- import { readFile, writeFile } from "node:fs/promises";
3
- import path from "node:path";
4
- import { createClient } from "@hey-api/openapi-ts";
1
+ import { detectImportExtension, findNearestTsConfigPath, generateClient, SpecError, writeGeneratedFiles, } from "./client/index.mjs";
5
2
  import { buildQueriesOutputPath, buildRequestsOutputPath, formatOptions, } from "./common.mjs";
6
3
  import { createSource } from "./createSource.mjs";
7
4
  import { CodegenError, ErrorCodes, toCodegenError } from "./errors.mjs";
8
5
  import { formatOutput, processOutput } from "./format.mjs";
9
6
  import { print } from "./print.mjs";
10
- // openapi-ts's own tsconfig auto-detection walks up from its *install*
11
- // location, which in this monorepo reaches this repo's own root tsconfig
12
- // (NodeNext) instead of the caller's project config. Anchoring the search
13
- // at cwd instead finds the tsconfig that actually applies to the generated
14
- // output, matching the resolution the caller's own `tsc` will use.
15
- export function findNearestTsConfigPath(startDir) {
16
- let dir = startDir;
17
- while (true) {
18
- const candidates = readdirSync(dir).filter((file) => file.startsWith("tsconfig") && file.endsWith(".json"));
19
- if (candidates.length > 0) {
20
- candidates.sort((a) => (a === "tsconfig.json" ? -1 : 1));
21
- return path.join(dir, candidates[0]);
22
- }
23
- const parent = path.dirname(dir);
24
- if (parent === dir)
25
- return undefined;
26
- dir = parent;
7
+ export { findNearestTsConfigPath };
8
+ /** Map a `--client` value (including the v3 `@hey-api/*` aliases) to a kind. */
9
+ export function resolveClientKind(client) {
10
+ switch (client) {
11
+ case "axios":
12
+ case "@hey-api/client-axios":
13
+ return "axios";
14
+ default:
15
+ return "fetch";
27
16
  }
28
17
  }
29
18
  /** Keep inline spec content out of error details; it can be huge. */
@@ -34,115 +23,64 @@ function describeInput(input) {
34
23
  return "(inline specification)";
35
24
  }
36
25
  /**
37
- * Translate @hey-api/openapi-ts failures into our stable error codes.
38
- * hey-api's error classes live in a transitive dependency, so they are
39
- * matched by name rather than imported. This is the only place that knows
40
- * about them (see the IR boundary notes in AGENTS.md).
26
+ * Translate a failure of the client generator into our stable error codes.
27
+ * This is the only place that knows how `src/client/` reports them.
41
28
  */
42
29
  export function mapClientError(error, input) {
43
30
  if (error instanceof CodegenError) {
44
31
  return error;
45
32
  }
46
33
  const inputDescription = describeInput(input);
47
- const err = error;
48
- const original = err?.originalError?.error;
49
- const reason = original?.message ?? err?.message ?? String(error);
50
- if (err?.name === "InputError") {
51
- return new CodegenError(ErrorCodes.inputNotFound, `OpenAPI input could not be read: ${inputDescription}`, { input: inputDescription, reason }, { cause: error });
34
+ const reason = error instanceof Error ? error.message : String(error);
35
+ if (error instanceof SpecError) {
36
+ return error.reason === "not-found"
37
+ ? new CodegenError(ErrorCodes.inputNotFound, `OpenAPI input could not be read: ${inputDescription}`, { input: inputDescription, reason }, { cause: error })
38
+ : new CodegenError(ErrorCodes.inputParseError, `OpenAPI input could not be parsed: ${inputDescription}`, { input: inputDescription, reason }, { cause: error });
52
39
  }
53
- if (err?.name === "JobError" && original?.code === "EPARSER") {
54
- return new CodegenError(ErrorCodes.inputParseError, `OpenAPI input could not be parsed: ${inputDescription}`, { input: inputDescription, reason }, { cause: error });
55
- }
56
- return new CodegenError(ErrorCodes.clientGenerationFailed, `@hey-api/openapi-ts failed to generate the client: ${reason}`, { input: inputDescription, reason, name: err?.name ?? "Error" }, { cause: error });
40
+ return new CodegenError(ErrorCodes.clientGenerationFailed, `The client could not be generated: ${reason}`, {
41
+ input: inputDescription,
42
+ reason,
43
+ name: error instanceof Error ? error.name : "Error",
44
+ }, { cause: error });
57
45
  }
58
46
  async function runGenerate(options, version, runtime) {
59
47
  const openApiOutputPath = buildRequestsOutputPath(options.output);
60
48
  const formattedOptions = formatOptions(options);
61
- // Map CLI options to new plugins system
62
- const clientPlugin = formattedOptions.client === "@hey-api/client-axios"
63
- ? "@hey-api/client-axios"
64
- : "@hey-api/client-fetch";
65
- const typescriptPlugin = formattedOptions.enums
66
- ? {
67
- name: "@hey-api/typescript",
49
+ const client = resolveClientKind(formattedOptions.client);
50
+ // One answer for both directories: the queries import the requests.
51
+ const importExtension = detectImportExtension(process.cwd());
52
+ let generated;
53
+ try {
54
+ generated = await generateClient({
55
+ input: formattedOptions.input,
56
+ client,
68
57
  enums: formattedOptions.enums,
69
- }
70
- : "@hey-api/typescript";
71
- const sdkPlugin = {
72
- name: "@hey-api/sdk",
73
- ...(formattedOptions.noOperationId
74
- ? {
75
- // `operationId: false` was deprecated in favor of `operations.nesting`
76
- operations: {
77
- nesting: "id",
78
- },
79
- }
80
- : {}),
81
- ...(formattedOptions.useDateType
82
- ? { transformer: "@hey-api/transformers" }
83
- : {}),
84
- };
85
- const plugins = [
86
- clientPlugin,
87
- typescriptPlugin,
88
- sdkPlugin,
89
- ];
90
- if (formattedOptions.useDateType) {
91
- plugins.push({
92
- name: "@hey-api/transformers",
93
- dates: "date",
58
+ importExtension,
59
+ noOperationId: formattedOptions.noOperationId,
60
+ pageParam: formattedOptions.pageParam,
61
+ schemas: formattedOptions.noSchemas
62
+ ? false
63
+ : (formattedOptions.schemaType ?? "json"),
64
+ useDateType: formattedOptions.useDateType,
94
65
  });
95
66
  }
96
- // Conditionally add schemas plugin
97
- if (!formattedOptions.noSchemas) {
98
- plugins.push(formattedOptions.schemaType
99
- ? {
100
- name: "@hey-api/schemas",
101
- type: formattedOptions.schemaType,
102
- }
103
- : "@hey-api/schemas");
104
- }
105
- const config = {
106
- dryRun: false,
107
- input: formattedOptions.input,
108
- output: {
109
- path: openApiOutputPath,
110
- tsConfigPath: findNearestTsConfigPath(process.cwd()) ?? null,
111
- },
112
- plugins,
113
- ...(runtime.silent
114
- ? { logs: { level: "silent", file: false } }
115
- : {}),
116
- };
117
- let contexts;
118
- try {
119
- contexts = await createClient(config);
120
- }
121
67
  catch (error) {
122
68
  throw mapClientError(error, formattedOptions.input);
123
69
  }
124
- // openapi-ts swallows input errors (file not found, HTTP failure), logs
125
- // them and resolves with no contexts instead of throwing.
126
- if (contexts.length === 0) {
127
- const inputDescription = describeInput(formattedOptions.input);
128
- throw new CodegenError(ErrorCodes.inputNotFound, `OpenAPI input could not be read (file not found or request failed): ${inputDescription}`, { input: inputDescription });
70
+ if (!runtime.silent) {
71
+ for (const warning of generated.warnings)
72
+ console.warn(warning);
129
73
  }
130
- // Generate backward-compatible services.gen.ts shim
131
- // client.gen.ts has the `client` instance; sdk.gen.ts has SDK functions.
132
- // Mirror whatever extension convention openapi-ts used for its own
133
- // cross-file imports (e.g. `.js` for NodeNext, none for bundler resolution).
134
- const sdkGenContent = await readFile(path.join(openApiOutputPath, "sdk.gen.ts"), "utf-8");
135
- const importExtension = sdkGenContent.match(/from ['"]\.\/client\.gen(\.\S*)?['"]/)?.[1] ?? "";
136
- const shimContent = `// This file is auto-generated for backward compatibility\nexport * from './client.gen${importExtension}';\nexport * from './sdk.gen${importExtension}';\n`;
137
- await writeFile(path.join(openApiOutputPath, "services.gen.ts"), shimContent);
138
- const source = await createSource({
139
- outputPath: openApiOutputPath,
140
- client: clientPlugin,
74
+ await writeGeneratedFiles(openApiOutputPath, generated.files);
75
+ const source = createSource({
76
+ generated,
77
+ client,
141
78
  version,
142
79
  pageParam: formattedOptions.pageParam,
143
80
  nextPageParam: formattedOptions.nextPageParam,
144
81
  initialPageParam: formattedOptions.initialPageParam.toString(),
145
82
  omitInitialPageParam: formattedOptions.omitInitialPageParam ?? false,
83
+ importExtension,
146
84
  });
147
85
  await print(source, formattedOptions);
148
86
  const queriesOutputPath = buildQueriesOutputPath(options.output);
package/dist/runCli.mjs CHANGED
@@ -26,8 +26,13 @@ export function buildProgram(version, io, { json }) {
26
26
  .requiredOption("-i, --input <value>", "OpenAPI specification, can be a path, url or string content (required)")
27
27
  .option("-o, --output <value>", "Output directory", defaultOutputPath)
28
28
  .addOption(new Option("-c, --client <value>", "HTTP client to generate")
29
- .choices(["@hey-api/client-fetch", "@hey-api/client-axios"])
30
- .default("@hey-api/client-fetch"))
29
+ .choices([
30
+ "fetch",
31
+ "axios",
32
+ "@hey-api/client-fetch",
33
+ "@hey-api/client-axios",
34
+ ])
35
+ .default("fetch"))
31
36
  .addOption(new Option("--format <value>", "Process output folder with formatter?").choices(["biome", "prettier"]))
32
37
  .addOption(new Option("--lint <value>", "Process output folder with linter?").choices(["biome", "eslint"]))
33
38
  .option("--noOperationId", "Do not use operationId to generate operation names")
@@ -1,4 +1,5 @@
1
1
  import { StructureKind, VariableDeclarationKind, } from "ts-morph";
2
+ import { isValidIdentifier, propertyKey } from "../client/naming.mjs";
2
3
  import { getDataTypeName, getErrorType } from "./operationNames.mjs";
3
4
  /**
4
5
  * SDK call arguments shared by every generated queryFn/mutationFn.
@@ -17,13 +18,8 @@ export function getPageParamType(op) {
17
18
  * Build the client options parameter string.
18
19
  */
19
20
  export function buildClientOptionsParam(op) {
20
- const dataTypeName = getDataTypeName(op);
21
- const hasParams = op.parameters.length > 0;
22
- if (!hasParams) {
23
- return `clientOptions: Options<${dataTypeName}, true> = {}`;
24
- }
25
21
  const defaultValue = op.allParamsOptional ? " = {}" : "";
26
- return `clientOptions: Options<${dataTypeName}, true>${defaultValue}`;
22
+ return `clientOptions: Options<${getDataTypeName(op)}, true>${defaultValue}`;
27
23
  }
28
24
  /**
29
25
  * Build the clientOptions parameter typed with the page-less infinite
@@ -56,9 +52,10 @@ export function buildPagedQueryFn(op, ctx) {
56
52
  const pageParamType = getPageParamType(op);
57
53
  // When the initial page param is omitted, the first request must send no
58
54
  // page param at all, so spread it in only once TanStack Query provides one.
55
+ const pageKey = propertyKey(ctx.pageParam);
59
56
  const pageQuery = ctx.omitInitialPageParam
60
- ? `...(pageParam === undefined ? {} : { ${ctx.pageParam}: pageParam as ${pageParamType} })`
61
- : `${ctx.pageParam}: pageParam as ${pageParamType}`;
57
+ ? `...(pageParam === undefined ? {} : { ${pageKey}: pageParam as ${pageParamType} })`
58
+ : `${pageKey}: pageParam as ${pageParamType}`;
62
59
  return `({ pageParam, signal }) => ${op.methodName}({ ...clientOptions, query: { ...clientOptions.query, ${pageQuery} }, signal, throwOnError: true } as Options<${dataTypeName}, true>)${thenClause}`;
63
60
  }
64
61
  /**
@@ -78,7 +75,8 @@ export function formatInitialPageParam(ctx, op) {
78
75
  if (isStringPageParam) {
79
76
  return JSON.stringify(ctx.initialPageParam);
80
77
  }
81
- return /^-?\d+$/.test(ctx.initialPageParam)
78
+ // `001` would be an octal literal, which TypeScript rejects.
79
+ return /^-?(0|[1-9]\d*)$/.test(ctx.initialPageParam)
82
80
  ? ctx.initialPageParam
83
81
  : JSON.stringify(ctx.initialPageParam);
84
82
  }
@@ -89,7 +87,7 @@ export function formatInitialPageParam(ctx, op) {
89
87
  export function buildNestedNextPageType(nextPageParam, pageParamType = "number") {
90
88
  const segments = nextPageParam.split(".");
91
89
  return segments.reduceRight((acc, segment) => {
92
- return `{ ${segment}: ${acc} }`;
90
+ return `{ ${propertyKey(segment)}: ${acc} }`;
93
91
  }, pageParamType);
94
92
  }
95
93
  /**
@@ -99,7 +97,17 @@ export function buildNestedNextPageType(nextPageParam, pageParamType = "number")
99
97
  */
100
98
  export function buildGetNextPageParamExpr(ctx, op) {
101
99
  const nestedType = buildNestedNextPageType(ctx.nextPageParam, op ? getPageParamType(op) : "number");
102
- return `(response: unknown) => (response as ${nestedType}).${ctx.nextPageParam}`;
100
+ const access = ctx.nextPageParam
101
+ .split(".")
102
+ .map((segment, index) => {
103
+ // The last page can leave out what holds the next one, or set it to null.
104
+ const optional = index > 0 ? "?." : "";
105
+ return isValidIdentifier(segment)
106
+ ? `${optional || "."}${segment}`
107
+ : `${optional}[${JSON.stringify(segment)}]`;
108
+ })
109
+ .join("");
110
+ return `(response: unknown) => (response as ${nestedType})${access}`;
103
111
  }
104
112
  /**
105
113
  * Build an options type where the pagination fields TanStack Query marks as