@rvoh/psychic 3.1.0 → 3.1.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.
@@ -23,7 +23,7 @@ export default async function writeInitializer({ exportName }) {
23
23
  await fs.mkdir(destDir, { recursive: true });
24
24
  }
25
25
  const filePath = path.join('.', 'src', 'conf', 'openapi', `${camelized}.openapi-codegen.json`);
26
- const execCmd = PackageManager.exec(`@rtk-query/codegen-openapi ${filePath}`);
26
+ const execCmd = PackageManager.exec(`rtk-query-codegen-openapi ${filePath}`);
27
27
  const contents = `\
28
28
  import { DreamCLI } from '@rvoh/dream/system'
29
29
  import { PsychicApp } from '@rvoh/psychic'
@@ -0,0 +1,74 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ /**
4
+ * Reads the generated sdk.gen.ts file, extracts exported function names,
5
+ * and generates a store.gen.ts file with Zustand stores wrapping each
6
+ * SDK function.
7
+ *
8
+ * This is called during `psy sync` after @hey-api/openapi-ts has generated
9
+ * the SDK, so that the store stays in sync with the API.
10
+ */
11
+ export default async function generateZustandStoreFromSdk(outputDir) {
12
+ const sdkPath = path.join(outputDir, 'sdk.gen.ts');
13
+ const storePath = path.join(outputDir, 'store.gen.ts');
14
+ let sdkContents;
15
+ try {
16
+ sdkContents = (await fs.readFile(sdkPath)).toString();
17
+ }
18
+ catch {
19
+ return; // sdk.gen.ts doesn't exist yet, nothing to generate from
20
+ }
21
+ const functionNames = extractExportedFunctionNames(sdkContents);
22
+ if (functionNames.length === 0)
23
+ return;
24
+ const storeLines = functionNames.map(name => {
25
+ const hookName = 'use' + name.charAt(0).toUpperCase() + name.slice(1);
26
+ return `export const ${hookName} = createSdkStore(sdk.${name})`;
27
+ });
28
+ const contents = `\
29
+ // This file is auto-generated during sync — do not edit
30
+ import { create } from 'zustand'
31
+ import * as sdk from './sdk.gen'
32
+
33
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
+ type SdkFn = (...args: any[]) => Promise<{ data?: any; error?: any }>
35
+
36
+ interface SdkStore<TData, TArgs extends unknown[]> {
37
+ data: TData | undefined
38
+ error: unknown
39
+ isLoading: boolean
40
+ fetch: (...args: TArgs) => Promise<TData | undefined>
41
+ reset: () => void
42
+ }
43
+
44
+ function createSdkStore<T extends SdkFn>(fn: T) {
45
+ type TData = Awaited<ReturnType<T>>['data']
46
+ return create<SdkStore<TData, Parameters<T>>>()((set) => ({
47
+ data: undefined as TData | undefined,
48
+ error: undefined as unknown,
49
+ isLoading: false,
50
+
51
+ fetch: async (...args: Parameters<T>) => {
52
+ set({ isLoading: true, error: undefined })
53
+ const { data, error } = await (fn as SdkFn)(...args)
54
+ set({ data, error, isLoading: false })
55
+ return data as TData | undefined
56
+ },
57
+
58
+ reset: () => set({ data: undefined, error: undefined, isLoading: false }),
59
+ }))
60
+ }
61
+
62
+ ${storeLines.join('\n')}
63
+ `;
64
+ await fs.writeFile(storePath, contents);
65
+ }
66
+ function extractExportedFunctionNames(sdkContents) {
67
+ const names = [];
68
+ const pattern = /export const (\w+)\s*=/g;
69
+ let match;
70
+ while ((match = pattern.exec(sdkContents)) !== null) {
71
+ names.push(match[1]);
72
+ }
73
+ return names;
74
+ }
@@ -8,17 +8,19 @@ export default function printFinalStepsMessage(opts) {
8
8
  const usageLine = colorize(` const { data, error } = await getAdminCities()`, {
9
9
  color: 'green',
10
10
  });
11
- const zustandLine = colorize(` const { data } = await getAdminCities()
12
- set({ cities: data?.results })`, { color: 'green' });
11
+ const storeImportLine = colorize(`+ import { useGetAdminCities } from '${opts.outputDir}/store.gen'`, {
12
+ color: 'green',
13
+ });
13
14
  DreamCLI.logger.log(`
