@kosmojs/dev 0.0.25 → 0.0.27

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/pkg/chassis.js ADDED
@@ -0,0 +1,636 @@
1
+ // src/chassis.ts
2
+ import http from "node:http";
3
+ import net from "node:net";
4
+ import { join, resolve as resolve2 } from "node:path";
5
+ import { styleText } from "node:util";
6
+ import { build, createServer } from "vite";
7
+ import {
8
+ defaults,
9
+ pathResolver as pathResolver3,
10
+ routesFactory,
11
+ spinnerFactory
12
+ } from "@kosmojs/lib";
13
+
14
+ // src/cache.ts
15
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
16
+ import { dirname, resolve } from "node:path";
17
+ import crc from "crc/crc32";
18
+ import self from "@kosmojs/dev/package.json" with { type: "json" };
19
+ import { pathExists, pathResolver } from "@kosmojs/lib";
20
+ var cacheFactory = (route, sourceFolder, extraContext) => {
21
+ const cacheFile = pathResolver(sourceFolder).createPath.libApi(
22
+ dirname(route.file),
23
+ "cache.json"
24
+ );
25
+ const validateCache = async (cache) => {
26
+ if (!cache?.hash) {
27
+ return;
28
+ }
29
+ if (!cache.typeDeclarations || !cache.referencedFiles) {
30
+ return;
31
+ }
32
+ const hash = await generateFileHash(route.fileFullpath, {
33
+ ...extraContext
34
+ });
35
+ if (!identicalHashSum(cache.hash, hash)) {
36
+ return;
37
+ }
38
+ for (const [file, hash2] of Object.entries(cache.referencedFiles)) {
39
+ if (!identicalHashSum(
40
+ hash2,
41
+ await generateFileHash(resolve(sourceFolder.root, file))
42
+ )) {
43
+ return;
44
+ }
45
+ }
46
+ return cache;
47
+ };
48
+ return {
49
+ async get(opt) {
50
+ if (await pathExists(cacheFile)) {
51
+ try {
52
+ const cache = JSON.parse(await readFile(cacheFile, "utf8"));
53
+ return opt?.validate ? validateCache(cache) : cache;
54
+ } catch (_e) {
55
+ }
56
+ }
57
+ return void 0;
58
+ },
59
+ async set(cache) {
60
+ const hash = await generateFileHash(route.fileFullpath, {
61
+ ...extraContext
62
+ });
63
+ const referencedFiles = {};
64
+ for (const file of cache.referencedFiles) {
65
+ referencedFiles[
66
+ // Strip project root to ensure cached paths are relative
67
+ // and portable across environments (CI, local, etc.)
68
+ file.replace(`${sourceFolder.root}/`, "")
69
+ ] = await generateFileHash(file);
70
+ }
71
+ const value = { ...cache, hash, referencedFiles };
72
+ await mkdir(dirname(cacheFile), { recursive: true });
73
+ await writeFile(cacheFile, JSON.stringify(value, null, 2), "utf8");
74
+ return value;
75
+ }
76
+ };
77
+ };
78
+ var generateFileHash = async (file, extraContext) => {
79
+ let fileContent;
80
+ try {
81
+ fileContent = await readFile(file, "utf8");
82
+ } catch (_e) {
83
+ return 0;
84
+ }
85
+ return fileContent ? crc(
86
+ JSON.stringify({
87
+ ...extraContext,
88
+ [self.cacheVersion]: fileContent
89
+ })
90
+ ) : 0;
91
+ };
92
+ var identicalHashSum = (a, b) => {
93
+ return a === b;
94
+ };
95
+
96
+ // src/core-generator/index.ts
97
+ import { dirname as dirname2 } from "node:path";
98
+ import {
99
+ defineGenerator,
100
+ defineGeneratorFactory,
101
+ generateTsconfig,
102
+ pathResolver as pathResolver2,
103
+ renderToFile
104
+ } from "@kosmojs/lib";
105
+
106
+ // src/templates/env.d.ts
107
+ var env_d_default = 'declare const KOSMO_PRODUCTION_BUILD: boolean;\n\n/**\n * Enhances base TypeScript types with JSON Schema validation constraints.\n * Allows declaring refined types that carry validation metadata for runtime\n * schema validation while maintaining full TypeScript type safety.\n *\n * Useful for generating validation schemas and ensuring\n * data conforms to specific business rules beyond basic type checking.\n * */\ndeclare type VRefine<\n T extends unknown[] | number | string | object,\n _ extends T extends unknown[]\n ? TArrayOptions\n : T extends number\n ? TNumberOptions\n : T extends string\n ? TStringOptions\n : TObjectOptions,\n> = T;\n\n/**\n * Type definitions inspired by and gently adapted from TypeBox.\n * Original TypeBox created by sinclairzx81: https://github.com/sinclairzx81/typebox\n * TypeBox is licensed under MIT: https://github.com/sinclairzx81/typebox/blob/main/license\n *\n * These types provide JSON Schema compatible type refinements for TypeScript.\n * */\ninterface TSchema {}\n\n// ------------------------------------------------------------------\n// ObjectOptions\n// ------------------------------------------------------------------\ninterface TObjectOptions {\n /**\n * Defines whether additional properties are allowed beyond those explicitly defined in `properties`.\n */\n additionalProperties?: TSchema | boolean;\n /**\n * The minimum number of properties required in the object.\n */\n minProperties?: number;\n /**\n * The maximum number of properties allowed in the object.\n */\n maxProperties?: number;\n /**\n * Defines conditional requirements for properties.\n */\n dependencies?: Record<string, boolean | TSchema | string[]>;\n /**\n * Specifies properties that *must* be present if a given property is present.\n */\n dependentRequired?: Record<string, string[]>;\n /**\n * Defines schemas that apply if a specific property is present.\n */\n dependentSchemas?: Record<string, TSchema>;\n /**\n * Maps regular expressions to schemas properties matching a pattern must validate against the schema.\n */\n patternProperties?: Record<string, TSchema>;\n /**\n * A schema that all property names within the object must validate against.\n */\n propertyNames?: TSchema;\n}\n\n// ------------------------------------------------------------------\n// ArrayOptions\n// ------------------------------------------------------------------\ninterface TArrayOptions {\n /**\n * The minimum number of items allowed in the array.\n */\n minItems?: number;\n /**\n * The maximum number of items allowed in the array.\n */\n maxItems?: number;\n /**\n * A schema that at least one item in the array must validate against.\n */\n contains?: TSchema;\n /**\n * The minimum number of array items that must validate against the `contains` schema.\n */\n minContains?: number;\n /**\n * The maximum number of array items that may validate against the `contains` schema.\n */\n maxContains?: number;\n /**\n * An array of schemas, where each schema in `prefixItems` validates against items at corresponding positions from the beginning of the array.\n */\n prefixItems?: TSchema[];\n /**\n * If `true`, all items in the array must be unique.\n */\n uniqueItems?: boolean;\n}\n\n// ------------------------------------------------------------------\n// NumberOptions\n// ------------------------------------------------------------------\ninterface TNumberOptions {\n /**\n * Specifies an exclusive upper limit for the number (number must be less than this value).\n */\n exclusiveMaximum?: number | bigint;\n /**\n * Specifies an exclusive lower limit for the number (number must be greater than this value).\n */\n exclusiveMinimum?: number | bigint;\n /**\n * Specifies an inclusive upper limit for the number (number must be less than or equal to this value).\n */\n maximum?: number | bigint;\n /**\n * Specifies an inclusive lower limit for the number (number must be greater than or equal to this value).\n */\n minimum?: number | bigint;\n /**\n * Specifies that the number must be a multiple of this value.\n */\n multipleOf?: number | bigint;\n}\n\n// ------------------------------------------------------------------\n// StringOptions\n// ------------------------------------------------------------------\ntype TFormat =\n | "date-time"\n | "date"\n | "duration"\n | "email"\n | "hostname"\n | "idn-email"\n | "idn-hostname"\n | "ipv4"\n | "ipv6"\n | "iri-reference"\n | "iri"\n | "json-pointer-uri-fragment"\n | "json-pointer"\n | "json-string"\n | "regex"\n | "relative-json-pointer"\n | "time"\n | "uri-reference"\n | "uri-template"\n | "url"\n | "uuid";\n\ninterface TStringOptions {\n /**\n * Specifies the expected string format.\n *\n * Common values include:\n * - `base64` \u2013 Base64-encoded string.\n * - `date-time` \u2013 [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time format.\n * - `date` \u2013 [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date (YYYY-MM-DD).\n * - `duration` \u2013 [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) duration format.\n * - `email` \u2013 RFC 5321/5322 compliant email address.\n * - `hostname` \u2013 RFC 1034/1035 compliant host name.\n * - `idn-email` \u2013 Internationalized email address.\n * - `idn-hostname` \u2013 Internationalized host name.\n * - `ipv4` \u2013 IPv4 address.\n * - `ipv6` \u2013 IPv6 address.\n * - `iri` / `iri-reference` \u2013 Internationalized Resource Identifier.\n * - `json-pointer` / `json-pointer-uri-fragment` \u2013 JSON Pointer format.\n * - `json-string` \u2013 String containing valid JSON.\n * - `regex` \u2013 Regular expression syntax.\n * - `relative-json-pointer` \u2013 Relative JSON Pointer format.\n * - `time` \u2013 [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) time (HH:MM:SS).\n * - `uri-reference` / `uri-template` \u2013 URI reference or template.\n * - `url` \u2013 Web URL format.\n * - `uuid` \u2013 RFC 4122 UUID string.\n *\n * May also be a custom format string.\n */\n format?: TFormat;\n /**\n * Specifies the minimum number of characters allowed in the string.\n * Must be a non-negative integer.\n */\n minLength?: number;\n /**\n * Specifies the maximum number of characters allowed in the string.\n * Must be a non-negative integer.\n */\n maxLength?: number;\n /**\n * Specifies a regular expression pattern that the string value must match.\n * Can be provided as a string (ECMA-262 regex syntax) or a `RegExp` object.\n */\n pattern?: string | RegExp;\n}\n';
108
+
109
+ // src/templates/gitignore.hbs
110
+ var gitignore_default = "# Ignore all files\n*\n\n# But don't ignore directories (so Git can traverse them)\n!*/\n\n# And don't ignore these files at any depth\n!cache.json\n!types.ts\n";
111
+
112
+ // src/templates/schemas.hbs
113
+ var schemas_default = '// stub schemas, specialized generators supposed to overwrite this file\nimport type { ValidationSchemas } from "@kosmojs/core/api";\nexport type { ValidationSchemas };\nexport const validationSchemas: ValidationSchemas = {};\n';
114
+
115
+ // src/core-generator/index.ts
116
+ var factory = defineGeneratorFactory((meta, sourceFolder) => {
117
+ const { createPath } = pathResolver2(sourceFolder);
118
+ const start = async () => {
119
+ await renderToFile(
120
+ createPath.lib("../tsconfig.base.json"),
121
+ JSON.stringify(generateTsconfig(), void 0, 2),
122
+ {}
123
+ );
124
+ {
125
+ const tsconfig = generateTsconfig(sourceFolder.name);
126
+ const compilerOptions = {};
127
+ const types = new Set(tsconfig.compilerOptions.types || []);
128
+ for (const { meta: meta2 } of sourceFolder.config.generators || []) {
129
+ if (meta2.jsxImportSource) {
130
+ compilerOptions.jsxImportSource = meta2.jsxImportSource;
131
+ }
132
+ for (const type of meta2.types || []) {
133
+ types.add(type);
134
+ }
135
+ }
136
+ await renderToFile(
137
+ createPath.lib("tsconfig.base.json"),
138
+ JSON.stringify(
139
+ {
140
+ ...tsconfig,
141
+ compilerOptions: {
142
+ ...tsconfig.compilerOptions,
143
+ ...compilerOptions,
144
+ types: [...types.values()]
145
+ }
146
+ },
147
+ void 0,
148
+ 2
149
+ ),
150
+ {}
151
+ );
152
+ }
153
+ await renderToFile(createPath.lib("../env.d.ts"), env_d_default, {});
154
+ await renderToFile(
155
+ createPath.lib("../.gitignore"),
156
+ gitignore_default,
157
+ {},
158
+ { overwrite: false }
159
+ );
160
+ await renderToFile(createPath.lib("ssg.ts"), "export default [];", {});
161
+ };
162
+ const generateLibFiles = async (entries) => {
163
+ for (const { kind, entry } of entries) {
164
+ if (kind === "apiRoute") {
165
+ await renderToFile(
166
+ createPath.libApi(dirname2(entry.file), "schemas.ts"),
167
+ schemas_default,
168
+ { route: entry },
169
+ { overwrite: false }
170
+ );
171
+ }
172
+ }
173
+ };
174
+ return {
175
+ meta,
176
+ options: void 0,
177
+ start,
178
+ watch: generateLibFiles,
179
+ build: generateLibFiles
180
+ };
181
+ });
182
+ var core_generator_default = defineGenerator(() => {
183
+ const meta = { name: "Core" };
184
+ return {
185
+ meta,
186
+ options: void 0,
187
+ factory: (sourceFolder) => factory(meta, sourceFolder)
188
+ };
189
+ });
190
+
191
+ // src/chassis.ts
192
+ var chassis_default = async (projectSettings) => {
193
+ const { devPort, command } = projectSettings;
194
+ for (const sourceFolder of projectSettings.sourceFolders) {
195
+ for (const base of folderGenerators(sourceFolder)) {
196
+ if (!base.meta?.name || typeof base.factory !== "function") {
197
+ throw new Error(
198
+ `${sourceFolder.name}: Unrecognized generator - must be created via defineGenerator()`
199
+ );
200
+ }
201
+ const factory2 = base.factory(sourceFolder);
202
+ if (!factory2.meta?.name) {
203
+ throw new Error(
204
+ `${sourceFolder.name}: ${base.meta.name} generator is missing meta property`
205
+ );
206
+ }
207
+ try {
208
+ await factory2.start?.();
209
+ } catch (error) {
210
+ console.error(
211
+ styleText(
212
+ "red",
213
+ `${sourceFolder.name}: ${base.meta.name} generator failed to initialize`
214
+ )
215
+ );
216
+ throw error;
217
+ }
218
+ }
219
+ }
220
+ if (command === "build") {
221
+ for (const sourceFolder of projectSettings.sourceFolders) {
222
+ const { config, baseurl } = sourceFolder;
223
+ const { createPath } = pathResolver3(sourceFolder);
224
+ const resolvedRoutes = [];
225
+ {
226
+ const { resolvers } = await routesFactory(sourceFolder, cacheFactory);
227
+ const spinner = spinnerFactory(
228
+ `${sourceFolder.name}: resolving routes`
229
+ );
230
+ for (const { name, handler } of resolvers.values()) {
231
+ spinner.append(
232
+ `[ ${resolvedRoutes.length + 1} of ${resolvers.size} ] ${name}`
233
+ );
234
+ resolvedRoutes.push(await handler());
235
+ }
236
+ spinner.succeed("ready \u2728");
237
+ }
238
+ const generators = folderGenerators(sourceFolder);
239
+ const plugins = [...config.plugins || []];
240
+ for (const base of generators) {
241
+ await base.factory(sourceFolder).build?.(resolvedRoutes);
242
+ plugins.push(...base.plugins?.(sourceFolder, command) || []);
243
+ }
244
+ {
245
+ const outDir = createPath.distDir("client");
246
+ await build({
247
+ ...config,
248
+ configFile: false,
249
+ root: createPath.src(),
250
+ base: join(baseurl, "/"),
251
+ plugins,
252
+ resolve: {
253
+ ...config.resolve,
254
+ tsconfigPaths: true
255
+ },
256
+ build: {
257
+ ...config?.build,
258
+ outDir,
259
+ manifest: true,
260
+ emptyOutDir: true
261
+ },
262
+ cacheDir: cacheDir(sourceFolder, command, "client")
263
+ });
264
+ }
265
+ const apiGenerator = generators.find((e) => e.meta.slot === "api");
266
+ if (apiGenerator) {
267
+ const dir = createPath.distDir("api");
268
+ const noExternal = Array.isArray(apiGenerator.options?.noExternal) ? apiGenerator.options.noExternal : generators.flatMap(({ meta }) => {
269
+ return Object.keys({
270
+ ...meta.dependencies,
271
+ ...meta.devDependencies
272
+ });
273
+ });
274
+ await build({
275
+ configFile: false,
276
+ root: createPath.src(),
277
+ appType: "custom",
278
+ plugins: [...apiGenerator.plugins?.(sourceFolder, command) || []],
279
+ define: {
280
+ ...config.define,
281
+ KOSMO_PRODUCTION_BUILD: "true"
282
+ },
283
+ ssr: { noExternal },
284
+ resolve: {
285
+ ...config.resolve,
286
+ tsconfigPaths: true,
287
+ conditions: ["node"]
288
+ },
289
+ build: {
290
+ ssr: true,
291
+ target: "esnext",
292
+ sourcemap: true,
293
+ emptyOutDir: true,
294
+ rolldownOptions: {
295
+ input: [createPath.api("app.ts"), createPath.api("server.ts")],
296
+ output: {
297
+ dir,
298
+ format: "esm"
299
+ }
300
+ }
301
+ },
302
+ cacheDir: cacheDir(sourceFolder, command, "backend")
303
+ });
304
+ }
305
+ for (const base of generators) {
306
+ await base.factory(sourceFolder).postBuild?.(resolvedRoutes);
307
+ }
308
+ }
309
+ return async () => {
310
+ };
311
+ }
312
+ const requestHandlers = [];
313
+ const teardownHandlers = [];
314
+ const eventMap = {};
315
+ for (const sourceFolder of projectSettings.sourceFolders) {
316
+ eventMap[sourceFolder.name] = await eventFactory(sourceFolder);
317
+ }
318
+ let port = await findFreePort(devPort);
319
+ for (const sourceFolder of projectSettings.sourceFolders) {
320
+ const { config, baseurl } = sourceFolder;
321
+ const { createPath } = pathResolver3(sourceFolder);
322
+ const requestMatchers = matchersFactory(sourceFolder);
323
+ const generators = folderGenerators(sourceFolder);
324
+ const plugins = [...config.plugins || []];
325
+ for (const base of generators) {
326
+ plugins.push(...base.plugins?.(sourceFolder, command) || []);
327
+ }
328
+ const viteServer = await createServer({
329
+ ...config,
330
+ configFile: false,
331
+ root: createPath.src(),
332
+ base: join(baseurl, "/"),
333
+ plugins,
334
+ server: {
335
+ ...config.server,
336
+ port: port++,
337
+ middlewareMode: true,
338
+ hmr: { port: port++ }
339
+ },
340
+ resolve: {
341
+ ...config.resolve,
342
+ tsconfigPaths: true
343
+ },
344
+ define: {
345
+ ...config.define
346
+ },
347
+ cacheDir: cacheDir(sourceFolder, command, "client")
348
+ });
349
+ for (const [evt, handler] of Object.entries(eventMap[sourceFolder.name])) {
350
+ viteServer.watcher.on(evt, handler);
351
+ }
352
+ requestHandlers.push([
353
+ [sourceFolder.baseurl],
354
+ () => requestMatchers.base,
355
+ () => viteServer.middlewares
356
+ ]);
357
+ teardownHandlers.push(viteServer.close);
358
+ }
359
+ for (const sourceFolder of projectSettings.sourceFolders) {
360
+ const { config } = sourceFolder;
361
+ if (!folderGenerators(sourceFolder).find((e) => e.meta.slot === "api")) {
362
+ continue;
363
+ }
364
+ const { createPath } = pathResolver3(sourceFolder);
365
+ const requestMatchers = matchersFactory(sourceFolder);
366
+ const viteServer = await createServer({
367
+ configFile: false,
368
+ root: createPath.src(),
369
+ appType: "custom",
370
+ server: {
371
+ port: port++,
372
+ middlewareMode: true,
373
+ hmr: { port: port++ }
374
+ },
375
+ resolve: { tsconfigPaths: true },
376
+ define: {
377
+ ...config?.define,
378
+ KOSMO_PRODUCTION_BUILD: "false"
379
+ },
380
+ environments: {
381
+ api: {
382
+ resolve: {
383
+ conditions: ["node"]
384
+ }
385
+ }
386
+ },
387
+ cacheDir: cacheDir(sourceFolder, command, "backend")
388
+ });
389
+ const env = viteServer.environments.api;
390
+ const loadDevSetup = async () => {
391
+ env.runner.clearCache();
392
+ return env.runner.import(join(defaults.apiDir, "dev.ts")).then((e) => e.default);
393
+ };
394
+ let devSetup = await loadDevSetup();
395
+ for (const [evt, handler] of Object.entries(eventMap[sourceFolder.name])) {
396
+ viteServer.watcher.on(evt, async (file) => {
397
+ const mods = env.moduleGraph.getModulesByFile(file);
398
+ if (mods?.size) {
399
+ await handler(file);
400
+ await devSetup?.teardownHandler?.();
401
+ devSetup = await loadDevSetup();
402
+ }
403
+ });
404
+ }
405
+ requestHandlers.push([
406
+ [sourceFolder.baseurl, sourceFolder.apiurl],
407
+ () => devSetup.requestMatcher || requestMatchers.api,
408
+ () => devSetup.requestHandler()
409
+ ]);
410
+ teardownHandlers.push(viteServer.close);
411
+ }
412
+ const requestHandlerWeight = ([
413
+ segments
414
+ ]) => {
415
+ const [base, api] = segments;
416
+ const weight = base.split("/").filter(Boolean).length;
417
+ return api ? weight + 5 : weight;
418
+ };
419
+ const handlers = requestHandlers.sort(
420
+ (a, b) => requestHandlerWeight(b) - requestHandlerWeight(a)
421
+ );
422
+ const httpServer = http.createServer((req, res) => {
423
+ for (const [, matcherFactory, handlerFactory] of handlers) {
424
+ const [matcher, handler] = [matcherFactory(), handlerFactory()];
425
+ if (matcher(req)) {
426
+ handler(req, res);
427
+ return;
428
+ }
429
+ }
430
+ res.writeHead(404, { "Content-Type": "text/html" });
431
+ res.end("<h1>404: Not Found</h1>");
432
+ });
433
+ httpServer.on("error", (error) => {
434
+ console.error(
435
+ styleText("red", `Failed to start dev server on port ${devPort}`)
436
+ );
437
+ console.error(error.message);
438
+ process.exit(1);
439
+ });
440
+ httpServer.listen(devPort);
441
+ teardownHandlers.push(async () => {
442
+ httpServer.close();
443
+ });
444
+ return async () => {
445
+ for (const handler of teardownHandlers) {
446
+ await handler().catch(console.error);
447
+ }
448
+ await new Promise((resolve3) => setTimeout(resolve3, 100));
449
+ };
450
+ };
451
+ var cacheDir = ({ root, name }, command, mode) => {
452
+ return resolve2(root, `var/.vite/${name}/${command}/${mode}`);
453
+ };
454
+ var folderGenerators = (sourceFolder) => {
455
+ const { generators = [] } = sourceFolder.config;
456
+ const coreGenerators = {};
457
+ const userGenerators = [];
458
+ for (const base of generators) {
459
+ if (base.meta.slot) {
460
+ coreGenerators[base.meta.slot] = base;
461
+ } else {
462
+ userGenerators.push(base);
463
+ }
464
+ }
465
+ return [
466
+ // core generator should run first
467
+ core_generator_default(),
468
+ // then api generator
469
+ ...coreGenerators.api ? [coreGenerators.api] : [],
470
+ // then fetch generator, only if api generator also enabled
471
+ ...coreGenerators.fetch && coreGenerators.api ? [coreGenerators.fetch] : [],
472
+ // then user generators in the order they were added
473
+ ...userGenerators,
474
+ // then ssr generator should run after user generators
475
+ ...coreGenerators.ssr ? [coreGenerators.ssr] : [],
476
+ // and ssg generator should run last
477
+ ...coreGenerators.ssg ? [coreGenerators.ssg] : []
478
+ ];
479
+ };
480
+ var eventFactory = async (sourceFolder) => {
481
+ const { resolvers, resolversFactory } = await routesFactory(
482
+ sourceFolder,
483
+ cacheFactory
484
+ );
485
+ const { createPath } = pathResolver3(sourceFolder);
486
+ const generators = [];
487
+ for (const base of folderGenerators(sourceFolder)) {
488
+ const factory2 = base.factory(sourceFolder);
489
+ generators.push({ name: base.meta.name, factory: factory2 });
490
+ }
491
+ const resolvedRoutes = /* @__PURE__ */ new Map();
492
+ const runGenerators = async (event) => {
493
+ const entries = Array.from(resolvedRoutes.values());
494
+ for (const { name, factory: factory2 } of generators) {
495
+ try {
496
+ await factory2.watch?.(entries, event);
497
+ } catch (error) {
498
+ console.error(
499
+ styleText("red", `${sourceFolder.name}: ${name} generator failed`)
500
+ );
501
+ if (event) {
502
+ console.error(event);
503
+ }
504
+ console.error(error);
505
+ }
506
+ }
507
+ };
508
+ const updateResolvedEntry = async (file) => {
509
+ const resolver = resolvers.get(file);
510
+ if (!resolver) {
511
+ return;
512
+ }
513
+ try {
514
+ const resolvedEntry = await resolver.handler(file);
515
+ resolvedRoutes.set(resolvedEntry.entry.fileFullpath, resolvedEntry);
516
+ return resolvedEntry;
517
+ } catch (error) {
518
+ const route = file.replace(`${createPath.api()}/`, "");
519
+ console.error(
520
+ styleText(
521
+ "red",
522
+ `${sourceFolder.name}: ${route} route resolution failed`
523
+ )
524
+ );
525
+ console.error(error);
526
+ return;
527
+ }
528
+ };
529
+ {
530
+ const spinner = spinnerFactory(`${sourceFolder.name}: resolving routes`);
531
+ for (const { name, handler } of resolvers.values()) {
532
+ spinner.append(
533
+ `[ ${resolvedRoutes.size + 1} of ${resolvers.size} ] ${name}`
534
+ );
535
+ const route = await handler();
536
+ resolvedRoutes.set(route.entry.fileFullpath, route);
537
+ }
538
+ spinner.succeed("ready \u2728");
539
+ }
540
+ await runGenerators();
541
+ return {
542
+ async add(file) {
543
+ const [resolver] = resolversFactory([file]).values();
544
+ if (!resolver) {
545
+ return;
546
+ }
547
+ resolvers.set(file, resolver);
548
+ const resolvedEntry = await updateResolvedEntry(file);
549
+ if (resolvedEntry) {
550
+ await runGenerators({ kind: "create", file });
551
+ }
552
+ },
553
+ async change(file) {
554
+ if (resolvedRoutes.has(file)) {
555
+ await updateResolvedEntry(file);
556
+ } else {
557
+ const relatedRoutes = resolvedRoutes.values().flatMap(({ kind, entry }) => {
558
+ return kind === "apiRoute" ? entry.referencedFiles.includes(file) ? [entry] : [] : [];
559
+ });
560
+ for (const route of relatedRoutes) {
561
+ await updateResolvedEntry(route.fileFullpath);
562
+ }
563
+ }
564
+ await runGenerators({ kind: "update", file });
565
+ },
566
+ async unlink(file) {
567
+ resolvers.delete(file);
568
+ resolvedRoutes.delete(file);
569
+ await runGenerators({ kind: "delete", file });
570
+ }
571
+ };
572
+ };
573
+ var matchersFactory = ({
574
+ baseurl,
575
+ apiurl
576
+ }) => {
577
+ const basePattern = new RegExp(`^${baseurl}($|/*)`);
578
+ const apiPattern = new RegExp(`^${join(baseurl, apiurl)}($|/*)`);
579
+ return {
580
+ base(req) {
581
+ return apiPattern.test(req.url) ? false : basePattern.test(req.url);
582
+ },
583
+ api(req) {
584
+ return apiPattern.test(req.url);
585
+ }
586
+ };
587
+ };
588
+ var findFreePort = async (devPort) => {
589
+ let minPort = 0;
590
+ let maxPort = 0;
591
+ for (const n of [3, 2, 1, ""]) {
592
+ minPort = Number(`${n}${devPort}`) + 100;
593
+ maxPort = minPort + 100;
594
+ if (maxPort < 65e3) {
595
+ break;
596
+ }
597
+ }
598
+ if (maxPort >= 65e3) {
599
+ throw new Error("the devPort in package.json should be less than 64000");
600
+ }
601
+ const range = maxPort - minPort + 1;
602
+ const startOffset = Math.floor(Math.random() * range);
603
+ const ports = Array.from({ length: range }, (_, i) => {
604
+ return minPort + (startOffset + i) % range;
605
+ });
606
+ const freePort = await ports.reduce(
607
+ async (prevPromise, port) => {
608
+ const freePort2 = await prevPromise;
609
+ if (freePort2) {
610
+ return freePort2;
611
+ }
612
+ const isFree = await isPortFree(port);
613
+ return isFree ? port : void 0;
614
+ },
615
+ Promise.resolve(void 0)
616
+ );
617
+ if (!freePort) {
618
+ throw new Error(`No free ports found in range ${minPort}-${maxPort}`);
619
+ }
620
+ return freePort;
621
+ };
622
+ var isPortFree = (port) => {
623
+ return new Promise((resolve3) => {
624
+ const server = net.createServer();
625
+ server.once("error", () => resolve3(false));
626
+ server.once("listening", () => {
627
+ server.close();
628
+ resolve3(true);
629
+ });
630
+ server.listen(port, "127.0.0.1");
631
+ });
632
+ };
633
+ export {
634
+ chassis_default as default
635
+ };
636
+ //# sourceMappingURL=chassis.js.map