@povio/openapi-codegen-cli 2.0.8-rc.17 → 2.0.8-rc.19

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.
package/dist/acl.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { r as ErrorHandler } from "./error-handling-p69GkKGP.mjs";
1
+ import { r as ErrorHandler } from "./error-handling-CXeVTk1T.mjs";
2
2
  import * as react from "react";
3
3
  import { PropsWithChildren } from "react";
4
4
  import * as react_jsx_runtime0 from "react/jsx-runtime";
package/dist/acl.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { a as SharedErrorHandler, n as OpenApiRouter, t as AuthContext } from "./auth.context-HV1I5QMx.mjs";
1
+ import { r as SharedErrorHandler } from "./error-handling-DkPY7Asf.mjs";
2
+ import { n as OpenApiRouter, t as AuthContext } from "./auth.context-Bu5KW2sI.mjs";
2
3
  import { createContext, useCallback, useEffect, useState } from "react";
3
4
  import { jsx } from "react/jsx-runtime";
4
5
  import { AbilityBuilder, createMongoAbility } from "@casl/ability";
@@ -0,0 +1,59 @@
1
+ import { createContext, use, useMemo } from "react";
2
+ import { jsx } from "react/jsx-runtime";
3
+
4
+ //#region src/lib/config/router.context.tsx
5
+ let OpenApiRouter;
6
+ (function(_OpenApiRouter) {
7
+ const Context = createContext(null);
8
+ _OpenApiRouter.Provider = ({ children, replace }) => {
9
+ return /* @__PURE__ */ jsx(Context, {
10
+ value: useMemo(() => ({ replace }), [replace]),
11
+ children
12
+ });
13
+ };
14
+ _OpenApiRouter.useRouter = () => {
15
+ const context = use(Context);
16
+ if (!context) throw new Error("useRouter must be used within an OpenApiRouter.Provider");
17
+ return context;
18
+ };
19
+ })(OpenApiRouter || (OpenApiRouter = {}));
20
+
21
+ //#endregion
22
+ //#region src/lib/auth/auth.context.tsx
23
+ let AuthContext;
24
+ (function(_AuthContext) {
25
+ const Context = createContext({});
26
+ _AuthContext.Provider = ({ isAuthenticated, isInitializing, logout, updateTokens, accessToken, user, userPromise, routes, loadingState, children }) => {
27
+ const value = useMemo(() => ({
28
+ isAuthenticated,
29
+ isInitializing,
30
+ logout,
31
+ updateTokens,
32
+ accessToken,
33
+ user,
34
+ userPromise,
35
+ routes,
36
+ loadingState
37
+ }), [
38
+ isAuthenticated,
39
+ isInitializing,
40
+ logout,
41
+ updateTokens,
42
+ accessToken,
43
+ user,
44
+ userPromise,
45
+ routes,
46
+ loadingState
47
+ ]);
48
+ return /* @__PURE__ */ jsx(Context.Provider, {
49
+ value,
50
+ children
51
+ });
52
+ };
53
+ _AuthContext.useAuth = () => {
54
+ return use(Context);
55
+ };
56
+ })(AuthContext || (AuthContext = {}));
57
+
58
+ //#endregion
59
+ export { OpenApiRouter as n, AuthContext as t };
@@ -1,4 +1,4 @@
1
- import { t as GenerateOptions } from "./options-Bvmh6rai.mjs";
1
+ import { t as GenerateOptions } from "./options-DmUw8IYE.mjs";
2
2
 
3
3
  //#region src/generators/types/config.d.ts
4
4
  type OpenAPICodegenConfig = Partial<GenerateOptions>;
@@ -1,8 +1,6 @@
1
1
  import { isAxiosError, isCancel } from "axios";
2
2
  import { z } from "zod";
3
3
  import i18next from "i18next";
4
- import { createContext, use, useMemo } from "react";
5
- import { jsx } from "react/jsx-runtime";
6
4
 
7
5
  //#region src/lib/assets/locales/en/translation.json
