vovk-cli 0.0.1-draft.4 → 0.0.1-draft.41

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 (83) hide show
  1. package/README.md +1 -1
  2. package/client-templates/compiled/client.d.ts.ejs +24 -0
  3. package/client-templates/compiled/client.js.ejs +26 -0
  4. package/client-templates/python/__init__.py +276 -0
  5. package/client-templates/ts/index.ts.ejs +36 -0
  6. package/dist/{watcher → dev}/diffSchema.d.mts +2 -2
  7. package/dist/{watcher → dev}/diffSchema.mjs +1 -1
  8. package/dist/dev/ensureClient.d.mts +5 -0
  9. package/dist/dev/ensureClient.mjs +31 -0
  10. package/dist/{watcher → dev}/ensureSchemaFiles.mjs +20 -8
  11. package/dist/dev/index.d.mts +4 -0
  12. package/dist/{watcher → dev}/index.mjs +102 -61
  13. package/dist/{watcher → dev}/logDiffResult.d.mts +2 -2
  14. package/dist/{watcher → dev}/logDiffResult.mjs +13 -9
  15. package/dist/{watcher → dev}/writeOneSchemaFile.d.mts +1 -1
  16. package/dist/{watcher → dev}/writeOneSchemaFile.mjs +4 -3
  17. package/dist/generateClient.d.mts +7 -2
  18. package/dist/generateClient.mjs +74 -80
  19. package/dist/getProjectInfo/getConfig.mjs +1 -1
  20. package/dist/getProjectInfo/getConfigAbsolutePaths.mjs +2 -2
  21. package/dist/getProjectInfo/getRelativeSrcRoot.mjs +4 -4
  22. package/dist/getProjectInfo/getUserConfig.mjs +4 -2
  23. package/dist/getProjectInfo/importUncachedModule.mjs +0 -1
  24. package/dist/getProjectInfo/importUncachedModuleWorker.mjs +0 -1
  25. package/dist/getProjectInfo/index.mjs +2 -2
  26. package/dist/index.d.mts +1 -23
  27. package/dist/index.mjs +29 -47
  28. package/dist/init/checkTSConfigForExperimentalDecorators.mjs +2 -2
  29. package/dist/init/createConfig.d.mts +3 -4
  30. package/dist/init/createConfig.mjs +5 -5
  31. package/dist/init/getTemplateFilesFromPackage.d.mts +2 -1
  32. package/dist/init/getTemplateFilesFromPackage.mjs +4 -5
  33. package/dist/init/index.d.mts +1 -2
  34. package/dist/init/index.mjs +46 -93
  35. package/dist/init/installDependencies.d.mts +4 -1
  36. package/dist/init/installDependencies.mjs +2 -2
  37. package/dist/init/logUpdateDependenciesError.d.mts +11 -0
  38. package/dist/init/logUpdateDependenciesError.mjs +45 -0
  39. package/dist/init/updateDependenciesWithoutInstalling.d.mts +3 -2
  40. package/dist/init/updateDependenciesWithoutInstalling.mjs +12 -7
  41. package/dist/init/updateNPMScripts.d.mts +3 -1
  42. package/dist/init/updateNPMScripts.mjs +10 -6
  43. package/dist/init/updateTypeScriptConfig.mjs +2 -2
  44. package/dist/initProgram.d.mts +2 -0
  45. package/dist/initProgram.mjs +21 -0
  46. package/dist/locateSegments.d.mts +7 -1
  47. package/dist/locateSegments.mjs +9 -6
  48. package/dist/new/addClassToSegmentCode.mjs +6 -2
  49. package/dist/new/addCommonTerms.mjs +1 -0
  50. package/dist/new/index.d.mts +2 -2
  51. package/dist/new/index.mjs +13 -3
  52. package/dist/new/newModule.d.mts +6 -2
  53. package/dist/new/newModule.mjs +51 -27
  54. package/dist/new/newSegment.d.mts +3 -2
  55. package/dist/new/newSegment.mjs +7 -5
  56. package/dist/new/render.d.mts +3 -7
  57. package/dist/new/render.mjs +11 -7
  58. package/dist/postinstall.mjs +5 -3
  59. package/dist/types.d.mts +40 -1
  60. package/dist/utils/debounceWithArgs.d.mts +1 -1
  61. package/dist/utils/debounceWithArgs.mjs +24 -9
  62. package/dist/utils/formatLoggedSegmentName.mjs +1 -1
  63. package/dist/utils/getAvailablePort.mjs +3 -2
  64. package/dist/utils/getFileSystemEntryType.mjs +1 -1
  65. package/package.json +14 -11
  66. package/templates/controller.ejs +20 -18
  67. package/templates/service.ejs +24 -4
  68. package/templates/worker.ejs +24 -1
  69. package/dist/getProjectInfo/directoryExists.d.mts +0 -1
  70. package/dist/getProjectInfo/directoryExists.mjs +0 -10
  71. package/dist/watcher/index.d.mts +0 -6
  72. package/templates_old/MyThingController.c.only.template.ts +0 -32
  73. package/templates_old/MyThingController.c.template.ts +0 -34
  74. package/templates_old/MyThingService.s.template.ts +0 -18
  75. package/templates_old/controller.ejs +0 -85
  76. package/templates_old/service.ejs +0 -9
  77. package/templates_old/worker.ejs +0 -9
  78. package/templates_old/zod/MyThingController.c.only.template.ts +0 -32
  79. package/templates_old/zod/MyThingController.c.template.ts +0 -39
  80. package/templates_old/zod/MyThingService.s.template.ts +0 -18
  81. /package/dist/{watcher → dev}/ensureSchemaFiles.d.mts +0 -0
  82. /package/dist/{watcher → dev}/isMetadataEmpty.d.mts +0 -0
  83. /package/dist/{watcher → dev}/isMetadataEmpty.mjs +0 -0