14
15
  Finished generating @hey-api/openapi-ts bindings for your application.
15
16
 
16
17
  First, you will need to be sure to sync, so that the typed API functions
17
- are generated from your openapi schema:
18
+ and Zustand store are generated from your openapi schema:
18
19
 
19
20
  pnpm psy sync
20
21
 
21
- This will generate typed API functions and types in ${opts.outputDir}/
22
+ This will generate typed API functions in ${opts.outputDir}/sdk.gen.ts
23
+ and a Zustand store in ${opts.outputDir}/store.gen.ts
22
24
 
23
25
  To use the generated API, first import the client config at your app's
24
26
  entry point to configure the base URL and credentials:
@@ -32,16 +34,11 @@ ${sdkImportLine}
32
34
  // all functions are fully typed with request params and response types
33
35
  ${usageLine}
34
36
 
35
- To use with a Zustand store:
37
+ Or use the auto-generated Zustand store hooks for state management:
36
38
 
37
- import { create } from 'zustand'
38
- ${sdkImportLine}
39
+ ${storeImportLine}
39
40
 
40
- const useCitiesStore = create((set) => ({
41
- cities: [],
42
- fetchCities: async () => {
43
- ${zustandLine}
44
- },
45
- }))
41
+ // each hook provides { data, error, isLoading, fetch, reset }
42
+ const { data, isLoading, fetch } = useGetAdminCities()
46
43
  `, { logPrefix: '' });
47
44
  }
@@ -6,26 +6,14 @@ import psychicPath from '../../../helpers/path/psychicPath.js';
6
6
  export default async function writeInitializer({ exportName, schemaFile, outputDir, }) {
7
7
  const pascalized = pascalize(exportName);
8
8
  const camelized = camelize(exportName);
9
- const execCmd = PackageManager.exec(`@hey-api/openapi-ts -i ${schemaFile} -o ${outputDir}`);
9
+ const execCmd = PackageManager.exec(`openapi-ts -i ${schemaFile} -o ${outputDir}`);
10
10
  const destDir = path.join(psychicPath('conf'), 'initializers', 'openapi');
11
11
  const initializerFilename = `${camelized}.ts`;
12
12
  const initializerPath = path.join(destDir, initializerFilename);
13
- try {
14
- await fs.access(initializerPath);
15
- return; // early return if the file already exists
16
- }
17
- catch {
18
- // noop
19
- }
20
- try {
21
- await fs.access(destDir);
22
- }
23
- catch {
24
- await fs.mkdir(destDir, { recursive: true });
25
- }
26
13
  const contents = `\
27
14
  import { DreamCLI } from '@rvoh/dream/system'
28
15
  import { PsychicApp } from '@rvoh/psychic'
16
+ import { generateZustandStoreFromSdk } from '@rvoh/psychic/system'
29
17
  import AppEnv from '../../AppEnv.js'
30
18
 
31
19
  export default function initialize${pascalized}(psy: PsychicApp) {
@@ -40,9 +28,28 @@ export default function initialize${pascalized}(psy: PsychicApp) {
40
28
  },
41
29
  })
42
30
  })
31
+
32
+ await DreamCLI.logger.logProgress(\`[${camelized}] generating zustand store...\`, async () => {
33
+ await generateZustandStoreFromSdk('${outputDir}')
34
+ })
43
35
  }
44
36
  })
45
37
  }\
46
38
  `;
39
+ try {
40
+ const existingContents = (await fs.readFile(initializerPath)).toString();
41
+ if (existingContents === contents) {
42
+ return; // early return if the file already matches exactly
43
+ }
44
+ }
45
+ catch {
46
+ // noop — file doesn't exist yet
47
+ }
48
+ try {
49
+ await fs.access(destDir);
50
+ }
51
+ catch {
52
+ await fs.mkdir(destDir, { recursive: true });
53
+ }
47
54
  await fs.writeFile(initializerPath, contents);
48
55
  }