8
6
  var translation_default$1 = { openapi: { "sharedErrors": {
@@ -186,59 +184,4 @@ var ErrorHandler = class {
186
184
  const SharedErrorHandler = new ErrorHandler({ entries: [] });
187
185
 
188
186
  //#endregion
189
- //#region src/lib/config/router.context.tsx
190
- let OpenApiRouter;
191
- (function(_OpenApiRouter) {
192
- const Context = createContext(null);
193
- _OpenApiRouter.Provider = ({ children, replace }) => {
194
- return /* @__PURE__ */ jsx(Context, {
195
- value: useMemo(() => ({ replace }), [replace]),
196
- children
197
- });
198
- };
199
- _OpenApiRouter.useRouter = () => {
200
- const context = use(Context);
201
- if (!context) throw new Error("useRouter must be used within an OpenApiRouter.Provider");
202
- return context;
203
- };
204
- })(OpenApiRouter || (OpenApiRouter = {}));
205
-
206
- //#endregion
207
- //#region src/lib/auth/auth.context.tsx
208
- let AuthContext;
209
- (function(_AuthContext) {
210
- const Context = createContext({});
211
- _AuthContext.Provider = ({ isAuthenticated, isInitializing, logout, updateTokens, accessToken, user, userPromise, routes, loadingState, children }) => {
212
- const value = useMemo(() => ({
213
- isAuthenticated,
214
- isInitializing,
215
- logout,
216
- updateTokens,
217
- accessToken,
218
- user,
219
- userPromise,
220
- routes,
221
- loadingState
222
- }), [
223
- isAuthenticated,
224
- isInitializing,
225
- logout,
226
- updateTokens,
227
- accessToken,
228
- user,
229
- userPromise,
230
- routes,
231
- loadingState
232
- ]);
233
- return /* @__PURE__ */ jsx(Context.Provider, {
234
- value,
235
- children
236
- });
237
- };
238
- _AuthContext.useAuth = () => {
239
- return use(Context);
240
- };
241
- })(AuthContext || (AuthContext = {}));
242
-
243
- //#endregion
244
- export { SharedErrorHandler as a, resources as c, ErrorHandler as i, OpenApiRouter as n, RestUtils as o, ApplicationException as r, ns as s, AuthContext as t };
187
+ export { ns as a, RestUtils as i, ErrorHandler as n, resources as o, SharedErrorHandler as r, ApplicationException as t };
@@ -1,4 +1,4 @@
1
- import { a as deepMerge, p as DEFAULT_GENERATE_OPTIONS, r as writeGenerateFileData, t as generateCodeFromOpenAPIDoc, x as Profiler } from "./generateCodeFromOpenAPIDoc-CV_esDUW.mjs";
1
+ import { a as deepMerge, p as DEFAULT_GENERATE_OPTIONS, r as writeGenerateFileData, t as generateCodeFromOpenAPIDoc, x as Profiler } from "./generateCodeFromOpenAPIDoc-BP7F6YJP.mjs";
2
2
  import fs from "fs";
3
3
  import path from "path";
4
4
  import SwaggerParser from "@apidevtools/swagger-parser";
@@ -2,7 +2,6 @@ import fs from "fs";
2
2
  import { match } from "ts-pattern";
3
3
  import { OpenAPIV3 } from "openapi-types";
4
4
  import path from "path";
5
- import { fileURLToPath } from "url";
6
5
 
7
6
  //#region src/generators/const/validation.const.ts
8
7
  const HTTP_STATUS_CODES = {
@@ -466,6 +465,7 @@ function groupByType(validationErrors) {
466
465
  //#region src/generators/const/package.const.ts
467
466
  const PACKAGE_IMPORT_PATH = "@povio/openapi-codegen-cli";
468
467
  const ACL_PACKAGE_IMPORT_PATH = "@povio/openapi-codegen-cli/acl";
468
+ const ZOD_PACKAGE_IMPORT_PATH = "@povio/openapi-codegen-cli/zod";
469
469
 
470
470
  //#endregion
471
471
  //#region src/generators/const/deps.const.ts
@@ -502,14 +502,6 @@ const MUTATION_EFFECTS = {
502
502
  hookName: "useMutationEffects",
503
503
  runFunctionName: "runMutationEffects"
504
504
  };
505
- const MUTATION_EFFECTS_FILE = {
506
- fileName: "useMutationEffects",
507
- extension: "ts"
508
- };
509
- const CROSS_TAB_QUERY_INVALIDATION_FILE = {
510
- fileName: "useCrossTabQueryInvalidation",
511
- extension: "ts"
512
- };
513
505
  const ZOD_EXTENDED = {
514
506
  namespace: "ZodExtended",
515
507
  exports: {
@@ -517,10 +509,6 @@ const ZOD_EXTENDED = {
517
509
  sortExp: "sortExp"
518
510
  }
519
511
  };
520
- const ZOD_EXTENDED_FILE = {
521
- fileName: "zod.extended",
522
- extension: "ts"
523
- };
524
512
 
525
513
  //#endregion
526
514
  //#region src/generators/utils/zod-schema.utils.ts
@@ -1061,12 +1049,6 @@ function getQueryModulesImportPath(options) {
1061
1049
  function getQueryTypesImportPath(options) {
1062
1050
  return options.queryTypesImportPath;
1063
1051
  }
1064
- function getMutationEffectsImportPath(options) {
1065
- return `${getImportPath(options)}${MUTATION_EFFECTS_FILE.fileName}`;
1066
- }
1067
- function getZodExtendedImportPath(options) {
1068
- return `${getImportPath(options)}${ZOD_EXTENDED_FILE.fileName}`;
1069
- }
1070
1052
 
1071
1053
  //#endregion
1072
1054
  //#region src/generators/utils/ts.utils.ts
@@ -3035,19 +3017,6 @@ function getTagElement(tag, data) {
3035
3017
 
3036
3018
  //#endregion
3037
3019
  //#region src/generators/utils/file.utils.ts
3038
- function readFileSync(filePath) {
3039
- const moduleDir = path.dirname(fileURLToPath(import.meta.url));
3040
- const candidates = [
3041
- path.resolve(process.cwd(), filePath),
3042
- path.resolve(moduleDir, "../../../", filePath),
3043
- path.resolve(moduleDir, "../", filePath)
3044
- ];
3045
- for (const candidatePath of candidates) if (fs.existsSync(candidatePath)) return fs.readFileSync(candidatePath, "utf-8");
3046
- throw new Error(`Cannot read file: ${filePath}`);
3047
- }
3048
- function readAssetSync(fileName) {
3049
- return readFileSync(`src/assets/${fileName}`);
3050
- }
3051
3020
  function getOutputFileName({ output, fileName }) {
3052
3021
  return `${output}/${fileName}`;
3053
3022
  }
@@ -3081,8 +3050,8 @@ function generateAcl({ resolver, data, tag }) {
3081
3050
  from: CASL_ABILITY_IMPORT.from
3082
3051
  };
3083
3052
  const lines = [];
3084
- lines.push(renderImport$5(caslAbilityTupleImport));
3085
- for (const modelsImport of modelsImports) lines.push(renderImport$5(modelsImport));
3053
+ lines.push(renderImport$4(caslAbilityTupleImport));
3054
+ for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
3086
3055
  lines.push("");
3087
3056
  if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3088
3057
  type: GenerateType.Acl,
@@ -3111,8 +3080,8 @@ function generateAppAcl({ resolver, data }) {
3111
3080
  from: CASL_ABILITY_IMPORT.from
3112
3081
  };
3113
3082
  const lines = [];
3114
- lines.push(renderImport$5(caslAbilityTupleImport));
3115
- for (const modelsImport of modelsImports) lines.push(renderImport$5(modelsImport));
3083
+ lines.push(renderImport$4(caslAbilityTupleImport));
3084
+ for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
3116
3085
  lines.push("");
3117
3086
  if (appAbilitiesType) {
3118
3087
  lines.push(`export type ${ACL_APP_ABILITIES} = `);
@@ -3122,7 +3091,7 @@ function generateAppAcl({ resolver, data }) {
3122
3091
  lines.push(`export type AppAbility = PureAbility<${ACL_APP_ABILITIES}>;`);
3123
3092
  return lines.join("\n");
3124
3093
  }
3125
- function renderImport$5(importData) {
3094
+ function renderImport$4(importData) {
3126
3095
  return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
3127
3096
  }
3128
3097
  function renderAbilityFunction(endpoint) {
@@ -3378,12 +3347,12 @@ function generateConfigs(generateTypeParams) {
3378
3347
  from: resolver.options.dynamicColumnsImportPath
3379
3348
  };
3380
3349
  const lines = [];
3381
- if (hasZodImport) lines.push(renderImport$4(ZOD_IMPORT));
3382
- if (hasDynamicInputsImport) lines.push(renderImport$4(dynamicInputsImport));
3383
- if (hasDynamicColumnsImport) lines.push(renderImport$4(dynamicColumnsImport));
3384
- for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
3385
- for (const queriesImport of queriesImports) lines.push(renderImport$4(queriesImport));
3386
- for (const aclImport of aclImports) lines.push(renderImport$4(aclImport));
3350
+ if (hasZodImport) lines.push(renderImport$3(ZOD_IMPORT));
3351
+ if (hasDynamicInputsImport) lines.push(renderImport$3(dynamicInputsImport));
3352
+ if (hasDynamicColumnsImport) lines.push(renderImport$3(dynamicColumnsImport));
3353
+ for (const modelsImport of modelsImports) lines.push(renderImport$3(modelsImport));
3354
+ for (const queriesImport of queriesImports) lines.push(renderImport$3(queriesImport));
3355
+ for (const aclImport of aclImports) lines.push(renderImport$3(aclImport));
3387
3356
  lines.push("");
3388
3357
  if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3389
3358
  type: GenerateType.Configs,
@@ -3397,7 +3366,7 @@ function generateConfigs(generateTypeParams) {
3397
3366
  if (resolver.options.tsNamespaces) lines.push("}");
3398
3367
  return lines.join("\n").trimEnd() + "\n";
3399
3368
  }
3400
- function renderImport$4(importData) {
3369
+ function renderImport$3(importData) {
3401
3370
  return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
3402
3371
  }
3403
3372
  function renderInputsConfig(inputsConfig) {
@@ -3501,7 +3470,7 @@ function generateEndpoints({ resolver, data, tag }) {
3501
3470
  const hasZodExtendedImport = resolver.options.parseRequestParams && endpointParamsParseSchemas.length > 0;
3502
3471
  const zodExtendedImport = {
3503
3472
  bindings: [ZOD_EXTENDED.namespace],
3504
- from: getZodExtendedImportPath(resolver.options)
3473
+ from: ZOD_PACKAGE_IMPORT_PATH
3505
3474
  };
3506
3475
  const modelsImports = getModelsImports({
3507
3476
  resolver,
@@ -3510,11 +3479,11 @@ function generateEndpoints({ resolver, data, tag }) {
3510
3479
  zodSchemasAsTypes: getUniqueArray(endpointParams.map((param) => param.zodSchema).filter(isNamedZodSchema))
3511
3480
  });
3512
3481
  const lines = [];
3513
- lines.push(renderImport$3(appRestClientImport));
3514
- if (hasAxiosImport) lines.push(renderImport$3(axiosImport));
3515
- if (hasZodImport) lines.push(renderImport$3(ZOD_IMPORT));
3516
- if (hasZodExtendedImport) lines.push(renderImport$3(zodExtendedImport));
3517
- for (const modelsImport of modelsImports) lines.push(renderImport$3(modelsImport));
3482
+ lines.push(renderImport$2(appRestClientImport));
3483
+ if (hasAxiosImport) lines.push(renderImport$2(axiosImport));
3484
+ if (hasZodImport) lines.push(renderImport$2(ZOD_IMPORT));
3485
+ if (hasZodExtendedImport) lines.push(renderImport$2(zodExtendedImport));
3486
+ for (const modelsImport of modelsImports) lines.push(renderImport$2(modelsImport));
3518
3487
  lines.push("");
3519
3488
  if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3520
3489
  type: GenerateType.Endpoints,
@@ -3541,7 +3510,7 @@ function generateEndpoints({ resolver, data, tag }) {
3541
3510
  if (resolver.options.tsNamespaces) lines.push("}");
3542
3511
  return lines.join("\n").trimEnd() + "\n";
3543
3512
  }
3544
- function renderImport$3(importData) {
3513
+ function renderImport$2(importData) {
3545
3514
  return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
3546
3515
  }
3547
3516
  function renderEndpointParams$1(resolver, endpoint, options) {
@@ -3613,8 +3582,8 @@ function generateModels({ resolver, data, tag }) {
3613
3582
  };
3614
3583
  }
3615
3584
  const lines = [];
3616
- lines.push(renderImport$2(ZOD_IMPORT));
3617
- for (const modelsImport of modelsImports) lines.push(renderImport$2(modelsImport));
3585
+ lines.push(renderImport$1(ZOD_IMPORT));
3586
+ for (const modelsImport of modelsImports) lines.push(renderImport$1(modelsImport));
3618
3587
  lines.push("");
3619
3588
  if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3620
3589
  type: GenerateType.Models,
@@ -3703,7 +3672,7 @@ function getUsedSchemaNames({ resolver, endpoints }) {
3703
3672
  }
3704
3673
  return Array.from(usedSchemaNames);
3705
3674
  }
3706
- function renderImport$2(importData) {
3675
+ function renderImport$1(importData) {
3707
3676
  return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
3708
3677
  }
3709
3678
  function renderModelJsDocs({ name, zodSchema, tag, resolver }) {
@@ -3771,7 +3740,7 @@ function generateQueries(params) {
3771
3740
  const hasMutationEffectsImport = hasMutationEffects && mutationEndpoints.length > 0;
3772
3741
  const mutationEffectsImport = {
3773
3742
  bindings: [...mutationEndpoints.length > 0 ? [MUTATION_EFFECTS.optionsType, MUTATION_EFFECTS.hookName] : []],
3774
- from: getMutationEffectsImportPath(resolver.options)
3743
+ from: PACKAGE_IMPORT_PATH
3775
3744
  };
3776
3745
  const hasAclCheck = resolver.options.checkAcl && aclEndpoints.length > 0;
3777
3746
  const aclCheckImport = {
@@ -3803,7 +3772,7 @@ function generateQueries(params) {
3803
3772
  };
3804
3773
  const zodExtendedImport = {
3805
3774
  bindings: [ZOD_EXTENDED.namespace],
3806
- from: getZodExtendedImportPath(resolver.options)
3775
+ from: ZOD_PACKAGE_IMPORT_PATH
3807
3776
  };
3808
3777
  const modelsImports = getModelsImports({
3809
3778
  resolver,
@@ -3827,23 +3796,23 @@ function generateQueries(params) {
3827
3796
  options: resolver.options
3828
3797
  });
3829
3798
  const lines = [];
3830
- if (hasAxiosImport) lines.push(renderImport$1(axiosImport));
3799
+ if (hasAxiosImport) lines.push(renderImport(axiosImport));
3831
3800
  if (inlineEndpoints) {
3832
- lines.push(renderImport$1(appRestClientImport));
3833
- if (hasZodImport) lines.push(renderImport$1(ZOD_IMPORT));
3834
- if (hasZodExtendedImport) lines.push(renderImport$1(zodExtendedImport));
3801
+ lines.push(renderImport(appRestClientImport));
3802
+ if (hasZodImport) lines.push(renderImport(ZOD_IMPORT));
3803
+ if (hasZodExtendedImport) lines.push(renderImport(zodExtendedImport));
3835
3804
  }
3836
- lines.push(renderImport$1(queryImport));
3837
- if (hasMutationEffects) lines.push(renderImport$1(queryModulesImport));
3838
- if (hasMutationEffectsImport) lines.push(renderImport$1(mutationEffectsImport));
3805
+ lines.push(renderImport(queryImport));
3806
+ if (hasMutationEffects) lines.push(renderImport(queryModulesImport));
3807
+ if (hasMutationEffectsImport) lines.push(renderImport(mutationEffectsImport));
3839
3808
  if (hasAclCheck) {
3840
- lines.push(renderImport$1(aclCheckImport));
3841
- for (const aclImport of aclImports) lines.push(renderImport$1(aclImport));
3809
+ lines.push(renderImport(aclCheckImport));
3810
+ for (const aclImport of aclImports) lines.push(renderImport(aclImport));
3842
3811
  }
3843
- lines.push(renderImport$1(queryTypesImport));
3844
- if (hasWorkspaceContext) lines.push(renderImport$1(workspaceContextImport));
3845
- for (const modelsImport of modelsImports) lines.push(renderImport$1(modelsImport));
3846
- for (const endpointsImport of endpointsImports) lines.push(renderImport$1(endpointsImport));
3812
+ lines.push(renderImport(queryTypesImport));
3813
+ if (hasWorkspaceContext) lines.push(renderImport(workspaceContextImport));
3814
+ for (const modelsImport of modelsImports) lines.push(renderImport(modelsImport));
3815
+ for (const endpointsImport of endpointsImports) lines.push(renderImport(endpointsImport));
3847
3816
  lines.push("");
3848
3817
  if (resolver.options.tsNamespaces) lines.push(`export namespace ${namespace} {`);
3849
3818
  if (inlineEndpoints) {
@@ -3911,7 +3880,7 @@ function getEndpointParamMapping(resolver, endpoint, options) {
3911
3880
  endpointCache.set(key, computed);
3912
3881
  return computed;
3913
3882
  }
3914
- function renderImport$1(importData) {
3883
+ function renderImport(importData) {
3915
3884
  return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
3916
3885
  }
3917
3886
  function renderEndpointParams(resolver, endpoint, options) {
@@ -4132,7 +4101,7 @@ function renderMutation({ resolver, endpoint, inlineEndpoints, precomputed }) {
4132
4101
  lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
4133
4102
  if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
4134
4103
  if (Object.keys(workspaceParamReplacements).length > 0) lines.push(" const workspaceContext = OpenApiWorkspaceContext.useContext();");
4135
- if (hasMutationEffects) lines.push(` const { runMutationEffects } = useMutationEffects({ currentModule: ${QUERIES_MODULE_NAME} });`);
4104
+ if (hasMutationEffects) lines.push(` const { runMutationEffects } = useMutationEffects<typeof ${QUERY_MODULE_ENUM}.${tag}>({ currentModule: ${QUERIES_MODULE_NAME} });`);
4136
4105
  lines.push("");
4137
4106
  lines.push(` return ${QUERY_HOOKS.mutation}({`);
4138
4107
  const mutationFnArg = endpointParams ? `{ ${destructuredMutationArgs}${endpoint.mediaUpload ? `${destructuredMutationArgs ? ", " : ""}abortController, onUploadProgress` : ""} }` : "";
@@ -4304,66 +4273,6 @@ function generateQueryModules({ resolver, data }) {
4304
4273
  return lines.join("\n");
4305
4274
  }
4306
4275
 
4307
- //#endregion
4308
- //#region src/generators/generate/generateZodExtended.ts
4309
- function generateZodExtended(resolver) {
4310
- const errorHandlingImport = {
4311
- ...ERROR_HANDLING_IMPORT,
4312
- from: resolver.options.errorHandlingImportPath ?? ERROR_HANDLING_IMPORT.from
4313
- };
4314
- return `${renderImport(ZOD_IMPORT)}
4315
- ${renderImport(errorHandlingImport)}
4316
-
4317
- export namespace ZodExtended {
4318
- interface ParseOptions {
4319
- type: "body" | "query";
4320
- name?: string;
4321
- errorHandler?: ${ERROR_HANDLERS.ErrorHandler}<never>;
4322
- }
4323
-
4324
- export function ${ZOD_EXTENDED.exports.parse}<ZOutput, ZInput>(
4325
- schema: z.ZodType<ZOutput, ZInput>,
4326
- data: unknown,
4327
- { type, name, errorHandler }: ParseOptions = { type: "body" },
4328
- ) {
4329
- try {
4330
- return schema.parse(data);
4331
- } catch (e) {
4332
- if (e instanceof z.ZodError) {
4333
- e.name = \`FE Request \${type === "body" ? "body" : "query param"}\${name ? \` ("\${name}")\` : ""} schema mismatch - ZodError\`;
4334
- }
4335
- (errorHandler ?? ${ERROR_HANDLERS.SharedErrorHandler}).rethrowError(e);
4336
- throw e;
4337
- }
4338
- }
4339
-
4340
- function isSortExpValid(enumSchema: z.ZodEnum, data?: string) {
4341
- if (data === undefined || data === "" || enumSchema.options.length === 0) {
4342
- return true;
4343
- }
4344
-
4345
- const prefixedEnumOptions = \`([+-]?(\${enumSchema.options.join("|")}))\`;
4346
- const commaSeparatedOptions = \`(\${prefixedEnumOptions})(\\s*,\\s*\${prefixedEnumOptions})*\`;
4347
- return new RegExp(\`^\${commaSeparatedOptions}$\`).test(data);
4348
- }
4349
-
4350
- export const ${ZOD_EXTENDED.exports.sortExp} = (enumSchema: z.ZodEnum) =>
4351
- z.string().superRefine((arg, ctx) => {
4352
- if (!isSortExpValid(enumSchema, arg)) {
4353
- ctx.addIssue({
4354
- code: "invalid_value",
4355
- message: "Invalid sorting string.",
4356
- values: [],
4357
- });
4358
- }
4359
- });
4360
- }
4361
- `;
4362
- }
4363
- function renderImport(importData) {
4364
- return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
4365
- }
4366
-
4367
4276
  //#endregion
4368
4277
  //#region src/generators/utils/generate-files.utils.ts
4369
4278
  function getAclFiles(data, resolver) {
@@ -4381,7 +4290,7 @@ function getAclFiles(data, resolver) {
4381
4290
  }
4382
4291
  function getMutationEffectsFiles(data, resolver) {
4383
4292
  if (!resolver.options.mutationEffects) return [];
4384
- return [...getAssetFiles([MUTATION_EFFECTS_FILE, CROSS_TAB_QUERY_INVALIDATION_FILE], resolver), {
4293
+ return [{
4385
4294
  fileName: getOutputFileName({
4386
4295
  output: resolver.options.output,
4387
4296
  fileName: getFileNameWithExtension(QUERY_MODULES_FILE)
@@ -4392,15 +4301,8 @@ function getMutationEffectsFiles(data, resolver) {
4392
4301
  })
4393
4302
  }];
4394
4303
  }
4395
- function getZodExtendedFiles(data, resolver) {
4396
- if (!resolver.options.parseRequestParams) return [];
4397
- return [{
4398
- fileName: getOutputFileName({
4399
- output: resolver.options.output,
4400
- fileName: getFileNameWithExtension(ZOD_EXTENDED_FILE)
4401
- }),
4402
- content: generateZodExtended(resolver)
4403
- }];
4304
+ function getZodExtendedFiles(_data, _resolver) {
4305
+ return [];
4404
4306
  }
4405
4307
  function getAppRestClientFiles(resolver) {
4406
4308
  if (resolver.options.restClientImportPath !== DEFAULT_GENERATE_OPTIONS.restClientImportPath) return [];
@@ -4412,21 +4314,6 @@ function getAppRestClientFiles(resolver) {
4412
4314
  content: generateAppRestClient(resolver)
4413
4315
  }];
4414
4316
  }
4415
- function getAssetFiles(files, resolver) {
4416
- return files.map((file) => getAssetFile(file, resolver));
4417
- }
4418
- function getAssetFile(file, resolver) {
4419
- const fileName = getFileNameWithExtension(file);
4420
- let content = readAssetSync(fileName);
4421
- if (file.fileName === MUTATION_EFFECTS_FILE.fileName) content = content.replace("import { OpenApiQueryConfig, QueryModule, InvalidationMap } from \"../lib/config/queryConfig.context\";", `import { OpenApiQueryConfig, InvalidationMap } from "${PACKAGE_IMPORT_PATH}";\nimport { QueryModule } from "./${QUERY_MODULES_FILE.fileName}";`);
4422
- return {
4423
- fileName: getOutputFileName({
4424
- output: resolver.options.output,
4425
- fileName
4426
- }),
4427
- content
4428
- };
4429
- }
4430
4317
 
4431
4318
  //#endregion
4432
4319
  //#region src/generators/generateCodeFromOpenAPIDoc.ts
@@ -1,4 +1,4 @@
1
- import { n as GenerateFileData, t as GenerateOptions } from "./options-Bvmh6rai.mjs";
1
+ import { n as GenerateFileData, t as GenerateOptions } from "./options-DmUw8IYE.mjs";
2
2
  import { OpenAPIV3 } from "openapi-types";
3
3
 
4
4
  //#region src/generators/types/metadata.d.ts
@@ -1,4 +1,4 @@
1
- import { _ as isMediaTypeAllowed, b as formatTag, c as getSchemaTsMetaType, d as getTagImportPath, f as getQueryName, h as GenerateType, i as getDataFromOpenAPIDoc, l as getTsTypeBase, m as getNamespaceName, o as isMutation, p as DEFAULT_GENERATE_OPTIONS, s as isQuery, t as generateCodeFromOpenAPIDoc, v as isParamMediaTypeAllowed, y as invalidVariableNameCharactersToCamel } from "./generateCodeFromOpenAPIDoc-CV_esDUW.mjs";
1
+ import { _ as isMediaTypeAllowed, b as formatTag, c as getSchemaTsMetaType, d as getTagImportPath, f as getQueryName, h as GenerateType, i as getDataFromOpenAPIDoc, l as getTsTypeBase, m as getNamespaceName, o as isMutation, p as DEFAULT_GENERATE_OPTIONS, s as isQuery, t as generateCodeFromOpenAPIDoc, v as isParamMediaTypeAllowed, y as invalidVariableNameCharactersToCamel } from "./generateCodeFromOpenAPIDoc-BP7F6YJP.mjs";
2
2
  import SwaggerParser from "@apidevtools/swagger-parser";
3
3
 
4
4
  //#region src/generators/core/getMetadataFromOpenAPIDoc.ts
package/dist/index.d.mts CHANGED
@@ -1,13 +1,13 @@
1
- import { a as GeneralErrorCodes, i as ErrorHandlerOptions, n as ErrorEntry, o as SharedErrorHandler, r as ErrorHandler, t as ApplicationException } from "./error-handling-p69GkKGP.mjs";
2
- import "./options-Bvmh6rai.mjs";
3
- import { t as OpenAPICodegenConfig } from "./config-B4HK4BLi.mjs";
1
+ import { a as GeneralErrorCodes, i as ErrorHandlerOptions, n as ErrorEntry, o as SharedErrorHandler, r as ErrorHandler, t as ApplicationException } from "./error-handling-CXeVTk1T.mjs";
2
+ import "./options-DmUw8IYE.mjs";
3
+ import { t as OpenAPICodegenConfig } from "./config-CDt7S_BM.mjs";
4
4
  import { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosResponseHeaders, CreateAxiosDefaults } from "axios";
5
5
  import { z } from "zod";
6
6
  import "i18next";
7
7
  import * as react from "react";
8
8
  import { PropsWithChildren, ReactNode } from "react";
9
- import * as react_jsx_runtime0 from "react/jsx-runtime";
10
9
  import { InfiniteData, QueryKey, UseInfiniteQueryOptions, UseMutationOptions, UseQueryOptions } from "@tanstack/react-query";
10
+ import * as react_jsx_runtime0 from "react/jsx-runtime";
11
11
 
12
12
  //#region src/lib/rest/rest-interceptor.d.ts
13
13
  declare class RestInterceptor<T extends any[]> {
@@ -80,43 +80,61 @@ type AppQueryOptions<TFunction extends Function, TData = Awaited<ReturnType<TFun
80
80
  type AppMutationOptions<TFunction extends Function, TVariables = void, TData = Awaited<ReturnType<TFunction>>, TErrorCodes = GeneralErrorCodes> = Omit<UseMutationOptions<TData, ApplicationException<TErrorCodes>, TVariables>, "mutationKey" | "mutationFn">;
81
81
  type AppInfiniteQueryOptions<TFunction extends Function, TData = InfiniteData<Awaited<ReturnType<TFunction>>>, TErrorCodes = GeneralErrorCodes, TQueryKey extends QueryKey = QueryKey, TPageParam = number> = Omit<UseInfiniteQueryOptions<Awaited<ReturnType<TFunction>>, ApplicationException<TErrorCodes>, IsUnknown<TData, InfiniteData<Awaited<ReturnType<TFunction>>>>, TQueryKey, TPageParam>, "queryKey" | "queryFn" | "initialPageParam" | "getNextPageParam">;
82
82
  //#endregion
83
- //#region src/lib/config/router.context.d.ts
84
- interface RouterProviderProps {
85
- replace: (url: string) => void;
86
- }
87
- declare namespace OpenApiRouter {
88
- const Provider: ({
89
- children,
90
- replace
91
- }: PropsWithChildren<RouterProviderProps>) => react_jsx_runtime0.JSX.Element;
92
- const useRouter: () => RouterProviderProps;
93
- }
94
- //#endregion
95
83
  //#region src/lib/config/queryConfig.context.d.ts
96
84
  type QueryModule = string | number | symbol;
97
85
  type InvalidationMapFunc<TData = any, TVariables = any> = (data: TData, variables: TVariables) => QueryKey[];
98
- type InvalidationMap<TData = any, TVariables = any> = Record<QueryModule, InvalidationMapFunc<TData, TVariables>>;
86
+ type InvalidationMap<TQueryModule extends QueryModule = QueryModule, TData = any, TVariables = any> = Partial<Record<TQueryModule, InvalidationMapFunc<TData, TVariables>>>;
99
87
  declare namespace OpenApiQueryConfig {
100
- interface Type {
88
+ export interface Type<TQueryModule extends QueryModule = QueryModule> {
101
89
  preferUpdate?: boolean;
102
90
  invalidateCurrentModule?: boolean;
103
- invalidationMap?: InvalidationMap;
91
+ invalidationMap?: InvalidationMap<TQueryModule>;
104
92
  crossTabInvalidation?: boolean;
105
93
  onError?: (error: unknown) => void;
106
94
  }
107
- type ProviderProps = Type;
108
- export const Provider: ({
95
+ type ProviderProps<TQueryModule extends QueryModule = QueryModule> = Type<TQueryModule>;
96
+ export function Provider<TQueryModule extends QueryModule = QueryModule>({
109
97
  preferUpdate,
110
98
  invalidateCurrentModule,
111
99
  invalidationMap,
112
100
  crossTabInvalidation,
113
101
  onError,
114
102
  children
115
- }: PropsWithChildren<ProviderProps>) => react_jsx_runtime0.JSX.Element;
116
- export const useConfig: () => Type;
103
+ }: PropsWithChildren<ProviderProps<TQueryModule>>): react_jsx_runtime0.JSX.Element;
104
+ export const useConfig: <TQueryModule extends QueryModule = QueryModule>() => Type<TQueryModule>;
117
105
  export {};
118
106
  }
119
107
  //#endregion
108
+ //#region src/lib/react-query/useMutationEffects.d.ts
109
+ interface MutationEffectsOptions<TQueryModule extends QueryModule = QueryModule> {
110
+ invalidateCurrentModule?: boolean;
111
+ crossTabInvalidation?: boolean;
112
+ invalidationMap?: InvalidationMap<TQueryModule>;
113
+ invalidateModules?: TQueryModule[];
114
+ invalidateKeys?: QueryKey[];
115
+ preferUpdate?: boolean;
116
+ }
117
+ interface UseMutationEffectsProps<TQueryModule extends QueryModule = QueryModule> {
118
+ currentModule: TQueryModule;
119
+ }
120
+ declare function useMutationEffects<TQueryModule extends QueryModule = QueryModule>({
121
+ currentModule
122
+ }: UseMutationEffectsProps<TQueryModule>): {
123
+ runMutationEffects: <TData, TVariables>(data: TData, variables: TVariables, options?: MutationEffectsOptions<TQueryModule>, updateKeys?: QueryKey[]) => Promise<void>;
124
+ };
125
+ //#endregion
126
+ //#region src/lib/config/router.context.d.ts
127
+ interface RouterProviderProps {
128
+ replace: (url: string) => void;
129
+ }
130
+ declare namespace OpenApiRouter {
131
+ const Provider: ({
132
+ children,
133
+ replace
134
+ }: PropsWithChildren<RouterProviderProps>) => react_jsx_runtime0.JSX.Element;
135
+ const useRouter: () => RouterProviderProps;
136
+ }
137
+ //#endregion
120
138
  //#region src/lib/config/workspace.context.d.ts
121
139
  type WorkspaceValues = Record<string, unknown>;
122
140
  interface WorkspaceProviderProps {
@@ -209,4 +227,4 @@ declare const AuthGuard: ({
209
227
  children
210
228
  }: PropsWithChildren<AuthGuardProps>) => react.ReactNode;
211
229
  //#endregion
212
- export { type AppInfiniteQueryOptions, type AppMutationOptions, type AppQueryOptions, ApplicationException, AuthContext, AuthGuard, type AuthGuardProps, type ErrorEntry, ErrorHandler, type ErrorHandlerOptions, type GeneralErrorCodes, type RestClient as IRestClient, type InvalidationMap, OpenAPICodegenConfig, OpenApiQueryConfig, OpenApiRouter, OpenApiWorkspaceContext, type RequestConfig, type RequestInfo, type Response, RestClient$1 as RestClient, RestInterceptor, RestUtils, SharedErrorHandler, ns, resources };
230
+ export { type AppInfiniteQueryOptions, type AppMutationOptions, type AppQueryOptions, ApplicationException, AuthContext, AuthGuard, type AuthGuardProps, type ErrorEntry, ErrorHandler, type ErrorHandlerOptions, type GeneralErrorCodes, type RestClient as IRestClient, type InvalidationMap, type InvalidationMapFunc, type MutationEffectsOptions, OpenAPICodegenConfig, OpenApiQueryConfig, OpenApiRouter, OpenApiWorkspaceContext, type QueryModule, type RequestConfig, type RequestInfo, type Response, RestClient$1 as RestClient, RestInterceptor, RestUtils, SharedErrorHandler, ns, resources, useMutationEffects };
package/dist/index.mjs CHANGED
@@ -1,7 +1,9 @@
1
- import { a as SharedErrorHandler, c as resources, i as ErrorHandler, n as OpenApiRouter, o as RestUtils, r as ApplicationException, s as ns, t as AuthContext } from "./auth.context-HV1I5QMx.mjs";
1
+ import { a as ns, i as RestUtils, n as ErrorHandler, o as resources, r as SharedErrorHandler, t as ApplicationException } from "./error-handling-DkPY7Asf.mjs";
2
+ import { n as OpenApiRouter, t as AuthContext } from "./auth.context-Bu5KW2sI.mjs";
2
3
  import axios from "axios";
3
4
  import { z } from "zod";
4
- import { createContext, use, useEffect, useMemo, useState } from "react";
5
+ import { createContext, use, useCallback, useEffect, useMemo, useState } from "react";
6
+ import { useQueryClient } from "@tanstack/react-query";
5
7
  import { jsx } from "react/jsx-runtime";
6
8
 
7
9
  //#region src/lib/rest/rest-client.ts
@@ -111,7 +113,7 @@ var RestInterceptor = class {
111
113
  let OpenApiQueryConfig;
112
114
  (function(_OpenApiQueryConfig) {
113
115
  const Context = createContext({});
114
- _OpenApiQueryConfig.Provider = ({ preferUpdate, invalidateCurrentModule, invalidationMap, crossTabInvalidation, onError, children }) => {
116
+ function Provider({ preferUpdate, invalidateCurrentModule, invalidationMap, crossTabInvalidation, onError, children }) {
115
117
  const value = useMemo(() => ({
116
118
  preferUpdate,
117
119
  invalidateCurrentModule,
@@ -129,12 +131,79 @@ let OpenApiQueryConfig;
129
131
  value,
130
132
  children
131
133
  });
132
- };
134
+ }
135
+ _OpenApiQueryConfig.Provider = Provider;
133
136
  _OpenApiQueryConfig.useConfig = () => {
134
137
  return use(Context) ?? {};
135
138
  };
136
139
  })(OpenApiQueryConfig || (OpenApiQueryConfig = {}));
137
140
 
141
+ //#endregion
142
+ //#region src/lib/react-query/cross-tab-invalidation.ts
143
+ const CROSS_TAB_INVALIDATE_KEY = "__rq_invalidate__";
144
+ const broadcastQueryInvalidation = (queryKeys) => {
145
+ localStorage.setItem(CROSS_TAB_INVALIDATE_KEY, JSON.stringify({
146
+ keys: queryKeys,
147
+ timestamp: Date.now()
148
+ }));
149
+ };
150
+ let isListenerSetUp = false;
151
+ const setupCrossTabListener = (queryClient) => {
152
+ if (isListenerSetUp) return;
153
+ isListenerSetUp = true;
154
+ window.addEventListener("storage", (e) => {
155
+ if (e.key !== CROSS_TAB_INVALIDATE_KEY || !e.newValue) return;
156
+ try {
157
+ const { keys } = JSON.parse(e.newValue);
158
+ for (const queryKey of keys) queryClient.invalidateQueries({ queryKey });
159
+ } catch {}
160
+ });
161
+ };
162
+
163
+ //#endregion
164
+ //#region src/lib/react-query/useMutationEffects.ts
165
+ function useMutationEffects({ currentModule }) {
166
+ const queryClient = useQueryClient();
167
+ const config = OpenApiQueryConfig.useConfig();
168
+ useEffect(() => {
169
+ if (!config.crossTabInvalidation) return;
170
+ setupCrossTabListener(queryClient);
171
+ }, [queryClient, config.crossTabInvalidation]);
172
+ return { runMutationEffects: useCallback(async (data, variables, options = {}, updateKeys) => {
173
+ const { invalidateCurrentModule, invalidationMap, invalidateModules, invalidateKeys, preferUpdate } = options;
174
+ const shouldUpdate = preferUpdate ?? config.preferUpdate ?? false;
175
+ const shouldInvalidateCurrentModule = invalidateCurrentModule ?? config.invalidateCurrentModule ?? true;
176
+ const isQueryKeyEqual = (keyA, keyB) => keyA.length === keyB.length && keyA.every((item, index) => item === keyB[index]);
177
+ const isQueryKeyPrefix = (queryKey, prefixKey) => prefixKey.length <= queryKey.length && prefixKey.every((item, index) => item === queryKey[index]);
178
+ const mappedInvalidationKeys = invalidationMap?.[currentModule]?.(data, variables) ?? config.invalidationMap?.[currentModule]?.(data, variables);
179
+ const shouldInvalidateQuery = (queryKey) => {
180
+ const isUpdateKey = updateKeys?.some((key) => isQueryKeyEqual(queryKey, key));
181
+ if (shouldUpdate && isUpdateKey) return false;
182
+ const isCurrentModule = shouldInvalidateCurrentModule && queryKey[0] === currentModule;
183
+ const isInvalidateModule = !!invalidateModules && invalidateModules.some((module) => queryKey[0] === module);
184
+ const isInvalidateKey = !!invalidateKeys && invalidateKeys.some((key) => isQueryKeyPrefix(queryKey, key));
185
+ const isMappedKey = !!mappedInvalidationKeys && mappedInvalidationKeys.some((key) => isQueryKeyPrefix(queryKey, key));
186
+ return isCurrentModule || isInvalidateModule || isInvalidateKey || isMappedKey;
187
+ };
188
+ const invalidatedQueryKeys = [];
189
+ const shouldBroadcast = options.crossTabInvalidation ?? config.crossTabInvalidation;
190
+ queryClient.invalidateQueries({ predicate: ({ queryKey }) => {
191
+ const shouldInvalidate = shouldInvalidateQuery(queryKey);
192
+ if (shouldInvalidate && shouldBroadcast) invalidatedQueryKeys.push([...queryKey]);
193
+ return shouldInvalidate;
194
+ } });
195
+ if (shouldBroadcast && invalidatedQueryKeys.length > 0) broadcastQueryInvalidation(invalidatedQueryKeys);
196
+ if (shouldUpdate && updateKeys) updateKeys.map((queryKey) => queryClient.setQueryData(queryKey, data));
197
+ }, [
198
+ queryClient,
199
+ currentModule,
200
+ config.preferUpdate,
201
+ config.invalidateCurrentModule,
202
+ config.invalidationMap,
203
+ config.crossTabInvalidation
204
+ ]) };
205
+ }
206
+
138
207
  //#endregion
139
208
  //#region src/lib/config/workspace.context.tsx
140
209
  let OpenApiWorkspaceContext;
@@ -180,4 +249,4 @@ const AuthGuard = ({ type, redirectTo, children }) => {
180
249
  };
181
250
 
182
251
  //#endregion
183
- export { ApplicationException, AuthContext, AuthGuard, ErrorHandler, OpenApiQueryConfig, OpenApiRouter, OpenApiWorkspaceContext, RestClient, RestInterceptor, RestUtils, SharedErrorHandler, ns, resources };
252
+ export { ApplicationException, AuthContext, AuthGuard, ErrorHandler, OpenApiQueryConfig, OpenApiRouter, OpenApiWorkspaceContext, RestClient, RestInterceptor, RestUtils, SharedErrorHandler, ns, resources, useMutationEffects };
package/dist/sh.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { S as VALIDATION_ERROR_TYPE_TITLE, g as groupByType, h as GenerateType, i as getDataFromOpenAPIDoc, n as getOutputFileName, u as getTagFileName, x as Profiler } from "./generateCodeFromOpenAPIDoc-CV_esDUW.mjs";
3
- import { n as resolveConfig, t as runGenerate } from "./generate.runner-CU-WCMgQ.mjs";
2
+ import { S as VALIDATION_ERROR_TYPE_TITLE, g as groupByType, h as GenerateType, i as getDataFromOpenAPIDoc, n as getOutputFileName, u as getTagFileName, x as Profiler } from "./generateCodeFromOpenAPIDoc-BP7F6YJP.mjs";
3
+ import { n as resolveConfig, t as runGenerate } from "./generate.runner-C93djZ78.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import yargs from "yargs";
6
6
  import { hideBin } from "yargs/helpers";
@@ -39,7 +39,7 @@ function logBanner(message) {
39
39
  * Fetch the version from package.json
40
40
  */
41
41
  function getVersion() {
42
- return "2.0.8-rc.17";
42
+ return "2.0.8-rc.19";
43
43
  }
44
44
 
45
45
  //#endregion
package/dist/vite.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import "./options-Bvmh6rai.mjs";
2
- import { t as OpenAPICodegenConfig } from "./config-B4HK4BLi.mjs";
1
+ import "./options-DmUw8IYE.mjs";
2
+ import { t as OpenAPICodegenConfig } from "./config-CDt7S_BM.mjs";
3
3
  import { Plugin } from "vite";
4
4
 
5
5
  //#region src/vite/openapi-codegen.plugin.d.ts
package/dist/vite.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { x as Profiler } from "./generateCodeFromOpenAPIDoc-CV_esDUW.mjs";
2
- import { t as runGenerate } from "./generate.runner-CU-WCMgQ.mjs";
1
+ import { x as Profiler } from "./generateCodeFromOpenAPIDoc-BP7F6YJP.mjs";
2
+ import { t as runGenerate } from "./generate.runner-C93djZ78.mjs";
3
3
  import path from "path";
4
4
 
5
5
  //#region src/vite/openapi-codegen.plugin.ts
package/dist/zod.d.mts ADDED
@@ -0,0 +1,20 @@
1
+ import { r as ErrorHandler } from "./error-handling-CXeVTk1T.mjs";
2
+ import { z } from "zod";
3
+
4
+ //#region src/zod.d.ts
5
+ declare namespace ZodExtended {
6
+ interface ParseOptions {
7
+ type: "body" | "query";
8
+ name?: string;
9
+ errorHandler?: ErrorHandler<never>;
10
+ }
11
+ export function parse<ZOutput, ZInput>(schema: z.ZodType<ZOutput, ZInput>, data: unknown, {
12
+ type,
13
+ name,
14
+ errorHandler
15
+ }?: ParseOptions): ZOutput;
16
+ export const sortExp: (enumSchema: z.ZodEnum) => z.ZodString;
17
+ export {};
18
+ }
19
+ //#endregion
20
+ export { ZodExtended };
package/dist/zod.mjs ADDED
@@ -0,0 +1,33 @@
1
+ import { r as SharedErrorHandler } from "./error-handling-DkPY7Asf.mjs";
2
+ import { z } from "zod";
3
+
4
+ //#region src/zod.ts
5
+ let ZodExtended;
6
+ (function(_ZodExtended) {
7
+ function parse(schema, data, { type, name, errorHandler } = { type: "body" }) {
8
+ try {
9
+ return schema.parse(data);
10
+ } catch (e) {
11
+ if (e instanceof z.ZodError) e.name = `FE Request ${type === "body" ? "body" : "query param"}${name ? ` ("${name}")` : ""} schema mismatch - ZodError`;
12
+ (errorHandler ?? SharedErrorHandler).rethrowError(e);
13
+ throw e;
14
+ }
15
+ }
16
+ _ZodExtended.parse = parse;
17
+ function isSortExpValid(enumSchema, data) {
18
+ if (data === void 0 || data === "" || enumSchema.options.length === 0) return true;
19
+ const prefixedEnumOptions = `([+-]?(${enumSchema.options.join("|")}))`;
20
+ const commaSeparatedOptions = `(${prefixedEnumOptions})(\\s*,\\s*${prefixedEnumOptions})*`;
21
+ return new RegExp(`^${commaSeparatedOptions}$`).test(data);
22
+ }
23
+ _ZodExtended.sortExp = (enumSchema) => z.string().superRefine((arg, ctx) => {
24
+ if (!isSortExpValid(enumSchema, arg)) ctx.addIssue({
25
+ code: "invalid_value",
26
+ message: "Invalid sorting string.",
27
+ values: []
28
+ });
29
+ });
30
+ })(ZodExtended || (ZodExtended = {}));
31
+
32
+ //#endregion
33
+ export { ZodExtended };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@povio/openapi-codegen-cli",
3
- "version": "2.0.8-rc.17",
3
+ "version": "2.0.8-rc.19",
4
4
  "keywords": [
5
5
  "codegen",
6
6
  "openapi",
@@ -42,6 +42,10 @@
42
42
  "./acl": {
43
43
  "types": "./dist/acl.d.mts",
44
44
  "import": "./dist/acl.mjs"
45
+ },
46
+ "./zod": {
47
+ "types": "./dist/zod.d.mts",
48
+ "import": "./dist/zod.mjs"
45
49
  }
46
50
  },
47
51
  "scripts": {
@@ -1,40 +0,0 @@
1
- import type { QueryClient, QueryKey } from "@tanstack/react-query";
2
-
3
- const CROSS_TAB_INVALIDATE_KEY = "__rq_invalidate__";
4
-
5
- /**
6
- * Broadcasts a query invalidation event to all other open tabs via localStorage.
7
- *
8
- * @param queryKeys - An array of query keys to invalidate (array of arrays).
9
- *
10
- * NOTE: The `storage` event only fires in *other* tabs — the calling tab
11
- * must invalidate its own queryClient separately if needed.
12
- */
13
- export const broadcastQueryInvalidation = (queryKeys: QueryKey[]) => {
14
- localStorage.setItem(CROSS_TAB_INVALIDATE_KEY, JSON.stringify({ keys: queryKeys, timestamp: Date.now() }));
15
- };
16
-
17
- /**
18
- * Registers a one-time global `storage` event listener that reacts to
19
- * cross-tab invalidation broadcasts. Safe to call from multiple hooks —
20
- * only the first call sets up the listener.
21
- */
22
- let isListenerSetUp = false;
23
-
24
- export const setupCrossTabListener = (queryClient: QueryClient) => {
25
- if (isListenerSetUp) return;
26
- isListenerSetUp = true;
27
-
28
- window.addEventListener("storage", (e: StorageEvent) => {
29
- if (e.key !== CROSS_TAB_INVALIDATE_KEY || !e.newValue) return;
30
-
31
- try {
32
- const { keys } = JSON.parse(e.newValue) as { keys: QueryKey[] };
33
- for (const queryKey of keys) {
34
- queryClient.invalidateQueries({ queryKey });
35
- }
36
- } catch {
37
- // Ignore malformed payloads
38
- }
39
- });
40
- };
@@ -1,94 +0,0 @@
1
- import { useCallback, useEffect } from "react";
2
-
3
- import { QueryKey, useQueryClient } from "@tanstack/react-query";
4
- import { OpenApiQueryConfig, QueryModule, InvalidationMap } from "../lib/config/queryConfig.context";
5
- import { broadcastQueryInvalidation, setupCrossTabListener } from "./useCrossTabQueryInvalidation";
6
-
7
- export interface MutationEffectsOptions {
8
- invalidateCurrentModule?: boolean;
9
- crossTabInvalidation?: boolean;
10
- invalidationMap?: InvalidationMap;
11
- invalidateModules?: QueryModule[];
12
- invalidateKeys?: QueryKey[];
13
- preferUpdate?: boolean;
14
- }
15
-
16
- export interface UseMutationEffectsProps {
17
- currentModule: QueryModule;
18
- }
19
-
20
- export function useMutationEffects({ currentModule }: UseMutationEffectsProps) {
21
- const queryClient = useQueryClient();
22
- const config = OpenApiQueryConfig.useConfig();
23
-
24
- useEffect(() => {
25
- if (!config.crossTabInvalidation) return;
26
- setupCrossTabListener(queryClient);
27
- }, [queryClient, config.crossTabInvalidation]);
28
-
29
- const runMutationEffects = useCallback(
30
- async <TData, TVariables>(
31
- data: TData,
32
- variables: TVariables,
33
- options: MutationEffectsOptions = {},
34
- updateKeys?: QueryKey[],
35
- ) => {
36
- const { invalidateCurrentModule, invalidateModules, invalidateKeys, preferUpdate } = options;
37
- const shouldUpdate = preferUpdate ?? config.preferUpdate ?? false;
38
- const shouldInvalidateCurrentModule = invalidateCurrentModule ?? config.invalidateCurrentModule ?? true;
39
-
40
- const isQueryKeyEqual = (keyA: QueryKey, keyB: QueryKey) =>
41
- keyA.length === keyB.length && keyA.every((item, index) => item === keyB[index]);
42
- const isQueryKeyPrefix = (queryKey: QueryKey, prefixKey: QueryKey) =>
43
- prefixKey.length <= queryKey.length && prefixKey.every((item, index) => item === queryKey[index]);
44
- const mappedInvalidationKeys = config.invalidationMap?.[currentModule]?.(data, variables);
45
-
46
- const shouldInvalidateQuery = (queryKey: QueryKey) => {
47
- const isUpdateKey = updateKeys?.some((key) => isQueryKeyEqual(queryKey, key));
48
- if (shouldUpdate && isUpdateKey) {
49
- return false;
50
- }
51
-
52
- const isCurrentModule = shouldInvalidateCurrentModule && queryKey[0] === currentModule;
53
- const isInvalidateModule = !!invalidateModules && invalidateModules.some((module) => queryKey[0] === module);
54
- const isInvalidateKey = !!invalidateKeys && invalidateKeys.some((key) => isQueryKeyPrefix(queryKey, key));
55
- const isMappedKey =
56
- !!mappedInvalidationKeys && mappedInvalidationKeys.some((key) => isQueryKeyPrefix(queryKey, key));
57
-
58
- return isCurrentModule || isInvalidateModule || isInvalidateKey || isMappedKey;
59
- };
60
-
61
- const invalidatedQueryKeys: QueryKey[] = [];
62
-
63
- queryClient.invalidateQueries({
64
- predicate: ({ queryKey }) => {
65
- const shouldInvalidate = shouldInvalidateQuery(queryKey);
66
-
67
- if (shouldInvalidate && config.crossTabInvalidation) {
68
- invalidatedQueryKeys.push([...queryKey]);
69
- }
70
-
71
- return shouldInvalidate;
72
- },
73
- });
74
-
75
- if (config.crossTabInvalidation && invalidatedQueryKeys.length > 0) {
76
- broadcastQueryInvalidation(invalidatedQueryKeys);
77
- }
78
-
79
- if (shouldUpdate && updateKeys) {
80
- updateKeys.map((queryKey) => queryClient.setQueryData(queryKey, data));
81
- }
82
- },
83
- [
84
- queryClient,
85
- currentModule,
86
- config.preferUpdate,
87
- config.invalidateCurrentModule,
88
- config.invalidationMap,
89
- config.crossTabInvalidation,
90
- ],
91
- );
92
-
93
- return { runMutationEffects };
94
- }