astro 1.6.4 → 1.6.6

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 (57) hide show
  1. package/dist/cli/index.js +1 -4
  2. package/dist/core/build/index.js +1 -2
  3. package/dist/core/build/static-build.js +2 -11
  4. package/dist/core/compile/compile.js +7 -9
  5. package/dist/core/compile/style.js +4 -6
  6. package/dist/core/config/config.js +13 -7
  7. package/dist/core/constants.js +1 -1
  8. package/dist/core/dev/dev.js +1 -1
  9. package/dist/core/endpoint/index.js +13 -12
  10. package/dist/core/errors/dev/utils.d.ts +1 -1
  11. package/dist/core/errors/dev/utils.js +64 -11
  12. package/dist/core/errors/dev/vite.d.ts +2 -2
  13. package/dist/core/errors/dev/vite.js +42 -29
  14. package/dist/core/errors/errors-data.d.ts +137 -0
  15. package/dist/core/errors/errors-data.js +144 -0
  16. package/dist/core/errors/errors.d.ts +20 -17
  17. package/dist/core/errors/errors.js +26 -20
  18. package/dist/core/errors/index.d.ts +3 -3
  19. package/dist/core/errors/index.js +4 -13
  20. package/dist/core/errors/printer.js +2 -2
  21. package/dist/core/errors/utils.d.ts +107 -2
  22. package/dist/core/errors/utils.js +15 -30
  23. package/dist/core/messages.js +11 -2
  24. package/dist/core/render/core.js +16 -5
  25. package/dist/core/render/result.js +21 -17
  26. package/dist/core/render/route-cache.d.ts +1 -1
  27. package/dist/core/render/route-cache.js +12 -12
  28. package/dist/core/routing/manifest/create.js +8 -18
  29. package/dist/core/routing/params.d.ts +1 -1
  30. package/dist/core/routing/params.js +2 -2
  31. package/dist/core/routing/validation.d.ts +6 -5
  32. package/dist/core/routing/validation.js +42 -31
  33. package/dist/events/error.js +3 -3
  34. package/dist/jsx/babel.js +6 -5
  35. package/dist/jsx-runtime/index.d.ts +1 -1
  36. package/dist/runtime/server/hydration.d.ts +2 -2
  37. package/dist/runtime/server/hydration.js +9 -4
  38. package/dist/runtime/server/jsx.js +53 -14
  39. package/dist/runtime/server/render/common.d.ts +2 -1
  40. package/dist/runtime/server/render/common.js +12 -0
  41. package/dist/runtime/server/render/component.d.ts +2 -2
  42. package/dist/runtime/server/render/component.js +46 -30
  43. package/dist/runtime/server/render/page.d.ts +2 -2
  44. package/dist/runtime/server/render/page.js +35 -9
  45. package/dist/runtime/server/render/slot.d.ts +3 -0
  46. package/dist/runtime/server/render/slot.js +7 -0
  47. package/dist/vite-plugin-astro-server/base.js +22 -3
  48. package/dist/vite-plugin-astro-server/plugin.js +7 -1
  49. package/dist/vite-plugin-astro-server/request.js +1 -1
  50. package/dist/vite-plugin-astro-server/route.js +7 -1
  51. package/dist/vite-plugin-env/index.js +40 -64
  52. package/dist/vite-plugin-load-fallback/index.js +8 -1
  53. package/dist/vite-plugin-markdown/index.js +3 -3
  54. package/dist/vite-plugin-markdown-legacy/index.js +3 -3
  55. package/package.json +4 -4
  56. package/dist/core/errors/codes.d.ts +0 -15
  57. package/dist/core/errors/codes.js +0 -19
package/dist/cli/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import * as colors from "kleur/colors";
2
- import { pathToFileURL } from "url";
3
2
  import yargs from "yargs-parser";
4
3
  import { z } from "zod";
5
4
  import {
@@ -73,9 +72,7 @@ async function handleConfigError(e, { cwd, flags, logging }) {
73
72
  error(logging, "astro", `Unable to load ${colors.bold(path)}
74
73
  `);
75
74
  }
76
- console.error(
77
- formatErrorMessage(collectErrorMetadata(e, path ? pathToFileURL(path) : void 0)) + "\n"
78
- );
75
+ console.error(formatErrorMessage(collectErrorMetadata(e)) + "\n");
79
76
  }
80
77
  }