package/README.md CHANGED
@@ -1 +1 @@
1
- Description is coming soon.
1
+ Description is coming soon.
@@ -0,0 +1,24 @@
1
+ <%- '// auto-generated\n/* eslint-disable */' %>
2
+ import type { clientizeController, VovkClientFetcher } from 'vovk/client';
3
+ import type { promisifyWorker } from 'vovk/worker';
4
+ import type fetcher from '<%= fetcherClientImportPath %>';
5
+
6
+ <% segments.forEach((segment, i) => { %>
7
+ import type { Controllers as Controllers<%= i %>, Workers as Workers<%= i %> } from "<%= segment.segmentImportPath %>";
8
+ <% }) %>
9
+
10
+ type Options = typeof fetcher extends VovkClientFetcher<infer U> ? U : never;
11
+
12
+ <% segments.forEach((segment, i) => {
13
+ const segSchema = segmentsSchema[segment.segmentName];
14
+ if (!segSchema || !segSchema.emitSchema) return;
15
+ const controllers = Object.keys(segSchema.controllers);
16
+ const workers = Object.keys(segSchema.workers);
17
+ %>
18
+ <% controllers.forEach((key) => { %>
19
+ export const <%= key %>: ReturnType<typeof clientizeController<Controllers<%= i %>["<%= key %>"], Options>>;
20
+ <% }) %>
21
+ <% workers.forEach((key) => { %>
22
+ export const <%= key %>: ReturnType<typeof promisifyWorker<Workers<%= i %>["<%= key %>"]>>;
23
+ <% }) %>
24
+ <% }) %>
@@ -0,0 +1,26 @@
1
+ <%- '// auto-generated\n/* eslint-disable */' %>
2
+ const { clientizeController } = require('vovk/client');
3
+ const { promisifyWorker } = require('vovk/worker');
4
+ const { default: fetcher } = require('<%= fetcherClientImportPath %>');
5
+ const schema = require('<%= schemaOutImportPath %>');
6
+
7
+ const { default: validateOnClient = null } = <%- validateOnClientImportPath ? `require('${validateOnClientImportPath}')` : '{}'%>;
8
+ const apiRoot = '<%= apiEntryPoint %>';
9
+
10
+ <% segments.forEach((segment) => {
11
+ const segSchema = segmentsSchema[segment.segmentName];
12
+ if (!segSchema || !segSchema.emitSchema) return;
13
+ const controllers = Object.keys(segSchema.controllers);
14
+ const workers = Object.keys(segSchema.workers);
15
+ %>
16
+ <% controllers.forEach((key) => { %>
17
+ exports.<%= key %> = clientizeController(
18
+ schema['<%= segment.segmentName %>'].controllers.<%= key %>,
19
+ '<%= segment.segmentName %>',
20
+ { fetcher, validateOnClient, defaultOptions: { apiRoot } }
21
+ );
22
+ <% }) %>
23
+ <% workers.forEach((key) => { %>
24
+ exports.<%= key %> = promisifyWorker(null, schema['<%= segment.segmentName %>'].workers.<%= key %>);
25
+ <% }) %>
26
+ <% }) %>
@@ -0,0 +1,276 @@
1
+ import os
2
+ import json
3
+ import requests
4
+ from jsonschema import validate
5
+ from jsonschema.exceptions import ValidationError
6
+ from typing import Optional
7
+
8
+ __all__ = [] # We'll populate this dynamically
9
+
10
+ class ServerError(Exception):
11
+ """Custom exception for server errors that include statusCode and/or message."""
12
+ def __init__(self, status_code: int, message: str):
13
+ super().__init__(f"[{status_code}] {message}")
14
+ self.status_code = status_code
15
+ self.server_message = message
16
+
17
+ def _load_full_schema() -> dict:
18
+ """
19
+ Loads the 'full-schema.json' file (which must sit in the same folder as this __init__.py).
20
+ Returns it as a Python dictionary.
21
+ """
22
+ current_dir = os.path.dirname(__file__)
23
+ schema_path = os.path.join(current_dir, "full-schema.json")
24
+ with open(schema_path, "r", encoding="utf-8") as f:
25
+ return json.load(f)
26
+
27
+ class _RPCBase:
28
+ """
29
+ Base class that provides a validated HTTP request mechanism.
30
+ All dynamic RPC classes will subclass this.
31
+ """
32
+ def __init__(self, base_url: str):
33
+ self.base_url = base_url.rstrip("/")
34
+
35
+ def _handle_stream_response(self, resp: requests.Response):
36
+ """
37
+ Returns a generator that yields JSON objects from a newline-delimited stream.
38
+ It attempts to parse each line as valid JSON.
39
+ If we encounter an 'isError' structure, we raise a ServerError immediately.
40
+ """
41
+ buffer = ""
42
+
43
+ # We'll use resp.iter_content(...) to handle partial chunks
44
+ # decode_unicode=True gives us str chunks in Python 3.
45
+ for chunk in resp.iter_content(chunk_size=None, decode_unicode=True):
46
+ buffer += chunk
47
+ lines = buffer.split("\n")
48
+ # We'll parse every line except the last, which might still be partial
49
+ for line in lines[:-1]:
50
+ line = line.strip()
51
+ if not line:
52
+ continue # skip empty lines
53
+
54
+ try:
55
+ data = json.loads(line)
56
+ except json.JSONDecodeError:
57
+ # Could happen if line is incomplete, but we got a newline anyway
58
+ continue
59
+
60
+ # If the server signals an error in-stream
61
+ if data.get("isError") and "reason" in data:
62
+ resp.close()
63
+ raise ServerError(resp.status_code, str(data["reason"]))
64
+
65
+ yield data
66
+
67
+ # The last piece (lines[-1]) may be incomplete
68
+ buffer = lines[-1]
69
+
70
+ # If there's leftover data in the buffer (no trailing newline at end):
71
+ leftover = buffer.strip()
72
+ if leftover:
73
+ try:
74
+ data = json.loads(leftover)
75
+ if data.get("isError") and "reason" in data:
76
+ resp.close()
77
+ raise ServerError(resp.status_code, str(data["reason"]))
78
+ yield data
79
+ except json.JSONDecodeError:
80
+ # Not valid JSON or partial leftover
81
+ pass
82
+
83
+ # End of stream; close the connection
84
+ resp.close()
85
+
86
+ def _request(
87
+ self,
88
+ method: str,
89
+ endpoint_path: str,
90
+ query: Optional[dict] = None,
91
+ body: Optional[dict] = None,
92
+ query_schema: Optional[dict] = None,
93
+ body_schema: Optional[dict] = None,
94
+ disable_client_validation: bool = False
95
+ ):
96
+ """
97
+ 1. If disable_client_validation is False, validates `query` & `body` (if schemas).
98
+ 2. Makes an HTTP request (using `requests` with stream=True).
99
+ 3. If the response is not 2xx:
100
+ - parse JSON for a possible error structure
101
+ - or raise requests.HTTPError if not available
102
+ 4. If 'x-vovk-stream' == 'true', return a generator that yields JSON objects.
103
+ 5. Otherwise, parse and return the actual response (JSON -> dict or fallback to text).
104
+ """
105
+ # Validate query and body if schemas are provided AND validation not disabled
106
+ if not disable_client_validation:
107
+ if query_schema:
108
+ validate(instance=query or {}, schema=query_schema)
109
+ if body_schema:
110
+ validate(instance=body or {}, schema=body_schema)
111
+
112
+ # Build the final URL
113
+ url = f"{self.base_url}/{endpoint_path}"
114
+
115
+ # Make the request (stream=True to handle streaming)
116
+ resp = requests.request(
117
+ method=method,
118
+ url=url,
119
+ params=query,
120
+ json=body,
121
+ stream=True
122
+ )
123
+
124
+ # Check if status is not 2xx
125
+ if not resp.ok:
126
+ try:
127
+ # Attempt to parse JSON error
128
+ data = resp.json()
129
+ # Example: { "statusCode": 400, "message": "Zod validation failed...", "isError": true }
130
+ if data.get("isError"):
131
+ status_code = data.get("statusCode", resp.status_code)
132
+ message = data.get("message", resp.text)
133
+ resp.close()
134
+ raise ServerError(status_code, message)
135
+ else:
136
+ # Not the structured error we expect - fallback
137
+ resp.raise_for_status()
138
+ except ValueError:
139
+ # If parsing fails, fallback
140
+ resp.raise_for_status()
141
+
142
+ # If we get here, resp is 2xx. Check if streaming is requested.
143
+ if resp.headers.get("x-vovk-stream", "").lower() == "true":
144
+ return self._handle_stream_response(resp)
145
+
146
+ # Non-streaming: parse JSON or return text
147
+ content_type = resp.headers.get("Content-Type", "").lower()
148
+ try:
149
+ if "application/json" in content_type:
150
+ result = resp.json() # parse the body as JSON
151
+ else:
152
+ result = resp.text # fallback if not JSON
153
+ finally:
154
+ # In either case, we can close the connection now since we're reading full body
155
+ resp.close()
156
+
157
+ return result
158
+
159
+
160
+ def _build_controller_class(
161
+ controller_name: str,
162
+ controller_spec: dict,
163
+ segment_name: str
164
+ ):
165
+ """
166
+ Builds a dynamic class (subclass of _RPCBase) for a single controller.
167
+ Instead of instance methods, we create class methods so we can call
168
+ them directly on the class (passing base_url, query, body, etc.).
169
+
170
+ The endpoints will be constructed as: `segmentName/prefix/path`.
171
+ If `prefix` or `path` contain placeholder segments like `:id`,
172
+ they can be replaced by passing a `params` dict, e.g. { "id": 123 }
173
+ which would convert "/foo/:id/bar" --> "/foo/123/bar"
174
+ """
175
+ prefix = controller_spec.get("prefix", "").strip("/")
176
+ handlers = controller_spec.get("handlers", {})
177
+
178
+ class_attrs = {}
179
+
180
+ for handler_name, handler_data in handlers.items():
181
+ # HTTP method (e.g., "GET", "POST", etc.)
182
+ http_method = handler_data["httpMethod"]
183
+
184
+ # Path defined in the schema (may contain ":id", etc.)
185
+ path = handler_data["path"].strip("/")
186
+
187
+ # Combine "segmentName/prefix/path" into a single path
188
+ endpoint_path = f"{segment_name}/{prefix}/{path}".strip("/")
189
+
190
+ # Optional JSON schemas (for query/body)
191
+ validation = handler_data.get("validation", {})
192
+ query_schema = validation.get("query")
193
+ body_schema = validation.get("body")
194
+
195
+ def make_class_method(
196
+ m=http_method,
197
+ ep=endpoint_path,
198
+ q_schema=query_schema,
199
+ b_schema=body_schema,
200
+ name=handler_name
201
+ ):
202
+ @classmethod
203
+ def handler(cls, base_url, *, query=None, body=None, params=None, disable_client_validation=False):
204
+ """
205
+ Class method that instantiates the RPC class (with base_url)
206
+ and immediately calls _request on that instance.
207
+
208
+ :param base_url: The base URL of your API.
209
+ :param query: An optional dict for query parameters.
210
+ :param body: An optional dict for the request JSON body.
211
+ :param params: A dict for path substitutions, e.g. {"id": 42}
212
+ which will replace ":id" in the endpoint path.
213
+ :param disable_client_validation: If True, skip schema validation.
214
+ """
215
+ final_endpoint_path = ep
216
+
217
+ # Perform path param substitution if needed
218
+ for param_key, param_val in (params or {}).items():
219
+ final_endpoint_path = final_endpoint_path.replace(
220
+ f":{param_key}",
221
+ str(param_val)
222
+ )
223
+
224
+ # Instantiate and make the request
225
+ temp_instance = cls(base_url)
226
+ return temp_instance._request(
227
+ method=m,
228
+ endpoint_path=final_endpoint_path,
229
+ query=query,
230
+ body=body,
231
+ query_schema=q_schema,
232
+ body_schema=b_schema,
233
+ disable_client_validation=disable_client_validation
234
+ )
235
+
236
+ handler.__name__ = name
237
+ return handler
238
+
239
+ # Attach the generated class method for this handler
240
+ class_attrs[handler_name] = make_class_method()
241
+
242
+ # Dynamically create a new subclass of _RPCBase with those methods
243
+ return type(controller_name, (_RPCBase,), class_attrs)
244
+
245
+ def _load_controllers():
246
+ """
247
+ Reads the entire 'full-schema.json',
248
+ iterates over each top-level segment (like 'xxx', 'yyy'),
249
+ extracts the segmentName + controllers,
250
+ and dynamically builds classes for each controller.
251
+ """
252
+ data = _load_full_schema()
253
+ all_controllers = {}
254
+
255
+ for segment_key, segment_obj in data.items():
256
+ segment_name = segment_obj.get("segmentName", "").strip("/")
257
+ controllers = segment_obj.get("controllers", {})
258
+
259
+ for ctrl_name, ctrl_spec in controllers.items():
260
+ dynamic_class = _build_controller_class(
261
+ controller_name=ctrl_name,
262
+ controller_spec=ctrl_spec,
263
+ segment_name=segment_name
264
+ )
265
+ all_controllers[ctrl_name] = dynamic_class
266
+
267
+ return all_controllers
268
+
269
+ # Build all controllers at import time
270
+ _controllers_dict = _load_controllers()
271
+
272
+ # Export them at the top level
273
+ for ctrl_name, ctrl_class in _controllers_dict.items():
274
+ globals()[ctrl_name] = ctrl_class
275
+ __all__.append(ctrl_name)
276
+
@@ -0,0 +1,36 @@
1
+ <%- '// auto-generated\n/* eslint-disable */' %>
2
+ import { clientizeController, type VovkClientFetcher } from 'vovk/client';
3
+ import { promisifyWorker } from 'vovk/worker';
4
+ import fetcher from '<%= fetcherClientImportPath %>';
5
+ import schema from '<%= schemaOutImportPath %>';
6
+
7
+ <% if (validateOnClientImportPath) { %>
8
+ import validateOnClient from '<%= validateOnClientImportPath %>';
9
+ <% } else { %>
10
+ const validateOnClient = undefined;
11
+ <% } %>
12
+
13
+ type Options = typeof fetcher extends VovkClientFetcher<infer U> ? U : never;
14
+ const apiRoot = '<%= apiEntryPoint %>';
15
+
16
+ <% segments.forEach((segment, i) => {
17
+ const segSchema = segmentsSchema[segment.segmentName];
18
+ if (!segSchema || !segSchema.emitSchema) return;
19
+ %>
20
+ import type { Controllers as Controllers<%= i %>, Workers as Workers<%= i %> } from "<%= segment.segmentImportPath %>";
21
+
22
+ <% Object.keys(segSchema.controllers).forEach((key) => { %>
23
+ export const <%= key %> = clientizeController<Controllers<%= i %>["<%= key %>"], Options>(
24
+ schema['<%= segment.segmentName %>'].controllers.<%= key %>,
25
+ '<%= segment.segmentName %>',
26
+ { fetcher, validateOnClient, defaultOptions: { apiRoot } }
27
+ );
28
+ <% }) %>
29
+
30
+ <% Object.keys(segSchema.workers).forEach((key) => { %>
31
+ export const <%= key %> = promisifyWorker<Workers<%= i %>["<%= key %>"]>(
32
+ null,
33
+ schema['<%= segment.segmentName %>'].workers.<%= key %>
34
+ );
35
+ <% }) %>
36
+ <% }) %>
@@ -1,5 +1,5 @@
1
1
  import type { VovkSchema } from 'vovk';
