vitral 0.10.0 → 0.11.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 (89) hide show
  1. package/dist/angular.d.ts +2 -2
  2. package/dist/angular.js +13 -10
  3. package/dist/auto.js +11 -8
  4. package/dist/{capture-A6JQNNQY.js → capture-2I5IQ2C2.js} +2 -1
  5. package/dist/{channel-2DUQQPPA.js → channel-ABGK26Q5.js} +5 -3
  6. package/dist/{chunk-WAU6OKK3.js → chunk-2SAI6S2H.js} +11 -3
  7. package/dist/chunk-2Z4OH3BP.js +85 -0
  8. package/dist/chunk-5O6XDJBR.js +15 -0
  9. package/dist/chunk-623K4UNS.js +70 -0
  10. package/dist/{chunk-VTGHPX4J.js → chunk-6JH2I65O.js} +15 -13
  11. package/dist/{chunk-FOEXP52G.js → chunk-7P5O3REI.js} +46 -15
  12. package/dist/{chunk-EVVYV5ED.js → chunk-AL6MLNVY.js} +49 -21
  13. package/dist/{chunk-CFJC4GRB.js → chunk-AQUQD3NA.js} +17 -8
  14. package/dist/chunk-B3PFMWZT.js +21 -0
  15. package/dist/{chunk-463H6B56.js → chunk-BQGVAXFM.js} +3 -4
  16. package/dist/{chunk-TW7KYJQ6.js → chunk-GGMM56TM.js} +1 -1
  17. package/dist/{chunk-SC2KF7GJ.js → chunk-IKCEA3YN.js} +3 -3
  18. package/dist/chunk-JWDDXX5O.js +6 -0
  19. package/dist/{chunk-B2MPYF4M.js → chunk-KCF46XOX.js} +4 -2
  20. package/dist/{chunk-R3HUMHNL.js → chunk-LDOSAAEF.js} +15 -0
  21. package/dist/{chunk-MGG5BW3U.js → chunk-MICF64AZ.js} +2 -2
  22. package/dist/{chunk-QINOFHG6.js → chunk-NQ6ZTGQZ.js} +2 -2
  23. package/dist/chunk-QQWE5J6U.js +37 -0
  24. package/dist/{chunk-5OM6KOCP.js → chunk-SOENZNXO.js} +52 -9
  25. package/dist/{chunk-VK6W7KHM.js → chunk-SPSAXBPR.js} +10 -6
  26. package/dist/{chunk-UYOPJ4XQ.js → chunk-UCFOXMOR.js} +1 -1
  27. package/dist/cli.js +119 -8
  28. package/dist/{contract-IXM52LVW.js → contract-3JY7SOGQ.js} +1 -1
  29. package/dist/{dedupe-SRAPOK3V.js → dedupe-M63VMCWA.js} +3 -1
  30. package/dist/edge.d.ts +4 -2
  31. package/dist/edge.js +69 -46
  32. package/dist/element.d.ts +2 -2
  33. package/dist/element.js +11 -8
  34. package/dist/embed.js +2 -2
  35. package/dist/{events-CWdYSrkz.d.ts → events-II6hXM3Q.d.ts} +1 -1
  36. package/dist/expose-2S3TCXSP.js +18 -0
  37. package/dist/federation.d.ts +1 -1
  38. package/dist/{hydrate-IVQNHOP3.js → hydrate-FJHHLW5G.js} +22 -12
  39. package/dist/iframe.js +15 -12
  40. package/dist/index.d.ts +6 -6
  41. package/dist/index.js +25 -11
  42. package/dist/{loader-CLRMRRFv.d.ts → loader-Bmul2-5T.d.ts} +1 -1
  43. package/dist/next-config.d.ts +30 -8
  44. package/dist/next-config.js +30 -18
  45. package/dist/next-host.d.ts +11 -5
  46. package/dist/next-host.js +65 -28
  47. package/dist/next-server.d.ts +56 -0
  48. package/dist/next-server.js +90 -0
  49. package/dist/next.d.ts +1 -1
  50. package/dist/preact.d.ts +4 -4
  51. package/dist/preact.js +10 -7
  52. package/dist/prefetch.d.ts +40 -3
  53. package/dist/prefetch.js +100 -30
  54. package/dist/react-server.d.ts +16 -5
  55. package/dist/react-server.js +8 -3
  56. package/dist/react.d.ts +20 -6
  57. package/dist/react.js +14 -9
  58. package/dist/{reframe-ZOQPW552.js → reframe-HIYA2TIU.js} +10 -9
  59. package/dist/route-4KQITYD4.js +138 -0
  60. package/dist/routes.d.ts +2 -2
  61. package/dist/routes.js +12 -9
  62. package/dist/{shadow-PZGQKUA4.js → shadow-7ZV4JEO6.js} +4 -3
  63. package/dist/sign.d.ts +49 -0
  64. package/dist/sign.js +15 -0
  65. package/dist/single-spa.d.ts +1 -1
  66. package/dist/{slot-DRYmGvvV.d.ts → slot--WLgdcW_.d.ts} +1 -1
  67. package/dist/snapshot.d.ts +6 -0
  68. package/dist/snapshot.js +125 -0
  69. package/dist/solid.d.ts +3 -3
  70. package/dist/solid.js +10 -7
  71. package/dist/sri-AMQOKKWR.js +17 -0
  72. package/dist/ssr-markup-BCPpGmss.d.ts +13 -0
  73. package/dist/state-B1FJi8I9.d.ts +14 -0
  74. package/dist/svelte.d.ts +4 -4
  75. package/dist/svelte.js +10 -7
  76. package/dist/sw.d.ts +48 -1
  77. package/dist/sw.js +79 -2
  78. package/dist/testing.d.ts +2 -2
  79. package/dist/testing.js +10 -7
  80. package/dist/{types-g8WEVD_b.d.ts → types-DJautV-K.d.ts} +86 -1
  81. package/dist/vitals.js +2 -1
  82. package/dist/vite.d.ts +4 -2
  83. package/dist/vite.js +63 -13
  84. package/dist/vue.d.ts +3 -3
  85. package/dist/vue.js +12 -9
  86. package/package.json +37 -19
  87. package/dist/expose-BA4HSXDP.js +0 -17
  88. package/dist/sri-LQBLQMG5.js +0 -14
  89. package/dist/state-BDdCwc21.d.ts +0 -4
package/dist/next-host.js CHANGED
@@ -1,41 +1,65 @@
1
1
  "use client";
2
- import {
3
- dedupe_exports
4
- } from "./chunk-R3HUMHNL.js";
5
2
  import {
6
3
  sri_exports
7
- } from "./chunk-VK6W7KHM.js";
4
+ } from "./chunk-SPSAXBPR.js";
5
+ import {
6
+ dedupe_exports
7
+ } from "./chunk-LDOSAAEF.js";
8
8
  import {
9
9
  Remote,
10
10
  preload
11
- } from "./chunk-FOEXP52G.js";
12
- import "./chunk-B2MPYF4M.js";
13
- import "./chunk-UYOPJ4XQ.js";
14
- import "./chunk-4E33RZMM.js";
15
- import "./chunk-WAU6OKK3.js";
16
- import "./chunk-VTGHPX4J.js";
17
- import "./chunk-EQZOJU3B.js";
11
+ } from "./chunk-7P5O3REI.js";
12
+ import "./chunk-KCF46XOX.js";
13
+ import "./chunk-UCFOXMOR.js";
14
+ import {
15
+ hintsOf
16
+ } from "./chunk-QQWE5J6U.js";
17
+ import "./chunk-5O6XDJBR.js";
18
+ import "./chunk-2SAI6S2H.js";
19
+ import "./chunk-6JH2I65O.js";
18
20
  import {
19
- configure
20
- } from "./chunk-EVVYV5ED.js";
21
+ configure,
22
+ policy,
23
+ register
24
+ } from "./chunk-AL6MLNVY.js";
21
25
  import {
22
26
  bundled
23
- } from "./chunk-MGG5BW3U.js";
24
- import "./chunk-SC2KF7GJ.js";
25
- import "./chunk-TW7KYJQ6.js";
26
- import "./chunk-463H6B56.js";
27
+ } from "./chunk-MICF64AZ.js";
28
+ import "./chunk-IKCEA3YN.js";
29
+ import "./chunk-GGMM56TM.js";
30
+ import "./chunk-BQGVAXFM.js";
31
+ import "./chunk-JWDDXX5O.js";
32
+ import "./chunk-2Z4OH3BP.js";
33
+ import "./chunk-4E33RZMM.js";
34
+ import "./chunk-EQZOJU3B.js";
27
35
  import "./chunk-GNPFWISJ.js";
28
36
  import "./chunk-MLKGABMK.js";
29
37
 
30
38
  // src/next-host.tsx
31
39
  import Head from "next/head";
32
40
  import Router, { useRouter } from "next/router";
33
- import { createElement, Fragment, useEffect, useMemo } from "react";
34
- import { remotes, shared } from "vitral-next-host-config";
41
+ import { createElement, Fragment, useEffect, useMemo, version as reactVersion } from "react";
42
+ import { plan, remotes, shared } from "vitral-next-host-config";
35
43
  var under = (path, prefix) => path === prefix || path.startsWith(prefix + "/");
36
44
  function remoteFor(path) {
37
45
  for (const [name, r] of Object.entries(remotes)) if (under(path, r.basePath) || r.routes?.some((x) => under(path, x.public))) return name;
38
46
  }
47
+ var offered = () => ({ react: reactVersion, ...Object.fromEntries(Object.entries(shared).map(([k, g]) => [k, g.version])) });
48
+ var offers = Object.fromEntries(
49
+ Object.entries(shared).map(([k, g]) => {
50
+ let p;
51
+ return [k, typeof g.modules === "function" ? { ...g, modules: () => p ??= g.modules().catch((e) => (p = void 0, Promise.reject(e))) } : g];
52
+ })
53
+ );
54
+ function warmOffers(path) {
55
+ const name = remoteFor(path);
56
+ if (!name) return;
57
+ const m = window.__NEXT_DATA__?.props?.pageProps?.vitral?.[name];
58
+ const list = m ? hintsOf(m, remotes[name].url, offered()).offers : remotes[name].hints?.offers;
59
+ for (const g of list ?? []) offers[g]?.modules().catch(() => {
60
+ });
61
+ }
62
+ if (typeof window !== "undefined") warmOffers(location.pathname);
39
63
  var configured = false;
