vovk-cli 0.0.1-draft.32 → 0.0.1-draft.322

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 (130) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +29 -1
  3. package/client-templates/cjs/index.cjs.ejs +19 -0
  4. package/client-templates/cjs/index.d.cts.ejs +25 -0
  5. package/client-templates/mixins/mixins.d.ts.ejs +64 -0
  6. package/client-templates/mixins/mixins.json.ejs +1 -0
  7. package/client-templates/mjs/index.d.mts.ejs +25 -0
  8. package/client-templates/mjs/index.mjs.ejs +23 -0
  9. package/client-templates/packageJson/package.json.ejs +1 -0
  10. package/client-templates/readme/README.md.ejs +38 -0
  11. package/client-templates/schemaCjs/schema.cjs.ejs +26 -0
  12. package/client-templates/schemaCjs/schema.d.cts.ejs +10 -0
  13. package/client-templates/schemaJson/schema.json.ejs +1 -0
  14. package/client-templates/schemaTs/schema.ts.ejs +35 -0
  15. package/client-templates/ts/index.ts.ejs +33 -0
  16. package/dist/bundle/index.d.mts +8 -0
  17. package/dist/bundle/index.mjs +88 -0
  18. package/dist/dev/diffSegmentSchema.d.mts +36 -0
  19. package/dist/dev/{diffSchema.mjs → diffSegmentSchema.mjs} +3 -11
  20. package/dist/dev/ensureSchemaFiles.d.mts +3 -0
  21. package/dist/dev/ensureSchemaFiles.mjs +15 -31
  22. package/dist/dev/index.d.mts +5 -1
  23. package/dist/dev/index.mjs +181 -78
  24. package/dist/dev/logDiffResult.d.mts +1 -1
  25. package/dist/dev/logDiffResult.mjs +6 -43
  26. package/dist/dev/writeMetaJson.d.mts +2 -0
  27. package/dist/dev/writeMetaJson.mjs +17 -0
  28. package/dist/dev/writeOneSegmentSchemaFile.d.mts +12 -0
  29. package/dist/dev/{writeOneSchemaFile.mjs → writeOneSegmentSchemaFile.mjs} +10 -6
  30. package/dist/generate/ensureClient.d.mts +3 -0
  31. package/dist/generate/ensureClient.mjs +32 -0
  32. package/dist/generate/generate.d.mts +16 -0
  33. package/dist/generate/generate.mjs +293 -0
  34. package/dist/generate/getClientTemplateFiles.d.mts +20 -0
  35. package/dist/generate/getClientTemplateFiles.mjs +94 -0
  36. package/dist/generate/getProjectFullSchema.d.mts +7 -0
  37. package/dist/generate/getProjectFullSchema.mjs +65 -0
  38. package/dist/generate/getTemplateClientImports.d.mts +18 -0
  39. package/dist/generate/getTemplateClientImports.mjs +38 -0
  40. package/dist/generate/index.d.mts +33 -0
  41. package/dist/generate/index.mjs +189 -0
  42. package/dist/generate/mergePackages.d.mts +7 -0
  43. package/dist/generate/mergePackages.mjs +55 -0
  44. package/dist/generate/writeOneClientFile.d.mts +36 -0
  45. package/dist/generate/writeOneClientFile.mjs +123 -0
  46. package/dist/getProjectInfo/getConfig/getConfigAbsolutePaths.d.mts +5 -0
  47. package/dist/getProjectInfo/{getConfigAbsolutePaths.mjs → getConfig/getConfigAbsolutePaths.mjs} +4 -1
  48. package/dist/getProjectInfo/{getRelativeSrcRoot.d.mts → getConfig/getRelativeSrcRoot.d.mts} +1 -1
  49. package/dist/getProjectInfo/{getRelativeSrcRoot.mjs → getConfig/getRelativeSrcRoot.mjs} +2 -2
  50. package/dist/getProjectInfo/getConfig/getTemplateDefs.d.mts +22 -0
  51. package/dist/getProjectInfo/getConfig/getTemplateDefs.mjs +145 -0
  52. package/dist/getProjectInfo/{getUserConfig.d.mts → getConfig/getUserConfig.d.mts} +3 -2
  53. package/dist/getProjectInfo/{getUserConfig.mjs → getConfig/getUserConfig.mjs} +6 -4
  54. package/dist/getProjectInfo/{importUncachedModule.mjs → getConfig/importUncachedModule.mjs} +1 -4
  55. package/dist/getProjectInfo/getConfig/index.d.mts +120 -0
  56. package/dist/getProjectInfo/getConfig/index.mjs +97 -0
  57. package/dist/getProjectInfo/index.d.mts +12 -9
  58. package/dist/getProjectInfo/index.mjs +21 -22
  59. package/dist/index.d.mts +2 -2
  60. package/dist/index.mjs +101 -36
  61. package/dist/init/createConfig.d.mts +2 -2
  62. package/dist/init/createConfig.mjs +14 -12
  63. package/dist/init/getTemplateFilesFromPackage.mjs +10 -5
  64. package/dist/init/index.d.mts +2 -2
  65. package/dist/init/index.mjs +81 -60
  66. package/dist/init/installDependencies.mjs +4 -2
  67. package/dist/init/logUpdateDependenciesError.d.mts +3 -1
  68. package/dist/init/logUpdateDependenciesError.mjs +7 -1
  69. package/dist/init/updateDependenciesWithoutInstalling.mjs +39 -9
  70. package/dist/init/updateNPMScripts.d.mts +3 -1
  71. package/dist/init/updateNPMScripts.mjs +9 -7
  72. package/dist/init/updateTypeScriptConfig.d.mts +4 -1
  73. package/dist/init/updateTypeScriptConfig.mjs +11 -7
  74. package/dist/initProgram.d.mts +1 -1
  75. package/dist/initProgram.mjs +16 -16
  76. package/dist/locateSegments.d.mts +8 -1
  77. package/dist/locateSegments.mjs +14 -4
  78. package/dist/new/addClassToSegmentCode.d.mts +1 -2
  79. package/dist/new/addClassToSegmentCode.mjs +3 -3
  80. package/dist/new/index.d.mts +1 -1
  81. package/dist/new/index.mjs +3 -2
  82. package/dist/new/newModule.d.mts +2 -1
  83. package/dist/new/newModule.mjs +18 -16
  84. package/dist/new/newSegment.d.mts +2 -1
  85. package/dist/new/newSegment.mjs +19 -10
  86. package/dist/new/render.d.mts +7 -3
  87. package/dist/new/render.mjs +29 -8
  88. package/dist/types.d.mts +51 -40
  89. package/dist/utils/compileJSONSchemaToTypeScriptType.d.mts +5 -0
  90. package/dist/utils/compileJSONSchemaToTypeScriptType.mjs +9 -0
  91. package/dist/utils/compileTs.d.mts +12 -0
  92. package/dist/utils/compileTs.mjs +261 -0
  93. package/dist/utils/debounceWithArgs.d.mts +2 -2
  94. package/dist/utils/debounceWithArgs.mjs +24 -6
  95. package/dist/utils/formatLoggedSegmentName.d.mts +3 -1
  96. package/dist/utils/formatLoggedSegmentName.mjs +3 -2
  97. package/dist/utils/getPackageJson.d.mts +3 -0
  98. package/dist/utils/getPackageJson.mjs +22 -0
  99. package/dist/utils/getPublicModuleNameFromPath.d.mts +4 -0
  100. package/dist/utils/getPublicModuleNameFromPath.mjs +9 -0
  101. package/dist/utils/normalizeOpenAPIMixins.d.mts +7 -0
  102. package/dist/utils/normalizeOpenAPIMixins.mjs +67 -0
  103. package/dist/utils/pickSegmentFullSchema.d.mts +3 -0
  104. package/dist/utils/pickSegmentFullSchema.mjs +15 -0
  105. package/dist/utils/removeUnlistedDirectories.d.mts +10 -0
  106. package/dist/utils/removeUnlistedDirectories.mjs +61 -0
  107. package/dist/utils/resolveAbsoluteModulePath.d.mts +2 -0
  108. package/dist/utils/resolveAbsoluteModulePath.mjs +32 -0
  109. package/module-templates/controller.ts.ejs +56 -0
  110. package/module-templates/service.ts.ejs +28 -0
  111. package/package.json +36 -22
  112. package/dist/dev/diffSchema.d.mts +0 -43
  113. package/dist/dev/ensureClient.d.mts +0 -5
  114. package/dist/dev/ensureClient.mjs +0 -31
  115. package/dist/dev/isMetadataEmpty.d.mts +0 -2
  116. package/dist/dev/isMetadataEmpty.mjs +0 -4
  117. package/dist/dev/writeOneSchemaFile.d.mts +0 -11
  118. package/dist/generateClient.d.mts +0 -7
  119. package/dist/generateClient.mjs +0 -97
  120. package/dist/getProjectInfo/getConfig.d.mts +0 -11
  121. package/dist/getProjectInfo/getConfig.mjs +0 -29
  122. package/dist/getProjectInfo/getConfigAbsolutePaths.d.mts +0 -4
  123. package/dist/postinstall.d.mts +0 -1
  124. package/dist/postinstall.mjs +0 -24
  125. package/templates/controller.ejs +0 -51
  126. package/templates/service.ejs +0 -27
  127. package/templates/worker.ejs +0 -24
  128. /package/dist/getProjectInfo/{importUncachedModule.d.mts → getConfig/importUncachedModule.d.mts} +0 -0
  129. /package/dist/getProjectInfo/{importUncachedModuleWorker.d.mts → getConfig/importUncachedModuleWorker.d.mts} +0 -0
  130. /package/dist/getProjectInfo/{importUncachedModuleWorker.mjs → getConfig/importUncachedModuleWorker.mjs} +0 -0