2
- import { _VovkControllerSchema, _VovkWorkerSchema } from 'vovk/types';
2
+ import type { _VovkControllerSchema, _VovkWorkerSchema } from 'vovk/types';
3
3
  interface HandlersDiff {
4
4
  nameOfClass: string;
5
5
  added: string[];
@@ -15,7 +15,7 @@ export interface DiffResult {
15
15
  workers: WorkersOrControllersDiff;
16
16
  controllers: WorkersOrControllersDiff;
17
17
  }
18
- export declare function diffHandlers<T extends _VovkWorkerSchema['_handlers'] | _VovkControllerSchema['_handlers']>(oldHandlers: T, newHandlers: T, nameOfClass: string): HandlersDiff;
18
+ export declare function diffHandlers<T extends _VovkWorkerSchema['handlers'] | _VovkControllerSchema['handlers']>(oldHandlers: T, newHandlers: T, nameOfClass: string): HandlersDiff;
19
19
  export declare function diffWorkersOrControllers<T extends VovkSchema['controllers'] | VovkSchema['workers']>(oldItems: T, newItems: T): WorkersOrControllersDiff;
20
20
  /**
21
21
  example output:
@@ -27,7 +27,7 @@ export function diffWorkersOrControllers(oldItems, newItems) {
27
27
  added.push(item);
28
28
  }
29
29
  else {
30
- const handlers = diffHandlers(oldItems[item]._handlers, newItem._handlers, item);
30
+ const handlers = diffHandlers(oldItems[item].handlers, newItem.handlers, item);
31
31
  if (handlers.added.length || handlers.removed.length || handlers.changed.length) {
32
32
  handlersDiff.push(handlers);
33
33
  }
@@ -0,0 +1,5 @@
1
+ import type { ProjectInfo } from '../getProjectInfo/index.mjs';
2
+ export default function ensureClient(projectInfo: ProjectInfo): Promise<{
3
+ written: boolean;
4
+ path: string;
5
+ }>;
@@ -0,0 +1,31 @@
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,5 +1,5 @@
1
- import fs from 'fs/promises';
2
- import path from 'path';
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
3
  import debounce from 'lodash/debounce.js';
4
4
  import writeOneSchemaFile, { ROOT_SEGMENT_SCHEMA_NAME } from './writeOneSchemaFile.mjs';
5
5
  import formatLoggedSegmentName from '../utils/formatLoggedSegmentName.mjs';
@@ -7,17 +7,29 @@ export default async function ensureSchemaFiles(projectInfo, schemaOutAbsolutePa
7
7
  const now = Date.now();
8
8
  let hasChanged = false;
9
9
  // Create index.js file
10
- const indexContent = segmentNames
10
+ const indexContent = `// auto-generated
11
+ ${segmentNames
11
12
  .map((segmentName) => {
12
13
  return `module.exports['${segmentName}'] = require('./${segmentName || ROOT_SEGMENT_SCHEMA_NAME}.json');`;
13
14
  })
14
- .join('\n');
15
- const dTsContent = `import type { VovkSchema } from 'vovk';
16
- declare const segmentSchema: Record<string, VovkSchema>;
15
+ .join('\n')}`;
16
+ const dTsContent = `// auto-generated
17
+ import type { VovkSchema } from 'vovk';
18
+ declare const segmentSchema: {
19
+ ${segmentNames.map((segmentName) => ` '${segmentName}': VovkSchema;`).join('\n')}
20
+ };
17
21
  export default segmentSchema;`;
22
+ const jsAbsolutePath = path.join(schemaOutAbsolutePath, 'index.js');
23
+ const dTsAbsolutePath = path.join(schemaOutAbsolutePath, 'index.d.ts');
24
+ const existingJs = await fs.readFile(jsAbsolutePath, 'utf-8').catch(() => null);
25
+ const existingDTs = await fs.readFile(dTsAbsolutePath, 'utf-8').catch(() => null);
18
26
  await fs.mkdir(schemaOutAbsolutePath, { recursive: true });
19
- await fs.writeFile(path.join(schemaOutAbsolutePath, 'index.js'), indexContent);
20
- await fs.writeFile(path.join(schemaOutAbsolutePath, 'index.d.ts'), dTsContent);
27
+ if (existingJs !== indexContent) {
28
+ await fs.writeFile(jsAbsolutePath, indexContent);
29
+ }
30
+ if (existingDTs !== dTsContent) {
31
+ await fs.writeFile(dTsAbsolutePath, dTsContent);
32
+ }
21
33
  // Create JSON files (if not exist) with name [segmentName].json (where segmentName can include /, which means the folder structure can be nested)
22
34
  await Promise.all(segmentNames.map(async (segmentName) => {
23
35
  const { isCreated } = await writeOneSchemaFile({
@@ -0,0 +1,4 @@
1
+ export declare class VovkDev {
2
+ #private;
3
+ start(): Promise<void>;
4
+ }