@@ -14,6 +14,7 @@ import writeInitializer from '../helpers/zustandBindings/writeInitializer.js';
14
14
  * * generates the client config file if it does not exist
15
15
  * * generates an initializer, which taps into the sync hooks
16
16
  * to automatically run the @hey-api/openapi-ts CLI util
17
+ * and generate a zustand store from the SDK output
17
18
  * * prints a helpful message, instructing devs on the final
18
19
  * steps for using the generated typed API functions
19
20
  * within their client application.
@@ -1,3 +1,4 @@
1
+ export { default as generateZustandStoreFromSdk } from '../generate/helpers/zustandBindings/generateStoreFromSdk.js';
1
2
  export { default as PsychicBin } from '../bin/index.js';
2
3
  export { default as PsychicLogos } from '../cli/helpers/PsychicLogos.js';
3
4
  export { default as PsychicCLI } from '../cli/index.js';
@@ -23,7 +23,7 @@ export default async function writeInitializer({ exportName }) {
23
23
  await fs.mkdir(destDir, { recursive: true });
24
24
  }
25
25
  const filePath = path.join('.', 'src', 'conf', 'openapi', `${camelized}.openapi-codegen.json`);
26
- const execCmd = PackageManager.exec(`@rtk-query/codegen-openapi ${filePath}`);
26
+ const execCmd = PackageManager.exec(`rtk-query-codegen-openapi ${filePath}`);
27
27
  const contents = `\
28
28
  import { DreamCLI } from '@rvoh/dream/system'
29
29
  import { PsychicApp } from '@rvoh/psychic'
@@ -0,0 +1,74 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ /**
4
+ * Reads the generated sdk.gen.ts file, extracts exported function names,
5
+ * and generates a store.gen.ts file with Zustand stores wrapping each
6
+ * SDK function.
7
+ *
8
+ * This is called during `psy sync` after @hey-api/openapi-ts has generated
9
+ * the SDK, so that the store stays in sync with the API.
10
+ */
11
+ export default async function generateZustandStoreFromSdk(outputDir) {
12
+ const sdkPath = path.join(outputDir, 'sdk.gen.ts');
13
+ const storePath = path.join(outputDir, 'store.gen.ts');
14
+ let sdkContents;
15
+ try {
16
+ sdkContents = (await fs.readFile(sdkPath)).toString();
17
+ }
18
+ catch {
19
+ return; // sdk.gen.ts doesn't exist yet, nothing to generate from
20
+ }
21
+ const functionNames = extractExportedFunctionNames(sdkContents);
22
+ if (functionNames.length === 0)
23
+ return;
24
+ const storeLines = functionNames.map(name => {
25
+ const hookName = 'use' + name.charAt(0).toUpperCase() + name.slice(1);
26
+ return `export const ${hookName} = createSdkStore(sdk.${name})`;
27
+ });
28
+ const contents = `\
29
+ // This file is auto-generated during sync — do not edit
30
+ import { create } from 'zustand'
31
+ import * as sdk from './sdk.gen'
32
+
33
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
+ type SdkFn = (...args: any[]) => Promise<{ data?: any; error?: any }>
35
+
36
+ interface SdkStore<TData, TArgs extends unknown[]> {
37
+ data: TData | undefined
38
+ error: unknown
39
+ isLoading: boolean
40
+ fetch: (...args: TArgs) => Promise<TData | undefined>
41
+ reset: () => void
42
+ }
43
+
44
+ function createSdkStore<T extends SdkFn>(fn: T) {
45
+ type TData = Awaited<ReturnType<T>>['data']
46
+ return create<SdkStore<TData, Parameters<T>>>()((set) => ({
47
+ data: undefined as TData | undefined,
48
+ error: undefined as unknown,
49
+ isLoading: false,
50
+
51
+ fetch: async (...args: Parameters<T>) => {
52
+ set({ isLoading: true, error: undefined })
53
+ const { data, error } = await (fn as SdkFn)(...args)
54
+ set({ data, error, isLoading: false })
55
+ return data as TData | undefined
56
+ },
57
+
58
+ reset: () => set({ data: undefined, error: undefined, isLoading: false }),
59
+ }))
60
+ }
61
+
62
+ ${storeLines.join('\n')}
63
+ `;
64
+ await fs.writeFile(storePath, contents);
65
+ }
66
+ function extractExportedFunctionNames(sdkContents) {
67
+ const names = [];
68
+ const pattern = /export const (\w+)\s*=/g;
69
+ let match;
70
+ while ((match = pattern.exec(sdkContents)) !== null) {
71
+ names.push(match[1]);
72
+ }
73
+ return names;
74
+ }
@@ -8,17 +8,19 @@ export default function printFinalStepsMessage(opts) {
8
8
  const usageLine = colorize(` const { data, error } = await getAdminCities()`, {
9
9
  color: 'green',
10
10
  });
11
- const zustandLine = colorize(` const { data } = await getAdminCities()
12
- set({ cities: data?.results })`, { color: 'green' });
11
+ const storeImportLine = colorize(`+ import { useGetAdminCities } from '${opts.outputDir}/store.gen'`, {
12
+ color: 'green',
13
+ });
13
14
  DreamCLI.logger.log(`
