vitral 0.7.1 → 0.8.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 (59) hide show
  1. package/README.md +74 -14
  2. package/dist/angular.d.ts +2 -2
  3. package/dist/angular.js +8 -6
  4. package/dist/auto.js +5 -4
  5. package/dist/chunk-4IWZIFAL.js +165 -0
  6. package/dist/chunk-6AFVJCQG.js +311 -0
  7. package/dist/{chunk-72H4FXMD.js → chunk-6T25WKNK.js} +44 -13
  8. package/dist/chunk-EQZOJU3B.js +48 -0
  9. package/dist/{chunk-O7DV3EVB.js → chunk-NTXMEZIZ.js} +9 -46
  10. package/dist/{chunk-4NSPG6NK.js → chunk-PQXS2UDM.js} +1 -1
  11. package/dist/{chunk-TXSHK3SK.js → chunk-ZJ4IM2PZ.js} +2 -2
  12. package/dist/{chunk-V24ZNHUF.js → chunk-ZRAGLT3I.js} +4 -4
  13. package/dist/cli.js +1 -1
  14. package/dist/{contract-46EZFQPQ.js → contract-OMHCH6LI.js} +1 -1
  15. package/dist/{dedupe-S7BHQMOZ.js → dedupe-PZCSKL3L.js} +1 -1
  16. package/dist/edge.d.ts +1 -1
  17. package/dist/element.d.ts +2 -2
  18. package/dist/element.js +5 -4
  19. package/dist/embed.js +2 -2
  20. package/dist/{events-DLdbFqBM.d.ts → events-Cieg_far.d.ts} +1 -1
  21. package/dist/{expose-ZLYQZUP2.js → expose-V5ASGX4E.js} +2 -2
  22. package/dist/federation.d.ts +1 -1
  23. package/dist/{hydrate-NFZZMYWT.js → hydrate-6NE4MYOD.js} +7 -5
  24. package/dist/iframe.js +9 -7
  25. package/dist/index.d.ts +6 -19
  26. package/dist/index.js +6 -4
  27. package/dist/loader-BIXjuvvp.d.ts +25 -0
  28. package/dist/next-config.d.ts +95 -0
  29. package/dist/next-config.js +149 -0
  30. package/dist/next-host.d.ts +26 -0
  31. package/dist/next-host.js +92 -0
  32. package/dist/next.d.ts +190 -0
  33. package/dist/next.js +287 -0
  34. package/dist/preact.d.ts +4 -4
  35. package/dist/preact.js +7 -5
  36. package/dist/prefetch.js +2 -2
  37. package/dist/react-server.d.ts +1 -1
  38. package/dist/react.d.ts +11 -4
  39. package/dist/react.js +17 -144
  40. package/dist/{reframe-7K5S6JC6.js → reframe-3ZN5CHEG.js} +4 -4
  41. package/dist/routes.d.ts +2 -2
  42. package/dist/routes.js +6 -4
  43. package/dist/single-spa.d.ts +1 -1
  44. package/dist/{slot-Ddzp7AgL.d.ts → slot-Dhczjs1E.d.ts} +1 -1
  45. package/dist/solid.d.ts +3 -3
  46. package/dist/solid.js +7 -5
  47. package/dist/{sri-576GTDIA.js → sri-TBZ6PYYY.js} +39 -24
  48. package/dist/svelte.d.ts +4 -4
  49. package/dist/svelte.js +6 -4
  50. package/dist/sw.d.ts +8 -0
  51. package/dist/sw.js +21 -0
  52. package/dist/testing.d.ts +1 -1
  53. package/dist/testing.js +3 -2
  54. package/dist/{types-EOz1rOHs.d.ts → types-wsKR1gfx.d.ts} +19 -3
  55. package/dist/vite.d.ts +33 -1
  56. package/dist/vite.js +353 -158
  57. package/dist/vue.d.ts +3 -3
  58. package/dist/vue.js +6 -4
  59. package/package.json +28 -12
