@kosmojs/dev 0.0.7 → 0.0.9

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 (156) hide show
  1. package/package.json +7 -6
  2. package/pkg/base-plugin/routes.js +384 -216
  3. package/pkg/base-plugin/routes.js.map +4 -4
  4. package/pkg/base-plugin/worker.js +297 -235
  5. package/pkg/base-plugin/worker.js.map +4 -4
  6. package/pkg/cli/cli.js +4 -8
  7. package/pkg/cli/cli.js.map +2 -2
  8. package/pkg/cli/index.js +4 -8
  9. package/pkg/cli/index.js.map +2 -2
  10. package/pkg/index.js +286 -219
  11. package/pkg/index.js.map +4 -4
  12. package/pkg/src/base-plugin/cache.d.ts +1 -1
  13. package/pkg/src/base-plugin/routes/nesting.d.ts +5 -0
  14. package/pkg/src/base-plugin/routes/resolve.d.ts +23 -0
  15. package/pkg/src/base-plugin/routes.d.ts +6 -10
  16. package/pkg/src/index.d.ts +1 -1
  17. package/pkg/stub-generator/index.js +5 -4
  18. package/pkg/stub-generator/index.js.map +2 -2
  19. package/pkg/test/@fixtures/app/@src/pages/about/careers/[jobId]/index.d.ts +0 -0
  20. package/pkg/test/@fixtures/app/@src/pages/about/careers/layout.d.ts +0 -0
  21. package/pkg/test/@fixtures/app/@src/pages/about/index.d.ts +0 -0
  22. package/pkg/test/@fixtures/app/@src/pages/about/layout.d.ts +0 -0
  23. package/pkg/test/@fixtures/app/@src/pages/about/team/index.d.ts +0 -0
  24. package/pkg/test/@fixtures/app/@src/pages/account/layout.d.ts +0 -0
  25. package/pkg/test/@fixtures/app/@src/pages/account/profile/index.d.ts +0 -0
  26. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/index.d.ts +0 -0
  27. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/resources/[[type]]/[...path]/index.d.ts +0 -0
  28. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/resources/[[type]]/index.d.ts +0 -0
  29. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/resources/[[type]]/layout.d.ts +0 -0
  30. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/resources/index.d.ts +0 -0
  31. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/resources/layout.d.ts +0 -0
  32. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/settings/general/index.d.ts +0 -0
  33. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/settings/index.d.ts +0 -0
  34. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/settings/layout.d.ts +0 -0
  35. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/settings/permissions/index.d.ts +0 -0
  36. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/users/[userId]/index.d.ts +0 -0
  37. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/users/index.d.ts +0 -0
  38. package/pkg/test/@fixtures/app/@src/pages/admin/[tenant]/users/layout.d.ts +0 -0
  39. package/pkg/test/@fixtures/app/@src/pages/admin/index.d.ts +0 -0
  40. package/pkg/test/@fixtures/app/@src/pages/admin/layout.d.ts +0 -0
  41. package/pkg/test/@fixtures/app/@src/pages/blog/[[category]]/[[tag]]/index.d.ts +0 -0
  42. package/pkg/test/@fixtures/app/@src/pages/blog/[[category]]/index.d.ts +0 -0
  43. package/pkg/test/@fixtures/app/@src/pages/blog/index.d.ts +0 -0
  44. package/pkg/test/@fixtures/app/@src/pages/blog/layout.d.ts +0 -0
  45. package/pkg/test/@fixtures/app/@src/pages/blog/post/[slug]/index.d.ts +0 -0
  46. package/pkg/test/@fixtures/app/@src/pages/blog/post/[slug]/layout.d.ts +0 -0
  47. package/pkg/test/@fixtures/app/@src/pages/contact/index.d.ts +0 -0
  48. package/pkg/test/@fixtures/app/@src/pages/contact/layout.d.ts +0 -0
  49. package/pkg/test/@fixtures/app/@src/pages/courses/[courseId]/layout.d.ts +0 -0
  50. package/pkg/test/@fixtures/app/@src/pages/courses/[courseId]/lessons/[[lessonId]]/assignments/[...assignmentPath]/index.d.ts +0 -0
  51. package/pkg/test/@fixtures/app/@src/pages/dashboard/[view]/index.d.ts +0 -0
  52. package/pkg/test/@fixtures/app/@src/pages/dashboard/analytics/index.d.ts +0 -0
  53. package/pkg/test/@fixtures/app/@src/pages/dashboard/index.d.ts +0 -0
  54. package/pkg/test/@fixtures/app/@src/pages/dashboard/layout.d.ts +0 -0
  55. package/pkg/test/@fixtures/app/@src/pages/dashboard/settings/billing/index.d.ts +0 -0
  56. package/pkg/test/@fixtures/app/@src/pages/dashboard/settings/index.d.ts +0 -0
  57. package/pkg/test/@fixtures/app/@src/pages/dashboard/settings/layout.d.ts +0 -0
  58. package/pkg/test/@fixtures/app/@src/pages/dashboard/settings/notifications/index.d.ts +0 -0
  59. package/pkg/test/@fixtures/app/@src/pages/dashboard/settings/profile/index.d.ts +0 -0
  60. package/pkg/test/@fixtures/app/@src/pages/dashboard/settings/security/index.d.ts +0 -0
  61. package/pkg/test/@fixtures/app/@src/pages/dashboard/settings/security/layout.d.ts +0 -0
  62. package/pkg/test/@fixtures/app/@src/pages/docs/[...path]/index.d.ts +0 -0
  63. package/pkg/test/@fixtures/app/@src/pages/docs/index.d.ts +0 -0
  64. package/pkg/test/@fixtures/app/@src/pages/docs/layout.d.ts +0 -0
  65. package/pkg/test/@fixtures/app/@src/pages/files/[...filePath]/index.d.ts +0 -0
  66. package/pkg/test/@fixtures/app/@src/pages/files/[...filePath]/layout.d.ts +0 -0
  67. package/pkg/test/@fixtures/app/@src/pages/legal/layout.d.ts +0 -0
  68. package/pkg/test/@fixtures/app/@src/pages/legal/privacy/index.d.ts +0 -0
  69. package/pkg/test/@fixtures/app/@src/pages/legal/terms/index.d.ts +0 -0
  70. package/pkg/test/@fixtures/app/@src/pages/news/[category]/articles/[...articlePath]/index.d.ts +0 -0
  71. package/pkg/test/@fixtures/app/@src/pages/news/[category]/layout.d.ts +0 -0
  72. package/pkg/test/@fixtures/app/@src/pages/portal/[clientId]/layout.d.ts +0 -0
  73. package/pkg/test/@fixtures/app/@src/pages/portal/[clientId]/reports/[reportType]/data/[dataView]/index.d.ts +0 -0
  74. package/pkg/test/@fixtures/app/@src/pages/portal/[clientId]/reports/[reportType]/data/[dataView]/layout.d.ts +0 -0
  75. package/pkg/test/@fixtures/app/@src/pages/portal/[clientId]/reports/[reportType]/layout.d.ts +0 -0
  76. package/pkg/test/@fixtures/app/@src/pages/portal/[clientId]/reports/layout.d.ts +0 -0
  77. package/pkg/test/@fixtures/app/@src/pages/portal/layout.d.ts +0 -0
  78. package/pkg/test/@fixtures/app/@src/pages/products/[id]/index.d.ts +0 -0
  79. package/pkg/test/@fixtures/app/@src/pages/products/index.d.ts +0 -0
  80. package/pkg/test/@fixtures/app/@src/pages/profile/[username]/layout.d.ts +0 -0
  81. package/pkg/test/@fixtures/app/@src/pages/profile/[username]/posts/[postId]/comments/[...thread]/index.d.ts +0 -0
  82. package/pkg/test/@fixtures/app/@src/pages/profile/[username]/posts/[postId]/layout.d.ts +0 -0
  83. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/files/[...path]/index.d.ts +0 -0
  84. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/files/index.d.ts +0 -0
  85. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/files/layout.d.ts +0 -0
  86. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/index.d.ts +0 -0
  87. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/layout.d.ts +0 -0
  88. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/tasks/[taskId]/comments/[commentId]/index.d.ts +0 -0
  89. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/tasks/[taskId]/comments/index.d.ts +0 -0
  90. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/tasks/[taskId]/comments/layout.d.ts +0 -0
  91. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/tasks/[taskId]/index.d.ts +0 -0
  92. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/tasks/[taskId]/layout.d.ts +0 -0
  93. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/tasks/index.d.ts +0 -0
  94. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/tasks/layout.d.ts +0 -0
  95. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/team/[userId]/index.d.ts +0 -0
  96. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/team/index.d.ts +0 -0
  97. package/pkg/test/@fixtures/app/@src/pages/projects/[projectId]/team/layout.d.ts +0 -0
  98. package/pkg/test/@fixtures/app/@src/pages/projects/index.d.ts +0 -0
  99. package/pkg/test/@fixtures/app/@src/pages/projects/layout.d.ts +0 -0
  100. package/pkg/test/@fixtures/app/@src/pages/properties/[[city]]/filters/[...filters]/index.d.ts +0 -0
  101. package/pkg/test/@fixtures/app/@src/pages/properties/filters/index.d.ts +0 -0
  102. package/pkg/test/@fixtures/app/@src/pages/properties/layout.d.ts +0 -0
  103. package/pkg/test/@fixtures/app/@src/pages/search/[[query]]/[[page]]/index.d.ts +0 -0
  104. package/pkg/test/@fixtures/app/@src/pages/search/[[query]]/layout.d.ts +0 -0
  105. package/pkg/test/@fixtures/app/@src/pages/search/index.d.ts +0 -0
  106. package/pkg/test/@fixtures/app/@src/pages/shop/[category]/[productId]/index.d.ts +0 -0
  107. package/pkg/test/@fixtures/app/@src/pages/shop/[category]/[productId]/layout.d.ts +0 -0
  108. package/pkg/test/@fixtures/app/@src/pages/shop/cart/index.d.ts +0 -0
  109. package/pkg/test/@fixtures/app/@src/pages/shop/checkout/confirm/index.d.ts +0 -0
  110. package/pkg/test/@fixtures/app/@src/pages/shop/checkout/layout.d.ts +0 -0
  111. package/pkg/test/@fixtures/app/@src/pages/shop/checkout/payment/index.d.ts +0 -0
  112. package/pkg/test/@fixtures/app/@src/pages/shop/checkout/shipping/index.d.ts +0 -0
  113. package/pkg/test/@fixtures/app/@src/pages/shop/checkout/shipping/layout.d.ts +0 -0
  114. package/pkg/test/@fixtures/app/@src/pages/shop/index.d.ts +0 -0
  115. package/pkg/test/@fixtures/app/@src/pages/shop/layout.d.ts +0 -0
  116. package/pkg/test/@fixtures/app/@src/pages/shop/orders/[orderId]/index.d.ts +0 -0
  117. package/pkg/test/@fixtures/app/@src/pages/shop/orders/index.d.ts +0 -0
  118. package/pkg/test/@fixtures/app/@src/pages/shop/orders/layout.d.ts +0 -0
  119. package/pkg/test/@fixtures/app/@src/pages/shop/product/[id]/index.d.ts +0 -0
  120. package/pkg/test/@fixtures/app/@src/pages/shop/product/[id]/layout.d.ts +0 -0
  121. package/pkg/test/@fixtures/app/@src/pages/shop/product/[id]/reviews/index.d.ts +0 -0
  122. package/pkg/test/@fixtures/app/@src/pages/shop/products/[[category]]/index.d.ts +0 -0
  123. package/pkg/test/@fixtures/app/@src/pages/shop/products/index.d.ts +0 -0
  124. package/pkg/test/@fixtures/app/@src/pages/shop/products/layout.d.ts +0 -0
  125. package/pkg/test/@fixtures/app/@src/pages/signup/index.d.ts +0 -0
  126. package/pkg/test/@fixtures/app/@src/pages/store/[category]/filters/[...filters]/index.d.ts +0 -0
  127. package/pkg/test/@fixtures/app/@src/pages/store/[category]/sort/[sortBy]/index.d.ts +0 -0
  128. package/pkg/test/@fixtures/app/@src/pages/store/[category]/sort/layout.d.ts +0 -0
  129. package/pkg/test/@fixtures/app/@src/pages/store/layout.d.ts +0 -0
  130. package/pkg/test/@fixtures/app/@src/pages/users/[username]/followers/index.d.ts +0 -0
  131. package/pkg/test/@fixtures/app/@src/pages/users/[username]/following/index.d.ts +0 -0
  132. package/pkg/test/@fixtures/app/@src/pages/users/[username]/index.d.ts +0 -0
  133. package/pkg/test/@fixtures/app/@src/pages/users/[username]/layout.d.ts +0 -0
  134. package/pkg/test/@fixtures/app/@src/pages/users/[username]/posts/[postId]/index.d.ts +0 -0
  135. package/pkg/test/@fixtures/app/@src/pages/users/[username]/posts/[postId]/layout.d.ts +0 -0
  136. package/pkg/test/@fixtures/app/@src/pages/users/[username]/posts/index.d.ts +0 -0
  137. package/pkg/test/@fixtures/app/@src/pages/users/[username]/posts/layout.d.ts +0 -0
  138. package/pkg/test/@fixtures/app/@src/pages/users/index.d.ts +0 -0
  139. package/pkg/test/@fixtures/app/@src/pages/users/layout.d.ts +0 -0
  140. package/pkg/test/@fixtures/app/@src/pages/workspace/[workspaceId]/analytics/[range]/index.d.ts +0 -0
  141. package/pkg/test/@fixtures/app/@src/pages/workspace/[workspaceId]/analytics/[range]/layout.d.ts +0 -0
  142. package/pkg/test/@fixtures/app/@src/pages/workspace/[workspaceId]/analytics/index.d.ts +0 -0
  143. package/pkg/test/@fixtures/app/@src/pages/workspace/[workspaceId]/analytics/layout.d.ts +0 -0
  144. package/pkg/test/@fixtures/app/@src/pages/workspace/[workspaceId]/team/[memberId]/permissions/[...permissionPath]/index.d.ts +0 -0
  145. package/pkg/test/@fixtures/app/@src/pages/workspace/[workspaceId]/team/layout.d.ts +0 -0
  146. package/pkg/test/@fixtures/app/lib/@src/{api}/articles/[...path]/index.ts/types.d.ts +3 -0
  147. package/pkg/test/@fixtures/app/lib/@src/{api}/books/[category]/[[author]]/index.ts/types.d.ts +4 -0
  148. package/pkg/test/@fixtures/app/lib/@src/{api}/books/[category]/index.ts/types.d.ts +3 -0
  149. package/pkg/test/@fixtures/app/lib/@src/{api}/books/index.ts/types.d.ts +1 -0
  150. package/pkg/test/@fixtures/app/lib/@src/{api}/files/[[folder]]/[[id]].json/index.ts/types.d.ts +4 -0
  151. package/pkg/test/@fixtures/app/lib/@src/{api}/files/[[folder]]/index.ts/types.d.ts +3 -0
  152. package/pkg/test/@fixtures/app/lib/@src/{api}/index/index.ts/types.d.ts +1 -0
  153. package/pkg/test/@fixtures/app/lib/@src/{api}/pages/[...path].html/index.ts/types.d.ts +3 -0
  154. package/pkg/test/@fixtures/app/lib/@src/{api}/users/[id].json/index.ts/types.d.ts +3 -0
  155. package/pkg/test/routes/base.d.ts +4 -0
  156. package/pkg/test/routes/nesting.test.d.ts +1 -0