14
15
  Finished generating @hey-api/openapi-ts bindings for your application.
15
16
 
16
17
  First, you will need to be sure to sync, so that the typed API functions
17
- are generated from your openapi schema:
18
+ and Zustand store are generated from your openapi schema:
18
19
 
19
20
  pnpm psy sync
20
21
 
21
- This will generate typed API functions and types in ${opts.outputDir}/
22
+ This will generate typed API functions in ${opts.outputDir}/sdk.gen.ts
23
+ and a Zustand store in ${opts.outputDir}/store.gen.ts
22
24
 
23
25
  To use the generated API, first import the client config at your app's
24
26
  entry point to configure the base URL and credentials:
@@ -32,16 +34,11 @@ ${sdkImportLine}
32
34
  // all functions are fully typed with request params and response types
33
35
  ${usageLine}
34
36
 
35
- To use with a Zustand store:
37
+ Or use the auto-generated Zustand store hooks for state management:
36
38
 
37
- import { create } from 'zustand'
38
- ${sdkImportLine}
39
+ ${storeImportLine}
39
40
 
40
- const useCitiesStore = create((set) => ({
41
- cities: [],
42
- fetchCities: async () => {
43
- ${zustandLine}
44
- },
45
- }))
41
+ // each hook provides { data, error, isLoading, fetch, reset }
42
+ const { data, isLoading, fetch } = useGetAdminCities()
46
43
  `, { logPrefix: '' });
47
44
  }
@@ -6,26 +6,14 @@ import psychicPath from '../../../helpers/path/psychicPath.js';
6
6
  export default async function writeInitializer({ exportName, schemaFile, outputDir, }) {
7
7
  const pascalized = pascalize(exportName);
8
8
  const camelized = camelize(exportName);
9
- const execCmd = PackageManager.exec(`@hey-api/openapi-ts -i ${schemaFile} -o ${outputDir}`);
9
+ const execCmd = PackageManager.exec(`openapi-ts -i ${schemaFile} -o ${outputDir}`);
10
10
  const destDir = path.join(psychicPath('conf'), 'initializers', 'openapi');
11
11
  const initializerFilename = `${camelized}.ts`;
12
12
  const initializerPath = path.join(destDir, initializerFilename);
13
- try {
14
- await fs.access(initializerPath);
15
- return; // early return if the file already exists
16
- }
17
- catch {
18
- // noop
19
- }
20
- try {
21
- await fs.access(destDir);
22
- }
23
- catch {
24
- await fs.mkdir(destDir, { recursive: true });
25
- }
26
13
  const contents = `\