81
78
  async function runCommand(cmd, flags) {
@@ -8,7 +8,6 @@ import {
8
8
  runHookConfigSetup
9
9
  } from "../../integrations/index.js";
10
10
  import { createVite } from "../create-vite.js";
11
- import { enhanceViteSSRError } from "../errors/dev/index.js";
12
11
  import { debug, info, levels, timerMessage } from "../logger/core.js";
13
12
  import { apply as applyPolyfill } from "../polyfill.js";
14
13
  import { RouteCache } from "../render/route-cache.js";
@@ -127,7 +126,7 @@ class AstroBuilder {
127
126
  try {
128
127
  await this.build(setupData);
129
128
  } catch (_err) {
130
- throw enhanceViteSSRError(_err);
129
+ throw _err;
131
130
  }
132
131
  }
133
132
  validateConfig() {
@@ -10,6 +10,7 @@ import { prependForwardSlash } from "../../core/path.js";
10
10
  import { isModeServerWithNoAdapter } from "../../core/util.js";
11
11
  import { runHookBuildSetup } from "../../integrations/index.js";
12
12
  import { PAGE_SCRIPT_ID } from "../../vite-plugin-scripts/index.js";
13
+ import { AstroError, AstroErrorData } from "../errors/index.js";
13
14
  import { info } from "../logger/core.js";
14
15
  import { getOutDirWithinCwd } from "./common.js";
15
16
  import { generatePages } from "./generate.js";
@@ -24,17 +25,7 @@ import { injectManifest, vitePluginSSR } from "./vite-plugin-ssr.js";
24
25
  async function staticBuild(opts) {
25
26
  const { allPages, settings } = opts;
26
27
  if (isModeServerWithNoAdapter(opts.settings)) {
27
- throw new Error(`Cannot use \`output: 'server'\` without an adapter.
28
- Install and configure the appropriate server adapter for your final deployment.
29
- Learn more: https://docs.astro.build/en/guides/server-side-rendering/
30
-
31
- // Example: astro.config.js
32
- import netlify from '@astrojs/netlify';
33
- export default {
34
- output: 'server',
35
- adapter: netlify(),
36
- }
37
- `);
28
+ throw new AstroError(AstroErrorData.NoAdapterInstalled);
38
29
  }
39
30
  const pageInput = /* @__PURE__ */ new Set();
40
31
  const facadeIdToPageDataMap = /* @__PURE__ */ new Map();
@@ -1,6 +1,6 @@
1
1
  import { transform } from "@astrojs/compiler";
2
- import { AstroErrorCodes } from "../errors/codes.js";
3
2
  import { AggregateError, CompilerError } from "../errors/errors.js";
3
+ import { AstroErrorData } from "../errors/index.js";
4
4
  import { prependForwardSlash } from "../path.js";
5
5
  import { resolvePath, viteID } from "../util.js";
6
6
  import { createStylePreprocessor } from "./style.js";
@@ -35,7 +35,7 @@ async function compile({
35
35
  }
36
36
  }).catch((err) => {
37
37
  throw new CompilerError({
38
- errorCode: AstroErrorCodes.UnknownCompilerError,
38
+ ...AstroErrorData.UnknownCompilerError,
39
39
  message: err.message ?? "Unknown compiler error",
40
40
  stack: err.stack,
41
41
  location: {
@@ -43,19 +43,17 @@ async function compile({
43
43
  }
44
44
  });
45
45
  }).then((result) => {
46
- const compilerError = result.diagnostics.find(
47
- (diag) => diag.severity === 1 && diag.code < 2e3
48
- );
46
+ const compilerError = result.diagnostics.find((diag) => diag.severity === 1);
49
47
  if (compilerError) {
50
48
  throw new CompilerError({
51
- errorCode: compilerError.code,
49
+ code: compilerError.code,
52
50
  message: compilerError.text,
53
51
  location: {
54
52
  line: compilerError.location.line,
55
53
  column: compilerError.location.column,
56
54
  file: compilerError.location.file
57
55
  },
58
- hint: compilerError.hint ? compilerError.hint : void 0
56
+ hint: compilerError.hint
59
57
  });
60
58
  }
61
59
  switch (cssTransformErrors.length) {
@@ -63,8 +61,8 @@ async function compile({
63
61
  return result;
64
62
  case 1: {
65
63
  let error = cssTransformErrors[0];
66
- if (!error.errorCode) {
67
- error.errorCode = AstroErrorCodes.UnknownCompilerCSSError;
64
+ if (!error.code) {
65
+ error.code = AstroErrorData.UnknownCSSError.code;
68
66
  }
69
67
  throw cssTransformErrors[0];
70
68
  }
@@ -1,8 +1,6 @@
1
1
  import fs from "fs";
2
2
  import { preprocessCSS } from "vite";
3
- import { AstroErrorCodes } from "../errors/codes.js";
4
- import { CSSError } from "../errors/errors.js";
5
- import { positionAt } from "../errors/index.js";
3
+ import { AstroErrorData, CSSError, positionAt } from "../errors/index.js";
6
4
  function createStylePreprocessor({
7
5
  filename,
8
6
  viteConfig,
@@ -44,7 +42,7 @@ function enhanceCSSError(err, filename) {
44
42
  if (err.name === "CssSyntaxError") {
45
43
  const errorLine = positionAt(styleTagBeginning, fileContent).line + (err.line ?? 0);
46
44
  return new CSSError({
47
- errorCode: AstroErrorCodes.CssSyntaxError,
45
+ ...AstroErrorData.CSSSyntaxError,
48
46
  message: err.reason,
49
47
  location: {
50
48
  file: filename,
@@ -56,7 +54,7 @@ function enhanceCSSError(err, filename) {
56
54
  if (err.line && err.column) {
57
55
  const errorLine = positionAt(styleTagBeginning, fileContent).line + (err.line ?? 0);
58
56
  return new CSSError({
59
- errorCode: AstroErrorCodes.CssUnknownError,
57
+ ...AstroErrorData.UnknownCSSError,
60
58
  message: err.message,
61
59
  location: {
62
60
  file: filename,
@@ -69,7 +67,7 @@ function enhanceCSSError(err, filename) {
69
67
  const errorPosition = positionAt(styleTagBeginning, fileContent);
70
68
  errorPosition.line += 1;
71
69
  return new CSSError({
72
- errorCode: AstroErrorCodes.CssUnknownError,
70
+ code: AstroErrorData.UnknownCSSError.code,
73
71
  message: err.message,
74
72
  location: {
75
73
  file: filename,
@@ -6,6 +6,7 @@ import path from "path";
6
6
  import { fileURLToPath, pathToFileURL } from "url";
7
7
  import * as vite from "vite";
8
8
  import { mergeConfig as mergeViteConfig } from "vite";
9
+ import { AstroError, AstroErrorData } from "../errors/index.js";
9
10
  import { arraify, isObject, isURL } from "../util.js";
10
11
  import { createRelativeSchema } from "./schema.js";
11
12
  load.use([loadTypeScript]);
@@ -58,11 +59,10 @@ async function validateConfig(userConfig, root, cmd) {
58
59
  }
59
60
  }
60
61
  if (legacyConfigKey) {
61
- throw new Error(
62
- `Legacy configuration detected: "${legacyConfigKey}".
63
- Please update your configuration to the new format!
64
- See https://astro.build/config for more information.`
65
- );
62
+ throw new AstroError({
63
+ ...AstroErrorData.ConfigLegacyKey,
64
+ message: AstroErrorData.ConfigLegacyKey.message(legacyConfigKey)
65
+ });
66
66
  }
67
67
  const AstroConfigRelativeSchema = createRelativeSchema(cmd, fileProtocolRoot);
68
68
  const result = await AstroConfigRelativeSchema.parseAsync(userConfig);
@@ -119,7 +119,10 @@ async function resolveConfigPath(configOptions) {
119
119
  return configPath;
120
120
  } catch (e) {
121
121
  if (e instanceof ProloadError && flags.config) {
122
- throw new Error(`Unable to resolve --config "${flags.config}"! Does the file exist?`);
122
+ throw new AstroError({
123
+ ...AstroErrorData.ConfigNotFound,
124
+ message: AstroErrorData.ConfigNotFound.message(flags.config)
125
+ });
123
126
  }
124
127
  throw e;
125
128
  }
@@ -174,7 +177,10 @@ async function tryLoadConfig(configOptions, flags, root) {
174
177
  return config;
175
178
  } catch (e) {
176
179
  if (e instanceof ProloadError && flags.config) {
177
- throw new Error(`Unable to resolve --config "${flags.config}"! Does the file exist?`);
180
+ throw new AstroError({
181
+ ...AstroErrorData.ConfigNotFound,
182
+ message: AstroErrorData.ConfigNotFound.message(flags.config)
183
+ });
178
184
  }
179
185
  const configPath = await resolveConfigPath(configOptions);
180
186
  if (!configPath) {
@@ -1,4 +1,4 @@
1
- const ASTRO_VERSION = "1.6.4";
1
+ const ASTRO_VERSION = "1.6.6";
2
2
  const SUPPORTED_MARKDOWN_FILE_EXTENSIONS = [
3
3
  ".markdown",
4
4
  ".mdown",
@@ -30,7 +30,7 @@ async function dev(settings, options) {
30
30
  isRestart: options.isRestart
31
31
  })
32
32
  );
33
- const currentVersion = "1.6.4";
33
+ const currentVersion = "1.6.6";
34
34
  if (currentVersion.includes("-")) {
35
35
  warn(options.logging, null, msg.prerelease({ currentVersion }));
36
36
  }
@@ -1,6 +1,7 @@
1
1
  import { renderEndpoint } from "../../runtime/server/index.js";
2
2
  import { ASTRO_VERSION } from "../constants.js";
3
3
  import { AstroCookies, attachToResponse } from "../cookies/index.js";
4
+ import { AstroError, AstroErrorData } from "../errors/index.js";
4
5
  import { getParamsAndProps, GetParamsAndPropsError } from "../render/core.js";
5
6
  const clientAddressSymbol = Symbol.for("astro.clientAddress");
6
7
  function createAPIContext({
@@ -29,13 +30,12 @@ function createAPIContext({
29
30
  get clientAddress() {
30
31
  if (!(clientAddressSymbol in request)) {
31
32
  if (adapterName) {
32
- throw new Error(
33
- `clientAddress is not available in the ${adapterName} adapter. File an issue with the adapter to add support.`
34
- );
33
+ throw new AstroError({
34
+ ...AstroErrorData.SSRClientAddressNotAvailableInAdapter,
35
+ message: AstroErrorData.SSRClientAddressNotAvailableInAdapter.message(adapterName)
36
+ });
35
37
  } else {
36
- throw new Error(
37
- `clientAddress is not available in your environment. Ensure that you are using an SSR adapter that supports this feature.`
38
- );
38
+ throw new AstroError(AstroErrorData.StaticClientAddressNotAvailable);
39
39
  }
40
40
  }
41
41
  return Reflect.get(request, clientAddressSymbol);
@@ -43,6 +43,7 @@ function createAPIContext({
43
43
  };
44
44
  }
45
45
  async function call(mod, env, ctx) {
46
+ var _a, _b;
46
47
  const paramsAndPropsResp = await getParamsAndProps({
47
48
  mod,
48
49
  route: ctx.route,
@@ -52,9 +53,11 @@ async function call(mod, env, ctx) {
52
53
  ssr: env.ssr
53
54
  });
54
55
  if (paramsAndPropsResp === GetParamsAndPropsError.NoMatchingStaticPath) {
55
- throw new Error(
56
- `[getStaticPath] route pattern matched, but no matching static path found. (${ctx.pathname})`
57
- );
56
+ throw new AstroError({
57
+ ...AstroErrorData.NoMatchingStaticPathFound,
58
+ message: AstroErrorData.NoMatchingStaticPathFound.message(ctx.pathname),
59
+ hint: ((_a = ctx.route) == null ? void 0 : _a.component) ? AstroErrorData.NoMatchingStaticPathFound.hint([(_b = ctx.route) == null ? void 0 : _b.component]) : ""
60
+ });
58
61
  }
59
62
  const [params, props] = paramsAndPropsResp;
60
63
  const context = createAPIContext({
@@ -84,9 +87,7 @@ function isRedirect(statusCode) {
84
87
  }
85
88
  function throwIfRedirectNotAllowed(response, config) {
86
89
  if (config.output !== "server" && isRedirect(response.status)) {
87
- throw new Error(
88
- `Redirects are only available when using output: 'server'. Update your Astro config if you need SSR features.`
89
- );
90
+ throw new AstroError(AstroErrorData.StaticRedirectNotAllowed);
90
91
  }
91
92
  }
92
93
  export {
@@ -7,4 +7,4 @@ export declare const incompatPackageExp: RegExp;
7
7
  * Takes any error-like object and returns a standardized Error + metadata object.
8
8
  * Useful for consistent reporting regardless of where the error surfaced from.
9
9
  */
10
- export declare function collectErrorMetadata(e: any, filePath?: URL): ErrorWithMetadata;
10
+ export declare function collectErrorMetadata(e: any, rootFolder?: URL | undefined): ErrorWithMetadata;
@@ -1,17 +1,24 @@
1
1
  import * as fs from "node:fs";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import stripAnsi from "strip-ansi";
2
5
  import { AggregateError } from "../errors.js";
3
6
  import { codeFrame } from "../printer.js";
4
- import { collectInfoFromStacktrace } from "../utils.js";
7
+ import { normalizeLF } from "../utils.js";
5
8
  const incompatiblePackages = {
6
9
  "react-spectrum": `@adobe/react-spectrum is not compatible with Vite's server-side rendering mode at the moment. You can still use React Spectrum from the client. Create an island React component and use the client:only directive. From there you can use React Spectrum.`
7
10
  };
8
11
  const incompatPackageExp = new RegExp(`(${Object.keys(incompatiblePackages).join("|")})`);
9
- function collectErrorMetadata(e, filePath) {
12
+ function collectErrorMetadata(e, rootFolder) {
10
13
  const err = AggregateError.is(e) ? e.errors : [e];
11
14
  err.forEach((error) => {
15
+ var _a;
12
16
  if (error.stack) {
13
17
  error = collectInfoFromStacktrace(e);
14
18
  }
19
+ if (((_a = error.loc) == null ? void 0 : _a.file) && rootFolder && !error.loc.file.startsWith("/")) {
20
+ error.loc.file = join(fileURLToPath(rootFolder), error.loc.file);
21
+ }
15
22
  if (!error.frame && error.loc) {
16
23
  try {
17
24
  const fileContents = fs.readFileSync(error.loc.file, "utf8");
@@ -20,17 +27,23 @@ function collectErrorMetadata(e, filePath) {
20
27
  } catch {
21
28
  }
22
29
  }
23
- if (!error.hint) {
24
- error.hint = generateHint(e, filePath);
25
- }
30
+ error.hint = generateHint(e);
26
31
  });
27
32
  if (!AggregateError.is(e) && Array.isArray(e.errors)) {
28
33
  e.errors.forEach((buildError, i) => {
29
- const { location, pluginName } = buildError;
34
+ var _a;
35
+ const { location, pluginName, text } = buildError;
36
+ err[i].message = text;
30
37
  if (location) {
31
38
  err[i].loc = { file: location.file, line: location.line, column: location.column };
32
39
  err[i].id = err[0].id || (location == null ? void 0 : location.file);
33
40
  }
41
+ if (err[i].frame) {
42
+ const errorLines = (_a = err[i].frame) == null ? void 0 : _a.trim().split("\n");
43
+ if (errorLines) {
44
+ err[i].frame = !/^\d/.test(errorLines[0]) ? errorLines == null ? void 0 : errorLines.slice(1).join("\n") : err[i].frame;
45
+ }
46
+ }
34
47
  const possibleFilePath = err[i].pluginCode || err[i].id || (location == null ? void 0 : location.file);
35
48
  if (possibleFilePath && !err[i].frame) {
36
49
  try {
@@ -42,17 +55,23 @@ function collectErrorMetadata(e, filePath) {
42
55
  if (pluginName) {
43
56
  err[i].plugin = pluginName;
44
57
  }
45
- err[i].hint = generateHint(err[0], filePath);
58
+ err[i].hint = generateHint(err[0]);
46
59
  });
47
60
  }
48
61
  return err[0];
49
62
  }
50
- function generateHint(err, filePath) {
63
+ function generateHint(err) {
51
64
  var _a, _b;
52
65
  if (/Unknown file extension \"\.(jsx|vue|svelte|astro|css)\" for /.test(err.message)) {
53
66
  return "You likely need to add this package to `vite.ssr.noExternal` in your astro config file.";
54
- } else if (err.toString().startsWith("ReferenceError") && ((_b = ((_a = err.loc) == null ? void 0 : _a.file) ?? (filePath == null ? void 0 : filePath.pathname)) == null ? void 0 : _b.endsWith(".astro"))) {
55
- return "export statements in `.astro` files do not have access to local variable declarations, only imported values.";
67
+ } else if (err.toString().includes("document")) {
68
+ const hint = `Browser APIs are not available on the server.
69
+
70
+ ${((_b = (_a = err.loc) == null ? void 0 : _a.file) == null ? void 0 : _b.endsWith(".astro")) ? "Move your code to a <script> tag outside of the frontmatter, so the code runs on the client" : "If the code is in a framework component, try to access these objects after rendering using lifecycle methods or use a `client:only` directive to make the component exclusively run on the client"}
71
+
72
+ See https://docs.astro.build/en/guides/troubleshooting/#document-or-window-is-not-defined for more information.
73
+ `;
74
+ return hint;
56
75
  } else {
57
76
  const res = incompatPackageExp.exec(err.stack);
58
77
  if (res) {
@@ -60,7 +79,41 @@ function generateHint(err, filePath) {
60
79
  return incompatiblePackages[key];
61
80
  }
62
81
  }
63
- return void 0;
82
+ return err.hint;
83
+ }
84
+ function collectInfoFromStacktrace(error) {
85
+ var _a, _b, _c;
86
+ if (!error.stack)
87
+ return error;
88
+ error.stack = normalizeLF(error.stack);
89
+ const stackText = stripAnsi(error.stack);
90
+ if (!error.loc || !error.loc.column && !error.loc.line) {
91
+ const possibleFilePath = ((_a = error.loc) == null ? void 0 : _a.file) || error.pluginCode || error.id || stackText.split("\n").find((ln) => ln.includes("src") || ln.includes("node_modules"));
92
+ const source = possibleFilePath == null ? void 0 : possibleFilePath.replace(/^[^(]+\(([^)]+).*$/, "$1").replace(/^\s+at\s+/, "");
93
+ let file = source == null ? void 0 : source.replace(/(:[0-9]+)/g, "");
94
+ const location = /:([0-9]+):([0-9]+)/g.exec(source) ?? [];
95
+ const line = location[1];
96
+ const column = location[2];
97
+ if (file && line && column) {
98
+ try {
99
+ file = fileURLToPath(file);
100
+ } catch {
101
+ }
102
+ error.loc = {
103
+ file,
104
+ line: Number.parseInt(line),
105
+ column: Number.parseInt(column)
106
+ };
107
+ }
108
+ }
109
+ if (!error.plugin) {
110
+ error.plugin = ((_b = /withastro\/astro\/packages\/integrations\/([\w-]+)/gim.exec(stackText)) == null ? void 0 : _b.at(1)) || ((_c = /(@astrojs\/[\w-]+)\/(server|client|index)/gim.exec(stackText)) == null ? void 0 : _c.at(1)) || void 0;
111
+ }
112
+ error.stack = cleanErrorStack(error.stack);
113
+ return error;
114
+ }
115
+ function cleanErrorStack(stack) {
116
+ return stack.split(/\n/g).map((l) => l.replace(/\/@fs\//g, "/")).join("\n");
64
117
  }
65
118
  export {
66
119
  collectErrorMetadata,
@@ -1,11 +1,11 @@
1
1
  import { type ErrorPayload, type Logger, type LogLevel } from 'vite';
2
2
  import type { ModuleLoader } from '../../module-loader/index.js';
3
- import { AstroError, type ErrorWithMetadata } from '../errors.js';
3
+ import { type ErrorWithMetadata } from '../errors.js';
4
4
  /**
5
5
  * Custom logger with better error reporting for incompatible packages
6
6
  */
7
7
  export declare function createCustomViteLogger(logLevel: LogLevel): Logger;
8
- export declare function enhanceViteSSRError(error: Error, filePath?: URL, loader?: ModuleLoader): AstroError;
8
+ export declare function enhanceViteSSRError(error: unknown, filePath?: URL, loader?: ModuleLoader): Error;
9
9
  /**
10
10
  * Generate a payload for Vite's error overlay
11
11
  */
@@ -1,8 +1,8 @@
1
1
  import * as fs from "fs";
2
2
  import { fileURLToPath } from "url";
3
3
  import { createLogger } from "vite";
4
- import { AstroErrorCodes } from "../codes.js";
5
- import { AstroError } from "../errors.js";
4
+ import { AstroErrorData } from "../errors-data.js";
5
+ import { createSafeError } from "../utils.js";
6
6
  import { incompatPackageExp } from "./utils.js";
7
7
  function createCustomViteLogger(logLevel) {
8
8
  const viteLogger = createLogger(logLevel);
@@ -17,41 +17,54 @@ function createCustomViteLogger(logLevel) {
17
17
  return logger;
18
18
  }
19
19
  function enhanceViteSSRError(error, filePath, loader) {
20
- var _a, _b;
20
+ var _a, _b, _c, _d;
21
+ const safeError = createSafeError(error);
21
22
  if (loader) {
22
23
  try {
23
- loader.fixStacktrace(error);
24
+ loader.fixStacktrace(safeError);
24
25
  } catch {
25
26
  }
26
27
  }
27
- const newError = new AstroError({
28
- name: error.name,
29
- message: error.message,
30
- location: error.loc,
31
- stack: error.stack,
32
- errorCode: error.errorCode ? error.errorCode : AstroErrorCodes.UnknownViteSSRError
33
- });
34
- if (filePath && /failed to load module for ssr:/.test(error.message)) {
35
- const importName = (_a = error.message.split("for ssr:").at(1)) == null ? void 0 : _a.trim();
36
- if (importName) {
37
- newError.setMessage(`Could not import "${importName}"`);
38
- newError.setHint("Make sure the file exists");
39
- newError.setErrorCode(AstroErrorCodes.FailedToLoadModuleSSR);
40
- const path = fileURLToPath(filePath);
41
- const content = fs.readFileSync(path).toString();
42
- const lns = content.split("\n");
43
- const line = lns.findIndex((ln) => ln.includes(importName));
44
- if (line !== -1) {
45
- const column = (_b = lns[line]) == null ? void 0 : _b.indexOf(importName);
46
- newError.setLocation({
47
- file: path,
48
- line: line + 1,
49
- column
50
- });
28
+ if (filePath) {
29
+ const path = fileURLToPath(filePath);
30
+ const content = fs.readFileSync(path).toString();
31
+ const lns = content.split("\n");
32
+ if (/failed to load module for ssr:/.test(safeError.message)) {
33
+ const importName = (_a = safeError.message.split("for ssr:").at(1)) == null ? void 0 : _a.trim();
34
+ if (importName) {
35
+ safeError.message = AstroErrorData.FailedToLoadModuleSSR.message(importName);
36
+ safeError.hint = AstroErrorData.FailedToLoadModuleSSR.hint;
37
+ safeError.code = AstroErrorData.FailedToLoadModuleSSR.code;
38
+ const line = lns.findIndex((ln) => ln.includes(importName));
39
+ if (line !== -1) {
40
+ const column = (_b = lns[line]) == null ? void 0 : _b.indexOf(importName);
41
+ safeError.loc = {
42
+ file: path,
43
+ line: line + 1,
44
+ column
45
+ };
46
+ }
47
+ }
48
+ }
49
+ if (/Invalid glob/.test(safeError.message)) {
50
+ const globPattern = (_c = safeError.message.match(/glob: "(.+)" \(/)) == null ? void 0 : _c[1];
51
+ if (globPattern) {
52
+ safeError.message = AstroErrorData.InvalidGlob.message(globPattern);
53
+ safeError.hint = AstroErrorData.InvalidGlob.hint;
54
+ safeError.code = AstroErrorData.InvalidGlob.code;
55
+ const line = lns.findIndex((ln) => ln.includes(globPattern));
56
+ if (line !== -1) {
57
+ const column = (_d = lns[line]) == null ? void 0 : _d.indexOf(globPattern);
58
+ safeError.loc = {
59
+ file: path,
60
+ line: line + 1,
61
+ column
62
+ };
63
+ }
51
64
  }
52
65
  }
53
66
  }
54
- return newError;
67
+ return safeError;
55
68
  }
56
69
  function getViteErrorPayload(err) {
57
70
  var _a, _b, _c, _d;
@@ -0,0 +1,137 @@
1
+ export declare const AstroErrorData: {
2
+ readonly UnknownCompilerError: {
3
+ readonly code: 1000;
4
+ };
5
+ readonly StaticRedirectNotAllowed: {
6
+ readonly code: 3001;
7
+ readonly message: "Redirects are only available when using output: 'server'. Update your Astro config if you need SSR features.";
8
+ readonly hint: "See https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project for more information on how to enable SSR.";
9
+ };
10
+ readonly SSRClientAddressNotAvailableInAdapter: {
11
+ readonly code: 3002;
12
+ readonly message: (adapterName: string) => string;
13
+ };
14
+ readonly StaticClientAddressNotAvailable: {
15
+ readonly code: 3003;
16
+ readonly message: "Astro.clientAddress is only available when using output: 'server'. Update your Astro config if you need SSR features.";
17
+ readonly hint: "See https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project for more information on how to enable SSR.";
18
+ };
19
+ readonly NoMatchingStaticPathFound: {
20
+ readonly code: 3004;
21
+ readonly message: (pathName: string) => string;
22
+ readonly hint: (possibleRoutes: string[]) => string;
23
+ };
24
+ readonly OnlyResponseCanBeReturned: {
25
+ readonly code: 3005;
26
+ readonly message: (route: string | undefined, returnedValue: string) => string;
27
+ readonly hint: "See https://docs.astro.build/en/guides/server-side-rendering/#response for more information.";
28
+ };
29
+ readonly MissingMediaQueryDirective: {
30
+ readonly code: 3006;
31
+ readonly message: (componentName: string) => string;
32
+ };
33
+ readonly NoMatchingRenderer: {
34
+ readonly code: 3007;
35
+ readonly message: (componentName: string, componentExtension: string | undefined, plural: boolean, validRenderersCount: number) => string;
36
+ readonly hint: (probableRenderers: string) => string;
37
+ };
38
+ readonly NoClientEntrypoint: {
39
+ readonly code: 3008;
40
+ readonly message: (componentName: string, clientDirective: string, rendererName: string) => string;
41
+ readonly hint: "See https://docs.astro.build/en/reference/integrations-reference/#addrenderer-option for more information on how to configure your renderer.";
42
+ };
43
+ readonly NoClientOnlyHint: {
44
+ readonly code: 3009;
45
+ readonly message: (componentName: string) => string;
46
+ readonly hint: (probableRenderers: string) => string;
47
+ };
48
+ readonly InvalidStaticPathParam: {
49
+ readonly code: 3010;
50
+ readonly message: (paramType: any) => string;
51
+ readonly hint: "See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.";
52
+ };
53
+ readonly InvalidGetStaticPathsReturn: {
54
+ readonly code: 3011;
55
+ readonly message: (returnType: any) => string;
56
+ readonly hint: "See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.";
57
+ };
58
+ readonly GetStaticPathsDeprecatedRSS: {
59
+ readonly code: 3012;
60
+ readonly message: "The RSS helper has been removed from getStaticPaths! Try the new @astrojs/rss package instead.";
61
+ readonly hint: "See https://docs.astro.build/en/guides/rss/ for more information.";
62
+ };
63
+ readonly GetStaticPathsExpectedParams: {
64
+ readonly code: 3013;
65
+ readonly message: "Missing or empty required params property on getStaticPaths route";
66
+ readonly hint: "See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.";
67
+ };
68
+ readonly GetStaticPathsInvalidRouteParam: {
69
+ readonly code: 3014;
70
+ readonly message: (key: string, value: any) => string;
71
+ readonly hint: "See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.";
72
+ };
73
+ readonly GetStaticPathsRequired: {
74
+ readonly code: 3015;
75
+ readonly message: "getStaticPaths() function is required for dynamic routes. Make sure that you `export` a `getStaticPaths` function from your dynamic route.";
76
+ readonly hint: "See https://docs.astro.build/en/core-concepts/routing/#dynamic-routes for more information on dynamic routes.\n\nAlternatively, set `output: \"server\"` in your Astro config file to switch to a non-static server build.\nSee https://docs.astro.build/en/guides/server-side-rendering/ for more information on non-static rendering.";
77
+ };
78
+ readonly ReservedSlotName: {
79
+ readonly code: 3016;
80
+ readonly message: (slotName: string) => string;
81
+ };
82
+ readonly NoAdapterInstalled: {
83
+ readonly code: 3017;
84
+ readonly message: "Cannot use `output: 'server'` without an adapter. Please install and configure the appropriate server adapter for your final deployment.";
85
+ readonly hint: "See https://docs.astro.build/en/guides/server-side-rendering/ for more information.";
86
+ };
87
+ readonly NoMatchingImport: {
88
+ readonly code: 3018;
89
+ readonly message: (componentName: string) => string;
90
+ readonly hint: "Please make sure the component is properly imported.";
91
+ };
92
+ readonly UnknownCSSError: {
93
+ readonly code: 4000;
94
+ };
95
+ readonly CSSSyntaxError: {
96
+ readonly code: 4001;
97
+ };
98
+ readonly UnknownViteError: {
99
+ readonly code: 5000;
100
+ };
101
+ readonly FailedToLoadModuleSSR: {
102
+ readonly code: 5001;
103
+ readonly message: (importName: string) => string;
104
+ readonly hint: "This is often caused by a typo in the import path. Please make sure the file exists.";
105
+ };
106
+ readonly InvalidGlob: {
107
+ readonly code: 5002;
108
+ readonly message: (globPattern: string) => string;
109
+ readonly hint: "See https://docs.astro.build/en/guides/imports/#glob-patterns for more information on supported glob patterns.";
110
+ };
111
+ readonly UnknownMarkdownError: {
112
+ readonly code: 6000;
113
+ };
114
+ readonly MarkdownFrontmatterParseError: {
115
+ readonly code: 6001;
116
+ };
117
+ readonly UnknownConfigError: {
118
+ readonly code: 7000;
119
+ };
120
+ readonly ConfigNotFound: {
121
+ readonly code: 7001;
122
+ readonly message: (configFile: string) => string;
123
+ };
124
+ readonly ConfigLegacyKey: {
125
+ readonly code: 7002;
126
+ readonly message: (legacyConfigKey: string) => string;
127
+ readonly hint: "Please update your configuration to the new format!\nSee https://astro.build/config for more information.";
128
+ };
129
+ readonly UnknownError: {
130
+ readonly code: 99999;
131
+ };
132
+ };
133
+ declare type ValueOf<T> = T[keyof T];
134
+ export declare type AstroErrorCodes = ValueOf<{
135
+ [T in keyof typeof AstroErrorData]: typeof AstroErrorData[T]['code'];
136
+ }>;
137
+ export {};