@ecopages/core 0.3.1 → 0.4.0

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 (67) hide show
  1. package/README.md +17 -1
  2. package/package.json +3 -3
  3. package/src/adapters/node/create-app.d.ts +31 -20
  4. package/src/adapters/node/create-app.js +44 -43
  5. package/src/adapters/node/dev-session.d.ts +3 -1
  6. package/src/adapters/node/dev-session.js +4 -1
  7. package/src/adapters/node/runtime-host.d.ts +5 -0
  8. package/src/adapters/node/runtime-host.js +8 -1
  9. package/src/adapters/node/server-adapter.js +5 -1
  10. package/src/adapters/shared/hmr/hmr-manager.d.ts +12 -2
  11. package/src/adapters/shared/hmr/hmr-manager.js +20 -16
  12. package/src/adapters/shared/http/define-api-handler.d.ts +41 -26
  13. package/src/adapters/shared/http/define-api-handler.js +15 -1
  14. package/src/adapters/shared/http/endpoint-route-handler.d.ts +46 -0
  15. package/src/adapters/shared/http/endpoint-route-handler.js +96 -0
  16. package/src/adapters/shared/runtime/bind-runtime-server.js +3 -1
  17. package/src/adapters/shared/runtime/copy-runtime-public-dir.js +10 -9
  18. package/src/adapters/shared/runtime/port-manager.d.ts +6 -0
  19. package/src/adapters/shared/runtime/port-manager.js +16 -2
  20. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +20 -3
  21. package/src/adapters/shared/runtime/server-request-pipeline.js +45 -12
  22. package/src/adapters/shared/runtime/server-route-handler.d.ts +8 -3
  23. package/src/adapters/shared/runtime/server-route-handler.js +12 -6
  24. package/src/adapters/shared/runtime/server-static-builder.d.ts +14 -1
  25. package/src/adapters/shared/runtime/server-static-builder.js +13 -2
  26. package/src/assets/app-browser-client-build.js +1 -2
  27. package/src/assets/asset-processing-service/browser-runtime-entry-resolution.js +8 -8
  28. package/src/assets/asset-processing-service/browser-runtime-entry.factory.js +4 -4
  29. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +12 -8
  30. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +36 -16
  31. package/src/assets/asset-processing-service/processors/stylesheet/file-stylesheet.processor.js +11 -6
  32. package/src/assets/browser-asset-output.d.ts +19 -0
  33. package/src/assets/browser-asset-output.js +30 -0
  34. package/src/assets/hashed-browser-asset.d.ts +8 -6
  35. package/src/assets/hashed-browser-asset.js +8 -6
  36. package/src/build/build-graph.js +2 -2
  37. package/src/build/preserve-import-meta-transform.js +2 -2
  38. package/src/build/rolldown/app-package-declarations.js +3 -3
  39. package/src/build/rolldown/rolldown-adapter-helpers.js +3 -3
  40. package/src/build/rolldown/server-side-css-shim-plugin.js +3 -3
  41. package/src/build/server-bundle-deploy-manifest.d.ts +1 -1
  42. package/src/build/server-bundle-deploy-manifest.js +1 -1
  43. package/src/build/server-bundle-publication.js +4 -5
  44. package/src/config/assembly/finalize-config.js +5 -0
  45. package/src/config/config-module-files.js +2 -3
  46. package/src/diagnostics/startup-trace.js +2 -5
  47. package/src/html-pages/html-page-module-scripts.js +4 -3
  48. package/src/html-pages/html-page-renderer.js +2 -3
  49. package/src/index.d.ts +1 -1
  50. package/src/index.js +1 -1
  51. package/src/plugins/component-import-discovery.js +4 -4
  52. package/src/plugins/foreign-jsx-override-plugin.js +2 -2
  53. package/src/plugins/tsconfig-import-resolver.js +12 -12
  54. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +0 -17
  55. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +0 -23
  56. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +2 -2
  57. package/src/route-renderer/page-loading/page-dependency-bundling.js +5 -5
  58. package/src/router/server/route-registry.d.ts +18 -9
  59. package/src/router/server/route-registry.js +50 -32
  60. package/src/router/server/segment-path-matcher.d.ts +8 -0
  61. package/src/router/server/segment-path-matcher.js +15 -0
  62. package/src/static-site-generator/static-site-generator.js +1 -1
  63. package/src/types/contracts.d.ts +87 -61
  64. package/src/types/contracts.js +4 -1
  65. package/src/types/public-types.d.ts +1 -1
  66. package/src/utils/endpoint-file-extensions.d.ts +11 -0
  67. package/src/utils/endpoint-file-extensions.js +13 -0
@@ -12,6 +12,7 @@ import { getServerBundleOutputPaths, writeServerBundleDeployManifest, } from '..
12
12
  import { bundleEcoConfigModule, EMITTED_ECO_CONFIG_FILENAME } from '../../../config/server-config-bundle.js';
13
13
  import { resolveEntryFile, SERVER_BUNDLE_FILENAME } from '../../../utils/resolve-entry-file.js';
14
14
  import { copyRuntimePublicDirIfChanged } from './copy-runtime-public-dir.js';