package/pkg/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/alias-plugin/index.ts", "../src/base-plugin/index.ts", "../src/base-plugin/api-handler.ts", "../src/base-plugin/routes.ts", "../src/base-plugin/ast.ts", "../src/base-plugin/cache.ts", "../src/base-plugin/templates/resolved-types.hbs", "../src/base-plugin/templates/types.hbs", "../src/base-plugin/spinner.ts", "../src/define-plugin/index.ts"],
4
- "sourcesContent": ["export type { SSRFactory } from \"@kosmojs/devlib\";\n\nexport { default as apiGenerator } from \"@kosmojs/api-generator\";\nexport { default as fetchGenerator } from \"@kosmojs/fetch-generator\";\n\nexport { default as aliasPlugin } from \"./alias-plugin\";\nexport { default } from \"./base-plugin\";\nexport { default as definePlugin } from \"./define-plugin\";\n", "import { glob } from \"tinyglobby\";\nimport type { Alias, Plugin } from \"vite\";\n\nexport default (\n appRoot: string,\n opt?: {\n ignore?: Array<string>;\n },\n): Plugin => {\n return {\n name: \"@kosmojs:aliasPlugin\",\n\n async config() {\n const compilerOptions: {\n paths: Record<string, Array<string>>;\n } = await import(`${appRoot}/tsconfig.json`, {\n with: { type: \"json\" },\n }).then((e) => e.default.compilerOptions);\n\n const aliasmap: Array<Alias> = [];\n\n const pathEntries = Object.entries({ ...compilerOptions?.paths });\n\n for (const [aliasPattern, pathPatterns] of pathEntries) {\n const alias = aliasPattern.replace(\"/*\", \"\");\n\n const paths = pathPatterns\n .map((e) => e.replace(\"/*\", \"\"))\n .sort((a, b) => a.split(/\\/+/).length - b.split(/\\/+/).length);\n\n if (paths.length === 1) {\n aliasmap.push({\n find: new RegExp(`^${alias}/`),\n replacement: `${appRoot}/${paths[0]}/`,\n });\n } else if (paths.length > 1) {\n aliasmap.push({\n find: new RegExp(`^${alias}/`),\n replacement: \"\",\n async customResolver(_src) {\n // escaping symbols that may break glob pattern matching\n const src = _src.replace(/(\\$|\\^|\\+|\\(|\\)|\\[|\\])/g, \"\\\\$1\");\n\n // Build a list of possible file resolution patterns for a given source path.\n // Covers explicit extensions, implicit extensions, and folder-based index files.\n const patterns = paths.flatMap((path) => [\n // Case 1: Extension is explicitly provided\n // e.g. import styles from \"@admin/{solid}/styles.module.css\"\n `${path}/${src}*`,\n\n // Case 2: No extension provided\n // Match any extension and return the first match\n `${path}/${src}.*`,\n\n // Case 3: Folder containing an index file of any extension\n `${path}/${src}/index.*`,\n ]);\n\n const [file] = await glob(patterns, {\n cwd: appRoot,\n onlyFiles: true,\n absolute: true,\n dot: true,\n followSymbolicLinks: false,\n braceExpansion: false,\n globstar: false,\n ignore: opt?.ignore || [\n \"**/.git/**\",\n \"**/node_modules/**\",\n \"**/public/**\",\n \"**/var/**\",\n ],\n });\n\n return file;\n },\n });\n }\n }\n\n return {\n resolve: {\n alias: aliasmap,\n },\n };\n },\n };\n};\n", "import { basename, join, resolve } from \"node:path\";\nimport { styleText } from \"node:util\";\nimport { Worker } from \"node:worker_threads\";\n\nimport type { Plugin, ResolvedConfig } from \"vite\";\n\nimport type {\n GeneratorConstructor,\n PluginOptions,\n PluginOptionsResolved,\n RouteResolverEntry,\n} from \"@kosmojs/devlib\";\n\nimport apiGenerator from \"@kosmojs/api-generator\";\nimport stubGenerator from \"@kosmojs/dev/stub-generator\";\nimport fetchGenerator from \"@kosmojs/fetch-generator\";\n\nimport apiHandlerFactory from \"./api-handler\";\nimport routesFactory from \"./routes\";\nimport { type SpinnerFactory, spinnerFactory, withSpinner } from \"./spinner\";\nimport type { WorkerData, WorkerError, WorkerSpinner } from \"./worker\";\n\nexport default (apiurl: string, pluginOptions?: PluginOptions): Plugin => {\n const outDirSuffix = \"client\";\n\n const store: {\n config: ResolvedConfig;\n resolvedOptions: PluginOptionsResolved;\n } = {} as typeof store;\n\n const createWorker = () => {\n // Destructuring to separate common options from function-based ones.\n // Functions (e.g. generators, formatters) can't be passed to worker threads.\n const {\n generators = [],\n formatters = [],\n ...restOptions\n } = store.resolvedOptions;\n\n const generatorModules: WorkerData[\"generatorModules\"] = generators.map(\n (e) => [e.moduleImport, e.moduleConfig],\n );\n\n const formatterModules: WorkerData[\"formatterModules\"] =\n pluginOptions?.formatters\n ? pluginOptions.formatters.map((e) => [e.moduleImport, e.moduleConfig])\n : [];\n\n const workerData: WorkerData = {\n ...restOptions,\n generatorModules,\n formatterModules,\n };\n\n return new Worker(resolve(import.meta.dirname, \"base-plugin/worker.js\"), {\n workerData,\n env: {\n ...process.env,\n FORCE_COLOR: \"1\",\n },\n });\n };\n\n const workerHandler = (\n onReady?: () => Promise<void>,\n onExit?: () => Promise<void>,\n ) => {\n const worker = createWorker();\n\n const spinnerMap = new Map<string, SpinnerFactory>();\n\n worker.on(\"error\", async (error) => {\n console.error(error);\n });\n\n worker.on(\"exit\", async () => {\n await onExit?.();\n // TODO: revive worker only if it exited due to an error.\n // Note: worker.terminate() triggers an exit with code 1,\n // so it's not always possible to distinguish normal termination from a crash.\n });\n\n worker.on(\n \"message\",\n async (msg: { spinner?: WorkerSpinner; error?: WorkerError }) => {\n if (msg?.spinner) {\n const { id, startText, method, text } = msg.spinner;\n withSpinner(\n startText,\n (spinner) => {\n spinnerMap.set(id, spinner);\n spinner[method](text || \"\");\n if (method === \"succeed\" || method === \"failed\") {\n spinnerMap.delete(id);\n }\n },\n spinnerMap.get(id),\n );\n } else if (msg?.error) {\n const { error } = msg;\n if (error.stack) {\n const [message, ...stack] = error.stack.split(\"\\n\");\n console.error(styleText(\"red\", message));\n console.error(stack.join(\"\\n\"));\n } else if (error?.message) {\n console.error(`${styleText(\"red\", error?.name)}: ${error.message}`);\n } else {\n console.error(error);\n }\n }\n },\n );\n\n const readyHandler = async (msg: string) => {\n if (msg === \"ready\") {\n worker.off(\"message\", readyHandler);\n await onReady?.();\n }\n };\n\n worker.on(\"message\", readyHandler);\n\n return async () => {\n await worker.terminate();\n };\n };\n\n return {\n name: \"@kosmojs:basePlugin\",\n\n config(config) {\n if (!config.build?.outDir) {\n throw new Error(\"Incomplete config, missing build.outDir\");\n }\n return {\n build: {\n outDir: join(config.build.outDir, outDirSuffix),\n manifest: true,\n },\n };\n },\n\n async configResolved(_config) {\n store.config = _config;\n\n const appRoot = resolve(store.config.root, \"..\");\n const sourceFolder = basename(store.config.root);\n\n // removing outDirSuffix\n const outDir = resolve(appRoot, resolve(store.config.build.outDir, \"..\"));\n\n const { stabilityThreshold = 1000 } =\n typeof store.config.server.watch?.awaitWriteFinish === \"object\"\n ? store.config.server.watch.awaitWriteFinish\n : {};\n\n const watcher: PluginOptionsResolved[\"watcher\"] = {\n delay: stabilityThreshold,\n ...(store.config.server.watch\n ? { options: store.config.server.watch }\n : {}),\n };\n\n {\n const {\n generators = [],\n formatters = [],\n refineTypeName = \"TRefine\",\n } = { ...pluginOptions };\n\n const _apiGenerator = generators.find((e) => e.kind === \"api\");\n const _fetchGenerator = generators.find((e) => e.kind === \"fetch\");\n const _ssrGenerator = generators.find((e) => e.kind === \"ssr\");\n\n store.resolvedOptions = {\n ...pluginOptions,\n command: store.config.command,\n watcher,\n generators: [\n // 1. stub generator should run first\n stubGenerator(),\n // 2. then api generator\n _apiGenerator || (apiGenerator() as GeneratorConstructor),\n // 3. then fetch generator\n _fetchGenerator || (fetchGenerator() as GeneratorConstructor),\n // 4. user generators in the order they were added\n ...generators.filter((e) => {\n return e.kind //\n ? ![\"api\", \"fetch\", \"ssr\"].includes(e.kind)\n : true;\n }),\n // 5. ssr generator should run last\n ...(_ssrGenerator ? [_ssrGenerator] : []),\n ],\n formatters: formatters.map((e) => e.formatter),\n refineTypeName,\n baseurl: store.config.base,\n apiurl,\n appRoot,\n sourceFolder,\n outDir,\n };\n }\n\n if (store.config.command === \"build\") {\n const { resolvers } = await routesFactory(store.resolvedOptions);\n const resolvedRoutes: RouteResolverEntry[] = [];\n\n {\n const spinner = spinnerFactory(\"Resolving Routes\");\n\n for (const { name, handler } of resolvers.values()) {\n spinner.append(\n `[ ${resolvedRoutes.length + 1} of ${resolvers.size} ] ${name}`,\n );\n resolvedRoutes.push(await handler());\n }\n\n spinner.succeed();\n }\n\n {\n const spinner = spinnerFactory(\"Running Generators\");\n\n for (const { name, factory } of store.resolvedOptions.generators) {\n spinner.append(name);\n const { watchHandler } = await factory(store.resolvedOptions);\n await watchHandler(resolvedRoutes);\n }\n\n spinner.succeed();\n }\n }\n },\n\n async configureServer(server) {\n if (store.config.command !== \"serve\") {\n return;\n }\n\n const apiHandler = await apiHandlerFactory(store.resolvedOptions);\n\n const apiWatcher = await apiHandler.watcher();\n\n const stopWorker = workerHandler(\n async () => {\n await apiWatcher.start();\n },\n async () => {\n await apiWatcher.stop();\n },\n );\n\n // Attach the dev middleware from apiHandler. It may intercept requests to\n // determine whether they should be handled by Vite or by another handler.\n server.middlewares.use(apiHandler.devMiddleware);\n\n // clean up when Vite dev server closes/restarts\n server.httpServer?.on(\"close\", stopWorker);\n },\n };\n};\n", "import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { join, resolve } from \"node:path\";\nimport { styleText } from \"node:util\";\n\nimport { type BuildOptions, context, type Plugin } from \"esbuild\";\n\nimport type { App } from \"@kosmojs/api\";\nimport { defaults, type PluginOptionsResolved } from \"@kosmojs/devlib\";\n\nexport default async (options: PluginOptionsResolved) => {\n const { appRoot, sourceFolder, baseurl, apiurl } = options;\n\n const apiDir = join(sourceFolder, defaults.apiDir);\n const outDir = join(options.outDir, defaults.apiDir);\n\n const esbuildOptions: BuildOptions = await import(\n resolve(appRoot, \"esbuild.json\"),\n { with: { type: \"json\" } }\n ).then((e) => e.default);\n\n let app: App;\n let devMiddlewareFactory: Function | undefined;\n let teardownHandler: Function | undefined;\n\n const watcher = async () => {\n const outfile = join(outDir, \"dev.js\");\n\n const rebuildPlugin: Plugin = {\n name: \"rebuild\",\n setup(build) {\n build.onEnd(async () => {\n if (app) {\n await teardownHandler?.(app);\n }\n try {\n const exports = await import([outfile, Date.now()].join(\"?\"));\n devMiddlewareFactory = exports.devMiddlewareFactory;\n teardownHandler = exports.teardownHandler;\n app = await exports.default();\n console.debug(`${styleText(\"green\", \"\u279C\")} Api handler ready`);\n } catch (error) {\n console.error(`${styleText(\"red\", \"\u2717\")} Api handler error`);\n console.error(error);\n }\n });\n },\n };\n\n const ctx = await context({\n ...esbuildOptions,\n logLevel: \"error\",\n bundle: true,\n entryPoints: [join(apiDir, \"app.ts\")],\n plugins: [rebuildPlugin],\n outfile,\n });\n\n return {\n async start() {\n await ctx.watch({\n // waits this many milliseconds before rebuilding after a change is detected\n delay: options.watcher.delay,\n });\n },\n async stop() {\n await ctx.dispose();\n },\n };\n };\n\n const devMiddleware = async (\n req: IncomingMessage,\n res: ServerResponse,\n viteHandler: () => void,\n ) => {\n const next = () => {\n return viteHandler();\n };\n if (devMiddlewareFactory) {\n const handler = devMiddlewareFactory(app);\n await handler(req, res, next);\n } else {\n !req?.url || !new RegExp(`^${join(baseurl, apiurl)}($|/)`).test(req.url)\n ? next() // do not await here\n : await app?.callback()(req, res);\n }\n };\n\n return {\n watcher,\n devMiddleware,\n };\n};\n", "import { dirname, join, resolve } from \"node:path\";\n\nimport crc from \"crc/crc32\";\nimport picomatch from \"picomatch\";\nimport { glob } from \"tinyglobby\";\n\nimport {\n type ApiRoute,\n defaults,\n type PageRoute,\n type PluginOptionsResolved,\n pathResolver,\n pathTokensFactory,\n type RouteEntry,\n type RouteResolver,\n render,\n renderToFile,\n} from \"@kosmojs/devlib\";\n\nimport { resolveRouteSignature, typeResolverFactory } from \"./ast\";\nimport { cacheFactory } from \"./cache\";\n\nimport resolvedTypesTpl from \"./templates/resolved-types.hbs\";\nimport typesFileTpl from \"./templates/types.hbs\";\n\nexport type Resolvers = Map<string, RouteResolver>;\n\nexport type ResolveRouteFile = (file: string) =>\n | [\n // Either `apiDir` or `pagesDir`\n folder: string,\n // Path to a file within the folder, nested at least one level deep\n file: string,\n ]\n | undefined;\n\nexport type ResolversFactory = (\n routeFiles: Array<string>,\n) => Map<string, RouteResolver>;\n\nexport default async (\n pluginOptions: PluginOptionsResolved,\n): Promise<{\n resolvers: Resolvers;\n resolversFactory: ResolversFactory;\n resolveRouteFile: ResolveRouteFile;\n}> => {\n const {\n appRoot,\n sourceFolder,\n generators = [],\n formatters = [],\n refineTypeName,\n } = pluginOptions;\n\n let resolveTypes = false;\n\n for (const { options } of generators) {\n if (options?.resolveTypes) {\n resolveTypes = true;\n }\n }\n\n const {\n //\n literalTypesResolver,\n getSourceFile,\n refreshSourceFile,\n } = typeResolverFactory(pluginOptions);\n\n const routeFilePatterns = [\n `${defaults.apiDir}/**/index.ts`,\n `${defaults.pagesDir}/**/index.{ts,tsx,vue,svelte}`,\n ];\n\n const resolveRouteFile: ResolveRouteFile = (file) => {\n const [_sourceFolder, folder, ...rest] = resolve(appRoot, file)\n .replace(`${appRoot}/`, \"\")\n .split(\"/\");\n\n /**\n * Ensure the file:\n * - is under the correct source root (`sourceFolder`)\n * - belongs to a known route folder (`apiDir` or `pagesDir`)\n * - is nested at least one level deep (not a direct child of the folder)\n */\n if (!folder || _sourceFolder !== sourceFolder || rest.length < 2) {\n return;\n }\n\n return picomatch.isMatch(join(folder, ...rest), routeFilePatterns)\n ? [folder, rest.join(\"/\")]\n : undefined;\n };\n\n const resolversFactory: ResolversFactory = (routeFiles) => {\n const resolvers = new Map<\n string, // fileFullpath\n RouteResolver\n >();\n\n const entries: Array<RouteEntry> = routeFiles.flatMap((_file) => {\n const resolvedPaths = resolveRouteFile(_file);\n\n if (!resolvedPaths) {\n return [];\n }\n\n const [folder, file] = resolvedPaths;\n\n const fileFullpath = join(appRoot, sourceFolder, folder, file);\n\n const pathTokens = pathTokensFactory(dirname(file));\n\n const name = pathTokens.map((e) => e.orig).join(\"/\");\n\n const importPath = dirname(file);\n\n const importName = [\n importPath\n .split(/\\[/)[0]\n .replace(/^\\W+|\\W+$/g, \"\")\n .replace(/\\W+/g, \"_\"),\n crc(importPath),\n ].join(\"_\");\n\n return [\n {\n name,\n folder,\n file,\n fileFullpath,\n pathTokens,\n importPath,\n importName,\n },\n ];\n });\n\n for (const entry of entries.filter((e) => e.folder === defaults.apiDir)) {\n const {\n name,\n file,\n folder,\n fileFullpath,\n pathTokens,\n importPath,\n importName,\n } = entry;\n\n const handler: RouteResolver[\"handler\"] = async (updatedFile) => {\n const paramsSchema = pathTokens.flatMap((e) => {\n return e.param ? [e.param] : [];\n });\n\n const optionalParams = paramsSchema.length\n ? !paramsSchema.some((e) => e.isRequired)\n : true;\n\n const { getCache, persistCache } = cacheFactory(\n { file, fileFullpath, importName, importPath },\n {\n appRoot,\n sourceFolder,\n extraContext: { resolveTypes },\n },\n );\n\n let cache = await getCache({ validate: true });\n\n if (!cache) {\n if (updatedFile === fileFullpath) {\n await refreshSourceFile(fileFullpath);\n }\n\n const {\n typeDeclarations,\n paramsRefinements,\n methods,\n payloadTypes,\n responseTypes,\n referencedFiles = [],\n } = await resolveRouteSignature(\n { importName, fileFullpath, optionalParams },\n {\n withReferencedFiles: true,\n sourceFile: getSourceFile(fileFullpath),\n relpathResolver(path) {\n return join(sourceFolder, defaults.apiDir, dirname(file), path);\n },\n },\n );\n\n const numericParams = paramsRefinements\n ? paramsRefinements.flatMap(({ text, index }) => {\n if (text === \"number\") {\n const param = paramsSchema.at(index);\n return param ? [param.name] : [];\n }\n return [];\n })\n : [];\n\n const typesFile = pathResolver({ appRoot, sourceFolder }).resolve(\n \"apiLibDir\",\n importPath,\n \"types.ts\",\n );\n\n const params: ApiRoute[\"params\"] = {\n id: [\"ParamsT\", crc(name)].join(\"\"),\n schema: paramsSchema,\n resolvedType: undefined,\n };\n\n const typesFileContent = render(typesFileTpl, {\n params,\n paramsSchema: paramsSchema.map((param, index) => {\n return {\n ...param,\n refinement: paramsRefinements?.at(index),\n };\n }),\n typeDeclarations,\n payloadTypes,\n responseTypes,\n });\n\n const resolvedTypes = resolveTypes\n ? literalTypesResolver(typesFileContent, {\n overrides: [...payloadTypes, ...responseTypes].reduce(\n (map: Record<string, string>, { id, skipValidation }) => {\n if (skipValidation) {\n map[id] = \"never\";\n }\n return map;\n },\n { [refineTypeName]: refineTypeName },\n ),\n withProperties: [params.id, ...payloadTypes.map((e) => e.id)],\n formatters,\n })\n : undefined;\n\n /**\n * Deploy types.ts file; required by core generators (like fetch).\n * If types resolved, write resolved types;\n * otherwise write original types extracted from API route.\n * */\n await renderToFile(\n typesFile,\n resolvedTypes ? resolvedTypesTpl : typesFileContent,\n { resolvedTypes },\n );\n\n params.resolvedType = resolvedTypes?.find(\n (e) => e.name === params.id,\n );\n\n cache = await persistCache({\n params,\n methods,\n typeDeclarations,\n numericParams,\n // text was needed at writing types.ts file, dropping from cache\n payloadTypes: payloadTypes.map(({ text, ...rest }) => {\n return {\n ...rest,\n resolvedType: resolvedTypes?.find((e) => e.name === rest.id),\n };\n }),\n responseTypes: responseTypes.map(({ text, ...rest }) => {\n return {\n ...rest,\n resolvedType: resolvedTypes?.find((e) => e.name === rest.id),\n };\n }),\n referencedFiles,\n });\n }\n\n const route: ApiRoute = {\n name,\n pathTokens,\n params: cache.params,\n numericParams: cache.numericParams,\n optionalParams,\n importName,\n importPath,\n folder,\n file,\n fileFullpath,\n methods: cache.methods,\n typeDeclarations: cache.typeDeclarations,\n payloadTypes: cache.payloadTypes,\n responseTypes: cache.responseTypes,\n referencedFiles: Object.keys(cache.referencedFiles).map(\n // expand referenced files path,\n // they are stored as relative in cache\n (e) => resolve(appRoot, e),\n ),\n };\n\n return {\n kind: \"api\",\n route,\n };\n };\n\n resolvers.set(fileFullpath, { name, handler });\n }\n\n for (const entry of entries.filter((e) => e.folder === defaults.pagesDir)) {\n const {\n //\n name,\n folder,\n file,\n fileFullpath,\n pathTokens,\n importPath,\n importName,\n } = entry;\n\n const handler: RouteResolver[\"handler\"] = async () => {\n const route: PageRoute = {\n name,\n pathTokens,\n params: {\n schema: pathTokens.flatMap((e) => (e.param ? [e.param] : [])),\n },\n folder,\n file,\n fileFullpath,\n importPath,\n importName,\n };\n\n return {\n kind: \"page\",\n route,\n };\n };\n\n resolvers.set(fileFullpath, { name, handler });\n }\n\n return resolvers;\n };\n\n const routeFiles = await glob(routeFilePatterns, {\n cwd: resolve(appRoot, sourceFolder),\n absolute: true,\n onlyFiles: true,\n ignore: [\n `${defaults.apiDir}/index.ts`,\n `${defaults.pagesDir}/index.ts{x,}`,\n ],\n });\n\n return {\n resolvers: resolversFactory(routeFiles),\n resolversFactory,\n resolveRouteFile,\n };\n};\n", "import { resolve } from \"node:path\";\n\nimport crc from \"crc/crc32\";\nimport { flattener } from \"tfusion\";\nimport {\n type CallExpression,\n type Identifier,\n type Node,\n Project,\n type ProjectOptions,\n type SourceFile,\n SyntaxKind,\n} from \"ts-morph\";\n\nimport { type HTTPMethod, HTTPMethods } from \"@kosmojs/api\";\nimport type {\n ApiRoute,\n PayloadType,\n PluginOptionsResolved,\n ResponseType,\n TypeDeclaration,\n} from \"@kosmojs/devlib\";\n\ntype PathResolver = (path: string) => string;\n\nexport const createProject = (opts?: ProjectOptions) => new Project(opts);\n\nexport const resolveRouteSignature = async (\n route: Pick<ApiRoute, \"importName\" | \"fileFullpath\" | \"optionalParams\">,\n opts?: {\n relpathResolver?: PathResolver;\n sourceFile?: SourceFile;\n withReferencedFiles?: boolean;\n },\n) => {\n const {\n sourceFile = createProject().addSourceFileAtPath(route.fileFullpath),\n } = { ...opts };\n\n const [typeDeclarations, referencedFiles] = extractTypeDeclarations(\n sourceFile,\n opts,\n );\n\n const defaultExport = extractDefaultExport(sourceFile);\n\n const paramsRefinements = defaultExport\n ? extractParamsRefinements(defaultExport)\n : undefined;\n\n const methods = defaultExport\n ? extractRouteMethods(defaultExport, route)\n : [];\n\n const payloadTypes = methods.flatMap((e) => {\n return e.payloadType ? [e.payloadType] : [];\n });\n\n const responseTypes = methods.flatMap((e) => {\n return e.responseType ? [e.responseType] : [];\n });\n\n return {\n typeDeclarations,\n paramsRefinements,\n methods: methods.map((e) => e.method),\n payloadTypes,\n responseTypes,\n referencedFiles,\n };\n};\n\nexport const extractDefaultExport = (\n sourceFile: SourceFile,\n): CallExpression | undefined => {\n const [defaultExport] = sourceFile\n .getExportAssignments()\n .flatMap((exportAssignment) => {\n if (exportAssignment.isExportEquals()) {\n return [];\n }\n const callExpression = exportAssignment.getExpression();\n return callExpression.isKind(SyntaxKind.CallExpression)\n ? [callExpression]\n : [];\n });\n return defaultExport;\n};\n\nexport const extractParamsRefinements = (\n callExpression: CallExpression,\n):\n | Array<{\n index: number;\n text: string;\n }>\n | undefined => {\n const [firstGeneric] = extractGenerics(callExpression);\n\n if (!firstGeneric?.node.isKind(SyntaxKind.TupleType)) {\n return;\n }\n\n const tupleElements = firstGeneric.node.getElements();\n\n if (!tupleElements?.length) {\n return;\n }\n\n return tupleElements.map((node, index) => {\n return {\n index,\n text: node.getText(),\n };\n });\n};\n\nexport const extractRouteMethods = (\n callExpression: CallExpression,\n route: Pick<ApiRoute, \"importName\" | \"optionalParams\">,\n): Array<{\n method: HTTPMethod;\n payloadType: (PayloadType & { text: string }) | undefined;\n responseType: (ResponseType & { text: string }) | undefined;\n}> => {\n const funcDeclaration =\n callExpression.getFirstChildByKind(SyntaxKind.ArrowFunction) ||\n callExpression.getFirstChildByKind(SyntaxKind.FunctionExpression);\n\n if (!funcDeclaration) {\n return [];\n }\n\n const arrayLiteralExpression = funcDeclaration.getFirstChildByKind(\n SyntaxKind.ArrayLiteralExpression,\n );\n\n if (!arrayLiteralExpression) {\n return [];\n }\n\n const callExpressions: Array<[CallExpression, HTTPMethod]> = [];\n\n for (const e of arrayLiteralExpression.getChildrenOfKind(\n SyntaxKind.CallExpression,\n )) {\n const name = e.getExpression().getText() as HTTPMethod;\n if (HTTPMethods[name]) {\n callExpressions.push([e, name]);\n }\n }\n\n const methods = [];\n\n const skipValidationFilter = (e: string) => /@skip-validation/.test(e);\n\n for (const [callExpression, method] of callExpressions) {\n const [payloadGeneric, responseGeneric] = extractGenerics(callExpression);\n\n const payloadText = payloadGeneric?.node\n ? payloadGeneric.node.getChildren().length === 0\n ? \"{}\"\n : payloadGeneric.node.getFullText()\n : undefined;\n\n const responseText = responseGeneric?.node.getText();\n\n const responseType = responseText\n ? {\n id: [\"ResponseT\", crc(route.importName + method)].join(\"\"),\n method,\n skipValidation: responseGeneric?.comments\n ? responseGeneric.comments.some(skipValidationFilter)\n : false,\n text: [\"never\", \"object\"].includes(responseText)\n ? \"{}\"\n : responseText,\n resolvedType: undefined,\n }\n : undefined;\n\n const payloadType = payloadText\n ? {\n id: [\"PayloadT\", crc(route.importName + method)].join(\"\"),\n responseTypeId: responseType?.id,\n method,\n skipValidation: payloadGeneric?.comments\n ? payloadGeneric.comments.some(skipValidationFilter)\n : false,\n isOptional: payloadText\n ? payloadText === \"{}\" || route.optionalParams\n : true,\n text: payloadText,\n resolvedType: undefined,\n }\n : undefined;\n\n methods.push({\n method,\n payloadType,\n responseType,\n });\n }\n\n return methods;\n};\n\nexport const extractTypeDeclarations = (\n sourceFile: SourceFile,\n opts?: {\n relpathResolver?: PathResolver;\n withReferencedFiles?: boolean;\n },\n): [d: Array<TypeDeclaration>, f?: Array<string>] => {\n const declarations: Array<TypeDeclaration> = [];\n\n const referencedFiles: Array<string> | undefined = opts?.withReferencedFiles\n ? []\n : undefined;\n\n for (const declaration of sourceFile.getImportDeclarations()) {\n const modulePath = declaration.getModuleSpecifierValue();\n\n const path = /^\\.\\.?\\/?/.test(modulePath)\n ? opts?.relpathResolver\n ? opts.relpathResolver(modulePath)\n : modulePath\n : modulePath;\n\n const typeOnlyDeclaration = declaration.isTypeOnly();\n\n const defaultImport = typeOnlyDeclaration\n ? declaration.getDefaultImport()\n : undefined;\n\n if (defaultImport) {\n const name = defaultImport.getText();\n const text = `import type ${name} from \"${path}\";`;\n declarations.push({\n importDeclaration: {\n name,\n path,\n },\n text,\n });\n if (referencedFiles) {\n referencedFiles.push(...getReferencedFiles(defaultImport));\n }\n }\n\n for (const namedImport of declaration.getNamedImports()) {\n if (namedImport.isTypeOnly() || typeOnlyDeclaration) {\n const nameNode = namedImport.getNameNode();\n const name = nameNode.getText();\n const alias = namedImport.getAliasNode()?.getText();\n const nameText = alias ? `${name} as ${alias}` : name;\n\n declarations.push({\n importDeclaration: {\n name,\n alias,\n path,\n },\n text: `import type { ${nameText} } from \"${path}\";`,\n });\n\n if (referencedFiles) {\n if (nameNode.isKind(SyntaxKind.Identifier)) {\n referencedFiles.push(...getReferencedFiles(nameNode));\n }\n }\n }\n }\n }\n\n for (const declaration of sourceFile.getTypeAliases()) {\n const name = declaration.getName();\n const text = declaration.getFullText().trim();\n declarations.push({\n typeAliasDeclaration: { name },\n text,\n });\n }\n\n for (const declaration of sourceFile.getInterfaces()) {\n const name = declaration.getName();\n const text = declaration.getFullText().trim();\n declarations.push({\n interfaceDeclaration: { name },\n text,\n });\n }\n\n for (const declaration of sourceFile.getEnums()) {\n const name = declaration.getName();\n const text = declaration.getFullText().trim();\n declarations.push({\n enumDeclaration: { name },\n text,\n });\n }\n\n for (const declaration of sourceFile.getExportDeclarations()) {\n const typeOnlyDeclaration = declaration.isTypeOnly();\n\n const modulePath = declaration.getModuleSpecifierValue();\n\n const path = modulePath\n ? /^\\.\\.?\\/?/.test(modulePath)\n ? opts?.relpathResolver\n ? opts.relpathResolver(modulePath)\n : modulePath\n : modulePath\n : undefined;\n\n for (const namedExport of declaration.getNamedExports()) {\n if (namedExport.isTypeOnly() || typeOnlyDeclaration) {\n const nameNode = namedExport.getNameNode();\n const name = nameNode.getText();\n const alias = namedExport.getAliasNode()?.getText();\n const nameText = alias ? `${name} as ${alias}` : name;\n\n declarations.push({\n exportDeclaration: {\n name,\n alias: alias ?? name,\n path,\n },\n text: path\n ? `export type { ${nameText} } from \"${path}\";`\n : `export type { ${nameText} };`,\n });\n\n if (referencedFiles) {\n if (nameNode.isKind(SyntaxKind.Identifier)) {\n referencedFiles.push(...getReferencedFiles(nameNode));\n }\n }\n }\n }\n }\n\n return referencedFiles\n ? [declarations, [...new Set<string>(referencedFiles)]]\n : [declarations];\n};\n\nconst getReferencedFiles = (importIdentifier: Identifier): Array<string> => {\n // ambient modules may have declarations in multiple files\n const declarations =\n importIdentifier //\n ?.getSymbol()\n ?.getAliasedSymbol()\n ?.getDeclarations() || [];\n\n return declarations.flatMap((e) => {\n const sourceFile = e.getSourceFile();\n return sourceFile //\n ? [sourceFile.getFilePath()]\n : [];\n });\n};\n\nconst extractGenerics = (\n callExpression: CallExpression,\n): Array<{ node: Node; comments: Array<string> }> => {\n return callExpression.getTypeArguments().map((node) => {\n return {\n node,\n comments: node\n .getLeadingCommentRanges()\n .map((range) => range.getText().trim()),\n };\n });\n};\n\nexport const typeResolverFactory = ({ appRoot }: PluginOptionsResolved) => {\n const project = createProject({\n tsConfigFilePath: resolve(appRoot, \"tsconfig.json\"),\n skipAddingFilesFromTsConfig: true,\n });\n\n const literalTypesResolver = (\n literalTypes: string,\n options: Parameters<typeof flattener>[2],\n ) => {\n const sourceFile = project.createSourceFile(\n `${crc(literalTypes)}-${Date.now()}.ts`,\n literalTypes,\n { overwrite: true },\n );\n\n const resolvedTypes = flattener(project, sourceFile, {\n ...options,\n stripComments: true,\n });\n\n project.removeSourceFile(sourceFile);\n\n return resolvedTypes;\n };\n\n return {\n getSourceFile: (fileFullpath: string) => {\n return (\n project.getSourceFile(fileFullpath) ||\n project.addSourceFileAtPath(fileFullpath)\n );\n },\n refreshSourceFile: async (fileFullpath: string) => {\n const sourceFile = project.getSourceFile(fileFullpath);\n if (sourceFile) {\n await sourceFile.refreshFromFileSystem();\n }\n },\n literalTypesResolver,\n };\n};\n", "import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\n\nimport crc from \"crc/crc32\";\n\n/**\n * Import from published package to ensure correct version at runtime.\n * Local import would be bundled with pre-bump version; this external\n * import resolves to the actual published package.json.\n * */\nimport self from \"@kosmojs/dev/package.json\" with { type: \"json\" };\nimport { type ApiRoute, pathExists, pathResolver } from \"@kosmojs/devlib\";\n\nexport type Cache = {\n hash: number;\n referencedFiles: Record<string, number>;\n} & Pick<\n ApiRoute,\n | \"params\"\n | \"methods\"\n | \"typeDeclarations\"\n | \"numericParams\"\n | \"payloadTypes\"\n | \"responseTypes\"\n>;\n\ntype ExtraContext = Record<string | number, unknown>;\n\nexport const cacheFactory = (\n route: Pick<ApiRoute, \"file\" | \"fileFullpath\" | \"importName\" | \"importPath\">,\n {\n appRoot,\n sourceFolder,\n extraContext,\n }: {\n appRoot: string;\n sourceFolder: string;\n extraContext?: ExtraContext;\n },\n) => {\n const cacheFile = pathResolver({\n appRoot,\n sourceFolder,\n }).resolve(\"apiLibDir\", route.importPath, \"cache.json\");\n\n const getCache = async (opt?: {\n validate?: boolean;\n }): Promise<Cache | undefined> => {\n if (await pathExists(cacheFile)) {\n try {\n const cache = JSON.parse(await readFile(cacheFile, \"utf8\"));\n return opt?.validate //\n ? validateCache(cache)\n : cache;\n } catch (_e) {}\n }\n return undefined;\n };\n\n const persistCache = async ({\n referencedFiles: _referencedFiles,\n ...rest\n }: Omit<Cache, \"hash\" | \"referencedFiles\"> & {\n referencedFiles: Array<string>;\n }): Promise<Cache> => {\n const hash = await generateFileHash(route.fileFullpath, {\n ...extraContext,\n });\n\n const referencedFiles: Cache[\"referencedFiles\"] = {};\n\n for (const file of _referencedFiles) {\n referencedFiles[\n // Strip project root to ensure cached paths are relative\n // and portable across environments (CI, local, etc.)\n file.replace(`${appRoot}/`, \"\")\n ] = await generateFileHash(file);\n }\n\n const cache = { ...rest, hash, referencedFiles };\n\n await mkdir(dirname(cacheFile), { recursive: true });\n await writeFile(cacheFile, JSON.stringify(cache, null, 2), \"utf8\");\n\n return cache;\n };\n\n const validateCache = async (\n cache: Cache | undefined,\n ): Promise<Cache | undefined> => {\n if (!cache?.hash) {\n return;\n }\n\n if (!cache.typeDeclarations || !cache.referencedFiles) {\n // incomplete cache\n return;\n }\n\n const hash = await generateFileHash(route.fileFullpath, {\n ...extraContext,\n });\n\n if (!identicalHashSum(cache.hash, hash)) {\n // route itself updated\n return;\n }\n\n for (const [file, hash] of Object.entries(cache.referencedFiles)) {\n if (\n !identicalHashSum(hash, await generateFileHash(resolve(appRoot, file)))\n ) {\n // some referenced file updated\n return;\n }\n }\n\n return cache;\n };\n\n return {\n getCache,\n validateCache,\n persistCache,\n };\n};\n\nconst generateFileHash = async (\n file: string,\n extraContext?: ExtraContext,\n): Promise<number> => {\n let fileContent: string | undefined;\n try {\n fileContent = await readFile(file, \"utf8\");\n } catch (_e) {\n // file could be deleted since last build\n return 0;\n }\n return fileContent\n ? crc(\n JSON.stringify({\n ...extraContext,\n [self.cacheVersion]: fileContent,\n }),\n )\n : 0;\n};\n\n// return true if sums are identical\nconst identicalHashSum = (a: number, b: number) => {\n return a === b;\n};\n", "{{#each resolvedTypes}}\nexport type {{name}} = {{text}};\n{{/each}}\n", "{{#each typeDeclarations}}{{text}}\n{{/each}}\n\nexport type {{params.id}} = {\n {{#each paramsSchema}}\n \"{{name}}\"{{#unless isRequired}}?{{/unless}}:{{#if isRest}} Array<{{/if}}\n {{#if refinement}}{{refinement.text}}{{else}}string{{/if}}\n {{#if isRest}}>{{/if}}\n {{/each}}\n};\n\n{{#each payloadTypes}}\nexport type {{id}} = {{text}};\n{{/each}}\n\n{{#each responseTypes}}\nexport type {{id}} = {{text}};\n{{/each}}\n", "import ora from \"ora\";\n\nexport type SpinnerFactory = {\n text: (text: string) => void;\n append: (text: string) => void;\n succeed: (text?: string) => void;\n failed: (text?: string) => void;\n};\n\nexport const spinnerFactory = (startText: string): SpinnerFactory => {\n const spinner = ora().start(startText);\n let _text = startText;\n return {\n text(text) {\n _text = text;\n spinner.text = text;\n },\n append(text) {\n spinner.text = `${_text} \u203A ${text}`;\n },\n succeed(text) {\n if (text) {\n this.append(text);\n } else {\n this.text(_text);\n }\n spinner.succeed();\n },\n failed(text) {\n if (text) {\n this.text([_text, text].join(\"\\n\"));\n }\n spinner.fail();\n },\n };\n};\n\nexport const withSpinner = (\n text: string,\n pipe: (spinner: SpinnerFactory) => void | Promise<void>,\n spinner?: SpinnerFactory,\n) => pipe(spinner || spinnerFactory(text));\n", "import { readFile } from \"node:fs/promises\";\n\nimport { parse as dotenv } from \"dotenv\";\nimport type { Plugin } from \"vite\";\n\nimport { pathExists } from \"@kosmojs/devlib\";\n\ntype Entry = {\n keys: Array<string>;\n file?: string;\n defineOn?: string;\n use?: (key: string, val: string | undefined) => void;\n};\n\nexport default (entries: Array<Entry>): Plugin => {\n return {\n name: \"@kosmojs:definePlugin\",\n\n async config() {\n const define: Record<string, unknown> = {};\n\n for (const { keys, file, defineOn = \"process.env\", use } of entries) {\n define[defineOn] = {};\n\n const fileExists = file //\n ? await pathExists(file)\n : false;\n\n const env = fileExists\n ? dotenv(await readFile(file as never, \"utf8\"))\n : process.env;\n\n for (const [key, val] of Object.entries(env)) {\n if (keys.includes(key)) {\n // only explicitly given keys available on client\n define[`${defineOn}.${key}`] = JSON.stringify(val);\n }\n use?.(key, val);\n }\n }\n\n return { define };\n },\n };\n};\n"],
5
- "mappings": ";AAEA,SAAoB,WAAXA,gBAA+B;AACxC,SAAoB,WAAXA,gBAAiC;;;ACH1C,SAAS,YAAY;AAGrB,IAAO,uBAAQ,CACb,SACA,QAGW;AACX,SAAO;AAAA,IACL,MAAM;AAAA,IAEN,MAAM,SAAS;AACb,YAAM,kBAEF,MAAM,OAAO,GAAG,OAAO,kBAAkB;AAAA,QAC3C,MAAM,EAAE,MAAM,OAAO;AAAA,MACvB,GAAG,KAAK,CAAC,MAAM,EAAE,QAAQ,eAAe;AAExC,YAAM,WAAyB,CAAC;AAEhC,YAAM,cAAc,OAAO,QAAQ,EAAE,GAAG,iBAAiB,MAAM,CAAC;AAEhE,iBAAW,CAAC,cAAc,YAAY,KAAK,aAAa;AACtD,cAAM,QAAQ,aAAa,QAAQ,MAAM,EAAE;AAE3C,cAAM,QAAQ,aACX,IAAI,CAAC,MAAM,EAAE,QAAQ,MAAM,EAAE,CAAC,EAC9B,KAAK,CAAC,GAAG,MAAM,EAAE,MAAM,KAAK,EAAE,SAAS,EAAE,MAAM,KAAK,EAAE,MAAM;AAE/D,YAAI,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S,UAAU;AAAA,IAC3C;AAAA,EACF;AACF;;;AQrQA,SAAS,YAAAG,iBAAgB;AAEzB,SAAS,SAAS,cAAc;AAGhC,SAAS,cAAAC,mBAAkB;AAS3B,IAAO,wBAAQ,CAAC,YAAkC;AAChD,SAAO;AAAA,IACL,MAAM;AAAA,IAEN,MAAM,SAAS;AACb,YAAM,SAAkC,CAAC;AAEzC,iBAAW,EAAE,MAAM,MAAM,WAAW,eAAe,IAAI,KAAK,SAAS;AACnE,eAAO,QAAQ,IAAI,CAAC;AAEpB,cAAM,aAAa,OACf,MAAMA,YAAW,IAAI,IACrB;AAEJ,cAAM,MAAM,aACR,OAAO,MAAMD,UAAS,MAAe,MAAM,CAAC,IAC5C,QAAQ;AAEZ,mBAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC5C,cAAI,KAAK,SAAS,GAAG,GAAG;AAEtB,mBAAO,GAAG,QAAQ,IAAI,GAAG,EAAE,IAAI,KAAK,UAAU,GAAG;AAAA,UACnD;AACA,gBAAM,KAAK,GAAG;AAAA,QAChB;AAAA,MACF;AAEA,aAAO,EAAE,OAAO;AAAA,IAClB;AAAA,EACF;AACF;",
6
- "names": ["default", "join", "resolve", "styleText", "dirname", "join", "resolve", "crc", "glob", "defaults", "pathResolver", "resolve", "callExpression", "resolve", "crc", "hash", "defaults", "resolve", "join", "routeFiles", "dirname", "crc", "pathResolver", "glob", "resolve", "styleText", "join", "readFile", "pathExists"]
3
+ "sources": ["../src/index.ts", "../src/alias-plugin/index.ts", "../src/base-plugin/index.ts", "../src/base-plugin/api-handler.ts", "../src/base-plugin/routes.ts", "../src/base-plugin/routes/resolve.ts", "../src/base-plugin/ast.ts", "../src/base-plugin/cache.ts", "../src/base-plugin/templates/resolved-types.hbs", "../src/base-plugin/templates/types.hbs", "../src/base-plugin/routes/nesting.ts", "../src/base-plugin/spinner.ts", "../src/define-plugin/index.ts"],
4
+ "sourcesContent": ["export type { SSRManifestEntry, SSRSetup } from \"@kosmojs/devlib\";\n\nexport { default as apiGenerator } from \"@kosmojs/api-generator\";\nexport { default as fetchGenerator } from \"@kosmojs/fetch-generator\";\n\nexport { default as aliasPlugin } from \"./alias-plugin\";\nexport { default } from \"./base-plugin\";\nexport { default as definePlugin } from \"./define-plugin\";\n", "import { glob } from \"tinyglobby\";\nimport type { Alias, Plugin } from \"vite\";\n\nexport default (\n appRoot: string,\n opt?: {\n ignore?: Array<string>;\n },\n): Plugin => {\n return {\n name: \"@kosmojs:aliasPlugin\",\n\n async config() {\n const compilerOptions: {\n paths: Record<string, Array<string>>;\n } = await import(`${appRoot}/tsconfig.json`, {\n with: { type: \"json\" },\n }).then((e) => e.default.compilerOptions);\n\n const aliasmap: Array<Alias> = [];\n\n const pathEntries = Object.entries({ ...compilerOptions?.paths });\n\n for (const [aliasPattern, pathPatterns] of pathEntries) {\n const alias = aliasPattern.replace(\"/*\", \"\");\n\n const paths = pathPatterns\n .map((e) => e.replace(\"/*\", \"\"))\n .sort((a, b) => a.split(/\\/+/).length - b.split(/\\/+/).length);\n\n if (paths.length === 1) {\n aliasmap.push({\n find: new RegExp(`^${alias}/`),\n replacement: `${appRoot}/${paths[0]}/`,\n });\n } else if (paths.length > 1) {\n aliasmap.push({\n find: new RegExp(`^${alias}/`),\n replacement: \"\",\n async customResolver(_src) {\n // escaping symbols that may break glob pattern matching\n const src = _src.replace(/(\\$|\\^|\\+|\\(|\\)|\\[|\\])/g, \"\\\\$1\");\n\n // Build a list of possible file resolution patterns for a given source path.\n // Covers explicit extensions, implicit extensions, and folder-based index files.\n const patterns = paths.flatMap((path) => [\n // Case 1: Extension is explicitly provided\n // e.g. import styles from \"@admin/{solid}/styles.module.css\"\n `${path}/${src}*`,\n\n // Case 2: No extension provided\n // Match any extension and return the first match\n `${path}/${src}.*`,\n\n // Case 3: Folder containing an index file of any extension\n `${path}/${src}/index.*`,\n ]);\n\n const [file] = await glob(patterns, {\n cwd: appRoot,\n onlyFiles: true,\n absolute: true,\n dot: true,\n followSymbolicLinks: false,\n braceExpansion: false,\n globstar: false,\n ignore: opt?.ignore || [\n \"**/.git/**\",\n \"**/node_modules/**\",\n \"**/public/**\",\n \"**/var/**\",\n ],\n });\n\n return file;\n },\n });\n }\n }\n\n return {\n resolve: {\n alias: aliasmap,\n },\n };\n },\n };\n};\n", "import { basename, join, resolve } from \"node:path\";\nimport { styleText } from \"node:util\";\nimport { Worker } from \"node:worker_threads\";\n\nimport type { Plugin, ResolvedConfig } from \"vite\";\n\nimport type {\n GeneratorConstructor,\n PluginOptions,\n PluginOptionsResolved,\n} from \"@kosmojs/devlib\";\n\nimport apiGenerator from \"@kosmojs/api-generator\";\nimport stubGenerator from \"@kosmojs/dev/stub-generator\";\nimport fetchGenerator from \"@kosmojs/fetch-generator\";\n\nimport apiHandlerFactory from \"./api-handler\";\nimport routesFactory from \"./routes\";\nimport { type SpinnerFactory, spinnerFactory, withSpinner } from \"./spinner\";\nimport type { WorkerData, WorkerError, WorkerSpinner } from \"./worker\";\n\nexport default (apiurl: string, pluginOptions?: PluginOptions): Plugin => {\n const outDirSuffix = \"client\";\n\n const store: {\n config: ResolvedConfig;\n resolvedOptions: PluginOptionsResolved;\n } = {} as typeof store;\n\n const createWorker = () => {\n // Destructuring to separate common options from function-based ones.\n // Functions (e.g. generators, formatters) can't be passed to worker threads.\n const {\n generators = [],\n formatters = [],\n ...restOptions\n } = store.resolvedOptions;\n\n const generatorModules: WorkerData[\"generatorModules\"] = generators.map(\n (e) => [e.moduleImport, e.moduleConfig],\n );\n\n const formatterModules: WorkerData[\"formatterModules\"] =\n pluginOptions?.formatters\n ? pluginOptions.formatters.map((e) => [e.moduleImport, e.moduleConfig])\n : [];\n\n const workerData: WorkerData = {\n ...restOptions,\n generatorModules,\n formatterModules,\n };\n\n return new Worker(resolve(import.meta.dirname, \"base-plugin/worker.js\"), {\n workerData,\n env: {\n ...process.env,\n FORCE_COLOR: \"1\",\n },\n });\n };\n\n const workerHandler = (\n onReady?: () => Promise<void>,\n onExit?: () => Promise<void>,\n ) => {\n const worker = createWorker();\n\n const spinnerMap = new Map<string, SpinnerFactory>();\n\n worker.on(\"error\", async (error) => {\n console.error(error);\n });\n\n worker.on(\"exit\", async () => {\n await onExit?.();\n // TODO: revive worker only if it exited due to an error.\n // Note: worker.terminate() triggers an exit with code 1,\n // so it's not always possible to distinguish normal termination from a crash.\n });\n\n worker.on(\n \"message\",\n async (msg: { spinner?: WorkerSpinner; error?: WorkerError }) => {\n if (msg?.spinner) {\n const { id, startText, method, text } = msg.spinner;\n withSpinner(\n startText,\n (spinner) => {\n spinnerMap.set(id, spinner);\n spinner[method](text || \"\");\n if (method === \"succeed\" || method === \"failed\") {\n spinnerMap.delete(id);\n }\n },\n spinnerMap.get(id),\n );\n } else if (msg?.error) {\n const { error } = msg;\n if (error.stack) {\n const [message, ...stack] = error.stack.split(\"\\n\");\n console.error(styleText(\"red\", message));\n console.error(stack.join(\"\\n\"));\n } else if (error?.message) {\n console.error(`${styleText(\"red\", error?.name)}: ${error.message}`);\n } else {\n console.error(error);\n }\n }\n },\n );\n\n const readyHandler = async (msg: string) => {\n if (msg === \"ready\") {\n worker.off(\"message\", readyHandler);\n await onReady?.();\n }\n };\n\n worker.on(\"message\", readyHandler);\n\n return async () => {\n await worker.terminate();\n };\n };\n\n return {\n name: \"@kosmojs:basePlugin\",\n\n config(config) {\n if (!config.build?.outDir) {\n throw new Error(\"Incomplete config, missing build.outDir\");\n }\n return {\n build: {\n outDir: join(config.build.outDir, outDirSuffix),\n manifest: true,\n },\n };\n },\n\n async configResolved(_config) {\n store.config = _config;\n\n const appRoot = resolve(store.config.root, \"..\");\n const sourceFolder = basename(store.config.root);\n\n // removing outDirSuffix\n const outDir = resolve(appRoot, resolve(store.config.build.outDir, \"..\"));\n\n const { stabilityThreshold = 1000 } =\n typeof store.config.server.watch?.awaitWriteFinish === \"object\"\n ? store.config.server.watch.awaitWriteFinish\n : {};\n\n const watcher: PluginOptionsResolved[\"watcher\"] = {\n delay: stabilityThreshold,\n ...(store.config.server.watch\n ? { options: store.config.server.watch }\n : {}),\n };\n\n {\n const {\n generators = [],\n formatters = [],\n refineTypeName = \"TRefine\",\n } = { ...pluginOptions };\n\n const _apiGenerator = generators.find((e) => e.kind === \"api\");\n const _fetchGenerator = generators.find((e) => e.kind === \"fetch\");\n const _ssrGenerator = generators.find((e) => e.kind === \"ssr\");\n\n store.resolvedOptions = {\n ...pluginOptions,\n command: store.config.command,\n watcher,\n generators: [\n // 1. stub generator should run first\n stubGenerator(),\n // 2. then api generator\n _apiGenerator || (apiGenerator() as GeneratorConstructor),\n // 3. then fetch generator\n _fetchGenerator || (fetchGenerator() as GeneratorConstructor),\n // 4. user generators in the order they were added\n ...generators.filter((e) => {\n return e.kind //\n ? ![\"api\", \"fetch\", \"ssr\"].includes(e.kind)\n : true;\n }),\n // 5. ssr generator should run last\n ...(_ssrGenerator ? [_ssrGenerator] : []),\n ],\n formatters: formatters.map((e) => e.formatter),\n refineTypeName,\n baseurl: store.config.base,\n apiurl,\n appRoot,\n sourceFolder,\n outDir,\n };\n }\n\n if (store.config.command === \"build\") {\n const { resolvers } = await routesFactory(store.resolvedOptions);\n const resolvedEntries = [];\n\n {\n const spinner = spinnerFactory(\"Resolving Routes\");\n\n for (const { name, handler } of resolvers.values()) {\n spinner.append(\n `[ ${resolvedEntries.length + 1} of ${resolvers.size} ] ${name}`,\n );\n resolvedEntries.push(await handler());\n }\n\n spinner.succeed();\n }\n\n {\n const spinner = spinnerFactory(\"Running Generators\");\n\n for (const { name, factory } of store.resolvedOptions.generators) {\n spinner.append(name);\n const { watchHandler } = await factory(store.resolvedOptions);\n await watchHandler(resolvedEntries);\n }\n\n spinner.succeed();\n }\n }\n },\n\n async configureServer(server) {\n if (store.config.command !== \"serve\") {\n return;\n }\n\n const apiHandler = await apiHandlerFactory(store.resolvedOptions);\n\n const apiWatcher = await apiHandler.watcher();\n\n const stopWorker = workerHandler(\n async () => {\n await apiWatcher.start();\n },\n async () => {\n await apiWatcher.stop();\n },\n );\n\n // Attach the dev middleware from apiHandler. It may intercept requests to\n // determine whether they should be handled by Vite or by another handler.\n server.middlewares.use(apiHandler.devMiddleware);\n\n // clean up when Vite dev server closes/restarts\n server.httpServer?.on(\"close\", stopWorker);\n },\n };\n};\n", "import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { join, resolve } from \"node:path\";\nimport { styleText } from \"node:util\";\n\nimport { type BuildOptions, context, type Plugin } from \"esbuild\";\n\nimport type { App } from \"@kosmojs/api\";\nimport { defaults, type PluginOptionsResolved } from \"@kosmojs/devlib\";\n\nexport default async (options: PluginOptionsResolved) => {\n const { appRoot, sourceFolder, baseurl, apiurl } = options;\n\n const apiDir = join(sourceFolder, defaults.apiDir);\n const outDir = join(options.outDir, defaults.apiDir);\n\n const esbuildOptions: BuildOptions = await import(\n resolve(appRoot, \"esbuild.json\"),\n { with: { type: \"json\" } }\n ).then((e) => e.default);\n\n let app: App;\n let devMiddlewareFactory: Function | undefined;\n let teardownHandler: Function | undefined;\n\n const watcher = async () => {\n const outfile = join(outDir, \"dev.js\");\n\n const rebuildPlugin: Plugin = {\n name: \"rebuild\",\n setup(build) {\n build.onEnd(async () => {\n if (app) {\n await teardownHandler?.(app);\n }\n try {\n const exports = await import([outfile, Date.now()].join(\"?\"));\n devMiddlewareFactory = exports.devMiddlewareFactory;\n teardownHandler = exports.teardownHandler;\n app = await exports.default();\n console.debug(`${styleText(\"green\", \"\u279C\")} Api handler ready`);\n } catch (error) {\n console.error(`${styleText(\"red\", \"\u2717\")} Api handler error`);\n console.error(error);\n }\n });\n },\n };\n\n const ctx = await context({\n ...esbuildOptions,\n logLevel: \"error\",\n bundle: true,\n entryPoints: [join(apiDir, \"app.ts\")],\n plugins: [rebuildPlugin],\n outfile,\n });\n\n return {\n async start() {\n await ctx.watch({\n // waits this many milliseconds before rebuilding after a change is detected\n delay: options.watcher.delay,\n });\n },\n async stop() {\n await ctx.dispose();\n },\n };\n };\n\n const devMiddleware = async (\n req: IncomingMessage,\n res: ServerResponse,\n viteHandler: () => void,\n ) => {\n const next = () => {\n return viteHandler();\n };\n if (devMiddlewareFactory) {\n const handler = devMiddlewareFactory(app);\n await handler(req, res, next);\n } else {\n !req?.url || !new RegExp(`^${join(baseurl, apiurl)}($|/)`).test(req.url)\n ? next() // do not await here\n : await app?.callback()(req, res);\n }\n };\n\n return {\n watcher,\n devMiddleware,\n };\n};\n", "import {\n defaults,\n type PluginOptionsResolved,\n type RouteEntry,\n} from \"@kosmojs/devlib\";\n\nimport {\n apiRouteResolverFactory,\n createRouteEntry,\n isPageFile,\n pageLayoutResolverFactory,\n pageRouteResolverFactory,\n type ResolverSignature,\n scanRoutes,\n} from \"./routes/resolve\";\n\nexport * from \"./routes/nesting\";\nexport * from \"./routes/resolve\";\n\nexport default async (pluginOptions: PluginOptionsResolved) => {\n const { appRoot, sourceFolder } = pluginOptions;\n\n const apiRouteResolver = apiRouteResolverFactory(pluginOptions);\n const pageRouteResolver = pageRouteResolverFactory(pluginOptions);\n const pageLayoutResolver = pageLayoutResolverFactory(pluginOptions);\n\n const resolversFactory = (routeFiles: Array<string>) => {\n const resolvers = new Map<\n string, // fileFullpath\n ResolverSignature\n >();\n\n const entries: Array<RouteEntry> = routeFiles.flatMap((file) => {\n const entry = createRouteEntry(file, pluginOptions);\n return entry ? [entry] : [];\n });\n\n for (const entry of entries) {\n if (entry.folder === defaults.apiDir) {\n resolvers.set(entry.fileFullpath, apiRouteResolver(entry));\n } else if (entry.folder === defaults.pagesDir) {\n const pageFile = isPageFile(entry.file);\n if (pageFile?.kind === \"index\") {\n resolvers.set(entry.fileFullpath, pageRouteResolver(entry));\n } else if (pageFile?.kind === \"layout\") {\n resolvers.set(entry.fileFullpath, pageLayoutResolver(entry));\n }\n }\n }\n\n return resolvers;\n };\n\n const routeFiles = await scanRoutes({ appRoot, sourceFolder });\n\n return {\n resolvers: resolversFactory(routeFiles),\n resolversFactory,\n };\n};\n", "import { dirname, join, resolve } from \"node:path\";\n\nimport crc from \"crc/crc32\";\nimport picomatch from \"picomatch\";\nimport { glob } from \"tinyglobby\";\n\nimport {\n type ApiRoute,\n defaults,\n type PageRoute,\n type PluginOptionsResolved,\n pathResolver,\n pathTokensFactory,\n type ResolvedEntry,\n type RouteEntry,\n render,\n renderToFile,\n} from \"@kosmojs/devlib\";\n\nimport { resolveRouteSignature, typeResolverFactory } from \"../ast\";\nimport { cacheFactory } from \"../cache\";\nimport resolvedTypesTpl from \"../templates/resolved-types.hbs\";\nimport typesFileTpl from \"../templates/types.hbs\";\n\nexport type ResolverSignature = {\n name: string;\n handler: (updatedFile?: string) => Promise<ResolvedEntry>;\n};\n\nexport const API_INDEX_BASENAME = \"index\";\nexport const API_INDEX_PATTERN = `${API_INDEX_BASENAME}.ts`;\n\nexport const PAGE_INDEX_BASENAME = \"index\";\nexport const PAGE_INDEX_PATTERN = `${PAGE_INDEX_BASENAME}.{tsx,vue}`;\n\nexport const PAGE_LAYOUT_BASENAME = \"layout\";\nexport const PAGE_LAYOUT_PATTERN = `${PAGE_LAYOUT_BASENAME}.{tsx,vue}`;\n\nconst ROUTE_FILE_PATTERNS = [\n // match index files in api dir\n `${defaults.apiDir}/**/${API_INDEX_PATTERN}`,\n // match index files in pages dir\n `${defaults.pagesDir}/**/${PAGE_INDEX_PATTERN}`,\n // match layout files in pages dir\n `${defaults.pagesDir}/**/${PAGE_LAYOUT_PATTERN}`,\n];\n\nexport const scanRoutes = async ({\n appRoot,\n sourceFolder,\n}: Pick<PluginOptionsResolved, \"appRoot\" | \"sourceFolder\">) => {\n return glob(ROUTE_FILE_PATTERNS, {\n cwd: resolve(appRoot, sourceFolder),\n absolute: true,\n onlyFiles: true,\n followSymbolicLinks: false,\n ignore: [\n // ignore top-level matches, routes resides in folders, even index route\n `${defaults.apiDir}/${API_INDEX_PATTERN}`,\n `${defaults.pagesDir}/${PAGE_INDEX_PATTERN}`,\n `${defaults.pagesDir}/${PAGE_LAYOUT_PATTERN}`,\n ],\n });\n};\n\nexport const isRouteFile = (\n file: string,\n {\n appRoot,\n sourceFolder,\n }: Pick<PluginOptionsResolved, \"appRoot\" | \"sourceFolder\">,\n):\n | [\n // Either `apiDir` or `pagesDir`\n folder: string,\n // Path to a file within the folder, nested at least one level deep\n file: string,\n ]\n | undefined => {\n const [_sourceFolder, folder, ...rest] = resolve(appRoot, file)\n .replace(`${appRoot}/`, \"\")\n .split(\"/\");\n\n /**\n * Ensure the file:\n * - is under the correct source root (`sourceFolder`)\n * - belongs to a known route folder (`apiDir` or `pagesDir`)\n * - is nested at least one level deep (not a direct child of the folder)\n * */\n if (!folder || _sourceFolder !== sourceFolder || rest.length < 2) {\n return;\n }\n\n return picomatch.isMatch(join(folder, ...rest), ROUTE_FILE_PATTERNS)\n ? [folder, rest.join(\"/\")]\n : undefined;\n};\n\nexport const isPageFile = (\n file: string,\n): { kind: \"index\" | \"layout\" } | undefined => {\n return picomatch.matchBase(file, `**/${PAGE_INDEX_PATTERN}`)\n ? { kind: \"index\" }\n : picomatch.matchBase(file, `**/${PAGE_LAYOUT_PATTERN}`)\n ? { kind: \"layout\" }\n : undefined;\n};\n\nexport const isIndexFile = (file: string) => {\n return (\n picomatch.matchBase(file, `**/${API_INDEX_PATTERN}`) ||\n picomatch.matchBase(file, `**/${PAGE_INDEX_PATTERN}`)\n );\n};\n\nexport const createRouteEntry = (\n _file: string,\n {\n appRoot,\n sourceFolder,\n }: Pick<PluginOptionsResolved, \"appRoot\" | \"sourceFolder\">,\n): RouteEntry | undefined => {\n // scanner already is doing a great job on matching only relevant files\n // but doing a double check here to make sure only needed files added to stack\n const resolvedPaths = isRouteFile(_file, { appRoot, sourceFolder });\n\n if (!resolvedPaths) {\n return;\n }\n\n const [folder, file] = resolvedPaths;\n\n const fileFullpath = join(appRoot, sourceFolder, folder, file);\n\n const pathTokens = pathTokensFactory(dirname(file));\n\n const name = pathTokens.map((e) => e.orig).join(\"/\");\n\n const importFile = file;\n\n const importName = `${importFile.replace(/\\W+/g, \"_\")}_${crc(importFile)}`;\n\n return {\n name,\n folder,\n file,\n fileFullpath,\n pathTokens,\n importFile,\n importName,\n };\n};\n\ntype ResolverFactory = (\n pluginOptions: PluginOptionsResolved,\n) => (entry: RouteEntry) => ResolverSignature;\n\nexport const pageLayoutResolverFactory: ResolverFactory = () => {\n return (entry) => {\n const { name } = entry;\n\n const handler: ResolverSignature[\"handler\"] = async () => {\n return {\n kind: \"pageLayout\",\n entry,\n };\n };\n\n return { name, handler };\n };\n};\n\nexport const pageRouteResolverFactory: ResolverFactory = () => {\n return (entry) => {\n const {\n name,\n folder,\n file,\n fileFullpath,\n pathTokens,\n importFile,\n importName,\n } = entry;\n\n const handler: ResolverSignature[\"handler\"] = async () => {\n const entry: PageRoute = {\n name,\n pathTokens,\n params: {\n schema: pathTokens.flatMap((e) => (e.param ? [e.param] : [])),\n },\n folder,\n file,\n fileFullpath,\n importFile,\n importName,\n };\n\n return {\n kind: \"pageRoute\",\n entry,\n };\n };\n\n return { name, handler };\n };\n};\n\nexport const apiRouteResolverFactory: ResolverFactory = (pluginOptions) => {\n const {\n appRoot,\n sourceFolder,\n generators = [],\n formatters = [],\n refineTypeName,\n } = pluginOptions;\n\n let resolveTypes = false;\n\n for (const { options } of generators) {\n if (options?.resolveTypes) {\n resolveTypes = true;\n }\n }\n\n const {\n //\n literalTypesResolver,\n getSourceFile,\n refreshSourceFile,\n } = typeResolverFactory(pluginOptions);\n\n return (entry) => {\n const {\n name,\n file,\n folder,\n fileFullpath,\n pathTokens,\n importFile,\n importName,\n } = entry;\n\n const handler: ResolverSignature[\"handler\"] = async (updatedFile) => {\n const paramsSchema = pathTokens.flatMap((e) => {\n return e.param ? [e.param] : [];\n });\n\n const optionalParams = paramsSchema.length\n ? !paramsSchema.some((e) => e.isRequired)\n : true;\n\n const { getCache, persistCache } = cacheFactory(\n { file, fileFullpath, importName },\n {\n appRoot,\n sourceFolder,\n extraContext: { resolveTypes },\n },\n );\n\n let cache = await getCache({ validate: true });\n\n if (!cache) {\n if (updatedFile === fileFullpath) {\n await refreshSourceFile(fileFullpath);\n }\n\n const {\n typeDeclarations,\n paramsRefinements,\n methods,\n payloadTypes,\n responseTypes,\n referencedFiles = [],\n } = await resolveRouteSignature(\n { importName, fileFullpath, optionalParams },\n {\n withReferencedFiles: true,\n sourceFile: getSourceFile(fileFullpath),\n relpathResolver(path) {\n return join(sourceFolder, defaults.apiDir, dirname(file), path);\n },\n },\n );\n\n const numericParams = paramsRefinements\n ? paramsRefinements.flatMap(({ text, index }) => {\n if (text === \"number\") {\n const param = paramsSchema.at(index);\n return param ? [param.name] : [];\n }\n return [];\n })\n : [];\n\n const typesFile = pathResolver({ appRoot, sourceFolder }).resolve(\n \"apiLibDir\",\n dirname(file),\n \"types.ts\",\n );\n\n const params: ApiRoute[\"params\"] = {\n id: [\"ParamsT\", crc(name)].join(\"\"),\n schema: paramsSchema,\n resolvedType: undefined,\n };\n\n const typesFileContent = render(typesFileTpl, {\n params,\n paramsSchema: paramsSchema.map((param, index) => {\n return {\n ...param,\n refinement: paramsRefinements?.at(index),\n };\n }),\n typeDeclarations,\n payloadTypes,\n responseTypes,\n });\n\n const resolvedTypes = resolveTypes\n ? literalTypesResolver(typesFileContent, {\n overrides: [...payloadTypes, ...responseTypes].reduce(\n (map: Record<string, string>, { id, skipValidation }) => {\n if (skipValidation) {\n map[id] = \"never\";\n }\n return map;\n },\n { [refineTypeName]: refineTypeName },\n ),\n withProperties: [params.id, ...payloadTypes.map((e) => e.id)],\n formatters,\n })\n : undefined;\n\n /**\n * Deploy types.ts file; required by core generators (like fetch).\n * If types resolved, write resolved types;\n * otherwise write original types extracted from API route.\n * */\n await renderToFile(\n typesFile,\n resolvedTypes ? resolvedTypesTpl : typesFileContent,\n { resolvedTypes },\n );\n\n params.resolvedType = resolvedTypes?.find((e) => e.name === params.id);\n\n cache = await persistCache({\n params,\n methods,\n typeDeclarations,\n numericParams,\n // text was needed at writing types.ts file, dropping from cache\n payloadTypes: payloadTypes.map(({ text, ...rest }) => {\n return {\n ...rest,\n resolvedType: resolvedTypes?.find((e) => e.name === rest.id),\n };\n }),\n responseTypes: responseTypes.map(({ text, ...rest }) => {\n return {\n ...rest,\n resolvedType: resolvedTypes?.find((e) => e.name === rest.id),\n };\n }),\n referencedFiles,\n });\n }\n\n const entry: ApiRoute = {\n name,\n pathTokens,\n params: cache.params,\n numericParams: cache.numericParams,\n optionalParams,\n importName,\n importFile,\n folder,\n file,\n fileFullpath,\n methods: cache.methods,\n typeDeclarations: cache.typeDeclarations,\n payloadTypes: cache.payloadTypes,\n responseTypes: cache.responseTypes,\n referencedFiles: Object.keys(cache.referencedFiles).map(\n // expand referenced files path,\n // they are stored as relative in cache\n (e) => resolve(appRoot, e),\n ),\n };\n\n return {\n kind: \"apiRoute\",\n entry,\n };\n };\n\n return { name, handler };\n };\n};\n", "import { resolve } from \"node:path\";\n\nimport crc from \"crc/crc32\";\nimport { flattener } from \"tfusion\";\nimport {\n type CallExpression,\n type Identifier,\n type Node,\n Project,\n type ProjectOptions,\n type SourceFile,\n SyntaxKind,\n} from \"ts-morph\";\n\nimport { type HTTPMethod, HTTPMethods } from \"@kosmojs/api\";\nimport type {\n ApiRoute,\n PayloadType,\n PluginOptionsResolved,\n ResponseType,\n TypeDeclaration,\n} from \"@kosmojs/devlib\";\n\ntype PathResolver = (path: string) => string;\n\nexport const createProject = (opts?: ProjectOptions) => new Project(opts);\n\nexport const resolveRouteSignature = async (\n route: Pick<ApiRoute, \"importName\" | \"fileFullpath\" | \"optionalParams\">,\n opts?: {\n relpathResolver?: PathResolver;\n sourceFile?: SourceFile;\n withReferencedFiles?: boolean;\n },\n) => {\n const {\n sourceFile = createProject().addSourceFileAtPath(route.fileFullpath),\n } = { ...opts };\n\n const [typeDeclarations, referencedFiles] = extractTypeDeclarations(\n sourceFile,\n opts,\n );\n\n const defaultExport = extractDefaultExport(sourceFile);\n\n const paramsRefinements = defaultExport\n ? extractParamsRefinements(defaultExport)\n : undefined;\n\n const methods = defaultExport\n ? extractRouteMethods(defaultExport, route)\n : [];\n\n const payloadTypes = methods.flatMap((e) => {\n return e.payloadType ? [e.payloadType] : [];\n });\n\n const responseTypes = methods.flatMap((e) => {\n return e.responseType ? [e.responseType] : [];\n });\n\n return {\n typeDeclarations,\n paramsRefinements,\n methods: methods.map((e) => e.method),\n payloadTypes,\n responseTypes,\n referencedFiles,\n };\n};\n\nexport const extractDefaultExport = (\n sourceFile: SourceFile,\n): CallExpression | undefined => {\n const [defaultExport] = sourceFile\n .getExportAssignments()\n .flatMap((exportAssignment) => {\n if (exportAssignment.isExportEquals()) {\n return [];\n }\n const callExpression = exportAssignment.getExpression();\n return callExpression.isKind(SyntaxKind.CallExpression)\n ? [callExpression]\n : [];\n });\n return defaultExport;\n};\n\nexport const extractParamsRefinements = (\n callExpression: CallExpression,\n):\n | Array<{\n index: number;\n text: string;\n }>\n | undefined => {\n const [firstGeneric] = extractGenerics(callExpression);\n\n if (!firstGeneric?.node.isKind(SyntaxKind.TupleType)) {\n return;\n }\n\n const tupleElements = firstGeneric.node.getElements();\n\n if (!tupleElements?.length) {\n return;\n }\n\n return tupleElements.map((node, index) => {\n return {\n index,\n text: node.getText(),\n };\n });\n};\n\nexport const extractRouteMethods = (\n callExpression: CallExpression,\n route: Pick<ApiRoute, \"importName\" | \"optionalParams\">,\n): Array<{\n method: HTTPMethod;\n payloadType: (PayloadType & { text: string }) | undefined;\n responseType: (ResponseType & { text: string }) | undefined;\n}> => {\n const funcDeclaration =\n callExpression.getFirstChildByKind(SyntaxKind.ArrowFunction) ||\n callExpression.getFirstChildByKind(SyntaxKind.FunctionExpression);\n\n if (!funcDeclaration) {\n return [];\n }\n\n const arrayLiteralExpression = funcDeclaration.getFirstChildByKind(\n SyntaxKind.ArrayLiteralExpression,\n );\n\n if (!arrayLiteralExpression) {\n return [];\n }\n\n const callExpressions: Array<[CallExpression, HTTPMethod]> = [];\n\n for (const e of arrayLiteralExpression.getChildrenOfKind(\n SyntaxKind.CallExpression,\n )) {\n const name = e.getExpression().getText() as HTTPMethod;\n if (HTTPMethods[name]) {\n callExpressions.push([e, name]);\n }\n }\n\n const methods = [];\n\n const skipValidationFilter = (e: string) => /@skip-validation/.test(e);\n\n for (const [callExpression, method] of callExpressions) {\n const [payloadGeneric, responseGeneric] = extractGenerics(callExpression);\n\n const payloadText = payloadGeneric?.node\n ? payloadGeneric.node.getChildren().length === 0\n ? \"{}\"\n : payloadGeneric.node.getFullText()\n : undefined;\n\n const responseText = responseGeneric?.node.getText();\n\n const responseType = responseText\n ? {\n id: [\"ResponseT\", crc(route.importName + method)].join(\"\"),\n method,\n skipValidation: responseGeneric?.comments\n ? responseGeneric.comments.some(skipValidationFilter)\n : false,\n text: [\"never\", \"object\"].includes(responseText)\n ? \"{}\"\n : responseText,\n resolvedType: undefined,\n }\n : undefined;\n\n const payloadType = payloadText\n ? {\n id: [\"PayloadT\", crc(route.importName + method)].join(\"\"),\n responseTypeId: responseType?.id,\n method,\n skipValidation: payloadGeneric?.comments\n ? payloadGeneric.comments.some(skipValidationFilter)\n : false,\n isOptional: payloadText\n ? payloadText === \"{}\" || route.optionalParams\n : true,\n text: payloadText,\n resolvedType: undefined,\n }\n : undefined;\n\n methods.push({\n method,\n payloadType,\n responseType,\n });\n }\n\n return methods;\n};\n\nexport const extractTypeDeclarations = (\n sourceFile: SourceFile,\n opts?: {\n relpathResolver?: PathResolver;\n withReferencedFiles?: boolean;\n },\n): [d: Array<TypeDeclaration>, f?: Array<string>] => {\n const declarations: Array<TypeDeclaration> = [];\n\n const referencedFiles: Array<string> | undefined = opts?.withReferencedFiles\n ? []\n : undefined;\n\n for (const declaration of sourceFile.getImportDeclarations()) {\n const modulePath = declaration.getModuleSpecifierValue();\n\n const path = /^\\.\\.?\\/?/.test(modulePath)\n ? opts?.relpathResolver\n ? opts.relpathResolver(modulePath)\n : modulePath\n : modulePath;\n\n const typeOnlyDeclaration = declaration.isTypeOnly();\n\n const defaultImport = typeOnlyDeclaration\n ? declaration.getDefaultImport()\n : undefined;\n\n if (defaultImport) {\n const name = defaultImport.getText();\n const text = `import type ${name} from \"${path}\";`;\n declarations.push({\n importDeclaration: {\n name,\n path,\n },\n text,\n });\n if (referencedFiles) {\n referencedFiles.push(...getReferencedFiles(defaultImport));\n }\n }\n\n for (const namedImport of declaration.getNamedImports()) {\n if (namedImport.isTypeOnly() || typeOnlyDeclaration) {\n const nameNode = namedImport.getNameNode();\n const name = nameNode.getText();\n const alias = namedImport.getAliasNode()?.getText();\n const nameText = alias ? `${name} as ${alias}` : name;\n\n declarations.push({\n importDeclaration: {\n name,\n alias,\n path,\n },\n text: `import type { ${nameText} } from \"${path}\";`,\n });\n\n if (referencedFiles) {\n if (nameNode.isKind(SyntaxKind.Identifier)) {\n referencedFiles.push(...getReferencedFiles(nameNode));\n }\n }\n }\n }\n }\n\n for (const declaration of sourceFile.getTypeAliases()) {\n const name = declaration.getName();\n const text = declaration.getFullText().trim();\n declarations.push({\n typeAliasDeclaration: { name },\n text,\n });\n }\n\n for (const declaration of sourceFile.getInterfaces()) {\n const name = declaration.getName();\n const text = declaration.getFullText().trim();\n declarations.push({\n interfaceDeclaration: { name },\n text,\n });\n }\n\n for (const declaration of sourceFile.getEnums()) {\n const name = declaration.getName();\n const text = declaration.getFullText().trim();\n declarations.push({\n enumDeclaration: { name },\n text,\n });\n }\n\n for (const declaration of sourceFile.getExportDeclarations()) {\n const typeOnlyDeclaration = declaration.isTypeOnly();\n\n const modulePath = declaration.getModuleSpecifierValue();\n\n const path = modulePath\n ? /^\\.\\.?\\/?/.test(modulePath)\n ? opts?.relpathResolver\n ? opts.relpathResolver(modulePath)\n : modulePath\n : modulePath\n : undefined;\n\n for (const namedExport of declaration.getNamedExports()) {\n if (namedExport.isTypeOnly() || typeOnlyDeclaration) {\n const nameNode = namedExport.getNameNode();\n const name = nameNode.getText();\n const alias = namedExport.getAliasNode()?.getText();\n const nameText = alias ? `${name} as ${alias}` : name;\n\n declarations.push({\n exportDeclaration: {\n name,\n alias: alias ?? name,\n path,\n },\n text: path\n ? `export type { ${nameText} } from \"${path}\";`\n : `export type { ${nameText} };`,\n });\n\n if (referencedFiles) {\n if (nameNode.isKind(SyntaxKind.Identifier)) {\n referencedFiles.push(...getReferencedFiles(nameNode));\n }\n }\n }\n }\n }\n\n return referencedFiles\n ? [declarations, [...new Set<string>(referencedFiles)]]\n : [declarations];\n};\n\nconst getReferencedFiles = (importIdentifier: Identifier): Array<string> => {\n // ambient modules may have declarations in multiple files\n const declarations =\n importIdentifier //\n ?.getSymbol()\n ?.getAliasedSymbol()\n ?.getDeclarations() || [];\n\n return declarations.flatMap((e) => {\n const sourceFile = e.getSourceFile();\n return sourceFile //\n ? [sourceFile.getFilePath()]\n : [];\n });\n};\n\nconst extractGenerics = (\n callExpression: CallExpression,\n): Array<{ node: Node; comments: Array<string> }> => {\n return callExpression.getTypeArguments().map((node) => {\n return {\n node,\n comments: node\n .getLeadingCommentRanges()\n .map((range) => range.getText().trim()),\n };\n });\n};\n\nexport const typeResolverFactory = ({ appRoot }: PluginOptionsResolved) => {\n const project = createProject({\n tsConfigFilePath: resolve(appRoot, \"tsconfig.json\"),\n skipAddingFilesFromTsConfig: true,\n });\n\n const literalTypesResolver = (\n literalTypes: string,\n options: Parameters<typeof flattener>[2],\n ) => {\n const sourceFile = project.createSourceFile(\n `${crc(literalTypes)}-${Date.now()}.ts`,\n literalTypes,\n { overwrite: true },\n );\n\n const resolvedTypes = flattener(project, sourceFile, {\n ...options,\n stripComments: true,\n });\n\n project.removeSourceFile(sourceFile);\n\n return resolvedTypes;\n };\n\n return {\n getSourceFile: (fileFullpath: string) => {\n return (\n project.getSourceFile(fileFullpath) ||\n project.addSourceFileAtPath(fileFullpath)\n );\n },\n refreshSourceFile: async (fileFullpath: string) => {\n const sourceFile = project.getSourceFile(fileFullpath);\n if (sourceFile) {\n await sourceFile.refreshFromFileSystem();\n }\n },\n literalTypesResolver,\n };\n};\n", "import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\n\nimport crc from \"crc/crc32\";\n\n/**\n * Import from published package to ensure correct version at runtime.\n * Local import would be bundled with pre-bump version; this external\n * import resolves to the actual published package.json.\n * */\nimport self from \"@kosmojs/dev/package.json\" with { type: \"json\" };\nimport { type ApiRoute, pathExists, pathResolver } from \"@kosmojs/devlib\";\n\nexport type Cache = {\n hash: number;\n referencedFiles: Record<string, number>;\n} & Pick<\n ApiRoute,\n | \"params\"\n | \"methods\"\n | \"typeDeclarations\"\n | \"numericParams\"\n | \"payloadTypes\"\n | \"responseTypes\"\n>;\n\ntype ExtraContext = Record<string | number, unknown>;\n\nexport const cacheFactory = (\n route: Pick<ApiRoute, \"file\" | \"fileFullpath\" | \"importName\">,\n {\n appRoot,\n sourceFolder,\n extraContext,\n }: {\n appRoot: string;\n sourceFolder: string;\n extraContext?: ExtraContext;\n },\n) => {\n const cacheFile = pathResolver({\n appRoot,\n sourceFolder,\n }).resolve(\"apiLibDir\", dirname(route.file), \"cache.json\");\n\n const getCache = async (opt?: {\n validate?: boolean;\n }): Promise<Cache | undefined> => {\n if (await pathExists(cacheFile)) {\n try {\n const cache = JSON.parse(await readFile(cacheFile, \"utf8\"));\n return opt?.validate //\n ? validateCache(cache)\n : cache;\n } catch (_e) {}\n }\n return undefined;\n };\n\n const persistCache = async ({\n referencedFiles: _referencedFiles,\n ...rest\n }: Omit<Cache, \"hash\" | \"referencedFiles\"> & {\n referencedFiles: Array<string>;\n }): Promise<Cache> => {\n const hash = await generateFileHash(route.fileFullpath, {\n ...extraContext,\n });\n\n const referencedFiles: Cache[\"referencedFiles\"] = {};\n\n for (const file of _referencedFiles) {\n referencedFiles[\n // Strip project root to ensure cached paths are relative\n // and portable across environments (CI, local, etc.)\n file.replace(`${appRoot}/`, \"\")\n ] = await generateFileHash(file);\n }\n\n const cache = { ...rest, hash, referencedFiles };\n\n await mkdir(dirname(cacheFile), { recursive: true });\n await writeFile(cacheFile, JSON.stringify(cache, null, 2), \"utf8\");\n\n return cache;\n };\n\n const validateCache = async (\n cache: Cache | undefined,\n ): Promise<Cache | undefined> => {\n if (!cache?.hash) {\n return;\n }\n\n if (!cache.typeDeclarations || !cache.referencedFiles) {\n // incomplete cache\n return;\n }\n\n const hash = await generateFileHash(route.fileFullpath, {\n ...extraContext,\n });\n\n if (!identicalHashSum(cache.hash, hash)) {\n // route itself updated\n return;\n }\n\n for (const [file, hash] of Object.entries(cache.referencedFiles)) {\n if (\n !identicalHashSum(hash, await generateFileHash(resolve(appRoot, file)))\n ) {\n // some referenced file updated\n return;\n }\n }\n\n return cache;\n };\n\n return {\n getCache,\n validateCache,\n persistCache,\n };\n};\n\nconst generateFileHash = async (\n file: string,\n extraContext?: ExtraContext,\n): Promise<number> => {\n let fileContent: string | undefined;\n try {\n fileContent = await readFile(file, \"utf8\");\n } catch (_e) {\n // file could be deleted since last build\n return 0;\n }\n return fileContent\n ? crc(\n JSON.stringify({\n ...extraContext,\n [self.cacheVersion]: fileContent,\n }),\n )\n : 0;\n};\n\n// return true if sums are identical\nconst identicalHashSum = (a: number, b: number) => {\n return a === b;\n};\n", "{{#each resolvedTypes}}\nexport type {{name}} = {{text}};\n{{/each}}\n", "{{#each typeDeclarations}}{{text}}\n{{/each}}\n\nexport type {{params.id}} = {\n {{#each paramsSchema}}\n \"{{name}}\"{{#unless isRequired}}?{{/unless}}:{{#if isRest}} Array<{{/if}}\n {{#if refinement}}{{refinement.text}}{{else}}string{{/if}}\n {{#if isRest}}>{{/if}}\n {{/each}}\n};\n\n{{#each payloadTypes}}\nexport type {{id}} = {{text}};\n{{/each}}\n\n{{#each responseTypes}}\nexport type {{id}} = {{text}};\n{{/each}}\n", "import { basename } from \"node:path\";\n\nimport {\n type NestedRouteEntry,\n type RouteEntry,\n sortRoutes,\n} from \"@kosmojs/devlib\";\n\nimport { PAGE_INDEX_BASENAME, PAGE_LAYOUT_BASENAME } from \"./resolve\";\n\n/**\n * Build a nested route tree from flat route entries.\n * */\nexport const nestedRoutesFactory = (routeEntries: Array<RouteEntry>) => {\n const entryStack = structuredClone(routeEntries).sort(sortRoutes);\n\n /**\n * Group entries by name (at the same level, both layout and index share same name).\n *\n * Handle 3 cases:\n * - both index and layout exists\n * - only index exists\n * - only layout exists\n *\n * */\n const transformEntries = (\n entries: Array<RouteEntry>,\n parent?: RouteEntry,\n ): Array<NestedRouteEntry> => {\n return [...new Set(entries.map((e) => e.name))].flatMap((name) => {\n const nameEntries = entryStack.flatMap(({ fileFullpath, ...entry }) => {\n return entry.name === name ? [entry] : [];\n });\n\n const index = nameEntries.find((e) =>\n basename(e.file).startsWith(PAGE_INDEX_BASENAME),\n ) as RouteEntry;\n\n const layout = nameEntries.find((e) =>\n basename(e.file).startsWith(PAGE_LAYOUT_BASENAME),\n ) as RouteEntry;\n\n if (index || layout) {\n return [\n {\n index: index\n ? {\n ...index,\n pathTokens: index.pathTokens.slice(\n parent?.pathTokens.length || 0,\n ),\n }\n : undefined,\n layout: layout\n ? {\n ...layout,\n pathTokens: layout.pathTokens.slice(\n parent?.pathTokens.length || 0,\n ),\n }\n : undefined,\n parent: parent?.name,\n children: transformEntries(\n findDescendantEntries(index || layout),\n index || layout,\n ),\n },\n ];\n }\n\n return [];\n });\n };\n\n /**\n * Recursively finds direct descendant routes.\n *\n * \"Direct\" means the next existing route in the path hierarchy,\n * skipping intermediate path segments that don't have index/layout files.\n *\n * Example: blog/post/[slug]/index.tsx is a direct child of blog/index.tsx\n * even though \"post\" segment exists (it has no index.tsx).\n * */\n const findDescendantEntries = ({\n name,\n pathTokens,\n }: RouteEntry): Array<RouteEntry> => {\n // Find all potential children - BOTH indexes AND layouts\n const potentialChildren = entryStack.filter((entry) => {\n // Must be deeper than current entry\n if (entry.pathTokens.length <= pathTokens.length) {\n return false;\n }\n // Must be a descendant path\n if (!entry.name.startsWith(`${name}/`)) {\n return false;\n }\n return true;\n });\n\n // Filter to direct children (no intermediate route between parent and child)\n return potentialChildren.filter((child) => {\n // Check if any route exists between parent and child\n const hasIntermediateRoute = potentialChildren.some((intermediate) => {\n if (intermediate === child) {\n return false;\n }\n // Intermediate must be between parent and child in depth\n if (intermediate.pathTokens.length <= pathTokens.length) {\n return false;\n }\n if (intermediate.pathTokens.length >= child.pathTokens.length) {\n return false;\n }\n // Child must be descendant of intermediate\n return child.name.startsWith(`${intermediate.name}/`);\n });\n\n return !hasIntermediateRoute;\n });\n };\n\n // Find root entries - entries that have no parent route\n const rootEntries = entryStack.filter((entry) => {\n // Check if any other entry could be its parent\n const hasParent = entryStack.some((potential) => {\n if (potential === entry) {\n return false;\n }\n if (potential.pathTokens.length >= entry.pathTokens.length) {\n return false;\n }\n return entry.name.startsWith(`${potential.name}/`);\n });\n\n return !hasParent;\n });\n\n return transformEntries(rootEntries);\n};\n", "import ora from \"ora\";\n\nexport type SpinnerFactory = {\n text: (text: string) => void;\n append: (text: string) => void;\n succeed: (text?: string) => void;\n failed: (text?: string) => void;\n};\n\nexport const spinnerFactory = (startText: string): SpinnerFactory => {\n const spinner = ora().start(startText);\n let _text = startText;\n return {\n text(text) {\n _text = text;\n spinner.text = text;\n },\n append(text) {\n spinner.text = `${_text} \u203A ${text}`;\n },\n succeed(text) {\n if (text) {\n this.append(text);\n } else {\n this.text(_text);\n }\n spinner.succeed();\n },\n failed(text) {\n if (text) {\n this.text([_text, text].join(\"\\n\"));\n }\n spinner.fail();\n },\n };\n};\n\nexport const withSpinner = (\n text: string,\n pipe: (spinner: SpinnerFactory) => void | Promise<void>,\n spinner?: SpinnerFactory,\n) => pipe(spinner || spinnerFactory(text));\n", "import { readFile } from \"node:fs/promises\";\n\nimport { parse as dotenv } from \"dotenv\";\nimport type { Plugin } from \"vite\";\n\nimport { pathExists } from \"@kosmojs/devlib\";\n\ntype Entry = {\n keys: Array<string>;\n file?: string;\n defineOn?: string;\n use?: (key: string, val: string | undefined) => void;\n};\n\nexport default (entries: Array<Entry>): Plugin => {\n return {\n name: \"@kosmojs:definePlugin\",\n\n async config() {\n const define: Record<string, unknown> = {};\n\n for (const { keys, file, defineOn = \"process.env\", use } of entries) {\n define[defineOn] = {};\n\n const fileExists = file //\n ? await pathExists(file)\n : false;\n\n const env = fileExists\n ? dotenv(await readFile(file as never, \"utf8\"))\n : process.env;\n\n for (const [key, val] of Object.entries(env)) {\n if (keys.includes(key)) {\n // only explicitly given keys available on client\n define[`${defineOn}.${key}`] = JSON.stringify(val);\n }\n use?.(key, val);\n }\n }\n\n return { define };\n },\n };\n};\n"],
5
+ "mappings": ";AAEA,SAAoB,WAAXA,gBAA+B;AACxC,SAAoB,WAAXA,gBAAiC;;;ACH1C,SAAS,YAAY;AAGrB,IAAO,uBAAQ,CACb,SACA,QAGW;AACX,SAAO;AAAA,IACL,MAAM;AAAA,IAEN,MAAM,SAAS;AACb,YAAM,kBAEF,MAAM,OAAO,GAAG,OAAO,kBAAkB;AAAA,QAC3C,MAAM,EAAE,MAAM,OAAO;AAAA,MACvB,GAAG,KAAK,CAAC,MAAM,EAAE,QAAQ,eAAe;AAExC,YAAM,WAAyB,CAAC;AAEhC,YAAM,cAAc,OAAO,QAAQ,EAAE,GAAG,iBAAiB,MAAM,CAAC;AAEhE,iBAAW,CAAC,cAAc,YAAY,KAAK,aAAa;AACtD,cAAM,QAAQ,aAAa,QAAQ,MAAM,EAAE;AAE3C,cAAM,QAAQ,aACX,IAAI,CAAC,MAAM,EAAE,QAAQ,MAAM,EAAE,CAAC,EAC9B,KAAK,CAAC,GAAG,MAAM,EAAE,MAAM,KAAK,EAAE,SAAS,EAAE,MAAM,KAAK,EAAE,MAAM;AAE/D,YAAI,MAAM,WAAW,GAAG;AACtB,mBAAS,KAAK;AAAA,YACZ,MAAM,IAAI,OAAO,IAAI,KAAK,GAAG;AAAA,YAC7B,aAAa,GAAG,OAAO,IAAI,MAAM,CAAC,CAAC;AAAA,UACrC,CAAC;AAAA,QACH,WAAW,MAAM,SAAS,GAAG;AAC3B,mBAAS,KAAK;AAAA,YACZ,MAAM,IAAI,OAAO,IAAI,KAAK,GAAG;AAAA,YAC7B,aAA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IAC3C;AAAA,EACF;AACF;;;AUpQA,SAAS,YAAAG,iBAAgB;AAEzB,SAAS,SAAS,cAAc;AAGhC,SAAS,cAAAC,mBAAkB;AAS3B,IAAO,wBAAQ,CAAC,YAAkC;AAChD,SAAO;AAAA,IACL,MAAM;AAAA,IAEN,MAAM,SAAS;AACb,YAAM,SAAkC,CAAC;AAEzC,iBAAW,EAAE,MAAM,MAAM,WAAW,eAAe,IAAI,KAAK,SAAS;AACnE,eAAO,QAAQ,IAAI,CAAC;AAEpB,cAAM,aAAa,OACf,MAAMA,YAAW,IAAI,IACrB;AAEJ,cAAM,MAAM,aACR,OAAO,MAAMD,UAAS,MAAe,MAAM,CAAC,IAC5C,QAAQ;AAEZ,mBAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC5C,cAAI,KAAK,SAAS,GAAG,GAAG;AAEtB,mBAAO,GAAG,QAAQ,IAAI,GAAG,EAAE,IAAI,KAAK,UAAU,GAAG;AAAA,UACnD;AACA,gBAAM,KAAK,GAAG;AAAA,QAChB;AAAA,MACF;AAEA,aAAO,EAAE,OAAO;AAAA,IAClB;AAAA,EACF;AACF;",
6
+ "names": ["default", "join", "resolve", "styleText", "defaults", "dirname", "join", "resolve", "crc", "glob", "defaults", "pathResolver", "resolve", "callExpression", "resolve", "crc", "hash", "defaults", "glob", "resolve", "join", "join", "dirname", "crc", "entry", "defaults", "pathResolver", "resolve", "routeFiles", "defaults", "resolve", "styleText", "join", "readFile", "pathExists"]
7
7
  }