40
64
  function setup() {
41
65
  if (configured || typeof window === "undefined") return;
@@ -43,8 +67,10 @@ function setup() {
43
67
  bundled.sri = sri_exports;
44
68
  bundled.dedupe = dedupe_exports;
45
69
  configure({
46
- remotes: Object.fromEntries(Object.entries(remotes).map(([name, r]) => [name, { url: r.url, ...r.integrity === false && { integrity: false } }])),
47
- dedupe: shared
70
+ remotes: Object.fromEntries(Object.entries(remotes).map(([name, r]) => [name, { url: r.url, ...r.integrity === false && { integrity: false }, ...r.keys && { keys: r.keys } }])),
71
+ dedupe: offers,
72
+ // Uma cópia de cada dependência para todos os remotes, escolhida no build.
73
+ ...plan && Object.keys(plan).length && { dedupePlan: plan }
48
74
  });
49
75
  }
50
76
  function interceptNavigation() {
@@ -90,8 +116,9 @@ function VitralNext() {
90
116
  const go = (name) => preload(name, { routes: !!remotes[name].warmRoutes });
91
117
  if (here) go(here);
92
118
  const idle = [];
119
+ const all = policy() === "all";
93
120
  for (const [name, r] of Object.entries(remotes))
94
- if (name !== here && (r.preload ?? "idle") === "idle")
121
+ if (all && name !== here && (r.preload ?? "idle") === "idle")
95
122
  idle.push(typeof requestIdleCallback === "function" ? requestIdleCallback(() => go(name), { timeout: 5e3 }) : window.setTimeout(() => go(name), 2e3));
96
123
  const stop = interceptNavigation();
97
124
  return () => {
@@ -101,27 +128,37 @@ function VitralNext() {
101
128
  }, []);
102
129
  return null;
103
130
  }
131
+ var seeded = /* @__PURE__ */ new Map();
132
+ function seed(name, m) {
133
+ const r = remotes[name];
134
+ if (!r || typeof window === "undefined" || seeded.get(name) === m) return;
135
+ seeded.set(name, m);
136
+ register(name, { url: r.url, manifest: m, ...r.integrity === false && { integrity: false }, ...r.keys && { keys: r.keys } });
137
+ }
104
138
  var push = (url, options) => void Router.push(url, void 0, options);
105
139
  var replace = (url, options) => void Router.replace(url, void 0, options);
106
- function hints(name, shadow) {
107
- const h = remotes[name]?.hints;
140
+ function hints(h, shadow) {
108
141
  if (!h) return null;
109
- const link = (as, [href, integrity]) => createElement("link", { key: `vitral:${href}`, rel: "preload", as, href, crossOrigin: "anonymous", ...integrity && { integrity } });
142
+ const link = (as, [href, integrity, fetchPriority]) => createElement("link", { key: `vitral:${href}`, rel: "preload", as, href, crossOrigin: "anonymous", ...integrity && { integrity }, ...fetchPriority && { fetchPriority } });
110
143
  return createElement(
111
144
  Head,
112
145
  null,
113
- link("fetch", [h.manifest]),
146
+ ...h.manifest ? [link("fetch", [h.manifest, h.signed])] : [],
114
147
  ...shadow ? [] : h.css.map((c) => link("style", c)),
115
148
  ...h.js.map((j) => link("script", j))
116
149
  );
117
150
  }
118
- function NextRemote({ name, props, fallback = null, ...rest }) {
151
+ function NextRemote({ name, props, fallback = null, manifest, ...rest }) {
119
152
  setup();
153
+ if (manifest) seed(name, manifest);
120
154
  const router = useRouter();
121
155
  const r = remotes[name];
122
156
  const host = useMemo(() => ({ asPath: router.asPath, basePath: r?.basePath, routes: r?.routes, push, replace, events: Router.events }), [router.asPath, r]);
123
157
  const all = useMemo(() => ({ ...props, __next: host }), [props, host]);
124
- const links = useMemo(() => hints(name, rest.isolate === "shadow"), [name, rest.isolate]);
158
+ const links = useMemo(() => {
159
+ const h = manifest && r ? hintsOf(manifest, r.url, offered(), r.integrity, r.keys) : r?.hints;
160
+ return hints(manifest && h ? { ...h, manifest: "" } : h, rest.isolate === "shadow");
161
+ }, [manifest, r, rest.isolate]);
125
162
  return createElement(Fragment, null, links, router.isReady ? createElement(Remote, { ...rest, name, fallback, props: all }) : fallback);
126
163
  }
127
164
  export {
@@ -0,0 +1,56 @@
1
+ import { S as ServerRendered } from './ssr-markup-BCPpGmss.js';
2
+ import { P as Props, d as RemoteManifest } from './types-DJautV-K.js';
3
+ import './errors-kjBv6IH_.js';
4
+
5
+ /** SSR de um remote na página do host: o `render` do servidor do remote e as props. */
6
+ interface RemoteSsr {
7
+ /** O `render` que o remote exporta para o servidor (`reactRender` de `vitral/react-server`). */
8
+ render: (props: Props) => ServerRendered | Promise<ServerRendered>;
9
+ /** As mesmas props que a página passa ao `NextRemote`. */
10
+ props?: Props;
11
+ }
12
+ interface RemotePropsOptions {
13
+ /** Segundos em que o manifesto guardado vale sem pedir de novo. Padrão 5. */
14
+ maxAge?: number;
15
+ /**
16
+ * Segundos a mais em que o manifesto guardado ainda serve, enquanto um
17
+ * pedido novo corre por trás. Padrão 30.
18
+ */
19
+ staleWhileRevalidate?: number;
20
+ /**
21
+ * Origem para o `url` relativo do remote (`/delivery-remote/vitral.json`).
22
+ * Padrão: `VITRAL_ORIGIN` do ambiente, ou o próprio servidor Next em
23
+ * `http://127.0.0.1:$PORT`. O header `Host` da requisição nunca é usado: um
24
+ * cliente poderia apontar o servidor para outra máquina.
25
+ */
26
+ origin?: string;
27
+ /** Tempo máximo do pedido, em ms. Padrão 3000. Vale também para o `render` do SSR. */
28
+ timeout?: number;
29
+ fetch?: typeof fetch;
30
+ /**
31
+ * SSR por remote. O HTML vai em `vitralSsr[nome]`, para o `ssr` do
32
+ * `NextRemote`. Sem o manifesto, com erro ou depois de `timeout`, `null`, e
33
+ * a página monta no navegador como antes.
34
+ */
35
+ ssr?: Record<string, RemoteSsr>;
36
+ }
37
+ /** Esvazia o cache (testes). */
38
+ declare function clearRemoteCache(): void;
39
+ /**
40
+ * O manifesto do remote `name`, com cache em memória: dentro de `maxAge`
41
+ * responde do cache; até `maxAge + staleWhileRevalidate`, responde do cache e
42
+ * renova por trás; depois disso, espera o pedido novo. Um pedido que falha
43
+ * não apaga a cópia boa que já estava guardada.
44
+ */
45
+ declare function remoteManifest(name: string, o?: RemotePropsOptions): Promise<RemoteManifest | null>;
46
+ /**
47
+ * Props para a página do remote: `{ vitral: { [name]: manifesto | null } }`.
48
+ * Passe `vitral[name]` ao `NextRemote` em `manifest`. Com `ssr`, também
49
+ * `vitralSsr: { [name]: html | null }`, para o `ssr` do `NextRemote`.
50
+ */
51
+ declare function remoteProps(names: string | string[], o?: RemotePropsOptions): Promise<{
52
+ vitral: Record<string, RemoteManifest | null>;
53
+ vitralSsr?: Record<string, string | null>;
54
+ }>;
55
+
56
+ export { type RemotePropsOptions, type RemoteSsr, clearRemoteCache, remoteManifest, remoteProps };
@@ -0,0 +1,90 @@
1
+ import {
2
+ ssrHolder
3
+ } from "./chunk-B3PFMWZT.js";
4
+ import "./chunk-MLKGABMK.js";
5
+
6
+ // src/next-server.ts
7
+ import { remotes } from "vitral-next-host-config";
8
+ var cache = /* @__PURE__ */ new Map();
9
+ function clearRemoteCache() {
10
+ cache.clear();
11
+ }
12
+ function absolute(url, origin) {
13
+ if (/^https?:\/\//.test(url)) return url;
14
+ const base = origin ?? process.env.VITRAL_ORIGIN ?? `http://127.0.0.1:${process.env.PORT ?? 3e3}`;
15
+ return new URL(url, base.endsWith("/") ? base : base + "/").href;
16
+ }
17
+ async function get(url, o, keys) {
18
+ const f = o.fetch ?? fetch;
19
+ try {
20
+ const res = await f(url, { signal: AbortSignal.timeout(o.timeout ?? 3e3), headers: { accept: "application/json" } });
21
+ if (!res.ok) return null;
22
+ const body = new Uint8Array(await res.arrayBuffer());
23
+ if (keys?.length && !(await import("./sign.js")).verifyBody(body, res.headers, keys)) {
24
+ console.error(`[vitral] a assinatura do manifesto em ${url} n\xE3o confere com keys`);
25
+ return null;
26
+ }
27
+ const m = JSON.parse(new TextDecoder().decode(body));
28
+ return typeof m?.entry === "string" ? m : null;
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+ async function remoteManifest(name, o = {}) {
34
+ const r = remotes[name];
35
+ if (!r) throw new Error(`[vitral] remote ${name} n\xE3o est\xE1 no withVitral`);
36
+ const url = absolute(r.url, o.origin);
37
+ const now = Date.now();
38
+ const fresh = (o.maxAge ?? 5) * 1e3;
39
+ const stale = fresh + (o.staleWhileRevalidate ?? 30) * 1e3;
40
+ const c = cache.get(url);
41
+ const renew = () => {
42
+ const entry = cache.get(url) ?? { at: 0, m: null };
43
+ entry.pending ??= get(url, o, r.keys).then((m) => {
44
+ cache.set(url, m ? { at: Date.now(), m } : { ...entry, pending: void 0 });
45
+ return m ?? entry.m;
46
+ });
47
+ cache.set(url, entry);
48
+ return entry.pending;
49
+ };
50
+ if (c?.m && now - c.at < fresh) return c.m;
51
+ if (c?.m && now - c.at < stale) {
52
+ void renew();
53
+ return c.m;
54
+ }
55
+ return renew();
56
+ }
57
+ async function remoteProps(names, o = {}) {
58
+ const list = Array.isArray(names) ? names : [names];
59
+ const found = await Promise.all(list.map((n) => remoteManifest(n, o)));
60
+ const vitral = Object.fromEntries(list.map((n, i) => [n, found[i]]));
61
+ if (!o.ssr) return { vitral };
62
+ const ssr = o.ssr;
63
+ const html = await Promise.all(list.map((n, i) => ssr[n] && found[i] ? renderRemote(n, found[i], ssr[n], o.timeout ?? 3e3) : null));
64
+ return { vitral, vitralSsr: Object.fromEntries(list.map((n, i) => [n, html[i]])) };
65
+ }
66
+ async function renderRemote(name, m, s, timeout) {
67
+ let timer;
68
+ try {
69
+ const rendered = await Promise.race([
70
+ Promise.resolve(s.render(s.props ?? {})),
71
+ new Promise((_, no) => timer = setTimeout(no, timeout, new Error(`render demorou mais de ${timeout} ms`)))
72
+ ]);
73
+ const base = new URL(remotes[name].url, "http://host.invalid/");
74
+ const at = (f) => {
75
+ const u = new URL(f, base);
76
+ return u.origin === "http://host.invalid" ? u.pathname + u.search : u.href;
77
+ };
78
+ return ssrHolder(name, m, rendered, (m.css ?? []).map((f) => [at(f), m.files?.[f]]));
79
+ } catch (e) {
80
+ console.error(`[vitral] SSR do remote ${name} falhou; a p\xE1gina monta no navegador.`, e);
81
+ return null;
82
+ } finally {
83
+ clearTimeout(timer);
84
+ }
85
+ }
86
+ export {
87
+ clearRemoteCache,
88
+ remoteManifest,
89
+ remoteProps
90
+ };
package/dist/next.d.ts CHANGED
@@ -118,7 +118,7 @@ type ImageProps = Omit<ImgHTMLAttributes<HTMLImageElement>, 'src' | 'width' | 'h
118
118
  }) => string;
119
119
  onLoadingComplete?: (img: HTMLImageElement) => void;
120
120
  };
121
- declare const Image: react.ForwardRefExoticComponent<Omit<ImgHTMLAttributes<HTMLImageElement>, "height" | "width" | "loading" | "src"> & {
121
+ declare const Image: react.ForwardRefExoticComponent<Omit<ImgHTMLAttributes<HTMLImageElement>, "loading" | "src" | "width" | "height"> & {
122
122
  src: string | StaticImage;
123
123
  alt: string;
124
124
  width?: number | string;
package/dist/preact.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import * as preact from 'preact';
2
2
  import { VNode, ComponentType } from 'preact';
3
- import { P as Props, I as Isolation, C as CheckedProps, a as RemoteModule, S as Shared } from './types-g8WEVD_b.js';
4
- export { R as RemoteContext } from './types-g8WEVD_b.js';
3
+ import { P as Props, I as Isolation, C as CheckedProps, a as RemoteModule, S as Shared } from './types-DJautV-K.js';
4
+ export { R as RemoteContext } from './types-DJautV-K.js';
5
5
  import { R as RemoteError } from './errors-kjBv6IH_.js';
6
- import { S as SlotStatus } from './slot-DRYmGvvV.js';
7
- export { e as events } from './events-CWdYSrkz.js';
6
+ import { S as SlotStatus } from './slot--WLgdcW_.js';
7
+ export { e as events } from './events-II6hXM3Q.js';
8
8
  export { n as navigate } from './navigate-BRG1WJUM.js';
9
9
  import { L as Loading, P as Prefetch } from './host-slot-Cz6EiGsB.js';
10
10
 
package/dist/preact.js CHANGED
@@ -1,21 +1,24 @@
1
1
  import {
2
2
  hostSlot
3
- } from "./chunk-WAU6OKK3.js";
3
+ } from "./chunk-2SAI6S2H.js";
4
4
  import {
5
5
  defineRemote,
6
6
  memoSelect,
7
7
  same,
8
8
  shared
9
- } from "./chunk-VTGHPX4J.js";
9
+ } from "./chunk-6JH2I65O.js";
10
+ import "./chunk-AL6MLNVY.js";
11
+ import "./chunk-MICF64AZ.js";
12
+ import "./chunk-IKCEA3YN.js";
13
+ import "./chunk-GGMM56TM.js";
14
+ import "./chunk-BQGVAXFM.js";
15
+ import "./chunk-JWDDXX5O.js";
16
+ import "./chunk-2Z4OH3BP.js";
17
+ import "./chunk-4E33RZMM.js";
10
18
  import {
11
19
  events,
12
20
  navigate
13
21
  } from "./chunk-EQZOJU3B.js";
14
- import "./chunk-EVVYV5ED.js";
15
- import "./chunk-MGG5BW3U.js";
16
- import "./chunk-SC2KF7GJ.js";
17
- import "./chunk-TW7KYJQ6.js";
18
- import "./chunk-463H6B56.js";
19
22
  import "./chunk-GNPFWISJ.js";
20
23
  import "./chunk-MLKGABMK.js";
21
24
 
@@ -1,8 +1,36 @@
1
+ /**
2
+ * Transições da população (dados agregados de muitos usuários), no mesmo
3
+ * formato: ajuda na primeira visita, quando o usuário ainda não tem contagens.
4
+ */
5
+ interface Prior {
6
+ t: Record<string, Record<string, number>>;
7
+ r?: Record<string, string[]>;
8
+ }
9
+
1
10
  interface PrefetchOptions {
2
- /** Probabilidade mínima da rota seguinte para baixar os remotes dela. Padrão: 0.4. */
11
+ /** Probabilidade mínima da rota seguinte, antes da conta de custo. Padrão: 0.1. */
3
12
  threshold?: number;
4
- /** Transições contadas a partir da rota atual antes de prever. Padrão: 2. */
13
+ /** Transições contadas a partir da rota atual (ou do contexto) antes de prever. Padrão: 2. */
5
14
  min?: number;
15
+ /**
16
+ * Transições da população, para a primeira visita: o objeto ou a URL do
17
+ * JSON (`vitral prior` gera a partir de sessões agregadas). Mistura com as
18
+ * contagens do usuário: usuário + `alpha` × população.
19
+ */
20
+ prior?: Prior | string;
21
+ /** Peso da população, em transições. Padrão: 5. */
22
+ alpha?: number;
23
+ /**
24
+ * Custo de cada byte baixado à toa, em ms de espera do usuário. Prefetch só
25
+ * quando probabilidade × tempo poupado > custo × bytes. Padrão: 0.0005
26
+ * (100 kB valem 50 ms). `0` desliga a conta.
27
+ */
28
+ byteCost?: number;
29
+ /**
30
+ * Speculation Rules (Chrome 121+) para a rota prevista quando ela não tem
31
+ * remote: o navegador baixa o documento dela. Só com a chave padrão (`pathname`). Padrão: false.
32
+ */
33
+ speculate?: boolean;
6
34
  /** Onde guardar as contagens. `null` guarda só na memória. Padrão: localStorage. */
7
35
  storage?: Pick<Storage, 'getItem' | 'setItem'> | null;
8
36
  /** Chave da rota. Padrão: `url.pathname`. */
@@ -15,6 +43,15 @@ interface PrefetchOptions {
15
43
  * função que para tudo (as contagens continuam guardadas).
16
44
  */
17
45
  declare function prefetch(options?: PrefetchOptions): () => void;
46
+ /**
47
+ * Vale baixar agora? Probabilidade × tempo poupado (duas idas e voltas e o
48
+ * download, pela rede estimada pelo navegador) contra o custo dos bytes
49
+ * (Padmanabhan e Mogul, 1996).
50
+ */
51
+ declare function worth(p: number, bytes: number, byteCost?: number, net?: {
52
+ rtt?: number;
53
+ downlink?: number;
54
+ } | undefined): boolean;
18
55
  /**
19
56
  * Baixa o manifesto e os arquivos de um remote sem executar nada. Com
20
57
  * integrity, pelo mesmo caminho de SRI que a montagem vai usar. Devolve
@@ -22,4 +59,4 @@ declare function prefetch(options?: PrefetchOptions): () => void;
22
59
  */
23
60
  declare function warm(name: string): Promise<boolean>;
24
61
 
25
- export { type PrefetchOptions, prefetch, warm };
62
+ export { type PrefetchOptions, prefetch, warm, worth };
package/dist/prefetch.js CHANGED
@@ -1,19 +1,22 @@
1
1
  import {
2
+ policy,
2
3
  resolveEntry
3
- } from "./chunk-EVVYV5ED.js";
4
- import "./chunk-MGG5BW3U.js";
5
- import "./chunk-SC2KF7GJ.js";
4
+ } from "./chunk-AL6MLNVY.js";
5
+ import "./chunk-MICF64AZ.js";
6
+ import "./chunk-IKCEA3YN.js";
6
7
  import {
7
8
  addLink
8
- } from "./chunk-TW7KYJQ6.js";
9
- import "./chunk-463H6B56.js";
9
+ } from "./chunk-GGMM56TM.js";
10
+ import "./chunk-BQGVAXFM.js";
11
+ import "./chunk-JWDDXX5O.js";
10
12
  import {
11
13
  protocol
12
14
  } from "./chunk-GNPFWISJ.js";
13
15
  import "./chunk-MLKGABMK.js";
14
16
 
15
17
  // src/core/markov.ts
16
- var LIMITS = { routes: 50, next: 10, remotes: 8, total: 1e3, key: 200 };
18
+ var LIMITS = { routes: 150, next: 10, remotes: 8, total: 1e3, key: 200 };
19
+ var own = (o, k) => o && Object.prototype.hasOwnProperty.call(o, k) ? o[k] : void 0;
17
20
  var ok = (k) => typeof k === "string" && k.length <= LIMITS.key && k !== "__proto__";
18
21
  var sum = (row) => Object.values(row).reduce((a, b) => a + b, 0);
19
22
  var smallest = (o, keep) => Object.keys(o).filter((k) => k !== keep).reduce((min, k) => min === void 0 || o[k] < o[min] ? k : min, void 0);
@@ -23,6 +26,7 @@ function parse(text) {
23
26
  const c = JSON.parse(text ?? "");
24
27
  const rows = Object.values(c.t).every((row) => row && typeof row === "object" && Object.values(row).every((n) => Number.isFinite(n)));
25
28
  const lists = Object.values(c.r).every((l) => Array.isArray(l) && l.every((n) => typeof n === "string"));
29
+ if (c.b && !Object.values(c.b).every((n) => Number.isFinite(n))) delete c.b;
26
30
  if (rows && lists) return c;
27
31
  } catch {
28
32
  }
@@ -51,26 +55,44 @@ function remember(c, route, remote) {
51
55
  if (routes.length > LIMITS.routes) delete c.r[routes.find((k) => k !== route)];
52
56
  return true;
53
57
  }
54
- function predict(c, from, threshold, min = 1) {
55
- const row = Object.prototype.hasOwnProperty.call(c.t, from) ? c.t[from] : void 0;
56
- if (!row) return null;
57
- const total = sum(row);
58
- let best = null;
59
- for (const k in row) if (best === null || row[k] > row[best]) best = k;
60
- return best !== null && total >= min && row[best] / total >= threshold ? best : null;
58
+ function recordPath(c, history, to, orders = 3) {
59
+ if (history[history.length - 1] === to) return;
60
+ for (let k = 1; k <= orders && k <= history.length; k++) record(c, history.slice(-k).join("\n"), to);
61
+ }
62
+ function predictNext(c, history, o = {}) {
63
+ const { threshold = 0, min = 2, prior, alpha = 5, orders = 3 } = o;
64
+ for (let k = Math.min(orders, history.length); k >= 1; k--) {
65
+ const key = history.slice(-k).join("\n");
66
+ const row = own(c.t, key) ?? {};
67
+ const pop = k === 1 ? own(prior?.t, key) : void 0;
68
+ const n = sum(row);
69
+ const total = pop ? sum(pop) : 0;
70
+ if (n < min && !total) continue;
71
+ const a = total ? alpha : 0;
72
+ let best = null;
73
+ let bp = 0;
74
+ for (const to of /* @__PURE__ */ new Set([...Object.keys(row), ...Object.keys(pop ?? {})])) {
75
+ if (!ok(to)) continue;
76
+ const p = ((own(row, to) ?? 0) + a * (own(pop, to) ?? 0) / (total || 1)) / (n + a);
77
+ if (p > bp) best = to, bp = p;
78
+ }
79
+ if (best !== null && bp >= threshold) return { to: best, p: bp };
80
+ }
81
+ return null;
61
82
  }
62
83
 
63
84
  // src/prefetch.ts
64
85
  var KEY = "vitral:prefetch";
65
- function slow() {
66
- const c = navigator.connection;
67
- return !!c?.saveData || /2g/.test(c?.effectiveType ?? "");
68
- }
86
+ var slow = () => policy() === "lazy";
69
87
  var idle = (fn) => typeof requestIdleCallback === "function" ? requestIdleCallback(fn, { timeout: 3e3 }) : setTimeout(fn, 300);
70
88
  function prefetch(options = {}) {
71
89
  if (typeof window === "undefined") return () => {
72
90
  };
73
- const { threshold = 0.4, min = 2, key = (u) => u.pathname, onPrefetch } = options;
91
+ const { threshold = 0.1, min = 2, alpha = 5, byteCost = 5e-4, key = (u) => u.pathname, onPrefetch } = options;
92
+ let prior = typeof options.prior === "object" ? options.prior : null;
93
+ if (typeof options.prior === "string")
94
+ fetch(options.prior, { priority: "low" }).then((r) => r.ok ? r.json() : null).then((p) => p && typeof p.t === "object" && (prior = p, schedule())).catch(() => {
95
+ });
74
96
  let storage = options.storage;
75
97
  if (storage === void 0)
76
98
  try {
@@ -91,28 +113,41 @@ function prefetch(options = {}) {
91
113
  };
92
114
  const here = () => key(new URL(location.href));
93
115
  let current = here();
116
+ const history = [current];
117
+ const remotesOf = (route) => chain.r[route] ?? prior?.r?.[route] ?? [];
118
+ const fetchFor = (route) => {
119
+ const names = remotesOf(route).filter((n) => !loaded.has(n));
120
+ if (!names.length) return;
121
+ for (const n of names) loaded.add(n);
122
+ Promise.all(names.map(warm)).then((ok2) => {
123
+ const done = names.filter((_, i) => ok2[i]);
124
+ if (done.length) onPrefetch?.(done, route);
125
+ });
126
+ };
94
127
  const loaded = /* @__PURE__ */ new Set();
95
128
  let seq = 0;
96
129
  const schedule = () => {
97
130
  const id = ++seq;
98
131
  if (slow()) return;
99
132
  idle(() => {
100
- const next = id === seq && predict(chain, current, threshold, min);
101
- if (!next) return;
102
- const names = (chain.r[next] ?? []).filter((n) => !loaded.has(n));
103
- if (!names.length) return;
104
- for (const n of names) loaded.add(n);
105
- Promise.all(names.map(warm)).then((ok2) => {
106
- const done = names.filter((_, i) => ok2[i]);
107
- if (done.length) onPrefetch?.(done, next);
108
- });
133
+ const guess = id === seq && predictNext(chain, history, { threshold, min, prior, alpha });
134
+ if (!guess) return;
135
+ const names = remotesOf(guess.to);
136
+ if (!names.length) {
137
+ if (options.speculate && !options.key && guess.to.startsWith("/")) speculate(guess.to);
138
+ return;
139
+ }
140
+ const bytes = names.reduce((a, n) => a + (chain.b?.[n] ?? 15e4), 0);
141
+ if (worth(guess.p, bytes, byteCost)) fetchFor(guess.to);
109
142
  });
110
143
  };
111
144
  const visit = () => {
112
145
  const next = here();
113
146
  if (next === current) return;
114
- record(chain, current, next);
147
+ recordPath(chain, history, next);
115
148
  current = next;
149
+ history.push(next);
150
+ if (history.length > 3) history.shift();
116
151
  save();
117
152
  schedule();
118
153
  };
@@ -126,6 +161,8 @@ function prefetch(options = {}) {
126
161
  if (!m) continue;
127
162
  loaded.add(m[1]);
128
163
  changed = remember(chain, current, m[1]) || changed;
164
+ const b = bytesOf(m[1]);
165
+ if (b) (chain.b ??= {})[m[1]] = b, changed = true;
129
166
  }
130
167
  if (changed) save();
131
168
  });
@@ -136,13 +173,45 @@ function prefetch(options = {}) {
136
173
  const event = nav ? "currententrychange" : "popstate";
137
174
  const target = nav ?? window;
138
175
  target.addEventListener(event, visit);
176
+ const down = (e) => {
177
+ if (slow()) return;
178
+ const a = e.target?.closest?.("a[href]");
179
+ if (!a) return;
180
+ const url = new URL(a.href, location.href);
181
+ if (url.origin === location.origin) fetchFor(key(url));
182
+ };
183
+ document.addEventListener("pointerdown", down, { passive: true });
139
184
  schedule();
140
185
  return () => {
141
186
  seq++;
142
187
  observer?.disconnect();
143
188
  target.removeEventListener(event, visit);
189
+ document.removeEventListener("pointerdown", down);
144
190
  };
145
191
  }
192
+ function worth(p, bytes, byteCost = 5e-4, net = navigator.connection) {
193
+ const rtt = net?.rtt || 100;
194
+ const mbps = net?.downlink || 10;
195
+ const saved = 2 * rtt + bytes * 8 / (mbps * 1e3);
196
+ return p * saved > byteCost * bytes;
197
+ }
198
+ function bytesOf(name) {
199
+ const url = protocol().entry(name)?.url;
200
+ if (!url || typeof performance === "undefined") return 0;
201
+ const dir = url.slice(0, url.lastIndexOf("/") + 1);
202
+ let total = 0;
203
+ for (const e of performance.getEntriesByType("resource")) if (e.name.startsWith(dir)) total += e.encodedBodySize || 0;
204
+ return total;
205
+ }
206
+ var speculated = /* @__PURE__ */ new Set();
207
+ function speculate(path) {
208
+ if (speculated.has(path) || !HTMLScriptElement.supports?.("speculationrules")) return;
209
+ speculated.add(path);
210
+ const s = document.createElement("script");
211
+ s.type = "speculationrules";
212
+ s.textContent = JSON.stringify({ prefetch: [{ source: "list", urls: [path], eagerness: "immediate" }] });
213
+ document.head.append(s);
214
+ }
146
215
  var heat = (u) => fetch(u, { priority: "low" }).then((res) => res.arrayBuffer());
147
216
  function modulepreload(href) {
148
217
  return new Promise((resolve, reject) => {
@@ -153,7 +222,7 @@ function modulepreload(href) {
153
222
  }
154
223
  async function verifiedOnly(r) {
155
224
  const b = r.split ?? { entry: r.entry, chunks: [], sri: { [r.entry]: r.integrity }, priority: "low" };
156
- const { verified } = await import("./sri-LQBLQMG5.js");
225
+ const { verified } = await import("./sri-AMQOKKWR.js");
157
226
  const url = await verified(b);
158
227
  if (!url) await Promise.all([...b.chunks, b.entry].map(heat));
159
228
  else if (!document.querySelector(`link[rel=modulepreload][href="${CSS.escape(url)}"]`)) await heat(url);
@@ -176,5 +245,6 @@ async function warm(name) {
176
245
  }
177
246
  export {
178
247
  prefetch,
179
- warm
248
+ warm,
249
+ worth
180
250
  };