27
14
  import { DreamCLI } from '@rvoh/dream/system'
28
15
  import { PsychicApp } from '@rvoh/psychic'
16
+ import { generateZustandStoreFromSdk } from '@rvoh/psychic/system'
29
17
  import AppEnv from '../../AppEnv.js'
30
18
 
31
19
  export default function initialize${pascalized}(psy: PsychicApp) {
@@ -40,9 +28,28 @@ export default function initialize${pascalized}(psy: PsychicApp) {
40
28
  },
41
29
  })
42
30
  })
31
+
32
+ await DreamCLI.logger.logProgress(\`[${camelized}] generating zustand store...\`, async () => {
33
+ await generateZustandStoreFromSdk('${outputDir}')
34
+ })
43
35
  }
44
36
  })
45
37
  }\
46
38
  `;
39
+ try {
40
+ const existingContents = (await fs.readFile(initializerPath)).toString();
41
+ if (existingContents === contents) {
42
+ return; // early return if the file already matches exactly
43
+ }
44
+ }
45
+ catch {
46
+ // noop — file doesn't exist yet
47
+ }
48
+ try {
49
+ await fs.access(destDir);
50
+ }
51
+ catch {
52
+ await fs.mkdir(destDir, { recursive: true });
53
+ }
47
54
  await fs.writeFile(initializerPath, contents);
48
55
  }
@@ -14,6 +14,7 @@ import writeInitializer from '../helpers/zustandBindings/writeInitializer.js';
14
14
  * * generates the client config file if it does not exist
15
15
  * * generates an initializer, which taps into the sync hooks
16
16
  * to automatically run the @hey-api/openapi-ts CLI util
17
+ * and generate a zustand store from the SDK output
17
18
  * * prints a helpful message, instructing devs on the final
18
19
  * steps for using the generated typed API functions
19
20
  * within their client application.
@@ -1,3 +1,4 @@
1
+ export { default as generateZustandStoreFromSdk } from '../generate/helpers/zustandBindings/generateStoreFromSdk.js';
1
2
  export { default as PsychicBin } from '../bin/index.js';
2
3
  export { default as PsychicLogos } from '../cli/helpers/PsychicLogos.js';
3
4
  export { default as PsychicCLI } from '../cli/index.js';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Reads the generated sdk.gen.ts file, extracts exported function names,
3
+ * and generates a store.gen.ts file with Zustand stores wrapping each
4
+ * SDK function.
5
+ *
6
+ * This is called during `psy sync` after @hey-api/openapi-ts has generated
7
+ * the SDK, so that the store stays in sync with the API.
8
+ */
9
+ export default function generateZustandStoreFromSdk(outputDir: string): Promise<void>;
@@ -8,6 +8,7 @@
8
8
  * * generates the client config file if it does not exist
9
9
  * * generates an initializer, which taps into the sync hooks
10
10
  * to automatically run the @hey-api/openapi-ts CLI util
11
+ * and generate a zustand store from the SDK output
11
12
  * * prints a helpful message, instructing devs on the final
12
13
  * steps for using the generated typed API functions
13
14
  * within their client application.
@@ -1,3 +1,4 @@
1
+ export { default as generateZustandStoreFromSdk } from '../generate/helpers/zustandBindings/generateStoreFromSdk.js';
1
2
  export { default as PsychicBin } from '../bin/index.js';
2
3
  export { default as PsychicLogos } from '../cli/helpers/PsychicLogos.js';
3
4
  export { default as PsychicCLI } from '../cli/index.js';
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "type": "module",
3
3
  "name": "@rvoh/psychic",
4
4
  "description": "Typescript web framework",
5
- "version": "3.1.0",
5
+ "version": "3.1.1",
6
6
  "author": "RVOHealth",
7
7
  "repository": {
8
8
  "type": "git",