astro 1.0.1 → 1.0.2

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 (35) hide show
  1. package/dist/core/add/index.js +1 -1
  2. package/dist/core/app/index.js +3 -0
  3. package/dist/core/app/node.js +11 -5
  4. package/dist/core/build/index.js +16 -35
  5. package/dist/core/dev/index.js +1 -1
  6. package/dist/core/errors.js +1 -1
  7. package/dist/core/messages.js +2 -2
  8. package/dist/core/render/dev/index.js +3 -4
  9. package/dist/core/util.js +13 -2
  10. package/dist/runtime/client/idle.prebuilt.js +11 -1
  11. package/dist/runtime/client/load.prebuilt.js +6 -1
  12. package/dist/runtime/client/media.prebuilt.js +14 -1
  13. package/dist/runtime/client/only.prebuilt.js +6 -1
  14. package/dist/runtime/client/visible.prebuilt.js +19 -1
  15. package/dist/runtime/server/astro-global.js +1 -1
  16. package/dist/runtime/server/astro-island.prebuilt.js +89 -1
  17. package/dist/runtime/server/hydration.js +6 -1
  18. package/dist/runtime/server/render/component.js +4 -3
  19. package/dist/types/@types/astro.d.ts +1 -0
  20. package/dist/types/core/app/node.d.ts +4 -3
  21. package/dist/types/core/build/page-data.d.ts +0 -6
  22. package/dist/types/core/errors.d.ts +5 -2
  23. package/dist/types/core/util.d.ts +6 -1
  24. package/dist/types/runtime/client/idle.prebuilt.d.ts +1 -1
  25. package/dist/types/runtime/client/load.prebuilt.d.ts +1 -1
  26. package/dist/types/runtime/client/media.prebuilt.d.ts +1 -1
  27. package/dist/types/runtime/client/only.prebuilt.d.ts +1 -1
  28. package/dist/types/runtime/client/visible.prebuilt.d.ts +1 -1
  29. package/dist/types/runtime/server/astro-island.prebuilt.d.ts +1 -1
  30. package/dist/types/runtime/server/hydration.d.ts +1 -0
  31. package/dist/types/vite-plugin-astro/query.d.ts +1 -0
  32. package/dist/vite-plugin-astro/hmr.js +12 -4
  33. package/dist/vite-plugin-astro/index.js +5 -1
  34. package/dist/vite-plugin-astro/query.js +5 -0
  35. package/package.json +2 -2
@@ -610,7 +610,7 @@ function parseIntegrationName(spec) {
610
610
  return { scope, name, tag };
611
611
  }
612
612
  async function askToContinue({ flags }) {
613
- if (flags.yes)
613
+ if (flags.yes || flags.y)
614
614
  return true;
615
615
  const response = await prompts({
616
616
  type: "confirm",
@@ -87,6 +87,9 @@ class App {
87
87
  });
88
88
  }
89
89
  }
90
+ if (routeData.route === "/404") {
91
+ defaultStatus = 404;
92
+ }
90
93
  let mod = __privateGet(this, _manifest).pageMap.get(routeData.component);