@@ -4,7 +4,7 @@ export type Cache = {
4
4
  referencedFiles: Record<string, number>;
5
5
  } & Pick<ApiRoute, "params" | "methods" | "typeDeclarations" | "numericParams" | "payloadTypes" | "responseTypes">;
6
6
  type ExtraContext = Record<string | number, unknown>;
7
- export declare const cacheFactory: (route: Pick<ApiRoute, "file" | "fileFullpath" | "importName" | "importPath">, { appRoot, sourceFolder, extraContext, }: {
7
+ export declare const cacheFactory: (route: Pick<ApiRoute, "file" | "fileFullpath" | "importName">, { appRoot, sourceFolder, extraContext, }: {
8
8
  appRoot: string;
9
9
  sourceFolder: string;
10
10
  extraContext?: ExtraContext;
@@ -0,0 +1,5 @@
1
+ import { type NestedRouteEntry, type RouteEntry } from "@kosmojs/devlib";
2
+ /**
3
+ * Build a nested route tree from flat route entries.
4
+ * */
5
+ export declare const nestedRoutesFactory: (routeEntries: Array<RouteEntry>) => NestedRouteEntry[];
@@ -0,0 +1,23 @@
1
+ import { type PluginOptionsResolved, type ResolvedEntry, type RouteEntry } from "@kosmojs/devlib";
2
+ export type ResolverSignature = {
3
+ name: string;
4
+ handler: (updatedFile?: string) => Promise<ResolvedEntry>;
5
+ };
6
+ export declare const API_INDEX_BASENAME = "index";
7
+ export declare const API_INDEX_PATTERN = "index.ts";
8
+ export declare const PAGE_INDEX_BASENAME = "index";
9
+ export declare const PAGE_INDEX_PATTERN = "index.{tsx,vue}";
10
+ export declare const PAGE_LAYOUT_BASENAME = "layout";
11
+ export declare const PAGE_LAYOUT_PATTERN = "layout.{tsx,vue}";
12
+ export declare const scanRoutes: ({ appRoot, sourceFolder, }: Pick<PluginOptionsResolved, "appRoot" | "sourceFolder">) => Promise<string[]>;
13
+ export declare const isRouteFile: (file: string, { appRoot, sourceFolder, }: Pick<PluginOptionsResolved, "appRoot" | "sourceFolder">) => [folder: string, file: string] | undefined;
14
+ export declare const isPageFile: (file: string) => {
15
+ kind: "index" | "layout";
16
+ } | undefined;
17
+ export declare const isIndexFile: (file: string) => boolean;
18
+ export declare const createRouteEntry: (_file: string, { appRoot, sourceFolder, }: Pick<PluginOptionsResolved, "appRoot" | "sourceFolder">) => RouteEntry | undefined;
19
+ type ResolverFactory = (pluginOptions: PluginOptionsResolved) => (entry: RouteEntry) => ResolverSignature;
20
+ export declare const pageLayoutResolverFactory: ResolverFactory;
21
+ export declare const pageRouteResolverFactory: ResolverFactory;
22
+ export declare const apiRouteResolverFactory: ResolverFactory;
23
+ export {};
@@ -1,13 +1,9 @@
1
- import { type PluginOptionsResolved, type RouteResolver } from "@kosmojs/devlib";
2
- export type Resolvers = Map<string, RouteResolver>;
3
- export type ResolveRouteFile = (file: string) => [
4
- folder: string,
5
- file: string
6
- ] | undefined;
7
- export type ResolversFactory = (routeFiles: Array<string>) => Map<string, RouteResolver>;
1
+ import { type PluginOptionsResolved } from "@kosmojs/devlib";
2
+ import { type ResolverSignature } from "./routes/resolve";
3
+ export * from "./routes/nesting";
4
+ export * from "./routes/resolve";
8
5
  declare const _default: (pluginOptions: PluginOptionsResolved) => Promise<{
9
- resolvers: Resolvers;
10
- resolversFactory: ResolversFactory;
11
- resolveRouteFile: ResolveRouteFile;
6
+ resolvers: Map<string, ResolverSignature>;
7
+ resolversFactory: (routeFiles: Array<string>) => Map<string, ResolverSignature>;
12
8
  }>;
13
9
  export default _default;
@@ -1,4 +1,4 @@
1
- export type { SSRFactory } from "@kosmojs/devlib";
1
+ export type { SSRManifestEntry, SSRSetup } from "@kosmojs/devlib";
2
2
  export { default as apiGenerator } from "@kosmojs/api-generator";
3
3
  export { default as fetchGenerator } from "@kosmojs/fetch-generator";
4
4
  export { default as aliasPlugin } from "./alias-plugin";
@@ -1,4 +1,5 @@
1
1
  // src/stub-generator/index.ts
2
+ import { dirname } from "node:path";
2
3
  import {
3
4
  pathResolver,
4
5
  renderToFile
@@ -30,12 +31,12 @@ var stub_generator_default = () => {
30
31
  {},
31
32
  { overwrite: false }
32
33
  );
33
- for (const { kind, route } of entries) {
34
- if (kind === "api") {
34
+ for (const { kind, entry } of entries) {
35
+ if (kind === "apiRoute") {
35
36
  await renderToFile(
36
- resolve("apiLibDir", route.importPath, "schemas.ts"),
37
+ resolve("apiLibDir", dirname(entry.file), "schemas.ts"),
37
38
  schemas_default,
38
- { route },
39
+ { route: entry },
39
40
  { overwrite: false }
40
41
  );
41
42
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/stub-generator/index.ts", "load-as-text:/volumes/studio/OpenSource/KosmoJS/Kosmo/packages/core/dev/src/stub-generator/templates/env.d.ts", "../../src/stub-generator/templates/gitignore.hbs", "../../src/stub-generator/templates/schemas.hbs"],
4
- "sourcesContent": ["import {\n type GeneratorConstructor,\n pathResolver,\n renderToFile,\n} from \"@kosmojs/devlib\";\n\nimport envTpl from \"./templates/env.d.ts?as=text\";\nimport gitignoreTpl from \"./templates/gitignore.hbs\";\nimport schemasTpl from \"./templates/schemas.hbs\";\n\n/**\n * Generates stub files required by various generators.\n * Ensures cross-generator dependencies remain resolvable\n * even if specialized generators supposed to generate these files are not installed.\n * */\nexport default (): GeneratorConstructor => {\n return {\n name: \"Stub\",\n moduleImport: import.meta.filename,\n moduleConfig: undefined,\n async factory({ appRoot, sourceFolder }) {\n return {\n async watchHandler(entries) {\n const { resolve } = pathResolver({ appRoot, sourceFolder });\n\n /**\n * expose TRefine as a global type.\n * not supposed to be overriden by generators.\n * */\n await renderToFile(resolve(\"libDir\", \"env.d.ts\"), envTpl, {});\n\n /**\n * deploy a default gitignore file that ignore everything,\n * except cache.json files; if file exists, do not override.\n * */\n await renderToFile(\n resolve(\"libDir\", \".gitignore\"),\n gitignoreTpl,\n {},\n { overwrite: false },\n );\n\n for (const { kind, route } of entries) {\n if (kind === \"api\") {\n // Generating stub schemas file.\n // It is required by various generators, e.g. api-generator, fetch-generator.\n // Specialized generators (e.g. typebox-generator) may override this later.\n await renderToFile(\n resolve(\"apiLibDir\", route.importPath, \"schemas.ts\"),\n schemasTpl,\n { route },\n { overwrite: false },\n );\n }\n }\n },\n };\n },\n };\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 * */\nexport declare global {\n type TRefine<\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/**\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", "# 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", "// stub schemas, specialized generators supposed to overwrite this file\nimport type { ValidationSchemas } from \"@kosmojs/api\";\nexport type { ValidationSchemas };\nexport const validationSchemas: ValidationSchemas = {};\n"],
5
- "mappings": ";AAAA;AAAA,EAEE;AAAA,EACA;AAAA,OACK;;;ACJP;;;ACAA;;;ACAA;;;AHeA,IAAO,yBAAQ,MAA4B;AACzC,SAAO;AAAA,IACL,MAAM;AAAA,IACN,cAAc,YAAY;AAAA,IAC1B,cAAc;AAAA,IACd,MAAM,QAAQ,EAAE,SAAS,aAAa,GAAG;AACvC,aAAO;AAAA,QACL,MAAM,aAAa,SAAS;AAC1B,gBAAM,EAAE,QAAQ,IAAI,aAAa,EAAE,SAAS,aAAa,CAAC;AAM1D,gBAAM,aAAa,QAAQ,UAAU,UAAU,GAAG,eAAQ,CAAC,CAAC;AAM5D,gBAAM;AAAA,YACJ,QAAQ,UAAU,YAAY;AAAA,YAC9B;AAAA,YACA,CAAC;AAAA,YACD,EAAE,WAAW,MAAM;AAAA,UACrB;AAEA,qBAAW,EAAE,MAAM,MAAM,KAAK,SAAS;AACrC,gBAAI,SAAS,OAAO;AAIlB,oBAAM;AAAA,gBACJ,QAAQ,aAAa,MAAM,YAAY,YAAY;AAAA,gBACnD;AAAA,gBACA,EAAE,MAAM;AAAA,gBACR,EAAE,WAAW,MAAM;AAAA,cACrB;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { dirname } from \"node:path\";\n\nimport {\n type GeneratorConstructor,\n pathResolver,\n renderToFile,\n} from \"@kosmojs/devlib\";\n\nimport envTpl from \"./templates/env.d.ts?as=text\";\nimport gitignoreTpl from \"./templates/gitignore.hbs\";\nimport schemasTpl from \"./templates/schemas.hbs\";\n\n/**\n * Generates stub files required by various generators.\n * Ensures cross-generator dependencies remain resolvable\n * even if specialized generators supposed to generate these files are not installed.\n * */\nexport default (): GeneratorConstructor => {\n return {\n name: \"Stub\",\n moduleImport: import.meta.filename,\n moduleConfig: undefined,\n async factory({ appRoot, sourceFolder }) {\n return {\n async watchHandler(entries) {\n const { resolve } = pathResolver({ appRoot, sourceFolder });\n\n /**\n * expose TRefine as a global type.\n * not supposed to be overriden by generators.\n * */\n await renderToFile(resolve(\"libDir\", \"env.d.ts\"), envTpl, {});\n\n /**\n * deploy a default gitignore file that ignore everything,\n * except cache.json files; if file exists, do not override.\n * */\n await renderToFile(\n resolve(\"libDir\", \".gitignore\"),\n gitignoreTpl,\n {},\n { overwrite: false },\n );\n\n for (const { kind, entry } of entries) {\n if (kind === \"apiRoute\") {\n // Generating stub schemas file.\n // It is required by various generators, e.g. api-generator, fetch-generator.\n // Specialized generators (e.g. typebox-generator) may override this later.\n await renderToFile(\n resolve(\"apiLibDir\", dirname(entry.file), \"schemas.ts\"),\n schemasTpl,\n { route: entry },\n { overwrite: false },\n );\n }\n }\n },\n };\n },\n };\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 * */\nexport declare global {\n type TRefine<\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/**\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", "# 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", "// stub schemas, specialized generators supposed to overwrite this file\nimport type { ValidationSchemas } from \"@kosmojs/api\";\nexport type { ValidationSchemas };\nexport const validationSchemas: ValidationSchemas = {};\n"],
5
+ "mappings": ";AAAA,SAAS,eAAe;AAExB;AAAA,EAEE;AAAA,EACA;AAAA,OACK;;;ACNP;;;ACAA;;;ACAA;;;AHiBA,IAAO,yBAAQ,MAA4B;AACzC,SAAO;AAAA,IACL,MAAM;AAAA,IACN,cAAc,YAAY;AAAA,IAC1B,cAAc;AAAA,IACd,MAAM,QAAQ,EAAE,SAAS,aAAa,GAAG;AACvC,aAAO;AAAA,QACL,MAAM,aAAa,SAAS;AAC1B,gBAAM,EAAE,QAAQ,IAAI,aAAa,EAAE,SAAS,aAAa,CAAC;AAM1D,gBAAM,aAAa,QAAQ,UAAU,UAAU,GAAG,eAAQ,CAAC,CAAC;AAM5D,gBAAM;AAAA,YACJ,QAAQ,UAAU,YAAY;AAAA,YAC9B;AAAA,YACA,CAAC;AAAA,YACD,EAAE,WAAW,MAAM;AAAA,UACrB;AAEA,qBAAW,EAAE,MAAM,MAAM,KAAK,SAAS;AACrC,gBAAI,SAAS,YAAY;AAIvB,oBAAM;AAAA,gBACJ,QAAQ,aAAa,QAAQ,MAAM,IAAI,GAAG,YAAY;AAAA,gBACtD;AAAA,gBACA,EAAE,OAAO,MAAM;AAAA,gBACf,EAAE,WAAW,MAAM;AAAA,cACrB;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }