@adonisjs/vite 3.0.0-2 → 3.0.0-3

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.
@@ -6,8 +6,8 @@ import {
6
6
  // src/vite.ts
7
7
  import { readFileSync } from "node:fs";
8
8
  var Vite = class {
9
- constructor(inDev, options) {
10
- this.inDev = inDev;
9
+ constructor(isViteRunning, options) {
10
+ this.isViteRunning = isViteRunning;
11
11
  this.#options = options;
12
12
  this.#options.assetsUrl = (this.#options.assetsUrl || "/").replace(/\/$/, "");
13
13
  }
@@ -96,7 +96,7 @@ var Vite = class {
96
96
  */
97
97
  #generateTag(asset, attributes) {
98
98
  let url = "";
99
- if (this.inDev) {
99
+ if (this.isViteRunning) {
100
100
  url = `/${asset}`;
101
101
  } else {
102
102
  url = `${this.#options.assetsUrl}/${asset}`;
@@ -150,7 +150,7 @@ var Vite = class {
150
150
  */
151
151
  generateEntryPointsTags(entryPoints, attributes) {
152
152
  entryPoints = Array.isArray(entryPoints) ? entryPoints : [entryPoints];
153
- if (this.inDev) {
153
+ if (this.isViteRunning) {
154
154
  return this.#generateEntryPointsTagsForHotMode(entryPoints, attributes);
155
155
  }
156
156
  return this.#generateEntryPointsTagsWithManifest(entryPoints, attributes);
@@ -161,7 +161,7 @@ var Vite = class {
161
161
  * "assets" URL
162
162
  */
163
163
  assetsUrl() {
164
- if (this.inDev)
164
+ if (this.isViteRunning)
165
165
  return this.#devServer.config.server.host;
166
166
  return this.#options.assetsUrl;
167
167
  }
@@ -169,7 +169,7 @@ var Vite = class {
169
169
  * Returns path to a given asset file
170
170
  */
171
171
  assetPath(asset) {
172
- if (this.inDev) {
172
+ if (this.isViteRunning) {
173
173
  return `/${asset}`;
174
174
  }
175
175
  const chunk = this.#chunk(this.manifest(), asset);
@@ -181,7 +181,7 @@ var Vite = class {
181
181
  * @throws Will throw an exception when running in dev
182
182
  */
183
183
  manifest() {
184
- if (this.inDev) {
184
+ if (this.isViteRunning) {
185
185
  throw new Error("Cannot read the manifest file when running in dev mode");
186
186
  }
187
187
  if (!this.#manifestCache) {
@@ -227,7 +227,7 @@ var Vite = class {
227
227
  * Returns the script needed for the HMR working with React
228
228
  */
229
229
  getReactHmrScript(attributes) {
230
- if (!this.inDev) {
230
+ if (!this.isViteRunning) {
231
231
  return null;
232
232
  }
233
233
  return this.#generateElement({
@@ -252,4 +252,4 @@ var Vite = class {
252
252
  export {
253
253
  Vite
254
254
  };
255
- //# sourceMappingURL=chunk-J6JUW6YH.js.map
255
+ //# sourceMappingURL=chunk-55PHIY4G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vite.ts"],"sourcesContent":["/*\n * @adonisjs/vite\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport { readFileSync } from 'node:fs'\nimport type { ViteRuntime } from 'vite/runtime'\nimport type { Manifest, ViteDevServer } from 'vite'\n\nimport { makeAttributes, uniqBy } from './utils.js'\nimport type { AdonisViteElement, SetAttributes, ViteOptions } from './types.js'\n\n/**\n * Vite class exposes the APIs to generate tags and URLs for\n * assets processed using vite.\n */\nexport class Vite {\n /**\n * We cache the manifest file content in production\n * to avoid reading the file multiple times\n */\n #manifestCache?: Manifest\n #options: ViteOptions\n #runtime?: ViteRuntime\n #devServer?: ViteDevServer\n\n constructor(\n protected isViteRunning: boolean,\n options: ViteOptions\n ) {\n this.#options = options\n this.#options.assetsUrl = (this.#options.assetsUrl || '/').replace(/\\/$/, '')\n }\n\n /**\n * Reads the file contents as JSON\n */\n #readFileAsJSON(filePath: string) {\n return JSON.parse(readFileSync(filePath, 'utf-8'))\n }\n\n /**\n * Generates a JSON element with a custom toString implementation\n */\n #generateElement(element: AdonisViteElement) {\n return {\n ...element,\n toString() {\n const attributes = `${makeAttributes(element.attributes)}`\n if (element.tag === 'link') {\n return `<${element.tag} ${attributes}/>`\n }\n\n return `<${element.tag} ${attributes}>${element.children.join('\\n')}</${element.tag}>`\n },\n }\n }\n\n /**\n * Returns the script needed for the HMR working with Vite\n */\n #getViteHmrScript(attributes?: Record<string, any>): AdonisViteElement | null {\n return this.#generateElement({\n tag: 'script',\n attributes: {\n type: 'module',\n src: '/@vite/client',\n ...attributes,\n },\n children: [],\n })\n }\n\n /**\n * Check if the given path is a CSS path\n */\n #isCssPath(path: string) {\n return path.match(/\\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/) !== null\n }\n\n /**\n * Unwrap attributes from the user defined function or return\n * the attributes as it is\n */\n #unwrapAttributes(src: string, url: string, attributes?: SetAttributes) {\n if (typeof attributes === 'function') {\n return attributes({ src, url })\n }\n\n return attributes\n }\n\n /**\n * Create a style tag for the given path\n */\n #makeStyleTag(src: string, url: string, attributes?: Record<string, any>): AdonisViteElement {\n const customAttributes = this.#unwrapAttributes(src, url, this.#options?.styleAttributes)\n return this.#generateElement({\n tag: 'link',\n attributes: { rel: 'stylesheet', ...customAttributes, ...attributes, href: url },\n })\n }\n\n /**\n * Create a script tag for the given path\n */\n #makeScriptTag(src: string, url: string, attributes?: Record<string, any>): AdonisViteElement {\n const customAttributes = this.#unwrapAttributes(src, url, this.#options?.scriptAttributes)\n return this.#generateElement({\n tag: 'script',\n attributes: { type: 'module', ...customAttributes, ...attributes, src: url },\n children: [],\n })\n }\n\n /**\n * Generate a HTML tag for the given asset\n */\n #generateTag(asset: string, attributes?: Record<string, any>): AdonisViteElement {\n let url = ''\n if (this.isViteRunning) {\n url = `/${asset}`\n } else {\n url = `${this.#options.assetsUrl}/${asset}`\n }\n\n if (this.#isCssPath(asset)) {\n return this.#makeStyleTag(asset, url, attributes)\n }\n\n return this.#makeScriptTag(asset, url, attributes)\n }\n\n /**\n * Generate style and script tags for the given entrypoints\n * Also adds the @vite/client script\n */\n #generateEntryPointsTagsForHotMode(\n entryPoints: string[],\n attributes?: Record<string, any>\n ): AdonisViteElement[] {\n const viteHmr = this.#getViteHmrScript(attributes)\n const tags = entryPoints.map((entrypoint) => this.#generateTag(entrypoint, attributes))\n\n const result = viteHmr ? [viteHmr].concat(tags) : tags\n\n return result\n }\n\n /**\n * Get a chunk from the manifest file for a given file name\n */\n #chunk(manifest: Manifest, fileName: string) {\n const chunk = manifest[fileName]\n\n if (!chunk) {\n throw new Error(`Cannot find \"${fileName}\" chunk in the manifest file`)\n }\n\n return chunk\n }\n\n /**\n * Generate style and script tags for the given entrypoints\n * using the manifest file\n */\n #generateEntryPointsTagsWithManifest(\n entryPoints: string[],\n attributes?: Record<string, any>\n ): AdonisViteElement[] {\n const manifest = this.manifest()\n const tags: { path: string; tag: AdonisViteElement }[] = []\n\n for (const entryPoint of entryPoints) {\n const chunk = this.#chunk(manifest, entryPoint)\n tags.push({\n path: chunk.file,\n tag: this.#generateTag(chunk.file, { ...attributes, integrity: chunk.integrity }),\n })\n\n for (const css of chunk.css || []) {\n tags.push({ path: css, tag: this.#generateTag(css) })\n }\n }\n\n return uniqBy(tags, 'path')\n .sort((a) => (a.path.endsWith('.css') ? -1 : 1))\n .map((tag) => tag.tag)\n }\n\n /**\n * Generate tags for the entry points\n */\n generateEntryPointsTags(\n entryPoints: string[] | string,\n attributes?: Record<string, any>\n ): AdonisViteElement[] {\n entryPoints = Array.isArray(entryPoints) ? entryPoints : [entryPoints]\n\n if (this.isViteRunning) {\n return this.#generateEntryPointsTagsForHotMode(entryPoints, attributes)\n }\n\n return this.#generateEntryPointsTagsWithManifest(entryPoints, attributes)\n }\n\n /**\n * Returns the dev server URL when running in hot\n * mode, otherwise returns the explicitly configured\n * \"assets\" URL\n */\n assetsUrl() {\n if (this.isViteRunning) return this.#devServer!.config.server.host\n\n return this.#options.assetsUrl\n }\n\n /**\n * Returns path to a given asset file\n */\n assetPath(asset: string): string {\n if (this.isViteRunning) {\n return `/${asset}`\n }\n\n const chunk = this.#chunk(this.manifest(), asset)\n return `${this.#options.assetsUrl}/${chunk.file}`\n }\n\n /**\n * Returns the manifest file contents\n *\n * @throws Will throw an exception when running in dev\n */\n manifest(): Manifest {\n if (this.isViteRunning) {\n throw new Error('Cannot read the manifest file when running in dev mode')\n }\n\n if (!this.#manifestCache) {\n this.#manifestCache = this.#readFileAsJSON(this.#options.manifestFile)\n }\n\n return this.#manifestCache!\n }\n\n /**\n * Create the Vite Dev Server and runtime\n *\n * We lazy load the APIs to avoid loading it in production\n * since we don't need it\n */\n async createDevServer() {\n const { createViteRuntime, createServer } = await import('vite')\n\n this.#devServer = await createServer({\n server: { middlewareMode: true, hmr: { port: 3001 } },\n appType: 'custom',\n })\n\n this.#runtime = await createViteRuntime(this.#devServer)\n }\n\n /**\n * Stop the Vite Dev server\n */\n async stopDevServer() {\n await this.#devServer?.close()\n }\n\n /**\n * Get the Vite Dev server instance\n * Will not be available when running in production\n */\n getDevServer() {\n return this.#devServer\n }\n\n /**\n * Get the Vite runtime instance\n * Will not be available when running in production\n */\n getRuntime() {\n return this.#runtime\n }\n\n /**\n * Returns the script needed for the HMR working with React\n */\n getReactHmrScript(attributes?: Record<string, any>): AdonisViteElement | null {\n if (!this.isViteRunning) {\n return null\n }\n\n return this.#generateElement({\n tag: 'script',\n attributes: {\n type: 'module',\n ...attributes,\n },\n children: [\n '',\n `import RefreshRuntime from '/@react-refresh'`,\n `RefreshRuntime.injectIntoGlobalHook(window)`,\n `window.$RefreshReg$ = () => {}`,\n `window.$RefreshSig$ = () => (type) => type`,\n `window.__vite_plugin_react_preamble_installed__ = true`,\n '',\n ],\n })\n }\n}\n"],"mappings":";;;;;;AASA,SAAS,oBAAoB;AAWtB,IAAM,OAAN,MAAW;AAAA,EAUhB,YACY,eACV,SACA;AAFU;AAGV,SAAK,WAAW;AAChB,SAAK,SAAS,aAAa,KAAK,SAAS,aAAa,KAAK,QAAQ,OAAO,EAAE;AAAA,EAC9E;AAAA;AAAA;AAAA;AAAA;AAAA,EAXA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAaA,gBAAgB,UAAkB;AAChC,WAAO,KAAK,MAAM,aAAa,UAAU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;AAAA;AAAA,EAQA,MAAM,kBAAkB;AACtB,UAAM,EAAE,mBAAmB,aAAa,IAAI,MAAM,OAAO,MAAM;AAE/D,SAAK,aAAa,MAAM,aAAa;AAAA,MACnC,QAAQ,EAAE,gBAAgB,MAAM,KAAK,EAAE,MAAM,KAAK,EAAE;AAAA,MACpD,SAAS;AAAA,IACX,CAAC;AAED,SAAK,WAAW,MAAM,kBAAkB,KAAK,UAAU;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,gBAAgB;AACpB,UAAM,KAAK,YAAY,MAAM;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,eAAe;AACb,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAa;AACX,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,kBAAkB,YAA4D;AAC5E,QAAI,CAAC,KAAK,eAAe;AACvB,aAAO;AAAA,IACT;AAEA,WAAO,KAAK,iBAAiB;AAAA,MAC3B,KAAK;AAAA,MACL,YAAY;AAAA,QACV,MAAM;AAAA,QACN,GAAG;AAAA,MACL;AAAA,MACA,UAAU;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
package/build/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Vite
3
- } from "./chunk-J6JUW6YH.js";
3
+ } from "./chunk-55PHIY4G.js";
4
4
  import "./chunk-CFRBPZ4N.js";
5
5
 
6
6
  // stubs/main.ts
@@ -6,13 +6,24 @@ declare module '@adonisjs/core/types' {
6
6
  }
7
7
  }
8
8
  export default class ViteProvider {
9
+ #private;
9
10
  protected app: ApplicationService;
10
11
  constructor(app: ApplicationService);
11
12
  /**
12
13
  * Registers edge plugin when edge is installed
13
14
  */
14
15
  protected registerEdgePlugin(): Promise<void>;
15
- register(): Promise<void>;
16
+ /**
17
+ * Register Vite bindings
18
+ */
19
+ register(): void;
20
+ /**
21
+ * - Register edge tags
22
+ * - Start Vite server when running in development or test
23
+ */
16
24
  boot(): Promise<void>;
25
+ /**
26
+ * Stop Vite server when running in development or test
27
+ */
17
28
  shutdown(): Promise<void>;
18
29
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Vite
3
- } from "../chunk-J6JUW6YH.js";
3
+ } from "../chunk-55PHIY4G.js";
4
4
  import "../chunk-CFRBPZ4N.js";
5
5
  import {
6
6
  ViteMiddleware
@@ -10,7 +10,10 @@ import {
10
10
  var ViteProvider = class {
11
11
  constructor(app) {
12
12
  this.app = app;
13
+ const env = this.app.getEnvironment();
14
+ this.#shouldRunVite = (this.app.inDev || this.app.inTest) && (env === "web" || env === "test");
13
15
  }
16
+ #shouldRunVite;
14
17
  /**
15
18
  * Registers edge plugin when edge is installed
16
19
  */
@@ -18,28 +21,37 @@ var ViteProvider = class {
18
21
  if (this.app.usingEdgeJS) {
19
22
  const edge = await import("edge.js");
20
23
  const vite = await this.app.container.make("vite");
21
- const { edgePluginVite } = await import("../edge-SDXKV2NF.js");
24
+ const { edgePluginVite } = await import("../src/plugins/edge.js");
22
25
  edge.default.use(edgePluginVite(vite));
23
26
  }
24
27
  }
25
- async register() {
28
+ /**
29
+ * Register Vite bindings
30
+ */
31
+ register() {
26
32
  const config = this.app.config.get("vite");
27
- const vite = new Vite(this.app.inDev, config);
33
+ const vite = new Vite(this.#shouldRunVite, config);
28
34
  this.app.container.bind("vite", () => vite);
29
35
  this.app.container.bind(ViteMiddleware, () => new ViteMiddleware(vite));
30
- if (this.app.inDev) {
31
- const server = await this.app.container.make("server");
32
- server.use([() => import("../vite_middleware-HYLIJP2B.js")]);
33
- }
34
36
  }
37
+ /**
38
+ * - Register edge tags
39
+ * - Start Vite server when running in development or test
40
+ */
35
41
  async boot() {
36
- if (!this.app.inDev)
42
+ await this.registerEdgePlugin();
43
+ if (!this.#shouldRunVite)
37
44
  return;
38
45
  const vite = await this.app.container.make("vite");
39
- await Promise.all([vite.createDevServer(), this.registerEdgePlugin()]);
46
+ const server = await this.app.container.make("server");
47
+ await vite.createDevServer();
48
+ server.use([() => import("../vite_middleware-HYLIJP2B.js")]);
40
49
  }
50
+ /**
51
+ * Stop Vite server when running in development or test
52
+ */
41
53
  async shutdown() {
42
- if (!this.app.inDev)
54
+ if (!this.#shouldRunVite)
43
55
  return;
44
56
  const vite = await this.app.container.make("vite");
45
57
  await vite.stopDevServer();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../providers/vite_provider.ts"],"sourcesContent":["/*\n * @adonisjs/vite\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport type { ApplicationService } from '@adonisjs/core/types'\n\nimport { Vite } from '../src/vite.js'\nimport type { ViteOptions } from '../src/types.js'\nimport ViteMiddleware from '../src/middlewares/vite_middleware.js'\n\ndeclare module '@adonisjs/core/types' {\n interface ContainerBindings {\n vite: Vite\n }\n}\n\nexport default class ViteProvider {\n constructor(protected app: ApplicationService) {}\n\n /**\n * Registers edge plugin when edge is installed\n */\n protected async registerEdgePlugin() {\n if (this.app.usingEdgeJS) {\n const edge = await import('edge.js')\n const vite = await this.app.container.make('vite')\n const { edgePluginVite } = await import('../src/plugins/edge.js')\n edge.default.use(edgePluginVite(vite))\n }\n }\n\n async register() {\n const config = this.app.config.get<ViteOptions>('vite')\n\n const vite = new Vite(this.app.inDev, config)\n this.app.container.bind('vite', () => vite)\n this.app.container.bind(ViteMiddleware, () => new ViteMiddleware(vite))\n\n if (this.app.inDev) {\n const server = await this.app.container.make('server')\n server.use([() => import('../src/middlewares/vite_middleware.js')])\n }\n }\n\n async boot() {\n if (!this.app.inDev) return\n\n const vite = await this.app.container.make('vite')\n await Promise.all([vite.createDevServer(), this.registerEdgePlugin()])\n }\n\n async shutdown() {\n if (!this.app.inDev) return\n\n const vite = await this.app.container.make('vite')\n await vite.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onisjs/vite\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport type { ApplicationService } from '@adonisjs/core/types'\n\nimport { Vite } from '../src/vite.js'\nimport type { ViteOptions } from '../src/types.js'\nimport ViteMiddleware from '../src/middlewares/vite_middleware.js'\n\ndeclare module '@adonisjs/core/types' {\n interface ContainerBindings {\n vite: Vite\n }\n}\n\nexport default class ViteProvider {\n #shouldRunVite: boolean\n\n constructor(protected app: ApplicationService) {\n /**\n * We should only run Vite in development and test environments\n */\n const env = this.app.getEnvironment()\n this.#shouldRunVite = (this.app.inDev || this.app.inTest) && (env === 'web' || env === 'test')\n }\n\n /**\n * Registers edge plugin when edge is installed\n */\n protected async registerEdgePlugin() {\n if (this.app.usingEdgeJS) {\n const edge = await import('edge.js')\n const vite = await this.app.container.make('vite')\n const { edgePluginVite } = await import('../src/plugins/edge.js')\n edge.default.use(edgePluginVite(vite))\n }\n }\n\n /**\n * Register Vite bindings\n */\n register() {\n const config = this.app.config.get<ViteOptions>('vite')\n\n const vite = new Vite(this.#shouldRunVite, config)\n this.app.container.bind('vite', () => vite)\n this.app.container.bind(ViteMiddleware, () => new ViteMiddleware(vite))\n }\n\n /**\n * - Register edge tags\n * - Start Vite server when running in development or test\n */\n async boot() {\n await this.registerEdgePlugin()\n\n if (!this.#shouldRunVite) return\n\n const vite = await this.app.container.make('vite')\n const server = await this.app.container.make('server')\n\n await vite.createDevServer()\n server.use([() => import('../src/middlewares/vite_middleware.js')])\n }\n\n /**\n * Stop Vite server when running in development or test\n */\n async shutdown() {\n if (!this.#shouldRunVite) return\n\n const vite = await this.app.container.make('vite')\n await vite.stopDevServer()\n }\n}\n"],"mappings":";;;;;;;;;AAqBA,IAAqB,eAArB,MAAkC;AAAA,EAGhC,YAAsB,KAAyB;AAAzB;AAIpB,UAAM,MAAM,KAAK,IAAI,eAAe;AACpC,SAAK,kBAAkB,KAAK,IAAI,SAAS,KAAK,IAAI,YAAY,QAAQ,SAAS,QAAQ;AAAA,EACzF;AAAA,EARA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAgB,qBAAqB;AACnC,QAAI,KAAK,IAAI,aAAa;AACxB,YAAM,OAAO,MAAM,OAAO,SAAS;AACnC,YAAM,OAAO,MAAM,KAAK,IAAI,UAAU,KAAK,MAAM;AACjD,YAAM,EAAE,eAAe,IAAI,MAAM,OAAO,wBAAwB;AAChE,WAAK,QAAQ,IAAI,eAAe,IAAI,CAAC;AAAA,IACvC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,WAAW;AACT,UAAM,SAAS,KAAK,IAAI,OAAO,IAAiB,MAAM;AAEtD,UAAM,OAAO,IAAI,KAAK,KAAK,gBAAgB,MAAM;AACjD,SAAK,IAAI,UAAU,KAAK,QAAQ,MAAM,IAAI;AAC1C,SAAK,IAAI,UAAU,KAAK,gBAAgB,MAAM,IAAI,eAAe,IAAI,CAAC;AAAA,EACxE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,OAAO;AACX,UAAM,KAAK,mBAAmB;AAE9B,QAAI,CAAC,KAAK;AAAgB;AAE1B,UAAM,OAAO,MAAM,KAAK,IAAI,UAAU,KAAK,MAAM;AACjD,UAAM,SAAS,MAAM,KAAK,IAAI,UAAU,KAAK,QAAQ;AAErD,UAAM,KAAK,gBAAgB;AAC3B,WAAO,IAAI,CAAC,MAAM,OAAO,gCAAuC,CAAC,CAAC;AAAA,EACpE;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAAW;AACf,QAAI,CAAC,KAAK;AAAgB;AAE1B,UAAM,OAAO,MAAM,KAAK,IAAI,UAAU,KAAK,MAAM;AACjD,UAAM,KAAK,cAAc;AAAA,EAC3B;AACF;","names":[]}
@@ -1,4 +1,4 @@
1
- import type { AssemblerHookHandler } from '@adonisjs/application/types';
1
+ import type { AssemblerHookHandler } from '@adonisjs/core/types/app';
2
2
  /**
3
3
  * This is an Assembler hook that should be executed when the application is
4
4
  * builded using the `node ace build` command.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/hooks/build_hook.ts"],"sourcesContent":["/*\n * @adonisjs/vite\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport { multibuild } from '@vavite/multibuild'\nimport type { AssemblerHookHandler } from '@adonisjs/application/types'\n\n/**\n * This is an Assembler hook that should be executed when the application is\n * builded using the `node ace build` command.\n *\n * The hook is responsible for launching a Vite multi-build process.\n */\nexport default async function viteBuildHook({ logger }: Parameters<AssemblerHookHandler>[0]) {\n logger.info('building assets with vite')\n\n await multibuild(undefined, {\n onStartBuildStep: (step) => {\n if (!step.currentStep.description) return\n\n logger.info(step.currentStep.description)\n },\n })\n}\n"],"mappings":";AASA,SAAS,kBAAkB;AAS3B,eAAO,cAAqC,EAAE,OAAO,GAAwC;AAC3F,SAAO,KAAK,2BAA2B;AAEvC,QAAM,WAAW,QAAW;AAAA,IAC1B,kBAAkB,CAAC,SAAS;AAC1B,UAAI,CAAC,KAAK,YAAY;AAAa;AAEnC,aAAO,KAAK,KAAK,YAAY,WAAW;AAAA,IAC1C;AAAA,EACF,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../../src/hooks/build_hook.ts"],"sourcesContent":["/*\n * @adonisjs/vite\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport { multibuild } from '@vavite/multibuild'\nimport type { AssemblerHookHandler } from '@adonisjs/core/types/app'\n\n/**\n * This is an Assembler hook that should be executed when the application is\n * builded using the `node ace build` command.\n *\n * The hook is responsible for launching a Vite multi-build process.\n */\nexport default async function viteBuildHook({ logger }: Parameters<AssemblerHookHandler>[0]) {\n logger.info('building assets with vite')\n\n await multibuild(undefined, {\n onStartBuildStep: (step) => {\n if (!step.currentStep.description) return\n\n logger.info(step.currentStep.description)\n },\n })\n}\n"],"mappings":";AASA,SAAS,kBAAkB;AAS3B,eAAO,cAAqC,EAAE,OAAO,GAAwC;AAC3F,SAAO,KAAK,2BAA2B;AAEvC,QAAM,WAAW,QAAW;AAAA,IAC1B,kBAAkB,CAAC,SAAS;AAC1B,UAAI,CAAC,KAAK,YAAY;AAAa;AAEnC,aAAO,KAAK,KAAK,YAAY,WAAW;AAAA,IAC1C;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -67,4 +67,4 @@ var edgePluginVite = (vite) => {
67
67
  export {
68
68
  edgePluginVite
69
69
  };
70
- //# sourceMappingURL=edge-SDXKV2NF.js.map
70
+ //# sourceMappingURL=edge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/plugins/edge.ts"],"sourcesContent":["/*\n * @adonisjs/vite\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport type { Edge } from 'edge.js'\nimport { EdgeError } from 'edge-error'\nimport type { PluginFn } from 'edge.js/types'\n\nimport type { Vite } from '../vite.js'\n\n/**\n * The edge plugin for vite to share vite service with edge\n * and register custom tags\n */\nexport const edgePluginVite: (vite: Vite) => PluginFn<undefined> = (vite) => {\n const edgeVite = (edge: Edge) => {\n edge.global('vite', vite)\n edge.global('asset', vite.assetPath.bind(vite))\n\n edge.registerTag({\n tagName: 'viteReactRefresh',\n seekable: true,\n block: false,\n compile(parser, buffer, token) {\n let attributes = ''\n if (token.properties.jsArg.trim()) {\n /**\n * Converting a single argument to a SequenceExpression so that we\n * work around the following edge cases.\n *\n * - If someone passes an object literal to the tag, ie { nonce: 'foo' }\n * it will be parsed as a LabeledStatement and not an object.\n * - If we wrap the object literal inside parenthesis, ie ({nonce: 'foo'})\n * then we will end up messing other expressions like a variable reference\n * , or a member expression and so on.\n * - So the best bet is to convert user supplied argument to a sequence expression\n * and hence ignore it during stringification.\n */\n const jsArg = `a,${token.properties.jsArg}`\n\n const parsed = parser.utils.transformAst(\n parser.utils.generateAST(jsArg, token.loc, token.filename),\n token.filename,\n parser\n )\n attributes = parser.utils.stringify(parsed.expressions[1])\n }\n\n /**\n * Get HMR script\n */\n buffer.writeExpression(\n `const __vite_hmr_script = state.vite.getReactHmrScript(${attributes})`,\n token.filename,\n token.loc.start.line\n )\n\n /**\n * Check if the script exists (only in hot mode)\n */\n buffer.writeStatement('if(__vite_hmr_script) {', token.filename, token.loc.start.line)\n\n /**\n * Write output\n */\n buffer.outputExpression(\n `__vite_hmr_script.toString()`,\n token.filename,\n token.loc.start.line,\n false\n )\n\n /**\n * Close if block\n */\n buffer.writeStatement('}', token.filename, token.loc.start.line)\n },\n })\n\n edge.registerTag({\n tagName: 'vite',\n seekable: true,\n block: false,\n compile(parser, buffer, token) {\n /**\n * Ensure an argument is defined\n */\n if (!token.properties.jsArg.trim()) {\n throw new EdgeError('Missing entrypoint name', 'E_RUNTIME_EXCEPTION', {\n filename: token.filename,\n line: token.loc.start.line,\n col: token.loc.start.col,\n })\n }\n\n const parsed = parser.utils.transformAst(\n parser.utils.generateAST(token.properties.jsArg, token.loc, token.filename),\n token.filename,\n parser\n )\n\n const entrypoints = parser.utils.stringify(parsed)\n const methodCall =\n parsed.type === 'SequenceExpression'\n ? `generateEntryPointsTags${entrypoints}`\n : `generateEntryPointsTags(${entrypoints})`\n\n buffer.outputExpression(\n `state.vite.${methodCall}.join('\\\\n')`,\n token.filename,\n token.loc.start.line,\n false\n )\n },\n })\n }\n\n return edgeVite\n}\n"],"mappings":";AAUA,SAAS,iBAAiB;AASnB,IAAM,iBAAsD,CAAC,SAAS;AAC3E,QAAM,WAAW,CAAC,SAAe;AAC/B,SAAK,OAAO,QAAQ,IAAI;AACxB,SAAK,OAAO,SAAS,KAAK,UAAU,KAAK,IAAI,CAAC;AAE9C,SAAK,YAAY;AAAA,MACf,SAAS;AAAA,MACT,UAAU;AAAA,MACV,OAAO;AAAA,MACP,QAAQ,QAAQ,QAAQ,OAAO;AAC7B,YAAI,aAAa;AACjB,YAAI,MAAM,WAAW,MAAM,KAAK,GAAG;AAajC,gBAAM,QAAQ,K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AAA,UAChB;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
@@ -7,8 +7,8 @@ import type { AdonisViteElement, ViteOptions } from './types.js';
7
7
  */
8
8
  export declare class Vite {
9
9
  #private;
10
- protected inDev: boolean;
11
- constructor(inDev: boolean, options: ViteOptions);
10
+ protected isViteRunning: boolean;
11
+ constructor(isViteRunning: boolean, options: ViteOptions);
12
12
  /**
13
13
  * Generate tags for the entry points
14
14
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@adonisjs/vite",
3
3
  "description": "Vite plugin for AdonisJS",
4
- "version": "3.0.0-2",
4
+ "version": "3.0.0-3",
5
5
  "engines": {
6
6
  "node": ">=20.6.0"
7
7
  },
@@ -16,10 +16,11 @@
16
16
  "exports": {
17
17
  ".": "./build/index.js",
18
18
  "./vite_provider": "./build/providers/vite_provider.js",
19
+ "./plugins/edge": "./build/src/plugins/edge.js",
20
+ "./build_hook": "./build/src/hooks/build_hook.js",
19
21
  "./services/main": "./build/services/vite.js",
20
- "./types": "./build/src/types.js",
21
22
  "./client": "./build/src/client/main.js",
22
- "./build_hook": "./build/src/hooks/build_hook.js"
23
+ "./types": "./build/src/types.js"
23
24
  },
24
25
  "scripts": {
25
26
  "clean": "del-cli build",
@@ -38,7 +39,6 @@
38
39
  "prepublishOnly": "npm run build"
39
40
  },
40
41
  "devDependencies": {
41
- "@adonisjs/application": "8.1.0",
42
42
  "@adonisjs/assembler": "^7.2.2",
43
43
  "@adonisjs/core": "6.3.1",
44
44
  "@adonisjs/eslint-config": "^1.2.1",
@@ -122,12 +122,13 @@
122
122
  },
123
123
  "tsup": {
124
124
  "entry": [
125
- "./index.ts",
125
+ "./src/hooks/build_hook.ts",
126
126
  "./providers/vite_provider.ts",
127
+ "./src/plugins/edge.ts",
128
+ "./src/client/main.ts",
127
129
  "./services/vite.ts",
128
130
  "./src/types.ts",
129
- "./src/client/main.ts",
130
- "./src/hooks/build_hook.ts"
131
+ "./index.ts"
131
132
  ],
132
133
  "outDir": "./build",
133
134
  "clean": true,
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/vite.ts"],"sourcesContent":["/*\n * @adonisjs/vite\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport { readFileSync } from 'node:fs'\nimport type { ViteRuntime } from 'vite/runtime'\nimport type { Manifest, ViteDevServer } from 'vite'\n\nimport { makeAttributes, uniqBy } from './utils.js'\nimport type { AdonisViteElement, SetAttributes, ViteOptions } from './types.js'\n\n/**\n * Vite class exposes the APIs to generate tags and URLs for\n * assets processed using vite.\n */\nexport class Vite {\n /**\n * We cache the manifest file content in production\n * to avoid reading the file multiple times\n */\n #manifestCache?: Manifest\n #options: ViteOptions\n #runtime?: ViteRuntime\n #devServer?: ViteDevServer\n\n constructor(\n protected inDev: boolean,\n options: ViteOptions\n ) {\n this.#options = options\n this.#options.assetsUrl = (this.#options.assetsUrl || '/').replace(/\\/$/, '')\n }\n\n /**\n * Reads the file contents as JSON\n */\n #readFileAsJSON(filePath: string) {\n return JSON.parse(readFileSync(filePath, 'utf-8'))\n }\n\n /**\n * Generates a JSON element with a custom toString implementation\n */\n #generateElement(element: AdonisViteElement) {\n return {\n ...element,\n toString() {\n const attributes = `${makeAttributes(element.attributes)}`\n if (element.tag === 'link') {\n return `<${element.tag} ${attributes}/>`\n }\n\n return `<${element.tag} ${attributes}>${element.children.join('\\n')}</${element.tag}>`\n },\n }\n }\n\n /**\n * Returns the script needed for the HMR working with Vite\n */\n #getViteHmrScript(attributes?: Record<string, any>): AdonisViteElement | null {\n return this.#generateElement({\n tag: 'script',\n attributes: {\n type: 'module',\n src: '/@vite/client',\n ...attributes,\n },\n children: [],\n })\n }\n\n /**\n * Check if the given path is a CSS path\n */\n #isCssPath(path: string) {\n return path.match(/\\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/) !== null\n }\n\n /**\n * Unwrap attributes from the user defined function or return\n * the attributes as it is\n */\n #unwrapAttributes(src: string, url: string, attributes?: SetAttributes) {\n if (typeof attributes === 'function') {\n return attributes({ src, url })\n }\n\n return attributes\n }\n\n /**\n * Create a style tag for the given path\n */\n #makeStyleTag(src: string, url: string, attributes?: Record<string, any>): AdonisViteElement {\n const customAttributes = this.#unwrapAttributes(src, url, this.#options?.styleAttributes)\n return this.#generateElement({\n tag: 'link',\n attributes: { rel: 'stylesheet', ...customAttributes, ...attributes, href: url },\n })\n }\n\n /**\n * Create a script tag for the given path\n */\n #makeScriptTag(src: string, url: string, attributes?: Record<string, any>): AdonisViteElement {\n const customAttributes = this.#unwrapAttributes(src, url, this.#options?.scriptAttributes)\n return this.#generateElement({\n tag: 'script',\n attributes: { type: 'module', ...customAttributes, ...attributes, src: url },\n children: [],\n })\n }\n\n /**\n * Generate a HTML tag for the given asset\n */\n #generateTag(asset: string, attributes?: Record<string, any>): AdonisViteElement {\n let url = ''\n if (this.inDev) {\n url = `/${asset}`\n } else {\n url = `${this.#options.assetsUrl}/${asset}`\n }\n\n if (this.#isCssPath(asset)) {\n return this.#makeStyleTag(asset, url, attributes)\n }\n\n return this.#makeScriptTag(asset, url, attributes)\n }\n\n /**\n * Generate style and script tags for the given entrypoints\n * Also adds the @vite/client script\n */\n #generateEntryPointsTagsForHotMode(\n entryPoints: string[],\n attributes?: Record<string, any>\n ): AdonisViteElement[] {\n const viteHmr = this.#getViteHmrScript(attributes)\n const tags = entryPoints.map((entrypoint) => this.#generateTag(entrypoint, attributes))\n\n const result = viteHmr ? [viteHmr].concat(tags) : tags\n\n return result\n }\n\n /**\n * Get a chunk from the manifest file for a given file name\n */\n #chunk(manifest: Manifest, fileName: string) {\n const chunk = manifest[fileName]\n\n if (!chunk) {\n throw new Error(`Cannot find \"${fileName}\" chunk in the manifest file`)\n }\n\n return chunk\n }\n\n /**\n * Generate style and script tags for the given entrypoints\n * using the manifest file\n */\n #generateEntryPointsTagsWithManifest(\n entryPoints: string[],\n attributes?: Record<string, any>\n ): AdonisViteElement[] {\n const manifest = this.manifest()\n const tags: { path: string; tag: AdonisViteElement }[] = []\n\n for (const entryPoint of entryPoints) {\n const chunk = this.#chunk(manifest, entryPoint)\n tags.push({\n path: chunk.file,\n tag: this.#generateTag(chunk.file, { ...attributes, integrity: chunk.integrity }),\n })\n\n for (const css of chunk.css || []) {\n tags.push({ path: css, tag: this.#generateTag(css) })\n }\n }\n\n return uniqBy(tags, 'path')\n .sort((a) => (a.path.endsWith('.css') ? -1 : 1))\n .map((tag) => tag.tag)\n }\n\n /**\n * Generate tags for the entry points\n */\n generateEntryPointsTags(\n entryPoints: string[] | string,\n attributes?: Record<string, any>\n ): AdonisViteElement[] {\n entryPoints = Array.isArray(entryPoints) ? entryPoints : [entryPoints]\n\n if (this.inDev) {\n return this.#generateEntryPointsTagsForHotMode(entryPoints, attributes)\n }\n\n return this.#generateEntryPointsTagsWithManifest(entryPoints, attributes)\n }\n\n /**\n * Returns the dev server URL when running in hot\n * mode, otherwise returns the explicitly configured\n * \"assets\" URL\n */\n assetsUrl() {\n if (this.inDev) return this.#devServer!.config.server.host\n\n return this.#options.assetsUrl\n }\n\n /**\n * Returns path to a given asset file\n */\n assetPath(asset: string): string {\n if (this.inDev) {\n return `/${asset}`\n }\n\n const chunk = this.#chunk(this.manifest(), asset)\n return `${this.#options.assetsUrl}/${chunk.file}`\n }\n\n /**\n * Returns the manifest file contents\n *\n * @throws Will throw an exception when running in dev\n */\n manifest(): Manifest {\n if (this.inDev) {\n throw new Error('Cannot read the manifest file when running in dev mode')\n }\n\n if (!this.#manifestCache) {\n this.#manifestCache = this.#readFileAsJSON(this.#options.manifestFile)\n }\n\n return this.#manifestCache!\n }\n\n /**\n * Create the Vite Dev Server and runtime\n *\n * We lazy load the APIs to avoid loading it in production\n * since we don't need it\n */\n async createDevServer() {\n const { createViteRuntime, createServer } = await import('vite')\n\n this.#devServer = await createServer({\n server: { middlewareMode: true, hmr: { port: 3001 } },\n appType: 'custom',\n })\n\n this.#runtime = await createViteRuntime(this.#devServer)\n }\n\n /**\n * Stop the Vite Dev server\n */\n async stopDevServer() {\n await this.#devServer?.close()\n }\n\n /**\n * Get the Vite Dev server instance\n * Will not be available when running in production\n */\n getDevServer() {\n return this.#devServer\n }\n\n /**\n * Get the Vite runtime instance\n * Will not be available when running in production\n */\n getRuntime() {\n return this.#runtime\n }\n\n /**\n * Returns the script needed for the HMR working with React\n */\n getReactHmrScript(attributes?: Record<string, any>): AdonisViteElement | null {\n if (!this.inDev) {\n return null\n }\n\n return this.#generateElement({\n tag: 'script',\n attributes: {\n type: 'module',\n ...attributes,\n },\n children: [\n '',\n `import RefreshRuntime from '/@react-refresh'`,\n `RefreshRuntime.injectIntoGlobalHook(window)`,\n `window.$RefreshReg$ = () => {}`,\n `window.$RefreshSig$ = () => (type) => type`,\n `window.__vite_plugin_react_preamble_installed__ = true`,\n '',\n ],\n })\n }\n}\n"],"mappings":";;;;;;AASA,SAAS,oBAAoB;AAWtB,IAAM,OAAN,MAAW;AAAA,EAUhB,YACY,OACV,SACA;AAFU;AAGV,SAAK,WAAW;AAChB,SAAK,SAAS,aAAa,KAAK,SAAS,aAAa,KAAK,QAAQ,OAAO,EAAE;AAAA,EAC9E;AAAA;AAAA;AAAA;AAAA;AAAA,EAXA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAaA,gBAAgB,UAAkB;AAChC,WAAO,KAAK,MAAM,aAAa,UAAU,OAAO,CAAC;AAAA,EACnD;AAAA;AAAA;AAAA;AAAA,EAKA,iBAAiB,SAA4B;AAC3C,WAAO;AAAA,MACL,GAAG;AAAA,MACH,WAAW;AACT,cAAM,aAAa,GAAG,eAAe,QAAQ,UAAU,CAAC;AACxD,YAAI,QAAQ,QAAQ,QAAQ;AAC1B,iBAAO,IAAI,QAAQ,GAAG,IAAI,UAAU;AAAA,QACtC;AAEA,eAAO,IAAI,QAAQ,GAAG,IAAI,UAAU,IAAI,QAAQ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gBAAgB;AACpB,UAAM,KAAK,YAAY,MAAM;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,eAAe;AACb,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAa;AACX,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,kBAAkB,YAA4D;AAC5E,QAAI,CAAC,KAAK,OAAO;AACf,aAAO;AAAA,IACT;AAEA,WAAO,KAAK,iBAAiB;AAAA,MAC3B,KAAK;AAAA,MACL,YAAY;AAAA,QACV,MAAM;AAAA,QACN,GAAG;AAAA,MACL;AAAA,MACA,UAAU;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/plugins/edge.ts"],"sourcesContent":["/*\n * @adonisjs/vite\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport type { Edge } from 'edge.js'\nimport { EdgeError } from 'edge-error'\nimport type { PluginFn } from 'edge.js/types'\n\nimport type { Vite } from '../vite.js'\n\n/**\n * The edge plugin for vite to share vite service with edge\n * and register custom tags\n */\nexport const edgePluginVite: (vite: Vite) => PluginFn<undefined> = (vite) => {\n const edgeVite = (edge: Edge) => {\n edge.global('vite', vite)\n edge.global('asset', vite.assetPath.bind(vite))\n\n edge.registerTag({\n tagName: 'viteReactRefresh',\n seekable: true,\n block: false,\n compile(parser, buffer, token) {\n let attributes = ''\n if (token.properties.jsArg.trim()) {\n /**\n * Converting a single argument to a SequenceExpression so that we\n * work around the following edge cases.\n *\n * - If someone passes an object literal to the tag, ie { nonce: 'foo' }\n * it will be parsed as a LabeledStatement and not an object.\n * - If we wrap the object literal inside parenthesis, ie ({nonce: 'foo'})\n * then we will end up messing other expressions like a variable reference\n * , or a member expression and so on.\n * - So the best bet is to convert user supplied argument to a sequence expression\n * and hence ignore it during stringification.\n */\n const jsArg = `a,${token.properties.jsArg}`\n\n const parsed = parser.utils.transformAst(\n parser.utils.generateAST(jsArg, token.loc, token.filename),\n token.filename,\n parser\n )\n attributes = parser.utils.stringify(parsed.expressions[1])\n }\n\n /**\n * Get HMR script\n */\n buffer.writeExpression(\n `const __vite_hmr_script = state.vite.getReactHmrScript(${attributes})`,\n token.filename,\n token.loc.start.line\n )\n\n /**\n * Check if the script exists (only in hot mode)\n */\n buffer.writeStatement('if(__vite_hmr_script) {', token.filename, token.loc.start.line)\n\n /**\n * Write output\n */\n buffer.outputExpression(\n `__vite_hmr_script.toString()`,\n token.filename,\n token.loc.start.line,\n false\n )\n\n /**\n * Close if block\n */\n buffer.writeStatement('}', token.filename, token.loc.start.line)\n },\n })\n\n edge.registerTag({\n tagName: 'vite',\n seekable: true,\n block: false,\n compile(parser, buffer, token) {\n /**\n * Ensure an argument is defined\n */\n if (!token.properties.jsArg.trim()) {\n throw new EdgeError('Missing entrypoint name', 'E_RUNTIME_EXCEPTION', {\n filename: token.filename,\n line: token.loc.start.line,\n col: token.loc.start.col,\n })\n }\n\n const parsed = parser.utils.transformAst(\n parser.utils.generateAST(token.properties.jsArg, token.loc, token.filename),\n token.filename,\n parser\n )\n\n const entrypoints = parser.utils.stringify(parsed)\n const methodCall =\n parsed.type === 'SequenceExpression'\n ? `generateEntryPointsTags${entrypoints}`\n : `generateEntryPointsTags(${entrypoints})`\n\n buffer.outputExpression(\n `state.vite.${methodCall}.join('\\\\n')`,\n token.filename,\n token.loc.start.line,\n false\n )\n },\n })\n }\n\n return edgeVite\n}\n"],"mappings":";AAUA,SAAS,iBAAiB;AASnB,IAAM,iBAAsD,CAAC,SAAS;AAC3E,QAAM,WAAW,CAAC,SAAe;AAC/B,SAAK,OAAO,QAAQ,IAAI;AACxB,SAAK,OAAO,SAAS,KAAK,UAAU,KAAK,IAAI,CAAC;AAE9C,SAA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