@alignable/bifrost-fastify 0.1.1 → 1.0.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.
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { FastifyPluginAsync } from 'fastify';
2
2
  import { FastifyRequest } from 'fastify/types/request';
3
+ import { GetLayout } from '@alignable/bifrost/config';
3
4
  import { renderPage } from 'vike/server';
4
- import { GetLayout, AugmentMe } from '@alignable/bifrost';
5
+ import { PageContextServer } from 'vike/types';
5
6
 
6
7
  type RenderedPageContext = Awaited<ReturnType<typeof renderPage<{
7
- redirectTo?: string;
8
8
  isClientSideNavigation?: boolean;
9
9
  }, {
10
10
  urlOriginal: string;
@@ -19,7 +19,7 @@ interface ViteProxyPluginOptions {
19
19
  upstream: URL;
20
20
  host: URL;
21
21
  onError?: (error: any, pageContext: RenderedPageContext) => void;
22
- buildPageContextInit?: (req: FastifyRequest) => Promise<AugmentMe.PageContextInit>;
22
+ buildPageContextInit?: (req: FastifyRequest) => Promise<Partial<Omit<PageContextServer, "headers">>>;
23
23
  }
24
24
  /**
25
25
  * Fastify plugin that wraps @fasitfy/http-proxy to proxy Rails/Turbolinks server into a vike site.
package/dist/index.js CHANGED
@@ -3,6 +3,37 @@ import proxy from "@fastify/http-proxy";
3
3
  import accepts from "@fastify/accepts";
4
4
  import forwarded from "@fastify/forwarded";
5
5
  import { renderPage } from "vike/server";
6
+
7
+ // lib/extractDomElements.ts
8
+ import { Parser } from "htmlparser2";
9
+ import { DomHandler } from "domhandler";
10
+ import { findOne } from "domutils";
11
+ import render from "dom-serializer";
12
+ function getInnerHtml(element) {
13
+ return element.children.map((c) => render(c)).join("");
14
+ }
15
+ function extractDomElements(html) {
16
+ let bodyInnerHtml = null;
17
+ let headInnerHtml = null;
18
+ let bodyAttributes = {};
19
+ const handler = new DomHandler((error, dom) => {
20
+ if (!error) {
21
+ const body = findOne((elem) => elem.name === "body", dom);
22
+ const head = findOne((elem) => elem.name === "head", dom);
23
+ if (body && head) {
24
+ bodyAttributes = body.attribs;
25
+ bodyInnerHtml = getInnerHtml(body);
26
+ headInnerHtml = getInnerHtml(head);
27
+ }
28
+ }
29
+ });
30
+ const parser = new Parser(handler);
31
+ parser.write(html);
32
+ parser.end();
33
+ return { bodyInnerHtml, headInnerHtml, bodyAttributes };
34
+ }
35
+
36
+ // index.ts
6
37
  function streamToString(stream) {
7
38
  const chunks = [];
8
39
  return new Promise((resolve, reject) => {
@@ -17,9 +48,6 @@ var viteProxyPlugin = async (fastify, { upstream, host, onError, buildPageContex
17
48
  if (onError && httpResponse?.statusCode === 500 && pageContext.errorWhileRendering) {
18
49
  onError(pageContext.errorWhileRendering, pageContext);
19
50
  }
20
- if (pageContext.redirectTo && !pageContext.isClientSideNavigation) {
21
- return reply.redirect(307, pageContext.redirectTo);
22
- }
23
51
  if (!httpResponse) {
24
52
  return reply.code(404).type("text/html").send("Not Found");
25
53
  }
@@ -99,8 +127,9 @@ var viteProxyPlugin = async (fastify, { upstream, host, onError, buildPageContex
99
127
  async onResponse(req, reply, res) {
100
128
  if ([301, 302, 303, 307, 308].includes(reply.statusCode)) {
101
129
  const location = reply.getHeader("location");
130
+ console.log(location);
102
131
  if (location) {
103
- const url = new URL(location);
132
+ const url = new URL(location, host.href);
104
133
  if (url.host === upstream.host || url.host === host.host) {
105
134
  url.host = host.host;
106
135
  url.protocol = host.protocol;
@@ -109,19 +138,24 @@ var viteProxyPlugin = async (fastify, { upstream, host, onError, buildPageContex
109
138
  return reply.send(res);
110
139
  }
111
140
  }
112
- const layoutInfo = req.getLayout?.(reply.getHeaders());
113
- if (!layoutInfo?.layout) {
141
+ const proxyLayoutInfo = req.getLayout?.(reply.getHeaders());
142
+ if (!proxyLayoutInfo) {
114
143
  return reply.send(res);
115
144
  }
116
145
  const html = await streamToString(res);
146
+ const { bodyAttributes, bodyInnerHtml, headInnerHtml } = extractDomElements(html);
147
+ if (!bodyInnerHtml || !headInnerHtml) {
148
+ throw new Error("Proxy failed");
149
+ }
117
150
  const pageContextInit = {
118
151
  urlOriginal: req.url,
119
152
  // Critical that we don't set any passToClient values in pageContextInit
120
153
  // If we do, Vike re-requests pageContext on client navigation. This breaks wrapped proxy.
121
- wrappedServerOnly: {
122
- layout: layoutInfo.layout,
123
- layoutProps: layoutInfo.layoutProps,
124
- html
154
+ _wrappedServerOnly: {
155
+ bodyAttributes,
156
+ bodyInnerHtml,
157
+ headInnerHtml,
158
+ proxyLayoutInfo
125
159
  }
126
160
  };
127
161
  const pageContext = await renderPage(pageContextInit);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../index.ts"],"sourcesContent":["// Note that this file isn't processed by Vite, see https://github.com/brillout/vike/issues/562\nimport { FastifyReply, RawServerBase, FastifyPluginAsync } from \"fastify\";\nimport { FastifyRequest, RequestGenericInterface } from \"fastify/types/request\";\nimport proxy from \"@fastify/http-proxy\";\nimport accepts from \"@fastify/accepts\";\nimport forwarded from \"@fastify/forwarded\";\nimport { Writable } from \"stream\";\nimport { IncomingMessage } from \"http\";\nimport { renderPage } from \"vike/server\";\nimport { AugmentMe, GetLayout, PageContext } from \"@alignable/bifrost\";\n\ntype RenderedPageContext = Awaited<\n ReturnType<\n typeof renderPage<\n {\n redirectTo?: string;\n isClientSideNavigation?: boolean;\n },\n { urlOriginal: string }\n >\n >\n>;\n\ndeclare module \"fastify\" {\n interface FastifyRequest {\n bifrostPageId?: string | null;\n getLayout: GetLayout;\n }\n}\n\ntype RawRequestExtendedWithProxy = FastifyRequest<\n RequestGenericInterface,\n RawServerBase\n>[\"raw\"] & {\n _bfproxy?: boolean;\n};\n\nfunction streamToString(stream: Writable): Promise<string> {\n const chunks: Buffer[] = [];\n return new Promise((resolve, reject) => {\n stream.on(\"data\", (chunk) => chunks.push(Buffer.from(chunk)));\n stream.on(\"error\", (err) => reject(err));\n stream.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n });\n}\n\ninterface ViteProxyPluginOptions {\n upstream: URL;\n host: URL;\n onError?: (error: any, pageContext: RenderedPageContext) => void;\n buildPageContextInit?: (\n req: FastifyRequest\n ) => Promise<AugmentMe.PageContextInit>;\n}\n/**\n * Fastify plugin that wraps @fasitfy/http-proxy to proxy Rails/Turbolinks server into a vike site.\n */\nexport const viteProxyPlugin: FastifyPluginAsync<\n ViteProxyPluginOptions\n> = async (fastify, { upstream, host, onError, buildPageContextInit }) => {\n async function replyWithPage(\n reply: FastifyReply<RawServerBase>,\n pageContext: RenderedPageContext\n ): Promise<FastifyReply> {\n const { httpResponse } = pageContext;\n\n if (\n onError &&\n httpResponse?.statusCode === 500 &&\n pageContext.errorWhileRendering\n ) {\n onError(pageContext.errorWhileRendering, pageContext);\n }\n\n if (pageContext.redirectTo && !pageContext.isClientSideNavigation) {\n return reply.redirect(307, pageContext.redirectTo);\n }\n\n if (!httpResponse) {\n return reply.code(404).type(\"text/html\").send(\"Not Found\");\n }\n\n const { body, statusCode, headers } = httpResponse;\n return reply\n .status(statusCode)\n .headers(Object.fromEntries(headers))\n .send(body);\n }\n await fastify.register(accepts);\n fastify.decorateRequest(\"bifrostPageId\", null);\n fastify.decorateRequest(\"getLayout\", null);\n await fastify.register(proxy, {\n upstream: upstream.href,\n websocket: true,\n async preHandler(req, reply) {\n if (\n (req.method === \"GET\" || req.method === \"HEAD\") &&\n req.accepts().type([\"html\"]) === \"html\"\n ) {\n const pageContextInit = {\n urlOriginal: req.url,\n ...(buildPageContextInit ? await buildPageContextInit(req) : {}),\n };\n\n const pageContext = await renderPage<\n PageContext,\n typeof pageContextInit\n >(pageContextInit);\n\n // this does not handle getting the original pageId when errors are thrown: https://github.com/vikejs/vike/issues/1112\n req.bifrostPageId = pageContext.pageId;\n\n const proxyMode = pageContext.config?.proxyMode;\n\n switch (proxyMode) {\n case \"passthru\": {\n req.log.info(`bifrost: passthru proxy to backend`);\n return;\n }\n case \"wrapped\": {\n req.log.info(`bifrost: proxy route matched, proxying to backend`);\n if (!!pageContext.isClientSideNavigation) {\n // This should never happen because wrapped proxy routes have no onBeforeRender. onRenderClient should make a request to the legacy backend.\n req.log.error(\n \"Wrapped proxy route is requesting index.pageContext.json. Something is wrong with the client.\"\n );\n return reply.redirect(\n req.url.replace(\"/index.pageContext.json\", \"\")\n );\n }\n if (!pageContext.config?.getLayout) {\n req.log.error(\n \"Config missing getLayout on wrapped route! Falling back to passthru proxy\"\n );\n return;\n }\n\n let proxyHeadersAlreadySet = true;\n for (const [key, val] of Object.entries(\n pageContext.config?.proxyHeaders || {}\n )) {\n proxyHeadersAlreadySet &&= req.headers[key.toLowerCase()] == val;\n req.headers[key.toLowerCase()] = val;\n }\n // If proxy headers set, this is a client navigation meant to go direct to legacy backend.\n // Use passthru proxy in this case. In prod, it'd be better to use ALB to flip target\n if (proxyHeadersAlreadySet) return;\n\n (req.raw as RawRequestExtendedWithProxy)._bfproxy = true;\n req.getLayout = pageContext.config.getLayout;\n return;\n }\n default:\n req.log.info(`bifrost: rendering page ${pageContext.pageId}`);\n return replyWithPage(reply, pageContext);\n }\n }\n },\n replyOptions: {\n rewriteRequestHeaders(request, headers) {\n const fwd = forwarded(request as IncomingMessage).reverse();\n // fwd.push(request.ip); TODO: not sure if this is needed\n headers[\"X-Forwarded-For\"] = fwd.join(\", \");\n headers[\"X-Forwarded-Host\"] = host.host;\n headers[\"X-Forwarded-Proto\"] = host.protocol;\n\n if ((request as RawRequestExtendedWithProxy)._bfproxy) {\n // Proxying and wrapping\n\n // Delete cache headers\n delete headers[\"if-modified-since\"];\n delete headers[\"if-none-match\"];\n delete headers[\"if-unmodified-since\"];\n delete headers[\"if-none-match\"];\n delete headers[\"if-range\"];\n }\n return headers;\n },\n async onResponse(req, reply: FastifyReply<RawServerBase>, res) {\n if ([301, 302, 303, 307, 308].includes(reply.statusCode)) {\n const location = reply.getHeader(\"location\") as string;\n if (location) {\n const url = new URL(location);\n if (url.host === upstream.host || url.host === host.host) {\n // rewrite redirect on upstream's host to the proxy host\n url.host = host.host;\n url.protocol = host.protocol;\n }\n reply.header(\"location\", url);\n return reply.send(res);\n }\n }\n\n const layoutInfo = req.getLayout?.(reply.getHeaders());\n if (!layoutInfo?.layout) {\n return reply.send(res);\n }\n\n const html = await streamToString(res);\n\n const pageContextInit = {\n urlOriginal: req.url,\n // Critical that we don't set any passToClient values in pageContextInit\n // If we do, Vike re-requests pageContext on client navigation. This breaks wrapped proxy.\n wrappedServerOnly: {\n layout: layoutInfo.layout,\n layoutProps: layoutInfo.layoutProps,\n html,\n },\n };\n const pageContext = await renderPage(pageContextInit);\n return replyWithPage(reply, pageContext);\n },\n },\n });\n};\n"],"mappings":";AAGA,OAAO,WAAW;AAClB,OAAO,aAAa;AACpB,OAAO,eAAe;AAGtB,SAAS,kBAAkB;AA6B3B,SAAS,eAAe,QAAmC;AACzD,QAAM,SAAmB,CAAC;AAC1B,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,WAAO,GAAG,QAAQ,CAAC,UAAU,OAAO,KAAK,OAAO,KAAK,KAAK,CAAC,CAAC;AAC5D,WAAO,GAAG,SAAS,CAAC,QAAQ,OAAO,GAAG,CAAC;AACvC,WAAO,GAAG,OAAO,MAAM,QAAQ,OAAO,OAAO,MAAM,EAAE,SAAS,MAAM,CAAC,CAAC;AAAA,EACxE,CAAC;AACH;AAaO,IAAM,kBAET,OAAO,SAAS,EAAE,UAAU,MAAM,SAAS,qBAAqB,MAAM;AACxE,iBAAe,cACb,OACA,aACuB;AACvB,UAAM,EAAE,aAAa,IAAI;AAEzB,QACE,WACA,cAAc,eAAe,OAC7B,YAAY,qBACZ;AACA,cAAQ,YAAY,qBAAqB,WAAW;AAAA,IACtD;AAEA,QAAI,YAAY,cAAc,CAAC,YAAY,wBAAwB;AACjE,aAAO,MAAM,SAAS,KAAK,YAAY,UAAU;AAAA,IACnD;AAEA,QAAI,CAAC,cAAc;AACjB,aAAO,MAAM,KAAK,GAAG,EAAE,KAAK,WAAW,EAAE,KAAK,WAA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,YAAY,QAAQ;AACvB,iBAAO,MAAM,KAAK,GAAG;AAAA,QACvB;AAEA,cAAM,OAAO,MAAM,eAAe,GAAG;AAErC,cAAM,kBAAkB;AAAA,UACtB,aAAa,IAAI;AAAA;AAAA;AAAA,UAGjB,mBAAmB;AAAA,YACjB,QAAQ,WAAW;AAAA,YACnB,aAAa,WAAW;AAAA,YACxB;AAAA,UACF;AAAA,QACF;AACA,cAAM,cAAc,MAAM,WAAW,eAAe;AACpD,eAAO,cAAc,OAAO,WAAW;AAAA,MACzC;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../index.ts","../lib/extractDomElements.ts"],"sourcesContent":["// Note that this file isn't processed by Vite, see https://github.com/brillout/vike/issues/562\nimport { FastifyReply, RawServerBase, FastifyPluginAsync } from \"fastify\";\nimport { FastifyRequest, RequestGenericInterface } from \"fastify/types/request\";\nimport proxy from \"@fastify/http-proxy\";\nimport accepts from \"@fastify/accepts\";\nimport forwarded from \"@fastify/forwarded\";\nimport type { GetLayout, WrappedServerOnly } from \"@alignable/bifrost/config\";\nimport { Writable } from \"stream\";\nimport { IncomingMessage } from \"http\";\nimport { renderPage } from \"vike/server\";\nimport { PageContextServer } from \"vike/types\";\nimport { extractDomElements } from \"./lib/extractDomElements\";\n\ntype RenderedPageContext = Awaited<\n ReturnType<\n typeof renderPage<\n {\n isClientSideNavigation?: boolean;\n },\n { urlOriginal: string }\n >\n >\n>;\n\ndeclare module \"fastify\" {\n interface FastifyRequest {\n bifrostPageId?: string | null;\n getLayout: GetLayout;\n }\n}\n\ntype RawRequestExtendedWithProxy = FastifyRequest<\n RequestGenericInterface,\n RawServerBase\n>[\"raw\"] & {\n _bfproxy?: boolean;\n};\n\nfunction streamToString(stream: Writable): Promise<string> {\n const chunks: Buffer[] = [];\n return new Promise((resolve, reject) => {\n stream.on(\"data\", (chunk) => chunks.push(Buffer.from(chunk)));\n stream.on(\"error\", (err) => reject(err));\n stream.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n });\n}\n\ninterface ViteProxyPluginOptions {\n upstream: URL;\n host: URL;\n onError?: (error: any, pageContext: RenderedPageContext) => void;\n buildPageContextInit?: (\n req: FastifyRequest\n ) => Promise<Partial<Omit<PageContextServer, \"headers\">>>;\n}\n/**\n * Fastify plugin that wraps @fasitfy/http-proxy to proxy Rails/Turbolinks server into a vike site.\n */\nexport const viteProxyPlugin: FastifyPluginAsync<\n ViteProxyPluginOptions\n> = async (fastify, { upstream, host, onError, buildPageContextInit }) => {\n async function replyWithPage(\n reply: FastifyReply<RawServerBase>,\n pageContext: RenderedPageContext\n ): Promise<FastifyReply> {\n const { httpResponse } = pageContext;\n\n if (\n onError &&\n httpResponse?.statusCode === 500 &&\n pageContext.errorWhileRendering\n ) {\n onError(pageContext.errorWhileRendering, pageContext);\n }\n\n if (!httpResponse) {\n return reply.code(404).type(\"text/html\").send(\"Not Found\");\n }\n\n const { body, statusCode, headers } = httpResponse;\n return reply\n .status(statusCode)\n .headers(Object.fromEntries(headers))\n .send(body);\n }\n await fastify.register(accepts);\n fastify.decorateRequest(\"bifrostPageId\", null);\n fastify.decorateRequest(\"getLayout\", null);\n await fastify.register(proxy, {\n upstream: upstream.href,\n websocket: true,\n async preHandler(req, reply) {\n if (\n (req.method === \"GET\" || req.method === \"HEAD\") &&\n req.accepts().type([\"html\"]) === \"html\"\n ) {\n const pageContextInit = {\n urlOriginal: req.url,\n ...(buildPageContextInit ? await buildPageContextInit(req) : {}),\n };\n\n const pageContext = await renderPage(pageContextInit);\n\n // this does not handle getting the original pageId when errors are thrown: https://github.com/vikejs/vike/issues/1112\n req.bifrostPageId = pageContext.pageId;\n\n const proxyMode = pageContext.config?.proxyMode;\n\n switch (proxyMode) {\n case \"passthru\": {\n req.log.info(`bifrost: passthru proxy to backend`);\n return;\n }\n case \"wrapped\": {\n req.log.info(`bifrost: proxy route matched, proxying to backend`);\n if (!!pageContext.isClientSideNavigation) {\n // This should never happen because wrapped proxy routes have no onBeforeRender. onRenderClient should make a request to the legacy backend.\n req.log.error(\n \"Wrapped proxy route is requesting index.pageContext.json. Something is wrong with the client.\"\n );\n return reply.redirect(\n req.url.replace(\"/index.pageContext.json\", \"\")\n );\n }\n if (!pageContext.config?.getLayout) {\n req.log.error(\n \"Config missing getLayout on wrapped route! Falling back to passthru proxy\"\n );\n return;\n }\n\n let proxyHeadersAlreadySet = true;\n for (const [key, val] of Object.entries(\n pageContext.config?.proxyHeaders || {}\n )) {\n proxyHeadersAlreadySet &&= req.headers[key.toLowerCase()] == val;\n req.headers[key.toLowerCase()] = val;\n }\n // If proxy headers set, this is a client navigation meant to go direct to legacy backend.\n // Use passthru proxy in this case.\n // ALB CANNOT be used for this. see `onBeforeRenderClient` for details\n if (proxyHeadersAlreadySet) return;\n\n (req.raw as RawRequestExtendedWithProxy)._bfproxy = true;\n req.getLayout = pageContext.config.getLayout;\n return;\n }\n default:\n req.log.info(`bifrost: rendering page ${pageContext.pageId}`);\n return replyWithPage(reply, pageContext);\n }\n }\n },\n replyOptions: {\n rewriteRequestHeaders(request, headers) {\n const fwd = forwarded(request as IncomingMessage).reverse();\n // fwd.push(request.ip); TODO: not sure if this is needed\n headers[\"X-Forwarded-For\"] = fwd.join(\", \");\n headers[\"X-Forwarded-Host\"] = host.host;\n headers[\"X-Forwarded-Proto\"] = host.protocol;\n\n if ((request as RawRequestExtendedWithProxy)._bfproxy) {\n // Proxying and wrapping\n\n // Delete cache headers\n delete headers[\"if-modified-since\"];\n delete headers[\"if-none-match\"];\n delete headers[\"if-unmodified-since\"];\n delete headers[\"if-none-match\"];\n delete headers[\"if-range\"];\n }\n return headers;\n },\n async onResponse(req, reply: FastifyReply<RawServerBase>, res) {\n if ([301, 302, 303, 307, 308].includes(reply.statusCode)) {\n const location = reply.getHeader(\"location\") as string;\n console.log(location);\n if (location) {\n const url = new URL(location, host.href);\n if (url.host === upstream.host || url.host === host.host) {\n // rewrite redirect on upstream's host to the proxy host\n url.host = host.host;\n url.protocol = host.protocol;\n }\n reply.header(\"location\", url);\n return reply.send(res);\n }\n }\n\n const proxyLayoutInfo = req.getLayout?.(reply.getHeaders());\n if (!proxyLayoutInfo) {\n return reply.send(res);\n }\n\n const html = await streamToString(res);\n\n const { bodyAttributes, bodyInnerHtml, headInnerHtml } =\n extractDomElements(html);\n\n if (!bodyInnerHtml || !headInnerHtml) {\n throw new Error(\"Proxy failed\");\n }\n\n const pageContextInit = {\n urlOriginal: req.url,\n // Critical that we don't set any passToClient values in pageContextInit\n // If we do, Vike re-requests pageContext on client navigation. This breaks wrapped proxy.\n _wrappedServerOnly: {\n bodyAttributes,\n bodyInnerHtml,\n headInnerHtml,\n proxyLayoutInfo,\n } satisfies WrappedServerOnly,\n };\n const pageContext = await renderPage(pageContextInit);\n return replyWithPage(reply, pageContext);\n },\n },\n });\n};\n","import { Parser } from \"htmlparser2\";\nimport { DomHandler, type Element } from \"domhandler\";\nimport { findOne } from \"domutils\";\nimport render from \"dom-serializer\";\n\nfunction getInnerHtml(element: Element): string {\n return element.children.map((c) => render(c)).join(\"\");\n}\n\nexport function extractDomElements(html: string): {\n bodyInnerHtml: string | null;\n headInnerHtml: string | null;\n bodyAttributes: Record<string, string>;\n} {\n let bodyInnerHtml: string | null = null;\n let headInnerHtml: string | null = null;\n let bodyAttributes: Record<string, string> = {};\n const handler = new DomHandler((error, dom) => {\n if (!error) {\n const body = findOne((elem) => elem.name === \"body\", dom);\n const head = findOne((elem) => elem.name === \"head\", dom);\n if (body && head) {\n bodyAttributes = body.attribs;\n bodyInnerHtml = getInnerHtml(body);\n headInnerHtml = getInnerHtml(head);\n }\n }\n });\n const parser = new Parser(handler);\n parser.write(html);\n parser.end();\n return { bodyInnerHtml, headInnerHtml, bodyAttributes };\n}\n"],"mappings":";AAGA,OAAO,WAAW;AAClB,OAAO,aAAa;AACpB,OAAO,eAAe;AAItB,SAAS,kBAAkB;;;ACT3B,SAAS,cAAc;AACvB,SAAS,kBAAgC;AACzC,SAAS,eAA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OAAO,YAAY,GAAG;AAC5B,mBAAO,MAAM,KAAK,GAAG;AAAA,UACvB;AAAA,QACF;AAEA,cAAM,kBAAkB,IAAI,YAAY,MAAM,WAAW,CAAC;AAC1D,YAAI,CAAC,iBAAiB;AACpB,iBAAO,MAAM,KAAK,GAAG;AAAA,QACvB;AAEA,cAAM,OAAO,MAAM,eAAe,GAAG;AAErC,cAAM,EAAE,gBAAgB,eAAe,cAAc,IACnD,mBAAmB,IAAI;AAEzB,YAAI,CAAC,iBAAiB,CAAC,eAAe;AACpC,gBAAM,IAAI,MAAM,cAAc;AAAA,QAChC;AAEA,cAAM,kBAAkB;AAAA,UACtB,aAAa,IAAI;AAAA;AAAA;AAAA,UAGjB,oBAAoB;AAAA,YAClB;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAAA,QACF;AACA,cAAM,cAAc,MAAM,WAAW,eAAe;AACpD,eAAO,cAAc,OAAO,WAAW;AAAA,MACzC;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@alignable/bifrost-fastify",
3
3
  "repository": "https://github.com/Alignable/bifrost.git",
4
- "version": "0.1.1",
4
+ "version": "1.0.0",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -12,23 +12,26 @@
12
12
  "@fastify/reply-from": "^9.0.1",
13
13
  "compression": "^1.7.4",
14
14
  "cross-env": "^7.0.3",
15
+ "dom-serializer": "^2.0.0",
16
+ "domhandler": "^5.0.3",
17
+ "domutils": "^3.2.2",
15
18
  "fastify": "^4.9.2",
19
+ "htmlparser2": "^10.0.0",
16
20
  "sirv": "^2.0.2",
17
21
  "vite": "^6.3.5"
18
22
  },
19
23
  "peerDependencies": {
20
- "@alignable/bifrost": "0.1.1",
24
+ "@alignable/bifrost": "1.0.0",
21
25
  "fastify": "^4.9.2",
22
- "vike": "0.4.244"
26
+ "vike": "0.4.247"
23
27
  },
24
28
  "devDependencies": {
25
29
  "@types/connect": "^3.4.35",
26
- "@types/jsdom": "^21.1.1",
27
30
  "@types/node": "^18.11.9",
28
31
  "@types/react": "^18.0.8",
29
32
  "@types/react-dom": "^18.0.3",
30
- "react": "^18.2.0",
31
- "react-dom": "^18.2.0",
33
+ "react": "^19.0.0",
34
+ "react-dom": "^19.0.0",
32
35
  "tsup": "^6.7.0",
33
36
  "typescript": "^5.0.4"
34
37
  },