@@ -1,11 +1,29 @@
1
- import debounce from 'lodash/debounce.js';
2
- export default function debounceWithArgs(fn, wait) {
3
- const debouncedFunctions = new Map();
1
+ export default function debounceWithArgs(callback, wait) {
2
+ // Stores timeouts keyed by the stringified arguments
3
+ const timeouts = new Map();
4
4
  return (...args) => {
5
+ // Convert arguments to a JSON string (or any other stable key generation)
5
6
  const key = JSON.stringify(args);
6
- if (!debouncedFunctions.has(key)) {
7
- debouncedFunctions.set(key, debounce(fn, wait));
7
+ // Clear any existing timer for this specific key
8
+ if (timeouts.has(key)) {
9
+ clearTimeout(timeouts.get(key));
8
10
  }
9
- return debouncedFunctions.get(key)(...args);
11
+ // Return a promise that resolves/rejects after the debounce delay
12
+ return new Promise((resolve, reject) => {
13
+ const timeoutId = setTimeout(async () => {
14
+ try {
15
+ const result = await callback(...args);
16
+ resolve(result);
17
+ }
18
+ catch (error) {
19
+ reject(error);
20
+ }
21
+ finally {
22
+ // Remove the entry once the callback is invoked
23
+ timeouts.delete(key);
24
+ }
25
+ }, wait);
26
+ timeouts.set(key, timeoutId);
27
+ });
10
28
  };
11
29
  }
@@ -1,4 +1,6 @@
1
- export default function formatLoggedSegmentName(segmentName: string, { withChalk, upperFirst }?: {
1
+ export default function formatLoggedSegmentName(segmentName: string, { withChalk, upperFirst, isStatic, segmentType, }?: {
2
2
  withChalk?: boolean;
3
3
  upperFirst?: boolean;
4
+ isStatic?: boolean;
5
+ segmentType?: 'segment' | 'mixin';
4
6
  }): string;
@@ -1,7 +1,8 @@
1
1
  import upperFirstLodash from 'lodash/upperFirst.js';
2
2
  import chalkHighlightThing from './chalkHighlightThing.mjs';
3
- export default function formatLoggedSegmentName(segmentName, { withChalk = true, upperFirst = false } = {}) {
4
- let text = segmentName ? `segment "${segmentName}"` : 'the root segment';
3
+ export default function formatLoggedSegmentName(segmentName, { withChalk = true, upperFirst = false, isStatic = false, segmentType = 'segment', // TODO: Apply to all formatLoggedSegmentName invocations
4
+ } = {}) {
5
+ let text = segmentName ? `${isStatic ? 'static ' : ''}${segmentType} "${segmentName}"` : 'the root segment';
5
6
  text = upperFirst ? upperFirstLodash(text) : text;
6
7
  return withChalk ? chalkHighlightThing(text) : text;
7
8
  }
@@ -0,0 +1,3 @@
1
+ import { PackageJson } from 'type-fest';
2
+ import type { ProjectInfo } from '../getProjectInfo/index.mjs';
3
+ export declare function getPackageJson(cwd: string, log: ProjectInfo['log']): Promise<PackageJson>;
@@ -0,0 +1,22 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ let cachedPromise;
4
+ export function getPackageJson(cwd, log) {
5
+ const pkgPath = path.join(cwd, 'package.json');
6
+ // If we have a cached promise, return it
7
+ if (cachedPromise) {
8
+ return cachedPromise;
9
+ }
10
+ const promise = fs
11
+ .readFile(pkgPath, 'utf8')
12
+ .then((content) => JSON.parse(content))
13
+ .catch(() => {
14
+ cachedPromise = undefined;
15
+ log.warn(`Failed to read package.json at ${pkgPath}. Using a fallback.`);
16
+ return {
17
+ name: 'unknown',
18
+ };
19
+ });
20
+ cachedPromise = promise;
21
+ return promise;
22
+ }
@@ -0,0 +1,4 @@
1
+ export default function getPublicModuleNameFromPath(modulePath: string): {
2
+ moduleName: string | null;
3
+ restPath: string;
4
+ };
@@ -0,0 +1,9 @@
1
+ export default function getPublicModuleNameFromPath(modulePath) {
2
+ if (modulePath && !modulePath.startsWith('.') && !modulePath.startsWith('/')) {
3
+ const pathParts = modulePath.split('/');
4
+ const moduleName = pathParts[0].startsWith('@') ? `${pathParts[0]}/${pathParts[1]}` : pathParts[0];
5
+ const restPath = pathParts.slice(pathParts[0].startsWith('@') ? 2 : 1).join('/');
6
+ return { moduleName, restPath };
7
+ }
8
+ return { moduleName: null, restPath: modulePath };
9
+ }
@@ -0,0 +1,7 @@
1
+ import { VovkStrictConfig, type VovkConfig } from 'vovk';
2
+ import type { ProjectInfo } from '../getProjectInfo/index.mjs';
3
+ export declare function normalizeOpenAPIMixins({ mixinModules, log, cwd, }: {
4
+ mixinModules: NonNullable<VovkConfig['openApiMixins']>;
5
+ log: ProjectInfo['log'];
6
+ cwd?: string;
7
+ }): Promise<VovkStrictConfig['openApiMixins']>;
@@ -0,0 +1,67 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import * as YAML from 'yaml';
4
+ import chalkHighlightThing from './chalkHighlightThing.mjs';
5
+ async function getOpenApiSpecLocal(openApiSpecFilePath, cwd) {
6
+ const openApiSpecAbsolutePath = path.resolve(cwd, openApiSpecFilePath);
7
+ const fileName = path.basename(openApiSpecAbsolutePath);
8
+ if (!fileName.endsWith('.json') && !fileName.endsWith('.yaml') && !fileName.endsWith('.yml')) {
9
+ throw new Error(`Invalid OpenAPI spec file format: ${fileName}. Please provide a JSON or YAML file.`);
10
+ }
11
+ const openApiSpecContent = await fs.readFile(openApiSpecAbsolutePath, 'utf8');
12
+ return (fileName.endsWith('.json') ? JSON.parse(openApiSpecContent) : YAML.parse(openApiSpecContent));
13
+ }
14
+ async function getOpenApiSpecRemote({ cwd, url, fallback, log, }) {
15
+ const resp = await fetch(url);
16
+ const text = await resp.text();
17
+ if (!resp.ok) {
18
+ if (fallback) {
19
+ log.warn(`Failed to fetch OpenAPI spec from ${chalkHighlightThing(url)}: ${resp.status} ${resp.statusText}. Falling back to ${chalkHighlightThing(fallback)}`);
20
+ return getOpenApiSpecLocal(fallback, cwd);
21
+ }
22
+ throw new Error(`Failed to fetch OpenAPI spec from ${chalkHighlightThing(url)}: ${resp.status} ${resp.statusText}`);
23
+ }
24
+ if (fallback) {
25
+ const fallbackAbsolutePath = path.resolve(cwd, fallback);
26
+ const existingFallback = await fs.readFile(fallbackAbsolutePath, 'utf8').catch(() => null);
27
+ if (existingFallback !== text) {
28
+ await fs.mkdir(path.dirname(fallbackAbsolutePath), { recursive: true });
29
+ await fs.writeFile(fallbackAbsolutePath, text);
30
+ log.info(`Saved OpenAPI spec to fallback file ${chalkHighlightThing(fallbackAbsolutePath)}`);
31
+ }
32
+ else {
33
+ log.debug(`OpenAPI spec at ${chalkHighlightThing(url)} is unchanged. Skipping write to fallback file ${chalkHighlightThing(fallbackAbsolutePath)}`);
34
+ }
35
+ }
36
+ return (text.trim().startsWith('{') || text.trim().startsWith('[') ? JSON.parse(text) : YAML.parse(text));
37
+ }
38
+ export async function normalizeOpenAPIMixins({ mixinModules, log, cwd = process.cwd(), }) {
39
+ if (mixinModules) {
40
+ const modules = await Promise.all(Object.entries(mixinModules).map(async ([mixinName, { source, apiRoot, getModuleName, getMethodName, errorMessageKey, package: packageJson },]) => {
41
+ let openAPIObject;
42
+ if ('url' in source) {
43
+ openAPIObject = await getOpenApiSpecRemote({ url: source.url, fallback: source.fallback, log, cwd });
44
+ }
45
+ else if ('file' in source) {
46
+ openAPIObject = await getOpenApiSpecLocal(source.file, cwd);
47
+ }
48
+ else if ('object' in source) {
49
+ openAPIObject = source.object;
50
+ }
51
+ else {
52
+ throw new Error('Invalid source type for OpenAPI configuration');
53
+ }
54
+ return {
55
+ source: { object: openAPIObject },
56
+ apiRoot,
57
+ getModuleName,
58
+ getMethodName,
59
+ errorMessageKey,
60
+ package: packageJson,
61
+ mixinName,
62
+ };
63
+ }));
64
+ return Object.fromEntries(modules.map((module) => [module.mixinName, module]));
65
+ }
66
+ return {};
67
+ }
@@ -0,0 +1,3 @@
1
+ import { type VovkSchema } from 'vovk';
2
+ export default function pickSegmentFullSchema(schema: VovkSchema, segmentNames: string[]): VovkSchema;
3
+ export declare function omitSegmentFullSchema(schema: VovkSchema, segmentNames: string[]): VovkSchema;
@@ -0,0 +1,15 @@
1
+ import { VovkSchemaIdEnum } from 'vovk';
2
+ export default function pickSegmentFullSchema(schema, segmentNames) {
3
+ return {
4
+ $schema: VovkSchemaIdEnum.SCHEMA,
5
+ meta: schema.meta,
6
+ segments: Object.fromEntries(segmentNames.map((segmentName) => [segmentName, schema.segments[segmentName]])),
7
+ };
8
+ }
9
+ export function omitSegmentFullSchema(schema, segmentNames) {
10
+ return {
11
+ $schema: VovkSchemaIdEnum.SCHEMA,
12
+ meta: schema.meta,
13
+ segments: Object.fromEntries(Object.entries(schema.segments).filter(([segmentName]) => !segmentNames.includes(segmentName))),
14
+ };
15
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Removes all directories in a folder that aren't in the provided allowlist
3
+ * Supports nested directory paths like 'foo/bar/baz'
4
+ *
5
+ * @param folderPath - The path to the folder to process
6
+ * @param allowedDirs - Array of relative directory paths to keep
7
+ * @returns Promise that resolves when all operations are complete
8
+ */
9
+ declare function removeUnlistedDirectories(folderPath: string, allowedDirs: string[]): Promise<void>;
10
+ export default removeUnlistedDirectories;
@@ -0,0 +1,61 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import getFileSystemEntryType, { FileSystemEntryType } from './getFileSystemEntryType.mjs';
4
+ /**
5
+ * Removes all directories in a folder that aren't in the provided allowlist
6
+ * Supports nested directory paths like 'foo/bar/baz'
7
+ *
8
+ * @param folderPath - The path to the folder to process
9
+ * @param allowedDirs - Array of relative directory paths to keep
10
+ * @returns Promise that resolves when all operations are complete
11
+ */
12
+ async function removeUnlistedDirectories(folderPath, allowedDirs) {
13
+ // Normalize all allowed paths to use the system-specific separator
14
+ const normalizedAllowedDirs = allowedDirs.map((dir) => dir.split('/').join(path.sep));
15
+ // Process the directory tree recursively
16
+ await processDirectory(folderPath, '', normalizedAllowedDirs);
17
+ }
18
+ /**
19
+ * Recursively processes directories to determine which should be kept or removed
20
+ *
21
+ * @param basePath - The absolute base path being processed
22
+ * @param relativePath - The current relative path from the base
23
+ * @param allowedDirs - Normalized list of allowed directory paths
24
+ */
25
+ async function processDirectory(basePath, relativePath, allowedDirs) {
26
+ const currentDirPath = path.join(basePath, relativePath);
27
+ // check if the current path is a directory
28
+ const type = await getFileSystemEntryType(currentDirPath);
29
+ if (type !== FileSystemEntryType.DIRECTORY) {
30
+ // If it's not a directory, return early
31
+ return;
32
+ }
33
+ // Read all entries in the current directory
34
+ const entries = await fs.readdir(currentDirPath, { withFileTypes: true });
35
+ // Process only directories
36
+ const dirEntries = entries.filter((entry) => entry.isDirectory());
37
+ // Check each directory
38
+ for (const dir of dirEntries) {
39
+ // Calculate the new relative path
40
+ const newRelativePath = relativePath ? path.join(relativePath, dir.name) : dir.name;
41
+ // Check if this directory or any of its subdirectories should be kept
42
+ const shouldKeep = allowedDirs.some((allowedDir) => {
43
+ // Direct match
44
+ if (allowedDir === newRelativePath)
45
+ return true;
46
+ // Check if it's a parent path of an allowed directory
47
+ // e.g. "foo" is a parent of "foo/bar/baz"
48
+ return allowedDir.startsWith(newRelativePath + path.sep);
49
+ });
50
+ if (shouldKeep) {
51
+ // Recursively process this directory's contents
52
+ await processDirectory(basePath, newRelativePath, allowedDirs);
53
+ }
54
+ else {
55
+ // Remove this directory since it's not in the allowed list
56
+ const fullPath = path.join(basePath, newRelativePath);
57
+ await fs.rm(fullPath, { recursive: true, force: true });
58
+ }
59
+ }
60
+ }
61
+ export default removeUnlistedDirectories;
@@ -0,0 +1,2 @@
1
+ export declare function getPathUpToModule(moduleName: string, fullPath: string): string;
2
+ export default function resolveAbsoluteModulePath(modulePath: string, cwd: string): string;
@@ -0,0 +1,32 @@
1
+ import path from 'node:path';
2
+ import { createRequire } from 'node:module';
3
+ import getPublicModuleNameFromPath from './getPublicModuleNameFromPath.mjs';
4
+ // Returns the path up to and including the last occurrence of the given module name
5
+ export function getPathUpToModule(moduleName, fullPath) {
6
+ const idx = fullPath.lastIndexOf(moduleName);
7
+ if (idx === -1)
8
+ return moduleName;
9
+ return fullPath.slice(0, idx + moduleName.length);
10
+ }
11
+ export default function resolveAbsoluteModulePath(modulePath, cwd) {
12
+ // If it's an absolute path or starts with '.' (relative), resolve it directly
13
+ if (modulePath.startsWith('/') || modulePath.startsWith('.')) {
14
+ return path.resolve(cwd, modulePath);
15
+ }
16
+ // For npm package names, use Node's module resolution algorithm
17
+ try {
18
+ const { moduleName, restPath } = getPublicModuleNameFromPath(modulePath);
19
+ if (!moduleName) {
20
+ throw new Error(`Invalid module path: ${modulePath}`);
21
+ }
22
+ const require = createRequire(import.meta.url);
23
+ const resolved = require.resolve(moduleName);
24
+ return path.resolve(getPathUpToModule(moduleName, path.dirname(resolved)), restPath);
25
+ }
26
+ catch (e) {
27
+ // eslint-disable-next-line no-console
28
+ console.error(`Error resolving module path: ${modulePath}`, e);
29
+ // If resolution fails, fall back to the original behavior
30
+ return path.resolve(cwd, './node_modules', modulePath);
31
+ }
32
+ }
@@ -0,0 +1,56 @@
1
+ <% const vars = {
2
+ rpcModuleName: t.TheThing + 'Controller',
3
+ ServiceName: t.TheThing + 'Service',
4
+ }; %>
5
+ ---
6
+ dir: <%= t.defaultDir %>
7
+ fileName: <%= vars.rpcModuleName + '.ts' %>
8
+ sourceName: <%= vars.rpcModuleName %>
9
+ compiledName: <%= t.TheThing + 'RPC' %>
10
+ ---
11
+
12
+ import { prefix, get, put, post, del, openapi, type VovkRequest } from 'vovk';
13
+ <% if(t.withService) { %>
14
+ import <%= vars.ServiceName %> from './<%= vars.ServiceName %><%= t.nodeNextResolutionExt.ts %>';
15
+ <% } %>
16
+
17
+ @prefix('<%= t['the-things'] %>')
18
+ export default class <%= vars.rpcModuleName %> {
19
+ @openapi({
20
+ summary: 'Get <%= t.TheThings %>',
21
+ })
22
+ @get()
23
+ static get<%= t.TheThings %> = async (req: VovkRequest<null, { search: string }>) => {
24
+ const search = req.nextUrl.searchParams.get('search');
25
+ <% if(t.withService) { %>
26
+ return <%= vars.ServiceName %>.get<%= t.TheThings %>(search);
27
+ <% } else { %>
28
+ return { results: [], search };
29
+ <% } %>
30
+ }
31
+
32
+ @openapi({
33
+ summary: 'Update <%= t.TheThing %>',
34
+ })
35
+ @put('{id}')
36
+ static update<%= t.TheThing %> = async (req: VovkRequest<{ foo: 'bar' | 'baz' }, { q: string }>, params: { id: string }) => {
37
+ const { id } = params;
38
+ const body = await req.json();
39
+ const q = req.nextUrl.searchParams.get('q');
40
+ <% if(t.withService) { %>
41
+ return <%= vars.ServiceName %>.update<%= t.TheThing %>(id, q, body);
42
+ <% } else { %>
43
+ return { id, body, q };
44
+ <% } %>
45
+ };
46
+
47
+ @post()
48
+ static create<%= t.TheThing %> = () => {
49
+ // ...
50
+ };
51
+
52
+ @del(':id')
53
+ static delete<%= t.TheThing %> = () => {
54
+ // ...
55
+ };
56
+ }
@@ -0,0 +1,28 @@
1
+ <% const vars = {
2
+ rpcModuleName: t.TheThing + 'Controller',
3
+ ServiceName: t.TheThing + 'Service',
4
+ }; %>
5
+ ---
6
+ dir: <%= t.defaultDir %>
7
+ fileName: <%= vars.ServiceName + '.ts' %>
8
+ sourceName: <%= vars.ServiceName %>
9
+ ---
10
+
11
+ import type { VovkBody, VovkQuery } from 'vovk';
12
+ import type <%= vars.rpcModuleName %> from './<%= vars.rpcModuleName %><%= t.nodeNextResolutionExt.ts %>';
13
+
14
+ export default class <%= vars.ServiceName %> {
15
+ static get<%= t.TheThings %> = (search: VovkQuery<typeof <%= vars.rpcModuleName %>.get<%= t.TheThings %>>['search']) => {
16
+ return { results: [], search };
17
+ };
18
+
19
+ static update<%= t.TheThing %> = (
20
+ id: string,
21
+ q: VovkQuery<typeof <%= vars.rpcModuleName %>.update<%= t.TheThing %>>['q'],
22
+ body: VovkBody<typeof <%= vars.rpcModuleName %>.update<%= t.TheThing %>>
23
+ ) => {
24
+ return { id, q, body };
25
+ };
26
+
27
+ // ...
28
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vovk-cli",
3
- "version": "0.0.1-draft.32",
3
+ "version": "0.0.1-draft.322",
4
4
  "bin": {
5
5
  "vovk": "./dist/index.mjs"
6
6
  },
@@ -10,12 +10,12 @@
10
10
  "prefix": ".",
11
11
  "scripts": {
12
12
  "build": "rm -rf dist tsconfig.build.tsbuildinfo && tsc -P tsconfig.build.json",
13
- "build-test": "rm -rf test_dist && tsc -P tsconfig.test.json",
14
- "pre-test": "npm run build && chmod +x ./dist/index.mjs && npm run build-test",
15
- "test-only": "npm run pre-test && node --test --test-only test_dist/test/**/*.mjs",
16
- "test": "npm run pre-test && node --test --test-concurrency=1 test_dist/test/**/*.mjs",
13
+ "postbuild": "chmod +x ./dist/index.mjs",
14
+ "pre-test": "npm run build",
15
+ "test-only": "npm run pre-test && node --experimental-transform-types --experimental-strip-types --test --test-only test/spec/**/*.mts",
16
+ "test": "npm run pre-test && node --experimental-transform-types --experimental-strip-types --test --test-concurrency=1 test/spec/**/*.mts",
17
17
  "tsc": "tsc --noEmit",
18
- "ncu": "npm-check-updates -u",
18
+ "ncu": "npm-check-updates -u -x commander",
19
19
  "npm-publish": "npm publish"
20
20
  },
21
21
  "repository": {
@@ -28,44 +28,58 @@
28
28
  "cli",
29
29
  "vovk"
30
30
  ],
31
- "author": "Andrii Gubanov",
31
+ "author": "Andrey Gubanov",
32
32
  "license": "MIT",
33
33
  "bugs": {
34
34
  "url": "https://github.com/finom/vovk/issues"
35
35
  },
36
36
  "homepage": "https://vovk.dev",
37
37
  "peerDependencies": {
38
- "vovk": "^3.0.0-draft.26"
38
+ "vovk": "^3.0.0-draft.356"
39
+ },
40
+ "optionalDependencies": {
41
+ "vovk-python": "^0.0.1-draft.59"
39
42
  },
40
43
  "dependencies": {
41
- "@inquirer/prompts": "^7.1.0",
42
- "@npmcli/package-json": "^6.1.0",
43
- "chalk": "^5.3.0",
44
- "chokidar": "^4.0.1",
45
- "commander": "^12.1.0",
46
- "concurrently": "^9.1.0",
47
- "dotenv": "^16.4.5",
44
+ "@iarna/toml": "^2.2.5",
45
+ "@inquirer/prompts": "^7.7.1",
46
+ "@npmcli/package-json": "^6.2.0",
47
+ "@types/json-schema": "^7.0.15",
48
+ "chalk": "^5.4.1",
49
+ "chokidar": "^4.0.3",
50
+ "clone-deep": "^4.0.1",
51
+ "commander": "^13.1.0",
52
+ "concurrently": "^9.2.0",
53
+ "dotenv": "^17.2.1",
48
54
  "ejs": "^3.1.10",
55
+ "get-tsconfig": "^4.10.1",
56
+ "glob": "^11.0.3",
49
57
  "gray-matter": "^4.0.3",
50
- "inflection": "^3.0.0",
58
+ "inflection": "^3.0.2",
51
59
  "jsonc-parser": "^3.3.1",
52
60
  "lodash": "^4.17.21",
53
61
  "loglevel": "^1.9.2",
62
+ "openapi3-ts": "^4.5.0",
54
63
  "pluralize": "^8.0.0",
55
- "prettier": "^3.4.1",
64
+ "prettier": "^3.6.2",
56
65
  "tar-stream": "^3.1.7",
57
- "ts-morph": "^24.0.0",
58
- "undici": "^7.0.0"
66
+ "ts-morph": "^26.0.0",
67
+ "tsdown": "^0.13.0",
68
+ "type-fest": "^4.41.0",
69
+ "undici": "^7.12.0",
70
+ "vovk-openapi": "^0.0.1-draft.112",
71
+ "yaml": "^2.8.0"
59
72
  },
60
73
  "devDependencies": {
61
74
  "@types/concat-stream": "^2.0.3",
62
75
  "@types/ejs": "^3.1.5",
76
+ "@types/js-yaml": "^4.0.9",
63
77
  "@types/npmcli__package-json": "^4.0.4",
64
78
  "@types/pluralize": "^0.0.33",
65
- "@types/tar-stream": "^3.1.3",
79
+ "@types/tar-stream": "^3.1.4",
66
80
  "concat-stream": "^2.0.0",
67
- "create-next-app": "^15.0.3",
81
+ "create-next-app": "^15.4.4",
68
82
  "node-pty": "^1.0.0",
69
- "type-fest": "^4.29.0"
83
+ "zod": "^4.0.10"
70
84
  }
71
85
  }
@@ -1,43 +0,0 @@
1
- import type { VovkSchema } from 'vovk';
2
- import type { _VovkControllerSchema, _VovkWorkerSchema } from 'vovk/types';
3
- interface HandlersDiff {
4
- nameOfClass: string;
5
- added: string[];
6
- removed: string[];
7
- changed: string[];
8
- }
9
- interface WorkersOrControllersDiff {
10
- added: string[];
11
- removed: string[];
12
- handlers: HandlersDiff[];
13
- }
14
- export interface DiffResult {
15
- workers: WorkersOrControllersDiff;
16
- controllers: WorkersOrControllersDiff;
17
- }
18
- export declare function diffHandlers<T extends _VovkWorkerSchema['handlers'] | _VovkControllerSchema['handlers']>(oldHandlers: T, newHandlers: T, nameOfClass: string): HandlersDiff;
19
- export declare function diffWorkersOrControllers<T extends VovkSchema['controllers'] | VovkSchema['workers']>(oldItems: T, newItems: T): WorkersOrControllersDiff;
20
- /**
21
- example output:
22
- {
23
- workers: {
24
- added: ["WorkerC"],
25
- removed: ["WorkerA"],
26
- handlers: []
27
- },
28
- controllers: {
29
- added: ["ControllerC"],
30
- removed: ["ControllerB"],
31
- handlers: [
32
- {
33
- nameOfClass: "ControllerA",
34
- added: ["handlerF"],
35
- removed: [],
36
- changed: ["handlerD"]
37
- }
38
- ]
39
- }
40
- }
41
- */
42
- export default function diffSchema(oldJson: VovkSchema, newJson: VovkSchema): DiffResult;
43
- export {};
@@ -1,5 +0,0 @@
1
- import type { ProjectInfo } from '../getProjectInfo/index.mjs';
2
- export default function ensureClient(projectInfo: ProjectInfo): Promise<{
3
- written: boolean;
4
- path: string;
5
- }>;
@@ -1,31 +0,0 @@
1
- import path from 'node:path';
2
- import fs from 'node:fs/promises';
3
- export default async function ensureClient(projectInfo) {
4
- const { config, cwd, log } = projectInfo;
5
- const now = Date.now();
6
- const clientoOutDirAbsolutePath = path.join(cwd, config.clientOutDir);
7
- const dts = `// auto-generated
8
- // This is a temporary placeholder to avoid errors if client is imported before it's generated.
9
- // If you still see this text, the client is not generated yet because of an unknown problem.
10
- // Feel free to report an issue at https://github.com/finom/vovk/issues`;
11
- const js = dts;
12
- const ts = dts;
13
- const localJsAbsolutePath = path.join(clientoOutDirAbsolutePath, 'client.js');
14
- const localDtsAbsolutePath = path.join(clientoOutDirAbsolutePath, 'client.d.ts');
15
- const localTsAbsolutePath = path.join(clientoOutDirAbsolutePath, 'index.ts');
16
- const existingJs = await fs.readFile(localJsAbsolutePath, 'utf-8').catch(() => null);
17
- const existingDts = await fs.readFile(localDtsAbsolutePath, 'utf-8').catch(() => null);
18
- const existingTs = await fs.readFile(localTsAbsolutePath, 'utf-8').catch(() => null);
19
- if (existingJs && existingDts && existingTs) {
20
- return { written: false, path: clientoOutDirAbsolutePath };
21
- }
22
- await fs.mkdir(clientoOutDirAbsolutePath, { recursive: true });
23
- if (!existingJs)
24
- await fs.writeFile(localJsAbsolutePath, js);
25
- if (!existingDts)
26
- await fs.writeFile(localDtsAbsolutePath, dts);
27
- if (!existingTs)
28
- await fs.writeFile(localTsAbsolutePath, ts);
29
- log.info(`Empty client files are generated in ${Date.now() - now}ms`);
30
- return { written: true, path: clientoOutDirAbsolutePath };
31
- }
@@ -1,2 +0,0 @@
1
- import type { VovkSchema } from 'vovk';
2
- export default function isSchemaEmpty(schema: VovkSchema): boolean;
@@ -1,4 +0,0 @@
1
- import isEmpty from 'lodash/isEmpty.js';
2
- export default function isSchemaEmpty(schema) {
3
- return isEmpty(schema.controllers) && isEmpty(schema.workers);
4
- }
@@ -1,11 +0,0 @@
1
- import type { VovkSchema } from 'vovk';
2
- import { type DiffResult } from './diffSchema.mjs';
3
- export declare const ROOT_SEGMENT_SCHEMA_NAME = "_root";
4
- export default function writeOneSchemaFile({ schemaOutAbsolutePath, schema, skipIfExists, }: {
5
- schemaOutAbsolutePath: string;
6
- schema: VovkSchema;
7
- skipIfExists?: boolean;
8
- }): Promise<{
9
- isCreated: boolean;
10
- diffResult: DiffResult | null;
11
- }>;
@@ -1,7 +0,0 @@
1
- import type { VovkSchema } from 'vovk';
2
- import type { ProjectInfo } from './getProjectInfo/index.mjs';
3
- import type { Segment } from './locateSegments.mjs';
4
- export default function generateClient(projectInfo: ProjectInfo, segments: Segment[], segmentsSchema: Record<string, VovkSchema>): Promise<{
5
- written: boolean;
6
- path: string;
7
- }>;