package/dist/iframe.js CHANGED
@@ -1,18 +1,20 @@
1
- import {
2
- splitName
3
- } from "./chunk-4NSPG6NK.js";
4
1
  import {
5
2
  verifyIntegrity
6
3
  } from "./chunk-UYOPJ4XQ.js";
7
4
  import {
8
- events,
9
- navigate,
5
+ splitName
6
+ } from "./chunk-PQXS2UDM.js";
7
+ import {
10
8
  setFrameMounter,
11
9
  track
12
- } from "./chunk-O7DV3EVB.js";
10
+ } from "./chunk-NTXMEZIZ.js";
11
+ import {
12
+ events,
13
+ navigate
14
+ } from "./chunk-EQZOJU3B.js";
13
15
  import {
14
16
  resolveEntry
15
- } from "./chunk-72H4FXMD.js";
17
+ } from "./chunk-6T25WKNK.js";
16
18
  import "./chunk-KU6HF2EW.js";
17
19
  import {
18
20
  fetchBytes,
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { V as VitralConfig, c as RemoteEntry, P as Props, a as RemoteModule, I as Isolation, d as StyleOptions, M as MountedRemote, E as EventBus, R as RemoteContext, e as SharedValue } from './types-EOz1rOHs.js';
2
- export { f as Channel, g as ChannelContext, C as CheckedProps, D as DevOverrides, H as Handler, h as McpAppBridge, i as PropsOf, j as ProvideOptions, k as ProvidedValue, l as RemoteContract, m as RemoteManifest, n as RemoteMetric, o as Remotes, p as RollbackInfo, S as Shared, q as SharedApi, b as SharedModules, r as SharedType, s as batch, t as provide, u as shared } from './types-EOz1rOHs.js';
1
+ import { V as VitralConfig, c as RemoteEntry, I as Isolation, d as StyleOptions, P as Props, M as MountedRemote, a as RemoteModule, E as EventBus, R as RemoteContext, e as SharedValue } from './types-wsKR1gfx.js';
2
+ export { f as Channel, g as ChannelContext, C as CheckedProps, D as DevOverrides, H as Handler, h as McpAppBridge, i as PropsOf, j as ProvideOptions, k as ProvidedValue, l as RemoteContract, m as RemoteManifest, n as RemoteMetric, o as Remotes, p as RollbackInfo, S as Shared, q as SharedApi, b as SharedModules, r as SharedType, s as batch, t as provide, u as shared } from './types-wsKR1gfx.js';
3
3
  import { R as RemoteError } from './errors-kjBv6IH_.js';
4
4
  export { a as RemoteErrorCode } from './errors-kjBv6IH_.js';
5
- export { R as RemoteSlot, a as SlotOptions, S as SlotStatus, c as createSlot } from './slot-Ddzp7AgL.js';
6
- export { e as events } from './events-DLdbFqBM.js';
5
+ export { P as PreloadOptions, l as loadModule, a as loadRemote, p as preload } from './loader-BIXjuvvp.js';
6
+ export { R as RemoteSlot, a as SlotOptions, S as SlotStatus, c as createSlot } from './slot-Dhczjs1E.js';
7
+ export { e as events } from './events-Cieg_far.js';
7
8
  export { n as navigate } from './navigate-BRG1WJUM.js';
8
9
  export { r as __reset } from './state-BDdCwc21.js';
9
10
 
@@ -60,20 +61,6 @@ declare function register(name: string, entry: string | RemoteEntry): void;
60
61
  */
61
62
  declare function registerSrc(src: string, name?: string, trusted?: boolean): string;
62
63
 
63
- /** Baixa (uma vez só) e devolve o módulo de um remote. */
64
- declare function loadRemote<P extends Props = Props>(name: string): Promise<RemoteModule<P>>;
65
- /**
66
- * Carrega um módulo sem UI que um remote expõe (funções, stores, constantes),
67
- * com a mesma verificação de SRI e de origem dos componentes.
68
- *
69
- * const api = await loadModule<typeof import('./tipos/carrinho-api')>('carrinho/api')
70
- *
71
- * Sem `/`, devolve os exports do arquivo principal do remote.
72
- */
73
- declare function loadModule<T = Record<string, unknown>>(name: string): Promise<T>;
74
- /** Começa a baixar um remote (JS e CSS) sem montar (ex.: no hover de um link). */
75
- declare function preload(name: string): void;
76
-
77
64
  interface MountOptions {
78
65
  isolate?: Isolation;
79
66
  /** `'high'` para o remote que aparece logo ao abrir a página: vira `fetchpriority` nos downloads. */
@@ -185,4 +172,4 @@ declare function syncTabs<V extends SharedValue<any>>(value: V): V;
185
172
  */
186
173
  declare function serializeShared(values: Record<string, unknown>): string;
187
174
 
188
- export { type ComponentOptions, EventBus, Isolation, type MountOptions, MountedRemote, type PersistOptions, Props, RemoteContext, RemoteEntry, RemoteError, RemoteModule, type RenderFn, type SharedEntry, type SharedStore, SharedValue, StyleOptions, type Template, type View, VitralConfig, checkUpdates, component, configure, createEventBus, defineRemote, html, loadModule, loadRemote, mountRemote, persist, preload, refresh, register, registerSrc, render, serializeShared, syncTabs, unsafeHTML, watchUpdates };
175
+ export { type ComponentOptions, EventBus, Isolation, type MountOptions, MountedRemote, type PersistOptions, Props, RemoteContext, RemoteEntry, RemoteError, RemoteModule, type RenderFn, type SharedEntry, type SharedStore, SharedValue, StyleOptions, type Template, type View, VitralConfig, checkUpdates, component, configure, createEventBus, defineRemote, html, mountRemote, persist, refresh, register, registerSrc, render, serializeShared, syncTabs, unsafeHTML, watchUpdates };
package/dist/index.js CHANGED
@@ -4,10 +4,8 @@ import {
4
4
  component,
5
5
  createSlot,
6
6
  defineRemote,
7
- events,
8
7
  html,
9
8
  mountRemote,
10
- navigate,
11
9
  persist,
12
10
  provide,
13
11
  refresh,
@@ -17,7 +15,11 @@ import {
17
15
  syncTabs,
18
16
  unsafeHTML,
19
17
  watchUpdates
20
- } from "./chunk-O7DV3EVB.js";
18
+ } from "./chunk-NTXMEZIZ.js";
19
+ import {
20
+ events,
21
+ navigate
22
+ } from "./chunk-EQZOJU3B.js";
21
23
  import {
22
24
  configure,
23
25
  loadModule,
@@ -25,7 +27,7 @@ import {
25
27
  preload,
26
28
  register,
27
29
  registerSrc
28
- } from "./chunk-72H4FXMD.js";
30
+ } from "./chunk-6T25WKNK.js";
29
31
  import "./chunk-KU6HF2EW.js";
30
32
  import "./chunk-TW7KYJQ6.js";
31
33
  import {
@@ -0,0 +1,25 @@
1
+ import { P as Props, a as RemoteModule } from './types-wsKR1gfx.js';
2
+
3
+ /** Baixa (uma vez só) e devolve o módulo de um remote. */
4
+ declare function loadRemote<P extends Props = Props>(name: string): Promise<RemoteModule<P>>;
5
+ /**
6
+ * Carrega um módulo sem UI que um remote expõe (funções, stores, constantes),
7
+ * com a mesma verificação de SRI e de origem dos componentes.
8
+ *
9
+ * const api = await loadModule<typeof import('./tipos/carrinho-api')>('carrinho/api')
10
+ *
11
+ * Sem `/`, devolve os exports do arquivo principal do remote.
12
+ */
13
+ declare function loadModule<T = Record<string, unknown>>(name: string): Promise<T>;
14
+ /** Começa a baixar um remote (JS e CSS) sem montar (ex.: no hover de um link). */
15
+ declare function preload(name: string, options?: PreloadOptions): void;
16
+ interface PreloadOptions {
17
+ /**
18
+ * Depois do remote, aquece no cache HTTP, com o navegador ocioso, os
19
+ * chunks que ele só carrega depois (`import()` das rotas). Não baixa as
20
+ * cópias de `dedupe`. Padrão: false.
21
+ */
22
+ routes?: boolean;
23
+ }
24
+
25
+ export { type PreloadOptions as P, loadRemote as a, loadModule as l, preload as p };
@@ -0,0 +1,95 @@
1
+ import { ZoneRoute } from './next.js';
2
+ import 'react';
3
+
4
+ interface NextRemoteConfig {
5
+ /** URL do `vitral.json`. Num caminho do próprio host (`/x/vitral.json`), ganha os headers de cache. */
6
+ url: string;
7
+ /**
8
+ * Página do host que renderiza o `NextRemote` (`pages/<basePath>/[[...slug]]`),
9
+ * e o `basePath` que o remote vê, como no `next.config` da zona.
10
+ */
11
+ basePath: string;
12
+ /** Rotas públicas que abrem o remote, como os `rewrites` do Multi-Zones. */
13
+ routes?: ZoneRoute[];
14
+ /**
15
+ * Quando baixar o remote antes de alguém abrir: `'idle'` com o navegador
16
+ * ocioso, `'route'` só ao abrir uma rota dele. Padrão: `'idle'`.
17
+ */
18
+ preload?: 'idle' | 'route' | false;
19
+ /**
20
+ * Depois do preload, aquece também os chunks das rotas do remote
21
+ * (`import()`), com o navegador ocioso: a primeira tela de cada rota abre
22
+ * sem download. Padrão: false.
23
+ */
24
+ warmRoutes?: boolean;
25
+ /**
26
+ * `false` dispensa a conferência de hash (SRI) do `vitral.json`. Só para
27
+ * remote servido pela mesma origem do host.
28
+ */
29
+ integrity?: false;
30
+ /**
31
+ * Em `next dev`, o dev server do remote (`http://localhost:5173`): o
32
+ * remote vem dele, com HMR, sem `?vitral=`. A CSP de dev do host precisa
33
+ * liberar essa origem em `script-src` e em `connect-src` (`ws:` do HMR).
34
+ */
35
+ devUrl?: string;
36
+ }
37
+ interface WithVitralOptions {
38
+ remotes: Record<string, NextRemoteConfig>;
39
+ /**
40
+ * Dependências que o host oferece aos remotes com `dedupe`, só baixadas
41
+ * quando um remote pede. `pacote/*` oferece o pacote e cada subpath do
42
+ * `exports`. O React o `NextRemote` já oferece.
43
+ */
44
+ share?: string[];
45
+ /** Pasta do app. Padrão: `process.cwd()`. */
46
+ dir?: string;
47
+ }
48
+ /** Id do módulo gerado; o `vitral/next-host` importa dele. */
49
+ declare const HOST_CONFIG = "vitral-next-host-config";
50
+ type Rewrite = {
51
+ source: string;
52
+ destination: string;
53
+ };
54
+ type Rewrites = Rewrite[] | {
55
+ beforeFiles?: Rewrite[];
56
+ afterFiles?: Rewrite[];
57
+ fallback?: Rewrite[];
58
+ };
59
+ type Header = {
60
+ source: string;
61
+ headers: {
62
+ key: string;
63
+ value: string;
64
+ }[];
65
+ };
66
+ type NextConfig = Record<string, any> & {
67
+ distDir?: string;
68
+ rewrites?: () => Promise<Rewrites> | Rewrites;
69
+ headers?: () => Promise<Header[]> | Header[];
70
+ webpack?: (config: any, context: any) => any;
71
+ turbopack?: {
72
+ resolveAlias?: Record<string, string>;
73
+ };
74
+ };
75
+ /** Grupos de `dedupe` do host: versão instalada e especificadores. */
76
+ declare function sharedGroups(dir: string, share: string[]): Record<string, {
77
+ version: string;
78
+ specs: string[];
79
+ }>;
80
+ /**
81
+ * O especificador como o webpack do app vai achar. Um alias do pacote para a
82
+ * pasta dele (`'@empresa/ui': '/app/node_modules/@empresa/ui'`) faz o webpack
83
+ * procurar `pasta/subpath` sem olhar o `exports`: aí o subpath vira o arquivo
84
+ * que o `exports` aponta.
85
+ */
86
+ declare function throughAlias(spec: string, alias?: Record<string, unknown>): string;
87
+ /** Código do módulo gerado: configuração dos remotes e ofertas que só importam quando pedidas. */
88
+ declare function hostModule(remotes: Record<string, NextRemoteConfig>, groups: ReturnType<typeof sharedGroups>, alias?: Record<string, unknown>, from?: string): string;
89
+ /** Em dev, `devUrl` no lugar de `url` (o manifesto do dev server, em `/vitral.json`). */
90
+ declare function devRemotes(remotes: Record<string, NextRemoteConfig>, dev: boolean): Record<string, NextRemoteConfig>;
91
+ declare function remoteRewrites(remotes: Record<string, NextRemoteConfig>): Rewrite[];
92
+ declare function remoteHeaders(remotes: Record<string, NextRemoteConfig>): Header[];
93
+ declare function withVitral(nextConfig: NextConfig, options: WithVitralOptions): NextConfig;
94
+
95
+ export { HOST_CONFIG, type NextRemoteConfig, type WithVitralOptions, ZoneRoute, devRemotes, hostModule, remoteHeaders, remoteRewrites, sharedGroups, throughAlias, withVitral };
@@ -0,0 +1,149 @@
1
+ import {
2
+ subpaths
3
+ } from "./chunk-6AFVJCQG.js";
4
+
5
+ // src/next-config.ts
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
7
+ import { createRequire } from "module";
8
+ import { dirname, isAbsolute, join, relative, resolve } from "path";
9
+ var HOST_CONFIG = "vitral-next-host-config";
10
+ var pkgOf = (spec) => spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
11
+ var REACT = /^(react|react-dom|scheduler)(\/|$)/;
12
+ function installed(dir, pkg) {
13
+ const req = createRequire(join(dir, "package.json"));
14
+ let file;
15
+ try {
16
+ file = req.resolve(`${pkg}/package.json`);
17
+ } catch {
18
+ file = req.resolve(pkg);
19
+ }
20
+ for (let d = dirname(file); d !== dirname(d); d = dirname(d)) {
21
+ const json = join(d, "package.json");
22
+ if (!existsSync(json)) continue;
23
+ const data = JSON.parse(readFileSync(json, "utf8"));
24
+ if (data.name === pkg) return data;
25
+ }
26
+ throw new Error(`[vitral] ${pkg} n\xE3o est\xE1 instalado no app`);
27
+ }
28
+ function sharedGroups(dir, share) {
29
+ const out = {};
30
+ for (const spec of share) {
31
+ const name = pkgOf(spec);
32
+ if (REACT.test(name)) continue;
33
+ const data = installed(dir, name);
34
+ const g = out[name] ??= { version: data.version, specs: [] };
35
+ for (const s of spec.endsWith("/*") ? subpaths(name, data) : [spec]) if (!g.specs.includes(s)) g.specs.push(s);
36
+ }
37
+ return out;
38
+ }
39
+ function throughAlias(spec, alias = {}) {
40
+ for (const [key, value] of Object.entries(alias)) {
41
+ if (typeof value !== "string" || key.endsWith("$") || !spec.startsWith(key + "/")) continue;
42
+ const json = join(value, "package.json");
43
+ if (!existsSync(json)) continue;
44
+ const exp = JSON.parse(readFileSync(json, "utf8")).exports;
45
+ const target = exp?.["." + spec.slice(key.length)];
46
+ const file = typeof target === "string" ? target : target?.import ?? target?.default;
47
+ if (typeof file === "string") return resolve(value, file);
48
+ }
49
+ return spec;
50
+ }
51
+ function hostModule(remotes, groups, alias, from) {
52
+ const spec = (s) => {
53
+ const t = throughAlias(s, alias);
54
+ if (!from || !isAbsolute(t)) return t;
55
+ const r = relative(from, t).replace(/\\/g, "/");
56
+ return r.startsWith(".") ? r : "./" + r;
57
+ };
58
+ const shared = Object.entries(groups).map(([name, g]) => {
59
+ const imports = g.specs.map((s) => `import(${JSON.stringify(spec(s))})`).join(", ");
60
+ const modules = g.specs.map((s, i) => `${JSON.stringify(s)}: m[${i}]`).join(", ");
61
+ return ` ${JSON.stringify(name)}: { version: ${JSON.stringify(g.version)}, modules: () => Promise.all([${imports}]).then((m) => ({ ${modules} })) },`;
62
+ });
63
+ return `export const remotes = ${JSON.stringify(remotes, null, 2)}
64
+ export const shared = {
65
+ ${shared.join("\n")}
66
+ }
67
+ `;
68
+ }
69
+ var localDir = (url) => url.startsWith("/") && !url.startsWith("//") ? url.slice(0, url.lastIndexOf("/") + 1) : void 0;
70
+ function devRemotes(remotes, dev) {
71
+ if (!dev) return remotes;
72
+ return Object.fromEntries(
73
+ Object.entries(remotes).map(([name, r]) => [name, r.devUrl ? { ...r, url: /\.json(\?|$)/.test(r.devUrl) ? r.devUrl : r.devUrl.replace(/\/?$/, "/vitral.json") } : r])
74
+ );
75
+ }
76
+ function remoteRewrites(remotes) {
77
+ return Object.values(remotes).flatMap(
78
+ (r) => (r.routes ?? []).filter((x) => x.public !== x.zone).map((x) => ({ source: `${x.public}/:path*`, destination: `${x.zone}/:path*` }))
79
+ );
80
+ }
81
+ function remoteHeaders(remotes) {
82
+ const immutable = [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }];
83
+ return Object.values(remotes).flatMap((r) => {
84
+ const dir = localDir(r.url);
85
+ if (!dir) return [];
86
+ return [
87
+ // O manifesto muda a cada deploy; os arquivos têm hash no nome.
88
+ { source: r.url, headers: [{ key: "Cache-Control", value: "no-cache" }] },
89
+ { source: `${dir}:file(remote-.*)`, headers: immutable },
90
+ { source: `${dir}split/:file*`, headers: immutable }
91
+ ];
92
+ });
93
+ }
94
+ function writeChanged(file, text) {
95
+ try {
96
+ if (readFileSync(file, "utf8") === text) return;
97
+ } catch {
98
+ }
99
+ writeFileSync(file, text);
100
+ }
101
+ function withVitral(nextConfig, options) {
102
+ const dir = resolve(options.dir ?? process.cwd());
103
+ const file = join(dir, ".vitral", "host-config.mjs");
104
+ const groups = sharedGroups(dir, options.share ?? []);
105
+ const emit = (alias) => {
106
+ try {
107
+ mkdirSync(dirname(file), { recursive: true });
108
+ writeChanged(join(dirname(file), ".gitignore"), "*\n");
109
+ writeChanged(file, hostModule(devRemotes(options.remotes, process.env.NODE_ENV === "development"), groups, alias, dirname(file)));
110
+ } catch (e) {
111
+ console.warn(`[vitral] n\xE3o consegui gravar ${file} (${e.message}). No build ele \xE9 necess\xE1rio; no next start, n\xE3o.`);
112
+ }
113
+ };
114
+ emit(Object.fromEntries(Object.entries(nextConfig.turbopack?.resolveAlias ?? {}).map(([k, v]) => [k, typeof v === "string" && v.startsWith(".") ? resolve(dir, v) : v])));
115
+ const ours = remoteRewrites(options.remotes);
116
+ const headers = remoteHeaders(options.remotes);
117
+ return {
118
+ ...nextConfig,
119
+ // O webpack do app empacota o vitral também no servidor: senão o Node não acha o módulo gerado.
120
+ transpilePackages: [.../* @__PURE__ */ new Set([...nextConfig.transpilePackages ?? [], "vitral"])],
121
+ async rewrites() {
122
+ const user = await nextConfig.rewrites?.() ?? [];
123
+ return Array.isArray(user) ? { beforeFiles: ours, afterFiles: user, fallback: [] } : { ...user, beforeFiles: [...ours, ...user.beforeFiles ?? []] };
124
+ },
125
+ async headers() {
126
+ return [...headers, ...await nextConfig.headers?.() ?? []];
127
+ },
128
+ webpack(config, context) {
129
+ const out = nextConfig.webpack ? nextConfig.webpack(config, context) : config;
130
+ if (out.resolve.alias && !Array.isArray(out.resolve.alias)) emit(out.resolve.alias);
131
+ out.resolve.alias = { ...out.resolve.alias, [`${HOST_CONFIG}$`]: file };
132
+ return out;
133
+ },
134
+ turbopack: {
135
+ ...nextConfig.turbopack,
136
+ resolveAlias: { ...nextConfig.turbopack?.resolveAlias, [HOST_CONFIG]: "./" + relative(dir, file).replace(/\\/g, "/") }
137
+ }
138
+ };
139
+ }
140
+ export {
141
+ HOST_CONFIG,
142
+ devRemotes,
143
+ hostModule,
144
+ remoteHeaders,
145
+ remoteRewrites,
146
+ sharedGroups,
147
+ throughAlias,
148
+ withVitral
149
+ };
@@ -0,0 +1,26 @@
1
+ import { ReactNode } from 'react';
2
+ import { RemoteProps } from './react.js';
3
+ import './host-slot-Cz6EiGsB.js';
4
+ import 'react/jsx-runtime';
5
+ import './types-wsKR1gfx.js';
6
+ import './errors-kjBv6IH_.js';
7
+ import './loader-BIXjuvvp.js';
8
+ import './events-Cieg_far.js';
9
+
10
+ /** O remote dono do caminho público `path`, se houver. */
11
+ declare function remoteFor(path: string): string | undefined;
12
+ /** Navegação de página inteira para uma rota de remote vira `Router.push`. Devolve a função que desliga. */
13
+ declare function interceptNavigation(): () => void;
14
+ /** Coloque uma vez, no `_app`. */
15
+ declare function VitralNext(): null;
16
+ type NextRemoteProps = Omit<RemoteProps, 'name' | 'src'> & {
17
+ name: string;
18
+ };
19
+ /**
20
+ * O remote na página do host. Passa o roteador do Next ao remote (prop
21
+ * `__next`, lida pelo plugin no modo `next`): `useRouter`, `<Link>` e
22
+ * `router.push` do remote usam o do host, com as rotas públicas.
23
+ */
24
+ declare function NextRemote({ name, props, fallback, ...rest }: NextRemoteProps): ReactNode;
25
+
26
+ export { NextRemote, type NextRemoteProps, VitralNext, interceptNavigation, remoteFor };
@@ -0,0 +1,92 @@
1
+ "use client";
2
+ import {
3
+ Remote,
4
+ preload
5
+ } from "./chunk-4IWZIFAL.js";
6
+ import "./chunk-B2MPYF4M.js";
7
+ import "./chunk-ZJ4IM2PZ.js";
8
+ import "./chunk-NTXMEZIZ.js";
9
+ import "./chunk-EQZOJU3B.js";
10
+ import {
11
+ configure
12
+ } from "./chunk-6T25WKNK.js";
13
+ import "./chunk-KU6HF2EW.js";
14
+ import "./chunk-TW7KYJQ6.js";
15
+ import "./chunk-463H6B56.js";
16
+ import "./chunk-GNPFWISJ.js";
17
+
18
+ // src/next-host.tsx
19
+ import Router, { useRouter } from "next/router";
20
+ import { createElement, useEffect, useMemo } from "react";
21
+ import { remotes, shared } from "vitral-next-host-config";
22
+ var under = (path, prefix) => path === prefix || path.startsWith(prefix + "/");
23
+ function remoteFor(path) {
24
+ for (const [name, r] of Object.entries(remotes)) if (under(path, r.basePath) || r.routes?.some((x) => under(path, x.public))) return name;
25
+ }
26
+ var configured = false;
27
+ function setup() {
28
+ if (configured || typeof window === "undefined") return;
29
+ configured = true;
30
+ configure({
31
+ remotes: Object.fromEntries(Object.entries(remotes).map(([name, r]) => [name, { url: r.url, ...r.integrity === false && { integrity: false } }])),
32
+ dedupe: shared
33
+ });
34
+ }
35
+ function interceptNavigation() {
36
+ const nav = globalThis.navigation;
37
+ if (!nav) return () => {
38
+ };
39
+ let last;
40
+ const done = () => last = void 0;
41
+ const on = (e) => {
42
+ if (e.destination.sameDocument || !e.cancelable || e.hashChange || e.downloadRequest || e.formData) return;
43
+ if (e.navigationType !== "push" && e.navigationType !== "replace") return;
44
+ const url = new URL(e.destination.url);
45
+ const path = url.pathname + url.search + url.hash;
46
+ if (url.origin !== location.origin || !remoteFor(url.pathname) || last === path) return;
47
+ e.preventDefault();
48
+ last = path;
49
+ void (e.navigationType === "replace" ? Router.replace(path) : Router.push(path));
50
+ };
51
+ nav.addEventListener("navigate", on);
52
+ Router.events.on("routeChangeComplete", done);
53
+ return () => {
54
+ nav.removeEventListener("navigate", on);
55
+ Router.events.off("routeChangeComplete", done);
56
+ };
57
+ }
58
+ function VitralNext() {
59
+ setup();
60
+ useEffect(() => {
61
+ const here = remoteFor(location.pathname);
62
+ const go = (name) => preload(name, { routes: !!remotes[name].warmRoutes });
63
+ if (here) go(here);
64
+ const idle = [];
65
+ for (const [name, r] of Object.entries(remotes))
66
+ if (name !== here && (r.preload ?? "idle") === "idle")
67
+ idle.push(typeof requestIdleCallback === "function" ? requestIdleCallback(() => go(name), { timeout: 5e3 }) : window.setTimeout(() => go(name), 2e3));
68
+ const stop = interceptNavigation();
69
+ return () => {
70
+ stop();
71
+ for (const id of idle) typeof cancelIdleCallback === "function" ? cancelIdleCallback(id) : clearTimeout(id);
72
+ };
73
+ }, []);
74
+ return null;
75
+ }
76
+ var push = (url, options) => void Router.push(url, void 0, options);
77
+ var replace = (url, options) => void Router.replace(url, void 0, options);
78
+ function NextRemote({ name, props, fallback = null, ...rest }) {
79
+ setup();
80
+ const router = useRouter();
81
+ const r = remotes[name];
82
+ const host = useMemo(() => ({ asPath: router.asPath, basePath: r?.basePath, routes: r?.routes, push, replace, events: Router.events }), [router.asPath, r]);
83
+ const all = useMemo(() => ({ ...props, __next: host }), [props, host]);
84
+ if (!router.isReady) return fallback;
85
+ return createElement(Remote, { ...rest, name, fallback, props: all });
86
+ }
87
+ export {
88
+ NextRemote,
89
+ VitralNext,
90
+ interceptNavigation,
91
+ remoteFor
92
+ };