15
+ import { readEndpointHandlers } from '../http/endpoint-route-handler.js';
15
16
  /**
16
17
  * Handles static site generation.
17
18
  */
@@ -85,7 +86,7 @@ export class ServerStaticBuilder {
85
86
  *
86
87
  * @remarks
87
88
  * Only invoked when the app requires a runtime server (API handlers,
88
- * websocket handlers, etc.). Static-only apps skip this step entirely.
89
+ * websocket handlers or endpoint files). Static-only apps skip this step entirely.
89
90
  * Every process bundles the entry from source.
90
91
  *
91
92
  * Source code is bundled: the app entry graph, workspace packages and
@@ -141,6 +142,12 @@ export class ServerStaticBuilder {
141
142
  * @param dependencies.router - The initialized router
142
143
  * @param dependencies.routeRendererFactory - The route renderer factory
143
144
  * @param dependencies.staticRoutes - Explicit static routes registered via app.static()
145
+ * @param dependencies.importServerModule - The server-module loader endpoint requests use
146
+ *
147
+ * @remarks
148
+ * Every endpoint file is imported and its exports checked as its first request would, before the
149
+ * server bundle and static generation, so a broken one fails the build with the request's error.
150
+ * The import is cached in this process only; `ecopages start` compiles the file again.
144
151
  */
145
152
  async build(options, dependencies) {
146
153
  const { baseUrl: explicitBaseUrl, force = false } = options ?? {};
@@ -150,7 +157,11 @@ export class ServerStaticBuilder {
150
157
  await this.prepareExport();
151
158
  }
152
159
  this.exportPrepared = false;
153
- if (this.needsServerBundle) {
160
+ const endpointRoutes = dependencies.router.templateRoutes.filter((route) => route.role === 'endpoint');
161
+ for (const route of endpointRoutes) {
162
+ readEndpointHandlers(await dependencies.importServerModule(route.filePath), route);
163
+ }
164
+ if (this.needsServerBundle || endpointRoutes.length > 0) {
154
165
  await this.bundleServerEntry();
155
166
  }
156
167
  await this.staticSiteGenerator.run({
@@ -1,6 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { contentHash } from '../utils/content-hash.js';
3
- import { realpathSync } from 'node:fs';
4
3
  import path from 'node:path';
5
4
  import { fileSystem } from '@ecopages/file-system';
6
5
  import { getBuildEntryOutput, collectBuildEntryInputPaths } from '../build/build-graph.js';
@@ -380,7 +379,7 @@ function collectHtmlScriptUrls(appConfig, result, htmlEntryNames) {
380
379
  for (const [script, entryName] of htmlEntryNames) {
381
380
  const output = getBuildEntryOutput(result, entryName, appConfig.rootDir);
382
381
  if (output) {
383
- urls.set(realpathSync(script), `/${path.relative(appConfig.absolutePaths.distDir, output).split(path.sep).join('/')}`);
382
+ urls.set(fileSystem.realpath(script), `/${path.relative(appConfig.absolutePaths.distDir, output).split(path.sep).join('/')}`);
384
383
  }
385
384
  }
386
385
  return urls;
@@ -1,5 +1,5 @@
1
- import fs from 'node:fs';
2
1
  import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { ResolverFactory } from 'oxc-resolver';
5
5
  import { isBarePackageImportSpecifier } from '../../plugins/tsconfig-import-resolver.js';
@@ -43,12 +43,12 @@ function resolveLegacyPackageModuleEntry(options) {
43
43
  }
44
44
  try {
45
45
  const packageJsonPath = options.requireFromRoot.resolve(`${packageRoot}/package.json`);
46
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
46
+ const packageJson = JSON.parse(fileSystem.readFileSync(packageJsonPath));
47
47
  if (packageJson.exports !== undefined || typeof packageJson.module !== 'string') {
48
48
  return undefined;
49
49
  }
50
50
  const modulePath = path.resolve(path.dirname(packageJsonPath), packageJson.module);
51
- return fs.existsSync(modulePath) ? modulePath : undefined;
51
+ return fileSystem.exists(modulePath) ? modulePath : undefined;
52
52
  }
53
53
  catch {
54
54
  return undefined;
@@ -92,7 +92,7 @@ export function resolveBrowserRuntimeEntryPath(options) {
92
92
  : resolvedPath.endsWith('.cts')
93
93
  ? `${resolvedPath.slice(0, -4)}.ts`
94
94
  : undefined;
95
- return esmSibling && fs.existsSync(esmSibling) ? esmSibling : resolvedPath;
95
+ return esmSibling && fileSystem.exists(esmSibling) ? esmSibling : resolvedPath;
96
96
  }
97
97
  catch {
98
98
  return undefined;
@@ -142,8 +142,8 @@ export function resolveBrowserRuntimeEntryImport(options) {
142
142
  export function inferBrowserRuntimeDefaultExportPolicy(options) {
143
143
  const { specifier, requireFromRoot, rootDir } = options;
144
144
  const entryPath = resolveBrowserRuntimeEntryPath({ specifier, requireFromRoot, rootDir });
145
- if (entryPath && fs.existsSync(entryPath)) {
146
- const source = fs.readFileSync(entryPath, 'utf8');
145
+ if (entryPath && fileSystem.exists(entryPath)) {
146
+ const source = fileSystem.readFileSync(entryPath);
147
147
  if (ESM_DEFAULT_EXPORT.test(source)) {
148
148
  return 'emit-default';
149
149
  }
@@ -171,10 +171,10 @@ export function inferBrowserRuntimeDefaultExportPolicy(options) {
171
171
  * files does not emit named ESM bindings such as `jsx`.
172
172
  */
173
173
  export function browserRuntimeEntryHasEsmExports(entryPath) {
174
- if (!entryPath || !fs.existsSync(entryPath)) {
174
+ if (!entryPath || !fileSystem.exists(entryPath)) {
175
175
  return true;
176
176
  }
177
- const source = fs.readFileSync(entryPath, 'utf8');
177
+ const source = fileSystem.readFileSync(entryPath);
178
178
  return ESM_DEFAULT_EXPORT.test(source) || ESM_NAMED_EXPORT.test(source);
179
179
  }
180
180
  /**
@@ -1,5 +1,5 @@
1
- import fs from 'node:fs';
2
1
  import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
3
  import { createRequire } from 'node:module';
4
4
  import { DEFAULT_ECOPAGES_WORK_DIR } from '../../constants.js';
5
5
  import { browserRuntimeEntryHasEsmExports, inferBrowserRuntimeDefaultExportPolicy, listBrowserRuntimeCjsExportNames, resolveBrowserRuntimeEntryImport, resolveBrowserRuntimeEntryPath, } from './browser-runtime-entry-resolution.js';
@@ -23,7 +23,7 @@ export function createBrowserRuntimeEntryModule(options) {
23
23
  const rootDir = options.rootDir ?? process.cwd();
24
24
  const workDir = options.workDir ?? path.join(rootDir, DEFAULT_ECOPAGES_WORK_DIR);
25
25
  const artifactsDir = path.join(workDir, '.browser-runtime-entries', options.cacheDirName ?? 'ecopages-browser-runtime');
26
- fs.mkdirSync(artifactsDir, { recursive: true });
26
+ fileSystem.ensureDir(artifactsDir);
27
27
  const requireFromRoot = createRequire(path.join(rootDir, 'package.json'));
28
28
  const seenExports = new Set();
29
29
  const statements = [];
@@ -60,8 +60,8 @@ export function createBrowserRuntimeEntryModule(options) {
60
60
  }
61
61
  }
62
62
  const content = statements.join('\n');
63
- if (!fs.existsSync(filePath) || fs.readFileSync(filePath, 'utf-8') !== content) {
64
- fs.writeFileSync(filePath, content, 'utf-8');
63
+ if (!fileSystem.exists(filePath) || fileSystem.readFileSync(filePath) !== content) {
64
+ fileSystem.write(filePath, content);
65
65
  }
66
66
  return filePath;
67
67
  }
@@ -21,11 +21,14 @@ export declare class FileScriptProcessor extends BaseScriptProcessor<FileScriptA
21
21
  processGrouped(deps: FileScriptAsset[]): Promise<ProcessedAsset[]>;
22
22
  /**
23
23
  * @remarks
24
- * With HMR active, bundled scripts are built and watched by the HMR manager, which emits ES
25
- * modules. In production, `bundle: false` scripts are written under a hash of their bytes.
26
- * In development they are copied to their source-relative path so HMR can refresh them.
27
- * `classic` scripts are compiled on their own as classic scripts. Vendor runtimes keep their
28
- * stable names.
24
+ * With HMR active, a bundled script is built and watched by the HMR manager, which emits an ES
25
+ * module and serves the dev-transform URL. In production, a `bundle: false` script is written
26
+ * under a hash of its bytes. In development, a non-classic `bundle: false` file inside `srcDir`
27
+ * is copied to its source-relative path. A classic script inside `srcDir` is compiled and written
28
+ * under that path with a `.js` name. A file outside `srcDir` has no such path that stays inside
29
+ * `dist`: an unbundled or classic script is written under a content hash, and a bundled script
30
+ * is emitted in `dist/assets` under the bundler's `[name]-[hash]` name. Vendor runtimes inside
31
+ * `src` keep their stable names.
29
32
  */
30
33
  process(dep: FileScriptAsset): Promise<ProcessedAsset>;
31
34
  private processWithHmr;
@@ -33,9 +36,10 @@ export declare class FileScriptProcessor extends BaseScriptProcessor<FileScriptA
33
36
  private processBundledScript;
34
37
  /**
35
38
  * @remarks
36
- * The output keeps the source path and name, with a TypeScript extension turned into `.js`, as a
37
- * copied classic `.js` does. A second source file for the same output is rejected while the first
38
- * still exists, so a last write cannot silently win.
39
+ * The output keeps the source path and name when the file is inside `srcDir`, with a TypeScript
40
+ * extension turned into `.js`, as a copied classic `.js` does. A file outside `srcDir` is written
41
+ * under a content hash in `dist/assets`. A second source file for the same output is rejected while
42
+ * the first still exists, so a last write cannot silently win.
39
43
  *
40
44
  * @throws When the file cannot be a classic script, or another existing file is emitted to its output.
41
45
  */
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path';
2
- import { RESOLVED_ASSETS_DIR } from '../../../../constants.js';
3
2
  import { fileSystem } from '@ecopages/file-system';
3
+ import { assertBrowserOutputInsideDist, sourceRelativeBrowserAssetPath } from '../../../browser-asset-output.js';
4
4
  import { writeHashedBrowserAsset } from '../../../hashed-browser-asset.js';
5
5
  import { BaseScriptProcessor } from '../base/base-script-processor.js';
6
6
  import { classicScriptOutputName, compileClassicScript } from './classic-script-compiler.js';
@@ -50,11 +50,14 @@ export class FileScriptProcessor extends BaseScriptProcessor {
50
50
  }
51
51
  /**
52
52
  * @remarks
53
- * With HMR active, bundled scripts are built and watched by the HMR manager, which emits ES
54
- * modules. In production, `bundle: false` scripts are written under a hash of their bytes.
55
- * In development they are copied to their source-relative path so HMR can refresh them.
56
- * `classic` scripts are compiled on their own as classic scripts. Vendor runtimes keep their
57
- * stable names.
53
+ * With HMR active, a bundled script is built and watched by the HMR manager, which emits an ES
54
+ * module and serves the dev-transform URL. In production, a `bundle: false` script is written
55
+ * under a hash of its bytes. In development, a non-classic `bundle: false` file inside `srcDir`
56
+ * is copied to its source-relative path. A classic script inside `srcDir` is compiled and written
57
+ * under that path with a `.js` name. A file outside `srcDir` has no such path that stays inside
58
+ * `dist`: an unbundled or classic script is written under a content hash, and a bundled script
59
+ * is emitted in `dist/assets` under the bundler's `[name]-[hash]` name. Vendor runtimes inside
60
+ * `src` keep their stable names.
58
61
  */
59
62
  async process(dep) {
60
63
  const hmrManager = this.getActiveHmrManager();
@@ -84,13 +87,15 @@ export class FileScriptProcessor extends BaseScriptProcessor {
84
87
  };
85
88
  }
86
89
  processUnbundledScript(dep, content) {
87
- const outFilepath = path.relative(this.appConfig.absolutePaths.srcDir, dep.filepath);
90
+ const outFilepath = sourceRelativeBrowserAssetPath(this.appConfig.absolutePaths.srcDir, dep.filepath);
88
91
  const output = dep.classic ? this.emitClassicScript(dep, outFilepath, content.toString()) : undefined;
89
92
  let filepath = output?.filepath;
90
93
  if (!dep.classic && !dep.inline) {
91
- if (dep.packageRole === 'runtime' || !this.isProduction) {
92
- filepath = path.join(this.getAssetsDir(), outFilepath);
93
- fileSystem.copyFile(dep.filepath, filepath);
94
+ if (outFilepath && (dep.packageRole === 'runtime' || !this.isProduction)) {
95
+ const destination = path.join(this.getAssetsDir(), outFilepath);
96
+ assertBrowserOutputInsideDist(this.appConfig.absolutePaths.distDir, destination);
97
+ fileSystem.copyFile(dep.filepath, destination);
98
+ filepath = destination;
94
99
  }
95
100
  else {
96
101
  filepath = writeHashedBrowserAsset({
@@ -114,12 +119,17 @@ export class FileScriptProcessor extends BaseScriptProcessor {
114
119
  };
115
120
  }
116
121
  async processBundledScript(dep) {
117
- const relativeFilepath = path.relative(this.appConfig.absolutePaths.srcDir, dep.filepath);
118
- const outdirPath = path.join(this.appConfig.absolutePaths.distDir, RESOLVED_ASSETS_DIR, relativeFilepath);
122
+ const relativeFilepath = sourceRelativeBrowserAssetPath(this.appConfig.absolutePaths.srcDir, dep.filepath);
123
+ const outdir = relativeFilepath
124
+ ? path.dirname(path.join(this.getAssetsDir(), relativeFilepath))
125
+ : this.getAssetsDir();
126
+ if (relativeFilepath) {
127
+ assertBrowserOutputInsideDist(this.appConfig.absolutePaths.distDir, outdir);
128
+ }
119
129
  const bundlerOptions = this.getBundlerOptions(dep);
120
130
  const bundledOutput = await this.bundleScript({
121
131
  entrypoint: dep.filepath,
122
- outdir: path.dirname(outdirPath),
132
+ outdir,
123
133
  minify: this.isProduction,
124
134
  ...bundlerOptions,
125
135
  plugins: bundlerOptions.plugins,
@@ -139,9 +149,10 @@ export class FileScriptProcessor extends BaseScriptProcessor {
139
149
  }
140
150
  /**
141
151
  * @remarks
142
- * The output keeps the source path and name, with a TypeScript extension turned into `.js`, as a
143
- * copied classic `.js` does. A second source file for the same output is rejected while the first
144
- * still exists, so a last write cannot silently win.
152
+ * The output keeps the source path and name when the file is inside `srcDir`, with a TypeScript
153
+ * extension turned into `.js`, as a copied classic `.js` does. A file outside `srcDir` is written
154
+ * under a content hash in `dist/assets`. A second source file for the same output is rejected while
155
+ * the first still exists, so a last write cannot silently win.
145
156
  *
146
157
  * @throws When the file cannot be a classic script, or another existing file is emitted to its output.
147
158
  */
@@ -153,7 +164,16 @@ export class FileScriptProcessor extends BaseScriptProcessor {
153
164
  if (dep.inline) {
154
165
  return { code: compiled.code };
155
166
  }
167
+ if (!outFilepath) {
168
+ const filepath = writeHashedBrowserAsset({
169
+ bytes: compiled.code,
170
+ directory: this.getAssetsDir(),
171
+ extension: '.js',
172
+ });
173
+ return { code: compiled.code, filepath };
174
+ }
156
175
  const filepath = path.join(this.getAssetsDir(), classicScriptOutputName(outFilepath));
176
+ assertBrowserOutputInsideDist(this.appConfig.absolutePaths.distDir, filepath);
157
177
  const other = this.classicScriptSources.get(filepath);
158
178
  if (other !== undefined && other !== dep.filepath && fileSystem.exists(other)) {
159
179
  throw new Error(`${dep.filepath} and ${other} are both emitted as ${filepath}. Rename one of them.`);
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { fileSystem } from '@ecopages/file-system';
3
+ import { assertBrowserOutputInsideDist, sourceRelativeBrowserAssetPath } from '../../../browser-asset-output.js';
3
4
  import { writeHashedBrowserAsset } from '../../../hashed-browser-asset.js';
4
5
  import { BaseProcessor } from '../base/base-processor.js';
5
6
  import { applyStylesheetProcessors } from './stylesheet-processor-pipeline.js';
@@ -13,14 +14,18 @@ export class FileStylesheetProcessor extends BaseProcessor {
13
14
  const processedContent = await applyStylesheetProcessors(this.appConfig, rawContent, dep.filepath);
14
15
  let filepath;
15
16
  if (!dep.inline) {
16
- filepath = this.isProduction
17
- ? writeHashedBrowserAsset({
17
+ const relativePath = sourceRelativeBrowserAssetPath(this.appConfig.absolutePaths.srcDir, dep.filepath);
18
+ const directory = this.getAssetsDir();
19
+ if (this.isProduction || !relativePath) {
20
+ filepath = writeHashedBrowserAsset({
18
21
  bytes: processedContent,
19
- directory: this.getAssetsDir(),
22
+ directory,
20
23
  extension: '.css',
21
- })
22
- : path.join(this.getAssetsDir(), path.relative(this.appConfig.absolutePaths.srcDir, dep.filepath));
23
- if (!this.isProduction) {
24
+ });
25
+ }
26
+ else {
27
+ filepath = path.join(directory, relativePath);
28
+ assertBrowserOutputInsideDist(this.appConfig.absolutePaths.distDir, filepath);
24
29
  fileSystem.ensureDir(path.dirname(filepath));
25
30
  fileSystem.write(filepath, processedContent);
26
31
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Source-relative path of a file inside `srcDir`.
3
+ *
4
+ * @remarks
5
+ * `path.relative` from `srcDir` to a file outside it starts with `..`. Joining
6
+ * that onto `dist` writes the asset outside the build. Callers then emit the file
7
+ * in `dist/assets`: a bundled script under the bundler's `[name]-[hash]` name, and
8
+ * an unbundled script or stylesheet under a content hash.
9
+ */
10
+ export declare function sourceRelativeBrowserAssetPath(srcDir: string, filepath: string): string | undefined;
11
+ /**
12
+ * Throws when a browser output is not inside `distDir`.
13
+ *
14
+ * @remarks
15
+ * The public URL and the gzip pass already skip a file outside `dist`. A write
16
+ * that appends a source-relative path uses the same check, so the file is not
17
+ * created there either.
18
+ */
19
+ export declare function assertBrowserOutputInsideDist(distDir: string, outputPath: string): void;
@@ -0,0 +1,30 @@
1
+ import path from 'node:path';
2
+ import { isPathInside } from '../utils/path-containment.js';
3
+ /**
4
+ * Source-relative path of a file inside `srcDir`.
5
+ *
6
+ * @remarks
7
+ * `path.relative` from `srcDir` to a file outside it starts with `..`. Joining
8
+ * that onto `dist` writes the asset outside the build. Callers then emit the file
9
+ * in `dist/assets`: a bundled script under the bundler's `[name]-[hash]` name, and
10
+ * an unbundled script or stylesheet under a content hash.
11
+ */
12
+ export function sourceRelativeBrowserAssetPath(srcDir, filepath) {
13
+ if (!isPathInside(filepath, srcDir))
14
+ return undefined;
15
+ const relativePath = path.relative(srcDir, filepath);
16
+ return relativePath === '' ? undefined : relativePath;
17
+ }
18
+ /**
19
+ * Throws when a browser output is not inside `distDir`.
20
+ *
21
+ * @remarks
22
+ * The public URL and the gzip pass already skip a file outside `dist`. A write
23
+ * that appends a source-relative path uses the same check, so the file is not
24
+ * created there either.
25
+ */
26
+ export function assertBrowserOutputInsideDist(distDir, outputPath) {
27
+ if (!isPathInside(outputPath, distDir)) {
28
+ throw new Error(`Refusing to write ${outputPath} outside ${distDir}`);
29
+ }
30
+ }
@@ -9,14 +9,16 @@ export declare function recordHashedBrowserAsset(filePath: string): void;
9
9
  export declare function isHashedBrowserAsset(filePath: string): boolean;
10
10
  export declare function forgetHashedBrowserAsset(filePath: string): void;
11
11
  /**
12
- * Writes a production browser asset under a name derived from a hash of its
13
- * final bytes, and returns that path.
12
+ * Writes a browser asset under a name derived from a hash of its final bytes,
13
+ * and returns that path.
14
14
  *
15
15
  * @remarks
16
- * The same bytes always produce the same name, so an unchanged stylesheet keeps
17
- * its URL and a quality or source change gets a new URL. Development keeps
18
- * source-relative names so CSS HMR can refresh the same href. Vendor runtimes
19
- * keep their own stable names and must not go through this helper.
16
+ * The same bytes always produce the same name, so an unchanged file keeps its URL
17
+ * and a content change gets a new URL. Callers use it for production assets, and
18
+ * for a source file outside `srcDir` in development, because a source-relative
19
+ * path would leave `dist`. A file inside `srcDir` keeps its source-relative name
20
+ * in development so CSS HMR can refresh the same href. A vendor runtime inside
21
+ * `src` keeps its stable name and does not use this helper.
20
22
  */
21
23
  export declare function writeHashedBrowserAsset(options: {
22
24
  bytes: string | Buffer;
@@ -77,14 +77,16 @@ function normalizeExtension(extension) {
77
77
  return extension.startsWith('.') ? extension : `.${extension}`;
78
78
  }
79
79
  /**
80
- * Writes a production browser asset under a name derived from a hash of its
81
- * final bytes, and returns that path.
80
+ * Writes a browser asset under a name derived from a hash of its final bytes,
81
+ * and returns that path.
82
82
  *
83
83
  * @remarks
84
- * The same bytes always produce the same name, so an unchanged stylesheet keeps
85
- * its URL and a quality or source change gets a new URL. Development keeps
86
- * source-relative names so CSS HMR can refresh the same href. Vendor runtimes
87
- * keep their own stable names and must not go through this helper.
84
+ * The same bytes always produce the same name, so an unchanged file keeps its URL
85
+ * and a content change gets a new URL. Callers use it for production assets, and
86
+ * for a source file outside `srcDir` in development, because a source-relative
87
+ * path would leave `dist`. A file inside `srcDir` keeps its source-relative name
88
+ * in development so CSS HMR can refresh the same href. A vendor runtime inside
89
+ * `src` keeps its stable name and does not use this helper.
88
90
  */
89
91
  export function writeHashedBrowserAsset(options) {
90
92
  const buffer = typeof options.bytes === 'string' ? Buffer.from(options.bytes) : options.bytes;
@@ -1,9 +1,9 @@
1
- import { existsSync, realpathSync } from 'node:fs';
2
1
  import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  function tryRealpath(filePath) {
5
5
  try {
6
- return existsSync(filePath) ? realpathSync(filePath) : undefined;
6
+ return fileSystem.exists(filePath) ? fileSystem.realpath(filePath) : undefined;
7
7
  }
8
8
  catch {
9
9
  return undefined;
@@ -1,5 +1,5 @@
1
- import { realpathSync } from 'node:fs';
2
1
  import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
3
  import { parseModuleSource } from '../cache/module-parse-cache.js';
4
4
  import { createCoreTransformPlugin, createMappedSourceTransformResult } from './mapped-source-transform.js';
5
5
  /**
@@ -13,7 +13,7 @@ import { createCoreTransformPlugin, createMappedSourceTransformResult } from './
13
13
  */
14
14
  export function realpathOfDirectory(dir) {
15
15
  try {
16
- return realpathSync(dir);
16
+ return fileSystem.realpath(dir);
17
17
  }
18
18
  catch {
19
19
  const parent = path.dirname(dir);
@@ -1,5 +1,5 @@
1
- import { readFileSync } from 'node:fs';
2
1
  import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
3
  import { toPackageRootSpecifier } from '../../plugins/package-specifier.js';
4
4
  const appDeclaredPackageCache = new Map();
5
5
  const appWorkspacePackageCache = new Map();
@@ -12,7 +12,7 @@ function getDeclaredAppPackages(rootDir) {
12
12
  const packageJsonPath = path.resolve(rootDir, 'package.json');
13
13
  const declaredPackages = new Set();
14
14
  try {
15
- const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
15
+ const packageJson = JSON.parse(fileSystem.readFileSync(packageJsonPath));
16
16
  for (const field of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {
17
17
  const entries = packageJson[field];
18
18
  if (!entries || typeof entries !== 'object') {
@@ -47,7 +47,7 @@ function getWorkspacePackages(rootDir) {
47
47
  const packageJsonPath = path.resolve(rootDir, 'package.json');
48
48
  const workspacePackages = new Set();
49
49
  try {
50
- const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
50
+ const packageJson = JSON.parse(fileSystem.readFileSync(packageJsonPath));
51
51
  for (const field of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {
52
52
  const entries = packageJson[field];
53
53
  if (!entries || typeof entries !== 'object') {
@@ -10,8 +10,8 @@
10
10
  * @module
11
11
  */
12
12
  import { builtinModules, createRequire } from 'node:module';
13
- import { readFileSync } from 'node:fs';
14
13
  import path from 'node:path';
14
+ import { fileSystem } from '@ecopages/file-system';
15
15
  import { fileURLToPath } from 'node:url';
16
16
  import { stripVTControlCharacters } from 'node:util';
17
17
  import { recordBuildEntryOutput, resolveBuildEntryPath } from '../build-graph.js';
@@ -43,10 +43,10 @@ function getCorePackageNames() {
43
43
  if (corePackageNames) {
44
44
  return corePackageNames;
45
45
  }
46
- const packageJsonPath = new URL('../../../package.json', import.meta.url);
46
+ const packageJsonPath = fileURLToPath(new URL('../../../package.json', import.meta.url));
47
47
  corePackageNames = new Set();
48
48
  try {
49
- const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
49
+ const packageJson = JSON.parse(fileSystem.readFileSync(packageJsonPath));
50
50
  for (const field of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {
51
51
  const entries = packageJson[field];
52
52
  if (!entries || typeof entries !== 'object') {
@@ -20,8 +20,8 @@
20
20
  * and continue to declare stylesheets in `dependencies.stylesheets`
21
21
  * — the shim is intentionally inert for those flows.
22
22
  */
23
- import { existsSync, readFileSync } from 'node:fs';
24
23
  import path from 'node:path';
24
+ import { fileSystem } from '@ecopages/file-system';
25
25
  import { id as idFilter, include } from 'rolldown/filter';
26
26
  const CSS_PATH = /\.css$/u;
27
27
  const CSS_QUERY = '?ecopages-css-shim';
@@ -41,13 +41,13 @@ export function createServerSideCssShimPlugin() {
41
41
  filter: [include(idFilter(CSS_PATH))],
42
42
  handler(source, importer) {
43
43
  const resolved = importer ? path.resolve(path.dirname(importer), source) : path.resolve(source);
44
- return existsSync(resolved) ? `${resolved}${CSS_QUERY}` : null;
44
+ return fileSystem.exists(resolved) ? `${resolved}${CSS_QUERY}` : null;
45
45
  },
46
46
  },
47
47
  load: {
48
48
  filter: [include(idFilter(CSS_SHIM_ID))],
49
49
  handler(id) {
50
- readFileSync(stripShimQuery(id), 'utf-8');
50
+ fileSystem.readFileSync(stripShimQuery(id));
51
51
  return {
52
52
  code: 'export default "";',
53
53
  moduleType: 'js',
@@ -42,7 +42,7 @@ export declare function writeServerBundleDeployManifest(appConfig: EcoPagesAppCo
42
42
  * not, and need `--dist-dir`. Guessing between several would run a stale bundle from an earlier build
43
43
  * that used another `distDir`.
44
44
  *
45
- * Static-only apps (no API or WebSocket handlers) build no server bundle. When the selected output, or `dist`
45
+ * Static-only apps (no API handlers, WebSocket handlers or endpoint files) build no server bundle. When the selected output, or `dist`
46
46
  * when none is named, holds built HTML but no bundle, the error says so and points to `ecopages preview`
47
47
  * instead of asking for another build. A static-only build in a custom `distDir` needs `--dist-dir` to be
48
48
  * recognised.
@@ -72,7 +72,7 @@ function readServerBundleDeployManifest(serverDir) {
72
72
  * not, and need `--dist-dir`. Guessing between several would run a stale bundle from an earlier build
73
73
  * that used another `distDir`.
74
74
  *
75
- * Static-only apps (no API or WebSocket handlers) build no server bundle. When the selected output, or `dist`
75
+ * Static-only apps (no API handlers, WebSocket handlers or endpoint files) build no server bundle. When the selected output, or `dist`
76
76
  * when none is named, holds built HTML but no bundle, the error says so and points to `ecopages preview`
77
77
  * instead of asking for another build. A static-only build in a custom `distDir` needs `--dist-dir` to be
78
78
  * recognised.
@@ -1,12 +1,11 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { mkdtempSync, renameSync } from 'node:fs';
3
2
  import path from 'node:path';
4
3
  import { fileSystem } from '@ecopages/file-system';
5
4
  /** Creates a sibling staging directory so publication stays on one filesystem. */
6
5
  export function createServerBundleStagingDirectory(serverOutdir) {
7
6
  const parentDir = path.dirname(serverOutdir);
8
7
  fileSystem.ensureDir(parentDir);
9
- return mkdtempSync(path.join(parentDir, `.${path.basename(serverOutdir)}.staging-`));
8
+ return fileSystem.mkdtemp(path.join(parentDir, `.${path.basename(serverOutdir)}.staging-`));
10
9
  }
11
10
  /**
12
11
  * Publishes a complete server bundle generation without exposing mixed artifacts.
@@ -20,12 +19,12 @@ export function publishServerBundleDirectory(stagingDir, serverOutdir) {
20
19
  const hadPublishedBundle = fileSystem.exists(serverOutdir);
21
20
  try {
22
21
  if (hadPublishedBundle)
23
- renameSync(serverOutdir, backupDir);
24
- renameSync(stagingDir, serverOutdir);
22
+ fileSystem.rename(serverOutdir, backupDir);
23
+ fileSystem.rename(stagingDir, serverOutdir);
25
24
  }
26
25
  catch (error) {
27
26
  if (hadPublishedBundle && !fileSystem.exists(serverOutdir) && fileSystem.exists(backupDir)) {
28
- renameSync(backupDir, serverOutdir);
27
+ fileSystem.rename(backupDir, serverOutdir);
29
28
  }
30
29
  throw error;
31
30
  }
@@ -7,6 +7,7 @@ import { appLogger } from '../../global/app-logger.js';
7
7
  import { HTML_PAGES_INTEGRATION_NAME } from '../../html-pages/html-page-module.js';
8
8
  import { HtmlPagesPlugin } from '../../html-pages/html-pages.plugin.js';
9
9
  import { invariant } from '../../utils/invariant.js';
10
+ import { ENDPOINT_FILE_EXTENSIONS, findEndpointFileExtension } from '../../utils/endpoint-file-extensions.js';
10
11
  import { DEFAULT_ECOPAGES_DIST_DIR, DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT, DEFAULT_ECOPAGES_WORK_DIR, } from '../../constants.js';
11
12
  import { collectConfigModuleFiles } from '../config-module-files.js';
12
13
  import { DEFAULT_ECO_CONFIG_FILENAME, resolveUserConfigRootDir } from '../resolve-eco-config-path.js';
@@ -84,6 +85,10 @@ function collectTemplateExtensions(integrations) {
84
85
  if (names.has('kitajs') && names.has('react')) {
85
86
  appLogger.debug('Both kitajs and react integrations are enabled. Use per-file JSX import source/pragma consistently (e.g. `/** @jsxImportSource react */` for React files and `/** @jsxImportSource @kitajs/html */` for Kita files).');
86
87
  }
88
+ for (const integration of integrations) {
89
+ const reserved = integration.extensions.find((extension) => findEndpointFileExtension(extension));
90
+ invariant(reserved === undefined, `Integration "${integration.name}" registers "${reserved}", which is reserved for endpoint files: ${ENDPOINT_FILE_EXTENSIONS.join(', ')}.`);
91
+ }
87
92
  const extensions = integrations.flatMap((integration) => integration.extensions);
88
93
  const duplicateExtension = findDuplicate(extensions);
89
94
  invariant(duplicateExtension === undefined, `Integration extensions must be unique: "${duplicateExtension}" is registered by more than one Integration.`);
@@ -1,4 +1,3 @@
1
- import { realpathSync } from 'node:fs';
2
1
  import path from 'node:path';
3
2
  import { fileSystem } from '@ecopages/file-system';
4
3
  import { rolldown } from 'rolldown';
@@ -27,9 +26,9 @@ function toProjectPath(id, realRoot, root) {
27
26
  */
28
27
  export async function collectConfigModuleFiles(configFilePath, rootDir) {
29
28
  const root = path.resolve(rootDir);
30
- const realRoot = fileSystem.exists(root) ? realpathSync(root) : root;
29
+ const realRoot = fileSystem.exists(root) ? fileSystem.realpath(root) : root;
31
30
  const configFile = path.resolve(configFilePath);
32
- const realConfigFile = fileSystem.exists(configFile) ? realpathSync(configFile) : configFile;
31
+ const realConfigFile = fileSystem.exists(configFile) ? fileSystem.realpath(configFile) : configFile;
33
32
  const moduleFiles = new Set([configFile]);
34
33
  try {
35
34
  const bundle = await rolldown({
@@ -1,5 +1,3 @@
1
- import { mkdirSync, statSync, writeFileSync } from 'node:fs';
2
- import path from 'node:path';
3
1
  import { fileSystem } from '@ecopages/file-system';
4
2
  import { resolveBuildParallelism } from '../build/build-parallelism.js';
5
3
  import { getProcessRuntime } from '../utils/runtime.js';
@@ -133,7 +131,7 @@ class StartupTrace {
133
131
  for (const output of outputs) {
134
132
  try {
135
133
  if (fileSystem.exists(output.path)) {
136
- this.firstRequestClientBytes += statSync(output.path).size;
134
+ this.firstRequestClientBytes += fileSystem.stat(output.path).size;
137
135
  }
138
136
  }
139
137
  catch {
@@ -210,8 +208,7 @@ class StartupTrace {
210
208
  return;
211
209
  }
212
210
  const report = this.createReport();
213
- mkdirSync(path.dirname(outputPath), { recursive: true });
214
- writeFileSync(outputPath, JSON.stringify(report, null, 2), 'utf-8');
211
+ fileSystem.write(outputPath, JSON.stringify(report, null, 2));
215
212
  }
216
213
  createReport() {
217
214
  const phases = {};