91
94
  if (routeData.type === "page") {
92
95
  let response = await __privateMethod(this, _renderPage, renderPage_fn).call(this, request, routeData, mod, defaultStatus);
@@ -19,10 +19,10 @@ function createRequestFromNodeRequest(req, body) {
19
19
  return request;
20
20
  }
21
21
  class NodeApp extends App {
22
- match(req) {
23
- return super.match(req instanceof Request ? req : createRequestFromNodeRequest(req));
22
+ match(req, opts = {}) {
23
+ return super.match(req instanceof Request ? req : createRequestFromNodeRequest(req), opts);
24
24
  }
25
- render(req) {
25
+ render(req, routeData) {
26
26
  if ("on" in req) {
27
27
  let body = Buffer.from([]);
28
28
  let reqBodyComplete = new Promise((resolve, reject) => {
@@ -37,10 +37,16 @@ class NodeApp extends App {
37
37
  });
38
38
  });
39
39
  return reqBodyComplete.then(() => {
40
- return super.render(req instanceof Request ? req : createRequestFromNodeRequest(req, body));
40
+ return super.render(
41
+ req instanceof Request ? req : createRequestFromNodeRequest(req, body),
42
+ routeData
43
+ );
41
44
  });
42
45
  }
43
- return super.render(req instanceof Request ? req : createRequestFromNodeRequest(req));
46
+ return super.render(
47
+ req instanceof Request ? req : createRequestFromNodeRequest(req),
48
+ routeData
49
+ );
44
50
  }
45
51
  }
46
52
  async function loadManifest(rootFolder) {
@@ -1,7 +1,6 @@
1
1
  import fs from "fs";
2
2
  import * as colors from "kleur/colors";
3
3
  import { performance } from "perf_hooks";
4
- import * as vite from "vite";
5
4
  import {
6
5
  runHookBuildDone,
7
6
  runHookBuildStart,
@@ -14,7 +13,6 @@ import { debug, info, levels, timerMessage } from "../logger/core.js";
14
13
  import { apply as applyPolyfill } from "../polyfill.js";
15
14
  import { RouteCache } from "../render/route-cache.js";
16
15
  import { createRouteManifest } from "../routing/index.js";
17
- import { createSafeError } from "../util.js";
18
16
  import { collectPagesData } from "./page-data.js";
19
17
  import { staticBuild } from "./static-build.js";
20
18
  import { getTimeStat } from "./util.js";
@@ -40,7 +38,6 @@ class AstroBuilder {
40
38
  debug("build", "Initial setup...");
41
39
  const { logging } = this;
42
40
  this.timer.init = performance.now();
43
- this.timer.viteStart = performance.now();
44
41
  this.config = await runHookConfigSetup({ config: this.config, command: "build" });
45
42
  this.manifest = createRouteManifest({ config: this.config }, this.logging);
46
43
  const viteConfig = await createVite(
@@ -55,15 +52,9 @@ class AstroBuilder {
55
52
  { astroConfig: this.config, logging, mode: "build" }
56
53
  );
57
54
  await runHookConfigDone({ config: this.config });
58
- const viteServer = await vite.createServer(viteConfig);
59
- debug("build", timerMessage("Vite started", this.timer.viteStart));
60
- return { viteConfig, viteServer };
55
+ return { viteConfig };
61
56
  }
62
- async build({
63
- viteConfig,
64
- viteServer
65
- }) {
66
- const { origin } = this;
57
+ async build({ viteConfig }) {
67
58
  const buildConfig = {
68
59
  client: new URL("./client/", this.config.outDir),
69
60
  server: new URL("./server/", this.config.outDir),
@@ -79,11 +70,7 @@ class AstroBuilder {
79
70
  const { assets, allPages } = await collectPagesData({
80
71
  astroConfig: this.config,
81
72
  logging: this.logging,
82
- manifest: this.manifest,
83
- origin,
84
- routeCache: this.routeCache,
85
- viteServer,
86
- ssr: this.config.output === "server"
73
+ manifest: this.manifest
87
74
  });
88
75
  debug("build", timerMessage("All pages loaded", this.timer.loadStart));
89
76
  const pageNames = [];
@@ -93,23 +80,18 @@ class AstroBuilder {
93
80
  "build",
94
81
  colors.dim(`Completed in ${getTimeStat(this.timer.init, performance.now())}.`)
95
82
  );
96
- try {
97
- await staticBuild({
98
- allPages,
99
- astroConfig: this.config,
100
- logging: this.logging,
101
- manifest: this.manifest,
102
- mode: this.mode,
103
- origin: this.origin,
104
- pageNames,
105
- routeCache: this.routeCache,
106
- viteConfig,
107
- buildConfig
108
- });
109
- } catch (err) {
110
- await viteServer.close();
111
- throw err;
112
- }
83
+ await staticBuild({
84
+ allPages,
85
+ astroConfig: this.config,
86
+ logging: this.logging,
87
+ manifest: this.manifest,
88
+ mode: this.mode,
89
+ origin: this.origin,
90
+ pageNames,
91
+ routeCache: this.routeCache,
92
+ viteConfig,
93
+ buildConfig
94
+ });
113
95
  this.timer.assetsStart = performance.now();
114
96
  Object.keys(assets).map((k) => {
115
97
  if (!assets[k])
@@ -120,7 +102,6 @@ class AstroBuilder {
120
102
  delete assets[k];
121
103
  });
122
104
  debug("build", timerMessage("Additional assets copied", this.timer.assetsStart));
123
- await viteServer.close();
124
105
  await runHookBuildDone({
125
106
  config: this.config,
126
107
  buildConfig,
@@ -141,7 +122,7 @@ class AstroBuilder {
141
122
  try {
142
123
  await this.build(setupData);
143
124
  } catch (_err) {
144
- throw fixViteErrorMessage(createSafeError(_err), setupData.viteServer);
125
+ throw fixViteErrorMessage(_err);
145
126
  }
146
127
  }
147
128
  async printStats({
@@ -46,7 +46,7 @@ async function dev(config, options) {
46
46
  https: !!((_a = viteConfig.server) == null ? void 0 : _a.https)
47
47
  })
48
48
  );
49
- const currentVersion = "1.0.1";
49
+ const currentVersion = "1.0.2";
50
50
  if (currentVersion.includes("-")) {
51
51
  warn(options.logging, null, msg.prerelease({ currentVersion }));
52
52
  }
@@ -17,7 +17,7 @@ function cleanErrorStack(stack) {
17
17
  function fixViteErrorMessage(_err, server, filePath) {
18
18
  var _a, _b;
19
19
  const err = createSafeError(_err);
20
- server.ssrFixStacktrace(err);
20
+ server == null ? void 0 : server.ssrFixStacktrace(err);
21
21
  if (err.message === "import.meta.glob() can only accept string literals.") {
22
22
  err.message = "Astro.glob() and import.meta.glob() can only accept string literals.";
23
23
  }
@@ -47,7 +47,7 @@ function devStart({
47
47
  https,
48
48
  site
49
49
  }) {
50
- const version = "1.0.1";
50
+ const version = "1.0.2";
51
51
  const rootPath = site ? site.pathname : "/";
52
52
  const localPrefix = `${dim("\u2503")} Local `;
53
53
  const networkPrefix = `${dim("\u2503")} Network `;
@@ -226,7 +226,7 @@ function printHelp({
226
226
  message.push(
227
227
  linebreak(),
228
228
  ` ${bgGreen(black(` ${commandName} `))} ${green(
229
- `v${"1.0.1"}`
229
+ `v${"1.0.2"}`
230
230
  )} ${headline}`
231
231
  );
232
232
  }
@@ -1,7 +1,6 @@
1
1
  import { fileURLToPath } from "url";
2
- import { prependForwardSlash } from "../../../core/path.js";
3
2
  import { PAGE_SCRIPT_ID } from "../../../vite-plugin-scripts/index.js";
4
- import { isPage } from "../../util.js";
3
+ import { isPage, resolveIdToUrl } from "../../util.js";
5
4
  import { render as coreRender } from "../core.js";
6
5
  import { collectMdMetadata } from "../util.js";
7
6
  import { getStylesForURL } from "./css.js";
@@ -54,7 +53,7 @@ async function render(renderers, mod, ssrOpts) {
54
53
  scripts.add({
55
54
  props: {
56
55
  type: "module",
57
- src: "/@id/astro/runtime/client/hmr.js"
56
+ src: await resolveIdToUrl(viteServer, "astro/runtime/client/hmr.js")
58
57
  },
59
58
  children: ""
60
59
  });
@@ -115,7 +114,7 @@ async function render(renderers, mod, ssrOpts) {
115
114
  if (s.startsWith("/@fs")) {
116
115
  return resolveClientDevPath(s);
117
116
  }
118
- return "/@id" + prependForwardSlash(s);
117
+ return await resolveIdToUrl(viteServer, s);
119
118
  },
120
119
  renderers,
121
120
  request,
package/dist/core/util.js CHANGED
@@ -4,8 +4,8 @@ import path from "path";
4
4
  import resolve from "resolve";
5
5
  import slash from "slash";
6
6
  import { fileURLToPath, pathToFileURL } from "url";
7
- import { removeTrailingForwardSlash } from "./path.js";
8
- const ASTRO_VERSION = "1.0.1";
7
+ import { prependForwardSlash, removeTrailingForwardSlash } from "./path.js";
8
+ const ASTRO_VERSION = "1.0.2";
9
9
  function isObject(value) {
10
10
  return typeof value === "object" && value != null;
11
11
  }
@@ -157,6 +157,16 @@ function getLocalAddress(serverAddress, host) {
157
157
  return serverAddress;
158
158
  }
159
159
  }
160
+ async function resolveIdToUrl(viteServer, id) {
161
+ const result = await viteServer.pluginContainer.resolveId(id);
162
+ if (!result) {
163
+ return VALID_ID_PREFIX + id;
164
+ }
165
+ if (path.isAbsolute(result.id)) {
166
+ return "/@fs" + prependForwardSlash(result.id);
167
+ }
168
+ return VALID_ID_PREFIX + result.id;
169
+ }
160
170
  export {
161
171
  ASTRO_VERSION,
162
172
  VALID_ID_PREFIX,
@@ -175,6 +185,7 @@ export {
175
185
  relativeToSrcDir,
176
186
  removeDir,
177
187
  resolveDependency,
188
+ resolveIdToUrl,
178
189
  resolvePages,
179
190
  unwrapId,
180
191
  viteID
@@ -1,4 +1,14 @@
1
- var idle_prebuilt_default = `(self.Astro=self.Astro||{}).idle=a=>{const e=async()=>{await(await a())()};"requestIdleCallback"in window?window.requestIdleCallback(e):setTimeout(e,200)};`;
1
+ var idle_prebuilt_default = `(self.Astro = self.Astro || {}).idle = (getHydrateCallback) => {
2
+ const cb = async () => {
3
+ let hydrate = await getHydrateCallback();
4
+ await hydrate();
5
+ };
6
+ if ("requestIdleCallback" in window) {
7
+ window.requestIdleCallback(cb);
8
+ } else {
9
+ setTimeout(cb, 200);
10
+ }
11
+ };`;
2
12
  export {
3
13
  idle_prebuilt_default as default
4
14
  };
@@ -1,4 +1,9 @@
1
- var load_prebuilt_default = `(self.Astro=self.Astro||{}).load=a=>{(async()=>await(await a())())()};`;
1
+ var load_prebuilt_default = `(self.Astro = self.Astro || {}).load = (getHydrateCallback) => {
2
+ (async () => {
3
+ let hydrate = await getHydrateCallback();
4
+ await hydrate();
5
+ })();
6
+ };`;
2
7
  export {
3
8
  load_prebuilt_default as default
4
9
  };
@@ -1,4 +1,17 @@
1
- var media_prebuilt_default = `(self.Astro=self.Astro||{}).media=(s,a)=>{const t=async()=>{await(await s())()};if(a.value){const e=matchMedia(a.value);e.matches?t():e.addEventListener("change",t,{once:!0})}};`;
1
+ var media_prebuilt_default = `(self.Astro = self.Astro || {}).media = (getHydrateCallback, options) => {
2
+ const cb = async () => {
3
+ let hydrate = await getHydrateCallback();
4
+ await hydrate();
5
+ };
6
+ if (options.value) {
7
+ const mql = matchMedia(options.value);
8
+ if (mql.matches) {
9
+ cb();
10
+ } else {
11
+ mql.addEventListener("change", cb, { once: true });
12
+ }
13
+ }
14
+ };`;
2
15
  export {
3
16
  media_prebuilt_default as default
4
17
  };
@@ -1,4 +1,9 @@
1
- var only_prebuilt_default = `(self.Astro=self.Astro||{}).only=a=>{(async()=>await(await a())())()};`;
1
+ var only_prebuilt_default = `(self.Astro = self.Astro || {}).only = (getHydrateCallback) => {
2
+ (async () => {
3
+ let hydrate = await getHydrateCallback();
4
+ await hydrate();
5
+ })();
6
+ };`;
2
7
  export {
3
8
  only_prebuilt_default as default
4
9
  };
@@ -1,4 +1,22 @@
1
- var visible_prebuilt_default = `(self.Astro=self.Astro||{}).visible=(i,c,n)=>{const r=async()=>{await(await i())()};let s=new IntersectionObserver(e=>{for(const t of e)if(!!t.isIntersecting){s.disconnect(),r();break}});for(let e=0;e<n.children.length;e++){const t=n.children[e];s.observe(t)}};`;
1
+ var visible_prebuilt_default = `(self.Astro = self.Astro || {}).visible = (getHydrateCallback, _opts, root) => {
2
+ const cb = async () => {
3
+ let hydrate = await getHydrateCallback();
4
+ await hydrate();
5
+ };
6
+ let io = new IntersectionObserver((entries) => {
7
+ for (const entry of entries) {
8
+ if (!entry.isIntersecting)
9
+ continue;
10
+ io.disconnect();
11
+ cb();
12
+ break;
13
+ }
14
+ });
15
+ for (let i = 0; i < root.children.length; i++) {
16
+ const child = root.children[i];
17
+ io.observe(child);
18
+ }
19
+ };`;
2
20
  export {
3
21
  visible_prebuilt_default as default
4
22
  };
@@ -1,4 +1,4 @@
1
- const ASTRO_VERSION = "1.0.1";
1
+ const ASTRO_VERSION = "1.0.2";
2
2
  function createDeprecatedFetchContentFn() {
3
3
  return () => {
4
4
  throw new Error("Deprecated: Astro.fetchContent() has been replaced with Astro.glob().");
@@ -1,4 +1,92 @@
1
- var astro_island_prebuilt_default = `var a;{const l={0:t=>t,1:t=>JSON.parse(t,n),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(JSON.parse(t,n)),5:t=>new Set(JSON.parse(t,n)),6:t=>BigInt(t),7:t=>new URL(t)},n=(t,r)=>{if(t===""||!Array.isArray(r))return r;const[e,i]=r;return e in l?l[e](i):void 0};customElements.get("astro-island")||customElements.define("astro-island",(a=class extends HTMLElement{constructor(){super(...arguments);this.hydrate=()=>{if(!this.hydrator||this.parentElement?.closest("astro-island[ssr]"))return;const r=this.querySelectorAll("astro-slot"),e={},i=this.querySelectorAll("template[data-astro-template]");for(const s of i)!s.closest(this.tagName)?.isSameNode(this)||(e[s.getAttribute("data-astro-template")||"default"]=s.innerHTML,s.remove());for(const s of r)!s.closest(this.tagName)?.isSameNode(this)||(e[s.getAttribute("name")||"default"]=s.innerHTML);const o=this.hasAttribute("props")?JSON.parse(this.getAttribute("props"),n):{};this.hydrator(this)(this.Component,o,e,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),window.removeEventListener("astro:hydrate",this.hydrate),window.dispatchEvent(new CustomEvent("astro:hydrate"))}}connectedCallback(){!this.hasAttribute("await-children")||this.firstChild?this.childrenConnectedCallback():new MutationObserver((r,e)=>{e.disconnect(),this.childrenConnectedCallback()}).observe(this,{childList:!0})}async childrenConnectedCallback(){window.addEventListener("astro:hydrate",this.hydrate),await import(this.getAttribute("before-hydration-url"));const r=JSON.parse(this.getAttribute("opts"));Astro[this.getAttribute("client")](async()=>{const e=this.getAttribute("renderer-url"),[i,{default:o}]=await Promise.all([import(this.getAttribute("component-url")),e?import(e):()=>()=>{}]);return this.Component=i[this.getAttribute("component-export")||"default"],this.hydrator=o,this.hydrate},r,this)}attributeChangedCallback(){this.hydrator&&this.hydrate()}},a.observedAttributes=["props"],a))}`;
1
+ var astro_island_prebuilt_default = `var _a;
2
+ {
3
+ const propTypes = {
4
+ 0: (value) => value,
5
+ 1: (value) => JSON.parse(value, reviver),
6
+ 2: (value) => new RegExp(value),
7
+ 3: (value) => new Date(value),
8
+ 4: (value) => new Map(JSON.parse(value, reviver)),
9
+ 5: (value) => new Set(JSON.parse(value, reviver)),
10
+ 6: (value) => BigInt(value),
11
+ 7: (value) => new URL(value)
12
+ };
13
+ const reviver = (propKey, raw) => {
14
+ if (propKey === "" || !Array.isArray(raw))
15
+ return raw;
16
+ const [type, value] = raw;
17
+ return type in propTypes ? propTypes[type](value) : void 0;
18
+ };
19
+ if (!customElements.get("astro-island")) {
20
+ customElements.define(
21
+ "astro-island",
22
+ (_a = class extends HTMLElement {
23
+ constructor() {
24
+ super(...arguments);
25
+ this.hydrate = () => {
26
+ if (!this.hydrator || this.parentElement?.closest("astro-island[ssr]")) {
27
+ return;
28
+ }
29
+ const slotted = this.querySelectorAll("astro-slot");
30
+ const slots = {};
31
+ const templates = this.querySelectorAll("template[data-astro-template]");
32
+ for (const template of templates) {
33
+ if (!template.closest(this.tagName)?.isSameNode(this))
34
+ continue;
35
+ slots[template.getAttribute("data-astro-template") || "default"] = template.innerHTML;
36
+ template.remove();
37
+ }
38
+ for (const slot of slotted) {
39
+ if (!slot.closest(this.tagName)?.isSameNode(this))
40
+ continue;
41
+ slots[slot.getAttribute("name") || "default"] = slot.innerHTML;
42
+ }
43
+ const props = this.hasAttribute("props") ? JSON.parse(this.getAttribute("props"), reviver) : {};
44
+ this.hydrator(this)(this.Component, props, slots, {
45
+ client: this.getAttribute("client")
46
+ });
47
+ this.removeAttribute("ssr");
48
+ window.removeEventListener("astro:hydrate", this.hydrate);
49
+ window.dispatchEvent(new CustomEvent("astro:hydrate"));
50
+ };
51
+ }
52
+ connectedCallback() {
53
+ if (!this.hasAttribute("await-children") || this.firstChild) {
54
+ this.childrenConnectedCallback();
55
+ } else {
56
+ new MutationObserver((_, mo) => {
57
+ mo.disconnect();
58
+ this.childrenConnectedCallback();
59
+ }).observe(this, { childList: true });
60
+ }
61
+ }
62
+ async childrenConnectedCallback() {
63
+ window.addEventListener("astro:hydrate", this.hydrate);
64
+ await import(this.getAttribute("before-hydration-url"));
65
+ const opts = JSON.parse(this.getAttribute("opts"));
66
+ Astro[this.getAttribute("client")](
67
+ async () => {
68
+ const rendererUrl = this.getAttribute("renderer-url");
69
+ const [componentModule, { default: hydrator }] = await Promise.all([
70
+ import(this.getAttribute("component-url")),
71
+ rendererUrl ? import(rendererUrl) : () => () => {
72
+ }
73
+ ]);
74
+ this.Component = componentModule[this.getAttribute("component-export") || "default"];
75
+ this.hydrator = hydrator;
76
+ return this.hydrate;
77
+ },
78
+ opts,
79
+ this
80
+ );
81
+ }
82
+ attributeChangedCallback() {
83
+ if (this.hydrator)
84
+ this.hydrate();
85
+ }
86
+ }, _a.observedAttributes = ["props"], _a)
87
+ );
88
+ }
89
+ }`;
2
90
  export {
3
91
  astro_island_prebuilt_default as default
4
92
  };
@@ -67,7 +67,7 @@ function extractDirectives(inputProps) {
67
67
  return extracted;
68
68
  }
69
69
  async function generateHydrateScript(scriptOptions, metadata) {
70
- const { renderer, result, astroId, props } = scriptOptions;
70
+ const { renderer, result, astroId, props, attrs } = scriptOptions;
71
71
  const { hydrate, componentUrl, componentExport } = metadata;
72
72
  if (!componentExport) {
73
73
  throw new Error(
@@ -80,6 +80,11 @@ async function generateHydrateScript(scriptOptions, metadata) {
80
80
  uid: astroId
81
81
  }
82
82
  };
83
+ if (attrs) {
84
+ for (const [key, value] of Object.entries(attrs)) {
85
+ island.props[key] = value;
86
+ }
87
+ }
83
88
  island.props["component-url"] = await result.resolve(componentUrl);
84
89
  if (renderer.clientEntrypoint) {
85
90
  island.props["component-export"] = componentExport.value;
@@ -77,6 +77,7 @@ Did you forget to import the component or is it possible there is a typo?`
77
77
  const metadata = { displayName };
78
78
  const { hydration, isPage, props } = extractDirectives(_props);
79
79
  let html = "";
80
+ let attrs = void 0;
80
81
  if (hydration) {
81
82
  metadata.hydrate = hydration.directive;
82
83
  metadata.hydrateArgs = hydration.value;
@@ -164,7 +165,7 @@ but ${plural ? "none were" : "it was not"} able to server-side render ${metadata
164
165
  Did you mean to enable ${formatList(probableRendererNames.map((r) => "`" + r + "`"))}?`);
165
166
  } else if (matchingRenderers.length === 1) {
166
167
  renderer = matchingRenderers[0];
167
- ({ html } = await renderer.ssr.renderToStaticMarkup.call(
168
+ ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
168
169
  { result },
169
170
  Component,
170
171
  props,
@@ -189,7 +190,7 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr
189
190
  if (metadata.hydrate === "only") {
190
191
  html = await renderSlot(result, slots == null ? void 0 : slots.fallback);
191
192
  } else {
192
- ({ html } = await renderer.ssr.renderToStaticMarkup.call(
193
+ ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
193
194
  { result },
194
195
  Component,
195
196
  props,
@@ -229,7 +230,7 @@ ${serializeProps(
229
230
  )}`
230
231
  );
231
232
  const island = await generateHydrateScript(
232
- { renderer, result, astroId, props },
233
+ { renderer, result, astroId, props, attrs },
233
234
  metadata
234
235
  );
235
236
  let unrenderedSlots = [];
@@ -917,6 +917,7 @@ export interface SSRLoadedRenderer extends AstroRenderer {
917
917
  check: AsyncRendererComponentFn<boolean>;
918
918
  renderToStaticMarkup: AsyncRendererComponentFn<{
919
919
  html: string;
920
+ attrs?: Record<string, string>;
920
921
  }>;
921
922
  };
922
923
  }
@@ -1,10 +1,11 @@
1
1
  /// <reference types="node" />
2
+ import type { RouteData } from '../../@types/astro';
2
3
  import type { SSRManifest } from './types';
3
4
  import { IncomingMessage } from 'http';
4
- import { App } from './index.js';
5
+ import { App, MatchOptions } from './index.js';
5
6
  export declare class NodeApp extends App {
6
- match(req: IncomingMessage | Request): import("../../@types/astro").RouteData | undefined;
7
- render(req: IncomingMessage | Request): Promise<Response>;
7
+ match(req: IncomingMessage | Request, opts?: MatchOptions): RouteData | undefined;
8
+ render(req: IncomingMessage | Request, routeData?: RouteData): Promise<Response>;
8
9
  }
9
10
  export declare function loadManifest(rootFolder: URL): Promise<SSRManifest>;
10
11
  export declare function loadApp(rootFolder: URL): Promise<NodeApp>;
@@ -1,16 +1,10 @@
1
- import type { ViteDevServer } from 'vite';
2
1
  import type { AstroConfig, ManifestData } from '../../@types/astro';
3
2
  import type { LogOptions } from '../logger/core';
4
3
  import type { AllPagesData } from './types';
5
- import { RouteCache } from '../render/route-cache.js';
6
4
  export interface CollectPagesDataOptions {
7
5
  astroConfig: AstroConfig;
8
6
  logging: LogOptions;
9
7
  manifest: ManifestData;
10
- origin: string;
11
- routeCache: RouteCache;
12
- viteServer: ViteDevServer;
13
- ssr: boolean;
14
8
  }
15
9
  export interface CollectPagesDataResult {
16
10
  assets: Record<string, string>;
@@ -22,8 +22,11 @@ export interface ErrorWithMetadata {
22
22
  };
23
23
  }
24
24
  export declare function cleanErrorStack(stack: string): string;
25
- /** Update the error message to correct any vite-isms that we don't want to expose to the user. */
26
- export declare function fixViteErrorMessage(_err: unknown, server: ViteDevServer, filePath?: URL): Error;
25
+ /**
26
+ * Update the error message to correct any vite-isms that we don't want to expose to the user.
27
+ * The `server` is required if the error may come from `server.ssrLoadModule()`.
28
+ */
29
+ export declare function fixViteErrorMessage(_err: unknown, server?: ViteDevServer, filePath?: URL): Error;
27
30
  export declare function createCustomViteLogger(logLevel: LogLevel): Logger;
28
31
  /**
29
32
  * Takes any error-like object and returns a standardized Error + metadata object.
@@ -1,4 +1,4 @@
1
- import type { ErrorPayload } from 'vite';
1
+ import type { ErrorPayload, ViteDevServer } from 'vite';
2
2
  import type { AstroConfig } from '../@types/astro';
3
3
  export declare const ASTRO_VERSION: string;
4
4
  /** Returns true if argument is an object of any prototype/class (but not null). */
@@ -41,3 +41,8 @@ export declare function isModeServerWithNoAdapter(config: AstroConfig): boolean;
41
41
  export declare function relativeToSrcDir(config: AstroConfig, idOrUrl: URL | string): string;
42
42
  export declare function emoji(char: string, fallback: string): string;
43
43
  export declare function getLocalAddress(serverAddress: string, host: string | boolean): string;
44
+ /**
45
+ * Simulate Vite's resolve and import analysis so we can import the id as an URL
46
+ * through a script tag or a dynamic import as-is.
47
+ */
48
+ export declare function resolveIdToUrl(viteServer: ViteDevServer, id: string): Promise<string>;
@@ -3,5 +3,5 @@
3
3
  * Do not edit this directly, but instead edit that file and rerun the prebuild
4
4
  * to generate this file.
5
5
  */
6
- declare const _default: "(self.Astro=self.Astro||{}).idle=a=>{const e=async()=>{await(await a())()};\"requestIdleCallback\"in window?window.requestIdleCallback(e):setTimeout(e,200)};";
6
+ declare const _default: "(self.Astro = self.Astro || {}).idle = (getHydrateCallback) => {\n const cb = async () => {\n let hydrate = await getHydrateCallback();\n await hydrate();\n };\n if (\"requestIdleCallback\" in window) {\n window.requestIdleCallback(cb);\n } else {\n setTimeout(cb, 200);\n }\n};";
7
7
  export default _default;
@@ -3,5 +3,5 @@
3
3
  * Do not edit this directly, but instead edit that file and rerun the prebuild
4
4
  * to generate this file.
5
5
  */
6
- declare const _default: "(self.Astro=self.Astro||{}).load=a=>{(async()=>await(await a())())()};";
6
+ declare const _default: "(self.Astro = self.Astro || {}).load = (getHydrateCallback) => {\n (async () => {\n let hydrate = await getHydrateCallback();\n await hydrate();\n })();\n};";
7
7
  export default _default;
@@ -3,5 +3,5 @@
3
3
  * Do not edit this directly, but instead edit that file and rerun the prebuild
4
4
  * to generate this file.
5
5
  */
6
- declare const _default: "(self.Astro=self.Astro||{}).media=(s,a)=>{const t=async()=>{await(await s())()};if(a.value){const e=matchMedia(a.value);e.matches?t():e.addEventListener(\"change\",t,{once:!0})}};";
6
+ declare const _default: "(self.Astro = self.Astro || {}).media = (getHydrateCallback, options) => {\n const cb = async () => {\n let hydrate = await getHydrateCallback();\n await hydrate();\n };\n if (options.value) {\n const mql = matchMedia(options.value);\n if (mql.matches) {\n cb();\n } else {\n mql.addEventListener(\"change\", cb, { once: true });\n }\n }\n};";
7
7
  export default _default;
@@ -3,5 +3,5 @@
3
3
  * Do not edit this directly, but instead edit that file and rerun the prebuild
4
4
  * to generate this file.
5
5
  */
6
- declare const _default: "(self.Astro=self.Astro||{}).only=a=>{(async()=>await(await a())())()};";
6
+ declare const _default: "(self.Astro = self.Astro || {}).only = (getHydrateCallback) => {\n (async () => {\n let hydrate = await getHydrateCallback();\n await hydrate();\n })();\n};";
7
7
  export default _default;
@@ -3,5 +3,5 @@
3
3
  * Do not edit this directly, but instead edit that file and rerun the prebuild
4
4
  * to generate this file.
5
5
  */
6
- declare const _default: "(self.Astro=self.Astro||{}).visible=(i,c,n)=>{const r=async()=>{await(await i())()};let s=new IntersectionObserver(e=>{for(const t of e)if(!!t.isIntersecting){s.disconnect(),r();break}});for(let e=0;e<n.children.length;e++){const t=n.children[e];s.observe(t)}};";
6
+ declare const _default: "(self.Astro = self.Astro || {}).visible = (getHydrateCallback, _opts, root) => {\n const cb = async () => {\n let hydrate = await getHydrateCallback();\n await hydrate();\n };\n let io = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n if (!entry.isIntersecting)\n continue;\n io.disconnect();\n cb();\n break;\n }\n });\n for (let i = 0; i < root.children.length; i++) {\n const child = root.children[i];\n io.observe(child);\n }\n};";
7
7
  export default _default;
@@ -3,5 +3,5 @@
3
3
  * Do not edit this directly, but instead edit that file and rerun the prebuild
4
4
  * to generate this file.
5
5
  */
6
- declare const _default: "var a;{const l={0:t=>t,1:t=>JSON.parse(t,n),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(JSON.parse(t,n)),5:t=>new Set(JSON.parse(t,n)),6:t=>BigInt(t),7:t=>new URL(t)},n=(t,r)=>{if(t===\"\"||!Array.isArray(r))return r;const[e,i]=r;return e in l?l[e](i):void 0};customElements.get(\"astro-island\")||customElements.define(\"astro-island\",(a=class extends HTMLElement{constructor(){super(...arguments);this.hydrate=()=>{if(!this.hydrator||this.parentElement?.closest(\"astro-island[ssr]\"))return;const r=this.querySelectorAll(\"astro-slot\"),e={},i=this.querySelectorAll(\"template[data-astro-template]\");for(const s of i)!s.closest(this.tagName)?.isSameNode(this)||(e[s.getAttribute(\"data-astro-template\")||\"default\"]=s.innerHTML,s.remove());for(const s of r)!s.closest(this.tagName)?.isSameNode(this)||(e[s.getAttribute(\"name\")||\"default\"]=s.innerHTML);const o=this.hasAttribute(\"props\")?JSON.parse(this.getAttribute(\"props\"),n):{};this.hydrator(this)(this.Component,o,e,{client:this.getAttribute(\"client\")}),this.removeAttribute(\"ssr\"),window.removeEventListener(\"astro:hydrate\",this.hydrate),window.dispatchEvent(new CustomEvent(\"astro:hydrate\"))}}connectedCallback(){!this.hasAttribute(\"await-children\")||this.firstChild?this.childrenConnectedCallback():new MutationObserver((r,e)=>{e.disconnect(),this.childrenConnectedCallback()}).observe(this,{childList:!0})}async childrenConnectedCallback(){window.addEventListener(\"astro:hydrate\",this.hydrate),await import(this.getAttribute(\"before-hydration-url\"));const r=JSON.parse(this.getAttribute(\"opts\"));Astro[this.getAttribute(\"client\")](async()=>{const e=this.getAttribute(\"renderer-url\"),[i,{default:o}]=await Promise.all([import(this.getAttribute(\"component-url\")),e?import(e):()=>()=>{}]);return this.Component=i[this.getAttribute(\"component-export\")||\"default\"],this.hydrator=o,this.hydrate},r,this)}attributeChangedCallback(){this.hydrator&&this.hydrate()}},a.observedAttributes=[\"props\"],a))}";
6
+ declare const _default: "var _a;\n{\n const propTypes = {\n 0: (value) => value,\n 1: (value) => JSON.parse(value, reviver),\n 2: (value) => new RegExp(value),\n 3: (value) => new Date(value),\n 4: (value) => new Map(JSON.parse(value, reviver)),\n 5: (value) => new Set(JSON.parse(value, reviver)),\n 6: (value) => BigInt(value),\n 7: (value) => new URL(value)\n };\n const reviver = (propKey, raw) => {\n if (propKey === \"\" || !Array.isArray(raw))\n return raw;\n const [type, value] = raw;\n return type in propTypes ? propTypes[type](value) : void 0;\n };\n if (!customElements.get(\"astro-island\")) {\n customElements.define(\n \"astro-island\",\n (_a = class extends HTMLElement {\n constructor() {\n super(...arguments);\n this.hydrate = () => {\n if (!this.hydrator || this.parentElement?.closest(\"astro-island[ssr]\")) {\n return;\n }\n const slotted = this.querySelectorAll(\"astro-slot\");\n const slots = {};\n const templates = this.querySelectorAll(\"template[data-astro-template]\");\n for (const template of templates) {\n if (!template.closest(this.tagName)?.isSameNode(this))\n continue;\n slots[template.getAttribute(\"data-astro-template\") || \"default\"] = template.innerHTML;\n template.remove();\n }\n for (const slot of slotted) {\n if (!slot.closest(this.tagName)?.isSameNode(this))\n continue;\n slots[slot.getAttribute(\"name\") || \"default\"] = slot.innerHTML;\n }\n const props = this.hasAttribute(\"props\") ? JSON.parse(this.getAttribute(\"props\"), reviver) : {};\n this.hydrator(this)(this.Component, props, slots, {\n client: this.getAttribute(\"client\")\n });\n this.removeAttribute(\"ssr\");\n window.removeEventListener(\"astro:hydrate\", this.hydrate);\n window.dispatchEvent(new CustomEvent(\"astro:hydrate\"));\n };\n }\n connectedCallback() {\n if (!this.hasAttribute(\"await-children\") || this.firstChild) {\n this.childrenConnectedCallback();\n } else {\n new MutationObserver((_, mo) => {\n mo.disconnect();\n this.childrenConnectedCallback();\n }).observe(this, { childList: true });\n }\n }\n async childrenConnectedCallback() {\n window.addEventListener(\"astro:hydrate\", this.hydrate);\n await import(this.getAttribute(\"before-hydration-url\"));\n const opts = JSON.parse(this.getAttribute(\"opts\"));\n Astro[this.getAttribute(\"client\")](\n async () => {\n const rendererUrl = this.getAttribute(\"renderer-url\");\n const [componentModule, { default: hydrator }] = await Promise.all([\n import(this.getAttribute(\"component-url\")),\n rendererUrl ? import(rendererUrl) : () => () => {\n }\n ]);\n this.Component = componentModule[this.getAttribute(\"component-export\") || \"default\"];\n this.hydrator = hydrator;\n return this.hydrate;\n },\n opts,\n this\n );\n }\n attributeChangedCallback() {\n if (this.hydrator)\n this.hydrate();\n }\n }, _a.observedAttributes = [\"props\"], _a)\n );\n }\n}";
7
7
  export default _default;
@@ -19,6 +19,7 @@ interface HydrateScriptOptions {
19
19
  result: SSRResult;
20
20
  astroId: string;
21
21
  props: Record<string | number, any>;
22
+ attrs: Record<string, string> | undefined;
22
23
  }
23
24
  /** For hydrated components, generate a <script type="module"> to load the component */
24
25
  export declare function generateHydrateScript(scriptOptions: HydrateScriptOptions, metadata: Required<AstroComponentMetadata>): Promise<SSRElement>;
@@ -11,3 +11,4 @@ export interface ParsedRequestResult {
11
11
  query: AstroQuery;
12
12
  }
13
13
  export declare function parseAstroRequest(id: string): ParsedRequestResult;
14
+ export declare function isAstroScript(id: string): boolean;
@@ -2,6 +2,7 @@ import { fileURLToPath } from "node:url";
2
2
  import { info } from "../core/logger/core.js";
3
3
  import * as msg from "../core/messages.js";
4
4
  import { invalidateCompilation, isCached } from "./compile.js";
5
+ import { isAstroScript } from "./query.js";
5
6
  async function trackCSSDependencies(opts) {
6
7
  const { viteDevServer, filename, deps, id } = opts;
7
8
  if (viteDevServer) {
@@ -29,7 +30,6 @@ const isPkgFile = (id) => {
29
30
  return (id == null ? void 0 : id.startsWith(fileURLToPath(PKG_PREFIX))) || (id == null ? void 0 : id.startsWith(PKG_PREFIX.pathname));
30
31
  };
31
32
  async function handleHotUpdate(ctx, { config, logging, compile }) {
32
- var _a;
33
33
  let isStyleOnlyChange = false;
34
34
  if (ctx.file.endsWith(".astro")) {
35
35
  const oldResult = await compile();
@@ -81,17 +81,25 @@ async function handleHotUpdate(ctx, { config, logging, compile }) {
81
81
  if (isStyleOnlyChange) {
82
82
  info(logging, "astro", msg.hmr({ file, style: true }));
83
83
  return mods.filter((mod) => {
84
- var _a2;
85
- return mod.id !== ctx.file && !((_a2 = mod.id) == null ? void 0 : _a2.endsWith(".ts"));
84
+ var _a;
85
+ return mod.id !== ctx.file && !((_a = mod.id) == null ? void 0 : _a.endsWith(".ts"));
86
86
  });
87
87
  }
88
88
  for (const mod of mods) {
89
89
  for (const imp of mod.importedModules) {
90
- if ((_a = imp.id) == null ? void 0 : _a.includes("?astro&type=script")) {
90
+ if (imp.id && isAstroScript(imp.id)) {
91
91
  mods.push(imp);
92
92
  }
93
93
  }
94
94
  }
95
+ for (const mod of filtered) {
96
+ if (mod.id && isAstroScript(mod.id) && mod.file) {
97
+ const astroMod = ctx.server.moduleGraph.getModuleById(mod.file);
98
+ if (astroMod) {
99
+ mods.unshift(astroMod);
100
+ }
101
+ }
102
+ }
95
103
  const isSelfAccepting = mods.every((m) => m.isSelfAccepting || m.url.endsWith(".svelte"));
96
104
  if (isSelfAccepting) {
97
105
  info(logging, "astro", msg.hmr({ file }));
@@ -294,7 +294,11 @@ ${source}
294
294
  pluginContext: this
295
295
  };
296
296
  const compile = () => cachedCompilation(compileProps);
297
- return handleHotUpdate.call(this, context, { config, logging, compile });
297
+ return handleHotUpdate.call(this, context, {
298
+ config,
299
+ logging,
300
+ compile
301
+ });
298
302
  }
299
303
  };
300
304
  }
@@ -18,6 +18,11 @@ function parseAstroRequest(id) {
18
18
  query
19
19
  };
20
20
  }
21
+ function isAstroScript(id) {
22
+ const parsed = parseAstroRequest(id);
23
+ return parsed.query.type === "script";
24
+ }
21
25
  export {
26
+ isAstroScript,
22
27
  parseAstroRequest
23
28
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Astro is a modern site builder with web best practices, performance, and DX front-of-mind.",
5
5
  "type": "module",
6
6
  "author": "withastro",
@@ -126,7 +126,7 @@
126
126
  "tsconfig-resolver": "^3.0.1",
127
127
  "unist-util-visit": "^4.1.0",
128
128
  "vfile": "^5.3.2",
129
- "vite": "3.0.4",
129
+ "vite": "3.0.5",
130
130
  "yargs-parser": "^21.0.1",
131
131
  "zod": "^3.17.3"
132
132
  },