@weapp-vite/web 1.3.35 → 1.3.37

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.
@@ -2,7 +2,7 @@ import { relativeModuleId, resolveRuntimePolyfillPath, toViteFsImport } from "./
2
2
 
3
3
  //#region src/plugin/entry.ts
4
4
  function generateEntryModule(result, root, wxssOptions, pluginOptions) {
5
- const importLines = [`import { initializePageRoutes } from '${toViteFsImport(resolveRuntimePolyfillPath())}'`];
5
+ const importLines = [`import { initializePageRoutes } from '${pluginOptions?.__runtimeProvider?.moduleId ?? toViteFsImport(resolveRuntimePolyfillPath())}'`];
6
6
  const bodyLines = [];
7
7
  for (const page of result.pages) importLines.push(`import '${relativeModuleId(root, page.script)}'`);
8
8
  for (const component of result.components) importLines.push(`import '${relativeModuleId(root, component.script)}'`);
@@ -1 +1 @@
1
- {"version":3,"file":"entry.mjs","names":[],"sources":["../../src/plugin/entry.ts"],"sourcesContent":["import type { WxssTransformOptions } from '../css/wxss'\n\nimport type { ScanResult, WeappWebPluginOptions } from './types'\nimport { relativeModuleId, resolveRuntimePolyfillPath, toViteFsImport } from './path'\n\nexport function generateEntryModule(\n result: ScanResult,\n root: string,\n wxssOptions?: WxssTransformOptions,\n pluginOptions?: WeappWebPluginOptions,\n) {\n const runtimePolyfillId = toViteFsImport(resolveRuntimePolyfillPath())\n const importLines: string[] = [`import { initializePageRoutes } from '${runtimePolyfillId}'`]\n const bodyLines: string[] = []\n\n for (const page of result.pages) {\n importLines.push(`import '${relativeModuleId(root, page.script)}'`)\n }\n for (const component of result.components) {\n importLines.push(`import '${relativeModuleId(root, component.script)}'`)\n }\n if (result.app) {\n importLines.push(`import '${relativeModuleId(root, result.app)}'`)\n }\n\n const pageOrder = result.pages.map(page => page.id)\n const rpxConfig = wxssOptions?.designWidth\n ? { designWidth: wxssOptions.designWidth, varName: wxssOptions.rpxVar }\n : undefined\n\n const initOptions: Record<string, any> = {}\n if (rpxConfig) {\n initOptions.rpx = rpxConfig\n }\n if (pluginOptions?.form?.preventDefault !== undefined) {\n initOptions.form = { preventDefault: pluginOptions.form.preventDefault }\n }\n\n const runtimeOptions: Record<string, any> = {}\n if (pluginOptions?.runtime?.executionMode) {\n runtimeOptions.executionMode = pluginOptions.runtime.executionMode\n }\n if (pluginOptions?.runtime?.warnings) {\n runtimeOptions.warnings = pluginOptions.runtime.warnings\n }\n if (Object.keys(runtimeOptions).length > 0) {\n initOptions.runtime = runtimeOptions\n }\n\n const initOptionsCode = Object.keys(initOptions).length > 0 ? `, ${JSON.stringify(initOptions)}` : ''\n bodyLines.push(`initializePageRoutes(${JSON.stringify(pageOrder)}${initOptionsCode})`)\n return [...importLines, ...bodyLines].join('\\n')\n}\n"],"mappings":";;;AAKA,SAAgB,oBACd,QACA,MACA,aACA,eACA;CAEA,MAAM,cAAwB,CAAC,yCADL,eAAe,2BAA2B,CACoB,EAAE,EAAE;CAC5F,MAAM,YAAsB,CAAC;CAE7B,KAAK,MAAM,QAAQ,OAAO,OACxB,YAAY,KAAK,WAAW,iBAAiB,MAAM,KAAK,MAAM,EAAE,EAAE;CAEpE,KAAK,MAAM,aAAa,OAAO,YAC7B,YAAY,KAAK,WAAW,iBAAiB,MAAM,UAAU,MAAM,EAAE,EAAE;CAEzE,IAAI,OAAO,KACT,YAAY,KAAK,WAAW,iBAAiB,MAAM,OAAO,GAAG,EAAE,EAAE;CAGnE,MAAM,YAAY,OAAO,MAAM,KAAI,SAAQ,KAAK,EAAE;CAClD,MAAM,YAAY,aAAa,cAC3B;EAAE,aAAa,YAAY;EAAa,SAAS,YAAY;CAAO,IACpE;CAEJ,MAAM,cAAmC,CAAC;CAC1C,IAAI,WACF,YAAY,MAAM;CAEpB,IAAI,eAAe,MAAM,mBAAmB,QAC1C,YAAY,OAAO,EAAE,gBAAgB,cAAc,KAAK,eAAe;CAGzE,MAAM,iBAAsC,CAAC;CAC7C,IAAI,eAAe,SAAS,eAC1B,eAAe,gBAAgB,cAAc,QAAQ;CAEvD,IAAI,eAAe,SAAS,UAC1B,eAAe,WAAW,cAAc,QAAQ;CAElD,IAAI,OAAO,KAAK,cAAc,CAAC,CAAC,SAAS,GACvC,YAAY,UAAU;CAGxB,MAAM,kBAAkB,OAAO,KAAK,WAAW,CAAC,CAAC,SAAS,IAAI,KAAK,KAAK,UAAU,WAAW,MAAM;CACnG,UAAU,KAAK,wBAAwB,KAAK,UAAU,SAAS,IAAI,gBAAgB,EAAE;CACrF,OAAO,CAAC,GAAG,aAAa,GAAG,SAAS,CAAC,CAAC,KAAK,IAAI;AACjD"}
1
+ {"version":3,"file":"entry.mjs","names":[],"sources":["../../src/plugin/entry.ts"],"sourcesContent":["import type { WxssTransformOptions } from '../css/wxss'\n\nimport type { ScanResult, WeappWebPluginOptions } from './types'\nimport { relativeModuleId, resolveRuntimePolyfillPath, toViteFsImport } from './path'\n\nexport function generateEntryModule(\n result: ScanResult,\n root: string,\n wxssOptions?: WxssTransformOptions,\n pluginOptions?: WeappWebPluginOptions,\n) {\n const runtimePolyfillId = pluginOptions?.__runtimeProvider?.moduleId\n ?? toViteFsImport(resolveRuntimePolyfillPath())\n const importLines: string[] = [`import { initializePageRoutes } from '${runtimePolyfillId}'`]\n const bodyLines: string[] = []\n\n for (const page of result.pages) {\n importLines.push(`import '${relativeModuleId(root, page.script)}'`)\n }\n for (const component of result.components) {\n importLines.push(`import '${relativeModuleId(root, component.script)}'`)\n }\n if (result.app) {\n importLines.push(`import '${relativeModuleId(root, result.app)}'`)\n }\n\n const pageOrder = result.pages.map(page => page.id)\n const rpxConfig = wxssOptions?.designWidth\n ? { designWidth: wxssOptions.designWidth, varName: wxssOptions.rpxVar }\n : undefined\n\n const initOptions: Record<string, any> = {}\n if (rpxConfig) {\n initOptions.rpx = rpxConfig\n }\n if (pluginOptions?.form?.preventDefault !== undefined) {\n initOptions.form = { preventDefault: pluginOptions.form.preventDefault }\n }\n\n const runtimeOptions: Record<string, any> = {}\n if (pluginOptions?.runtime?.executionMode) {\n runtimeOptions.executionMode = pluginOptions.runtime.executionMode\n }\n if (pluginOptions?.runtime?.warnings) {\n runtimeOptions.warnings = pluginOptions.runtime.warnings\n }\n if (Object.keys(runtimeOptions).length > 0) {\n initOptions.runtime = runtimeOptions\n }\n\n const initOptionsCode = Object.keys(initOptions).length > 0 ? `, ${JSON.stringify(initOptions)}` : ''\n bodyLines.push(`initializePageRoutes(${JSON.stringify(pageOrder)}${initOptionsCode})`)\n return [...importLines, ...bodyLines].join('\\n')\n}\n"],"mappings":";;;AAKA,SAAgB,oBACd,QACA,MACA,aACA,eACA;CAGA,MAAM,cAAwB,CAAC,yCAFL,eAAe,mBAAmB,YACvD,eAAe,2BAA2B,CAAC,EAC0C,EAAE;CAC5F,MAAM,YAAsB,CAAC;CAE7B,KAAK,MAAM,QAAQ,OAAO,OACxB,YAAY,KAAK,WAAW,iBAAiB,MAAM,KAAK,MAAM,EAAE,EAAE;CAEpE,KAAK,MAAM,aAAa,OAAO,YAC7B,YAAY,KAAK,WAAW,iBAAiB,MAAM,UAAU,MAAM,EAAE,EAAE;CAEzE,IAAI,OAAO,KACT,YAAY,KAAK,WAAW,iBAAiB,MAAM,OAAO,GAAG,EAAE,EAAE;CAGnE,MAAM,YAAY,OAAO,MAAM,KAAI,SAAQ,KAAK,EAAE;CAClD,MAAM,YAAY,aAAa,cAC3B;EAAE,aAAa,YAAY;EAAa,SAAS,YAAY;CAAO,IACpE;CAEJ,MAAM,cAAmC,CAAC;CAC1C,IAAI,WACF,YAAY,MAAM;CAEpB,IAAI,eAAe,MAAM,mBAAmB,QAC1C,YAAY,OAAO,EAAE,gBAAgB,cAAc,KAAK,eAAe;CAGzE,MAAM,iBAAsC,CAAC;CAC7C,IAAI,eAAe,SAAS,eAC1B,eAAe,gBAAgB,cAAc,QAAQ;CAEvD,IAAI,eAAe,SAAS,UAC1B,eAAe,WAAW,cAAc,QAAQ;CAElD,IAAI,OAAO,KAAK,cAAc,CAAC,CAAC,SAAS,GACvC,YAAY,UAAU;CAGxB,MAAM,kBAAkB,OAAO,KAAK,WAAW,CAAC,CAAC,SAAS,IAAI,KAAK,KAAK,UAAU,WAAW,MAAM;CACnG,UAAU,KAAK,wBAAwB,KAAK,UAAU,SAAS,IAAI,gBAAgB,EAAE;CACrF,OAAO,CAAC,GAAG,aAAa,GAAG,SAAS,CAAC,CAAC,KAAK,IAAI;AACjD"}
@@ -75,6 +75,8 @@ function weappWebPlugin(options = {}) {
75
75
  let enableHmr = false;
76
76
  const state = createEmptyScanState();
77
77
  const wxssOptions = options.wxss;
78
+ const runtimeProvider = options.__runtimeProvider;
79
+ const hmrAcceptCode = runtimeProvider ? runtimeProvider.hmrAcceptCode : "if (import.meta.hot) { import.meta.hot.accept() }";
78
80
  const resolveTemplatePath = (raw, importer) => resolveTemplatePathSync(raw, importer, srcRoot);
79
81
  const resolveWxsPath = (raw, importer) => resolveWxsPathSync(raw, importer, srcRoot);
80
82
  return {
@@ -177,7 +179,9 @@ function weappWebPlugin(options = {}) {
177
179
  code,
178
180
  cleanId: clean,
179
181
  meta,
180
- enableHmr
182
+ enableHmr,
183
+ runtimeModuleId: runtimeProvider?.moduleId,
184
+ hmrAcceptCode
181
185
  });
182
186
  }
183
187
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type { SourceMap } from 'magic-string'\nimport type { WeappWebPluginOptions } from './types'\nimport process from 'node:process'\n\nimport { extname, resolve } from 'pathe'\nimport { compileWxml } from '../compiler/wxml'\nimport { transformWxsToEsm } from '../compiler/wxs'\nimport { transformWxssToCss } from '../css/wxss'\nimport { ENTRY_ID, SCRIPT_EXTS, STYLE_EXTS, TEMPLATE_EXTS, TRANSFORM_STYLE_EXTS, WXS_EXTS } from './constants'\nimport { generateEntryModule } from './entry'\nimport { cleanUrl, isHtmlEntry, isInsideDir, normalizePath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from './path'\nimport { transformScriptModule } from './register'\nimport { scanProject } from './scan'\nimport { createEmptyScanState } from './state'\n\ninterface WebPluginContext {\n warn?: (message: string) => void\n addWatchFile?: (id: string) => void\n}\n\ntype WebTransformResult = { code: string, map: SourceMap | null } | null\n\ninterface WebResolvedConfig {\n root: string\n command: string\n}\n\ninterface WebHmrContext {\n file: string\n}\n\ninterface WeappWebVitePlugin {\n name: string\n enforce?: 'pre' | 'post'\n configResolved?: (this: WebPluginContext, config: WebResolvedConfig) => void | Promise<void>\n buildStart?: (this: WebPluginContext) => void | Promise<void>\n resolveId?: (id: string) => string | null | Promise<string | null>\n load?: (id: string) => string | null | Promise<string | null>\n handleHotUpdate?: (this: WebPluginContext, ctx: WebHmrContext) => void | Promise<void>\n transform?: (\n this: WebPluginContext,\n code: string,\n id: string,\n ) => WebTransformResult | Promise<WebTransformResult>\n}\n\nfunction isTemplateFile(id: string) {\n const lower = id.toLowerCase()\n return TEMPLATE_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction isWxsFile(id: string) {\n const lower = id.toLowerCase()\n return WXS_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction hasWxsQuery(id: string) {\n return id.includes('?wxs') || id.includes('&wxs')\n}\n\nfunction createInlineStyleModule(css: string) {\n const serialized = JSON.stringify(css)\n return [\n `const __weapp_injected_styles__ = new Map()`,\n `function __weapp_createStyleId__(css) {`,\n ` let hash = 2166136261`,\n ` for (let i = 0; i < css.length; i++) {`,\n ` hash ^= css.charCodeAt(i)`,\n ` hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24)`,\n ` }`,\n ` return 'weapp-web-style-' + (hash >>> 0).toString(36)`,\n `}`,\n `function __weapp_removeStyle__(id) {`,\n ` if (typeof document === 'undefined') {`,\n ` return`,\n ` }`,\n ` const style = __weapp_injected_styles__.get(id)`,\n ` if (style) {`,\n ` style.remove()`,\n ` __weapp_injected_styles__.delete(id)`,\n ` }`,\n `}`,\n `function injectStyle(css, id) {`,\n ` if (typeof document === 'undefined') {`,\n ` return () => {}`,\n ` }`,\n ` const styleId = id ?? __weapp_createStyleId__(css)`,\n ` const existing = __weapp_injected_styles__.get(styleId)`,\n ` if (existing) {`,\n ` if (existing.textContent !== css) {`,\n ` existing.textContent = css`,\n ` }`,\n ` return () => __weapp_removeStyle__(styleId)`,\n ` }`,\n ` const style = document.createElement('style')`,\n ` style.id = styleId`,\n ` style.textContent = css`,\n ` document.head.append(style)`,\n ` __weapp_injected_styles__.set(styleId, style)`,\n ` return () => __weapp_removeStyle__(styleId)`,\n `}`,\n `const css = ${serialized}`,\n `export default css`,\n `export function useStyle(id) {`,\n ` return injectStyle(css, id)`,\n `}`,\n ].join('\\n')\n}\n\nexport function weappWebPlugin(options: WeappWebPluginOptions = {}): WeappWebVitePlugin {\n let root = process.cwd()\n let srcRoot = resolve(root, options.srcDir ?? 'src')\n let enableHmr = false\n\n const state = createEmptyScanState()\n const wxssOptions = options.wxss\n\n const resolveTemplatePath = (raw: string, importer: string) => resolveTemplatePathSync(raw, importer, srcRoot)\n const resolveWxsPath = (raw: string, importer: string) => resolveWxsPathSync(raw, importer, srcRoot)\n\n return {\n name: '@weapp-vite/web',\n enforce: 'pre',\n async configResolved(this: WebPluginContext, config: WebResolvedConfig) {\n root = config.root\n srcRoot = resolve(root, options.srcDir ?? 'src')\n enableHmr = config.command === 'serve'\n await scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n },\n async buildStart(this: WebPluginContext) {\n await scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n },\n resolveId(id: string) {\n if (id === '/@weapp-vite/web/entry' || id === '@weapp-vite/web/entry') {\n return ENTRY_ID\n }\n return null\n },\n load(id: string) {\n if (id === ENTRY_ID) {\n return generateEntryModule(state.scanResult, root, wxssOptions, options)\n }\n return null\n },\n async handleHotUpdate(this: WebPluginContext, ctx: WebHmrContext) {\n const clean = cleanUrl(ctx.file)\n if (clean.endsWith('.json') || isTemplateFile(clean) || isWxsFile(clean) || clean.endsWith('.wxss') || SCRIPT_EXTS.includes(extname(clean))) {\n await scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n }\n },\n transform(this: WebPluginContext, code: string, id: string) {\n const clean = cleanUrl(id)\n\n if (isTemplateFile(clean)) {\n if (isHtmlEntry(clean, root)) {\n return null\n }\n const normalizedId = normalizePath(clean)\n if (state.templatePathSet.size > 0) {\n if (!isInsideDir(clean, srcRoot)) {\n return null\n }\n if (!state.templatePathSet.has(normalizedId)) {\n return null\n }\n }\n const navigationConfig = state.pageNavigationMap.get(normalizedId)\n const componentTags = state.templateComponentMap.get(normalizedId)\n const { code: compiled, dependencies, warnings } = compileWxml({\n id: clean,\n source: code,\n resolveTemplatePath,\n resolveWxsPath,\n navigationBar: navigationConfig ? { config: navigationConfig } : undefined,\n componentTags,\n })\n const addWatchFile = this.addWatchFile\n if (dependencies.length > 0 && addWatchFile) {\n for (const dep of dependencies) {\n addWatchFile.call(this, dep)\n }\n }\n const warn = this.warn\n if (warnings?.length && warn) {\n for (const warning of warnings) {\n warn.call(this, warning)\n }\n }\n return { code: compiled, map: null }\n }\n\n if (isWxsFile(clean) || hasWxsQuery(id)) {\n const { code: compiled, dependencies, warnings } = transformWxsToEsm(code, clean, {\n resolvePath: resolveWxsPath,\n toImportPath: (resolved, importer) => normalizePath(toRelativeImport(importer, resolved)),\n })\n const addWatchFile = this.addWatchFile\n if (dependencies.length > 0 && addWatchFile) {\n for (const dep of dependencies) {\n addWatchFile.call(this, dep)\n }\n }\n const warn = this.warn\n if (warnings?.length && warn) {\n for (const warning of warnings) {\n warn.call(this, warning)\n }\n }\n return { code: compiled, map: null }\n }\n\n if (TRANSFORM_STYLE_EXTS.some(ext => clean.endsWith(ext))) {\n const { css } = transformWxssToCss(code, wxssOptions)\n return {\n code: createInlineStyleModule(css),\n map: null,\n }\n }\n\n if (STYLE_EXTS.some(ext => clean.endsWith(ext)) && !clean.endsWith('.wxss')) {\n const { css } = transformWxssToCss(code, wxssOptions)\n return { code: css, map: null }\n }\n\n if (!SCRIPT_EXTS.some(ext => clean.endsWith(ext))) {\n return null\n }\n if (clean.includes('node_modules')) {\n return null\n }\n\n const meta = state.moduleMeta.get(normalizePath(clean))\n if (!meta) {\n return null\n }\n\n return transformScriptModule({\n code,\n cleanId: clean,\n meta,\n enableHmr,\n })\n },\n }\n}\n\nexport type { WeappWebPluginOptions } from './types'\n"],"mappings":";;;;;;;;;;;;;AA8CA,SAAS,eAAe,IAAY;CAClC,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,cAAc,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC;AACtD;AAEA,SAAS,UAAU,IAAY;CAC7B,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,SAAS,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC;AACjD;AAEA,SAAS,YAAY,IAAY;CAC/B,OAAO,GAAG,SAAS,MAAM,KAAK,GAAG,SAAS,MAAM;AAClD;AAEA,SAAS,wBAAwB,KAAa;CAE5C,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,eAxCiB,KAAK,UAAU,GAwCR;EACxB;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAgB,eAAe,UAAiC,CAAC,GAAuB;CACtF,IAAI,OAAO,QAAQ,IAAI;CACvB,IAAI,UAAU,QAAQ,MAAM,QAAQ,UAAU,KAAK;CACnD,IAAI,YAAY;CAEhB,MAAM,QAAQ,qBAAqB;CACnC,MAAM,cAAc,QAAQ;CAE5B,MAAM,uBAAuB,KAAa,aAAqB,wBAAwB,KAAK,UAAU,OAAO;CAC7G,MAAM,kBAAkB,KAAa,aAAqB,mBAAmB,KAAK,UAAU,OAAO;CAEnG,OAAO;EACL,MAAM;EACN,SAAS;EACT,MAAM,eAAuC,QAA2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AGT,MAAM,OAAO,MAAM,WAAW,IAAI,cAAc,KAAK,CAAC;GACtD,IAAI,CAAC,MACH,OAAO;GAGT,OAAO,sBAAsB;IAC3B;IACA,SAAS;IACT;IACA;GACF,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type { SourceMap } from 'magic-string'\nimport type { WeappWebPluginOptions } from './types'\nimport process from 'node:process'\n\nimport { extname, resolve } from 'pathe'\nimport { compileWxml } from '../compiler/wxml'\nimport { transformWxsToEsm } from '../compiler/wxs'\nimport { transformWxssToCss } from '../css/wxss'\nimport { ENTRY_ID, SCRIPT_EXTS, STYLE_EXTS, TEMPLATE_EXTS, TRANSFORM_STYLE_EXTS, WXS_EXTS } from './constants'\nimport { generateEntryModule } from './entry'\nimport { cleanUrl, isHtmlEntry, isInsideDir, normalizePath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from './path'\nimport { transformScriptModule } from './register'\nimport { scanProject } from './scan'\nimport { createEmptyScanState } from './state'\n\ninterface WebPluginContext {\n warn?: (message: string) => void\n addWatchFile?: (id: string) => void\n}\n\ntype WebTransformResult = { code: string, map: SourceMap | null } | null\n\ninterface WebResolvedConfig {\n root: string\n command: string\n}\n\ninterface WebHmrContext {\n file: string\n}\n\ninterface WeappWebVitePlugin {\n name: string\n enforce?: 'pre' | 'post'\n configResolved?: (this: WebPluginContext, config: WebResolvedConfig) => void | Promise<void>\n buildStart?: (this: WebPluginContext) => void | Promise<void>\n resolveId?: (id: string) => string | null | Promise<string | null>\n load?: (id: string) => string | null | Promise<string | null>\n handleHotUpdate?: (this: WebPluginContext, ctx: WebHmrContext) => void | Promise<void>\n transform?: (\n this: WebPluginContext,\n code: string,\n id: string,\n ) => WebTransformResult | Promise<WebTransformResult>\n}\n\nfunction isTemplateFile(id: string) {\n const lower = id.toLowerCase()\n return TEMPLATE_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction isWxsFile(id: string) {\n const lower = id.toLowerCase()\n return WXS_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction hasWxsQuery(id: string) {\n return id.includes('?wxs') || id.includes('&wxs')\n}\n\nfunction createInlineStyleModule(css: string) {\n const serialized = JSON.stringify(css)\n return [\n `const __weapp_injected_styles__ = new Map()`,\n `function __weapp_createStyleId__(css) {`,\n ` let hash = 2166136261`,\n ` for (let i = 0; i < css.length; i++) {`,\n ` hash ^= css.charCodeAt(i)`,\n ` hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24)`,\n ` }`,\n ` return 'weapp-web-style-' + (hash >>> 0).toString(36)`,\n `}`,\n `function __weapp_removeStyle__(id) {`,\n ` if (typeof document === 'undefined') {`,\n ` return`,\n ` }`,\n ` const style = __weapp_injected_styles__.get(id)`,\n ` if (style) {`,\n ` style.remove()`,\n ` __weapp_injected_styles__.delete(id)`,\n ` }`,\n `}`,\n `function injectStyle(css, id) {`,\n ` if (typeof document === 'undefined') {`,\n ` return () => {}`,\n ` }`,\n ` const styleId = id ?? __weapp_createStyleId__(css)`,\n ` const existing = __weapp_injected_styles__.get(styleId)`,\n ` if (existing) {`,\n ` if (existing.textContent !== css) {`,\n ` existing.textContent = css`,\n ` }`,\n ` return () => __weapp_removeStyle__(styleId)`,\n ` }`,\n ` const style = document.createElement('style')`,\n ` style.id = styleId`,\n ` style.textContent = css`,\n ` document.head.append(style)`,\n ` __weapp_injected_styles__.set(styleId, style)`,\n ` return () => __weapp_removeStyle__(styleId)`,\n `}`,\n `const css = ${serialized}`,\n `export default css`,\n `export function useStyle(id) {`,\n ` return injectStyle(css, id)`,\n `}`,\n ].join('\\n')\n}\n\nexport function weappWebPlugin(options: WeappWebPluginOptions = {}): WeappWebVitePlugin {\n let root = process.cwd()\n let srcRoot = resolve(root, options.srcDir ?? 'src')\n let enableHmr = false\n\n const state = createEmptyScanState()\n const wxssOptions = options.wxss\n const runtimeProvider = options.__runtimeProvider\n const hmrAcceptCode = runtimeProvider\n ? runtimeProvider.hmrAcceptCode\n : 'if (import.meta.hot) { import.meta.hot.accept() }'\n\n const resolveTemplatePath = (raw: string, importer: string) => resolveTemplatePathSync(raw, importer, srcRoot)\n const resolveWxsPath = (raw: string, importer: string) => resolveWxsPathSync(raw, importer, srcRoot)\n\n return {\n name: '@weapp-vite/web',\n enforce: 'pre',\n async configResolved(this: WebPluginContext, config: WebResolvedConfig) {\n root = config.root\n srcRoot = resolve(root, options.srcDir ?? 'src')\n enableHmr = config.command === 'serve'\n await scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n },\n async buildStart(this: WebPluginContext) {\n await scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n },\n resolveId(id: string) {\n if (id === '/@weapp-vite/web/entry' || id === '@weapp-vite/web/entry') {\n return ENTRY_ID\n }\n return null\n },\n load(id: string) {\n if (id === ENTRY_ID) {\n return generateEntryModule(state.scanResult, root, wxssOptions, options)\n }\n return null\n },\n async handleHotUpdate(this: WebPluginContext, ctx: WebHmrContext) {\n const clean = cleanUrl(ctx.file)\n if (clean.endsWith('.json') || isTemplateFile(clean) || isWxsFile(clean) || clean.endsWith('.wxss') || SCRIPT_EXTS.includes(extname(clean))) {\n await scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n }\n },\n transform(this: WebPluginContext, code: string, id: string) {\n const clean = cleanUrl(id)\n\n if (isTemplateFile(clean)) {\n if (isHtmlEntry(clean, root)) {\n return null\n }\n const normalizedId = normalizePath(clean)\n if (state.templatePathSet.size > 0) {\n if (!isInsideDir(clean, srcRoot)) {\n return null\n }\n if (!state.templatePathSet.has(normalizedId)) {\n return null\n }\n }\n const navigationConfig = state.pageNavigationMap.get(normalizedId)\n const componentTags = state.templateComponentMap.get(normalizedId)\n const { code: compiled, dependencies, warnings } = compileWxml({\n id: clean,\n source: code,\n resolveTemplatePath,\n resolveWxsPath,\n navigationBar: navigationConfig ? { config: navigationConfig } : undefined,\n componentTags,\n })\n const addWatchFile = this.addWatchFile\n if (dependencies.length > 0 && addWatchFile) {\n for (const dep of dependencies) {\n addWatchFile.call(this, dep)\n }\n }\n const warn = this.warn\n if (warnings?.length && warn) {\n for (const warning of warnings) {\n warn.call(this, warning)\n }\n }\n return { code: compiled, map: null }\n }\n\n if (isWxsFile(clean) || hasWxsQuery(id)) {\n const { code: compiled, dependencies, warnings } = transformWxsToEsm(code, clean, {\n resolvePath: resolveWxsPath,\n toImportPath: (resolved, importer) => normalizePath(toRelativeImport(importer, resolved)),\n })\n const addWatchFile = this.addWatchFile\n if (dependencies.length > 0 && addWatchFile) {\n for (const dep of dependencies) {\n addWatchFile.call(this, dep)\n }\n }\n const warn = this.warn\n if (warnings?.length && warn) {\n for (const warning of warnings) {\n warn.call(this, warning)\n }\n }\n return { code: compiled, map: null }\n }\n\n if (TRANSFORM_STYLE_EXTS.some(ext => clean.endsWith(ext))) {\n const { css } = transformWxssToCss(code, wxssOptions)\n return {\n code: createInlineStyleModule(css),\n map: null,\n }\n }\n\n if (STYLE_EXTS.some(ext => clean.endsWith(ext)) && !clean.endsWith('.wxss')) {\n const { css } = transformWxssToCss(code, wxssOptions)\n return { code: css, map: null }\n }\n\n if (!SCRIPT_EXTS.some(ext => clean.endsWith(ext))) {\n return null\n }\n if (clean.includes('node_modules')) {\n return null\n }\n\n const meta = state.moduleMeta.get(normalizePath(clean))\n if (!meta) {\n return null\n }\n\n return transformScriptModule({\n code,\n cleanId: clean,\n meta,\n enableHmr,\n runtimeModuleId: runtimeProvider?.moduleId,\n hmrAcceptCode,\n })\n },\n }\n}\n\nexport type { WeappWebPluginOptions } from './types'\n"],"mappings":";;;;;;;;;;;;;AA8CA,SAAS,eAAe,IAAY;CAClC,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,cAAc,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC;AACtD;AAEA,SAAS,UAAU,IAAY;CAC7B,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,SAAS,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC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U,cAAc,aAAa,kBAAkB,MAAM,OAAO;KAChF,aAAa;KACb,eAAe,UAAU,aAAa,cAAc,iBAAiB,UAAU,QAAQ,CAAC;IAC1F,CAAC;IACD,MAAM,eAAe,KAAK;IAC1B,IAAI,aAAa,SAAS,KAAK,cAC7B,KAAK,MAAM,OAAO,cAChB,aAAa,KAAK,MAAM,GAAG;IAG/B,MAAM,OAAO,KAAK;IAClB,IAAI,UAAU,UAAU,MACtB,KAAK,MAAM,WAAW,UACpB,KAAK,KAAK,MAAM,OAAO;IAG3B,OAAO;KAAE,MAAM;KAAU,KAAK;IAAK;GACrC;GAEA,IAAI,qBAAqB,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC,GAAG;IACzD,MAAM,EAAE,QAAQ,mBAAmB,MAAM,WAAW;IACpD,OAAO;KACL,MAAM,wBAAwB,GAAG;KACjC,KAAK;IACP;GACF;GAEA,IAAI,WAAW,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC,KAAK,CAAC,MAAM,SAAS,OAAO,GAAG;IAC3E,MAAM,EAAE,QAAQ,mBAAmB,MAAM,WAAW;IACpD,OAAO;KAAE,MAAM;KAAK,KAAK;IAAK;GAChC;GAEA,IAAI,CAAC,YAAY,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC,GAC9C,OAAO;GAET,IAAI,MAAM,SAAS,cAAc,GAC/B,OAAO;GAGT,MAAM,OAAO,MAAM,WAAW,IAAI,cAAc,KAAK,CAAC;GACtD,IAAI,CAAC,MACH,OAAO;GAGT,OAAO,sBAAsB;IAC3B;IACA,SAAS;IACT;IACA;IACA,iBAAiB,iBAAiB;IAClC;GACF,CAAC;EACH;CACF;AACF"}
@@ -36,7 +36,7 @@ function overwriteCall(path, meta, registerName, templateIdent, styleIdent, s) {
36
36
  s.overwrite(callee.start, callee.end, registerName);
37
37
  s.appendLeft(insertPosition, `, ${metaCode}`);
38
38
  }
39
- function transformScriptModule({ code, cleanId, meta, enableHmr }) {
39
+ function transformScriptModule({ code, cleanId, meta, enableHmr, runtimeModuleId, hmrAcceptCode }) {
40
40
  const registerName = getRegisterName(meta.kind);
41
41
  if (!registerName) return null;
42
42
  let ast;
@@ -53,7 +53,7 @@ function transformScriptModule({ code, cleanId, meta, enableHmr }) {
53
53
  const s = new MagicString(code);
54
54
  let transformed = false;
55
55
  const imports = [];
56
- const runtimePolyfillId = toViteFsImport(resolveRuntimePolyfillPath());
56
+ const runtimePolyfillId = runtimeModuleId ?? toViteFsImport(resolveRuntimePolyfillPath());
57
57
  const templateIdent = meta.templatePath ? "__weapp_template__" : void 0;
58
58
  const styleIdent = meta.stylePath ? "__weapp_style__" : void 0;
59
59
  if (meta.templatePath && templateIdent) imports.push(`import ${templateIdent} from '${toRelativeImport(cleanId, meta.templatePath)}'`);
@@ -71,7 +71,7 @@ function transformScriptModule({ code, cleanId, meta, enableHmr }) {
71
71
  if (registerImports.size > 0) imports.unshift(`import { ${Array.from(registerImports).join(", ")} } from '${runtimePolyfillId}'`);
72
72
  const prefix = `${imports.join("\n")}\n`;
73
73
  s.prepend(prefix);
74
- if (enableHmr) s.append(`\nif (import.meta.hot) { import.meta.hot.accept() }\n`);
74
+ if (enableHmr && hmrAcceptCode) s.append(`\n${hmrAcceptCode}\n`);
75
75
  return {
76
76
  code: s.toString(),
77
77
  map: s.generateMap({ hires: true })
@@ -1 +1 @@
1
- {"version":3,"file":"register.mjs","names":[],"sources":["../../src/plugin/register.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse'\nimport type { CallExpression } from '@babel/types'\nimport type { SourceMap } from 'magic-string'\n\nimport type { ModuleMeta } from './types'\nimport { parse } from '@babel/parser'\nimport _babelTraverse from '@babel/traverse'\nimport * as t from '@babel/types'\n\nimport MagicString from 'magic-string'\nimport { appendInlineQuery, resolveRuntimePolyfillPath, toRelativeImport, toViteFsImport } from './path'\n\ntype TraverseFunction = typeof _babelTraverse extends (...args: any[]) => any\n ? typeof _babelTraverse\n : typeof _babelTraverse extends { default: infer D }\n ? D\n : typeof _babelTraverse\n\nconst traverseCandidate: any = (() => {\n const mod: any = _babelTraverse\n if (typeof mod === 'function') {\n return mod\n }\n if (mod?.default && typeof mod.default === 'function') {\n return mod.default\n }\n if (mod?.traverse && typeof mod.traverse === 'function') {\n return mod.traverse\n }\n return undefined\n})()\n\nif (typeof traverseCandidate !== 'function') {\n throw new TypeError('[@weapp-vite/web] Failed to resolve @babel/traverse export.')\n}\n\nconst traverse: TraverseFunction = traverseCandidate\n\nfunction mapRegisterIdentifier(kind: ModuleMeta['kind']) {\n if (kind === 'page') {\n return 'Page'\n }\n if (kind === 'component') {\n return 'Component'\n }\n if (kind === 'app') {\n return 'App'\n }\n return ''\n}\n\nfunction getRegisterName(kind: ModuleMeta['kind']) {\n if (kind === 'page') {\n return 'registerPage'\n }\n if (kind === 'component') {\n return 'registerComponent'\n }\n if (kind === 'app') {\n return 'registerApp'\n }\n return undefined\n}\n\nfunction overwriteCall(\n path: NodePath<CallExpression>,\n meta: ModuleMeta,\n registerName: string,\n templateIdent: string | undefined,\n styleIdent: string | undefined,\n s: MagicString,\n) {\n const node = path.node\n const callee = node.callee\n if (!t.isIdentifier(callee)) {\n return\n }\n const end = node.end!\n const insertPosition = end - 1\n const metaParts: string[] = [`id: ${JSON.stringify(meta.id)}`]\n if (templateIdent) {\n metaParts.push(`template: ${templateIdent}`)\n }\n if (styleIdent) {\n metaParts.push(`style: ${styleIdent}`)\n }\n const metaCode = `{ ${metaParts.join(', ')} }`\n s.overwrite(callee.start!, callee.end!, registerName)\n s.appendLeft(insertPosition, `, ${metaCode}`)\n}\n\ninterface TransformScriptModuleOptions {\n code: string\n cleanId: string\n meta: ModuleMeta\n enableHmr: boolean\n}\n\nexport function transformScriptModule({\n code,\n cleanId,\n meta,\n enableHmr,\n}: TransformScriptModuleOptions): null | { code: string, map: SourceMap } {\n const registerName = getRegisterName(meta.kind)\n if (!registerName) {\n return null\n }\n\n let ast: ReturnType<typeof parse> | undefined\n try {\n ast = parse(code, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n errorRecovery: true,\n ranges: true,\n })\n }\n catch {\n return null\n }\n\n const s = new MagicString(code)\n let transformed = false\n\n const imports: string[] = []\n const runtimePolyfillId = toViteFsImport(resolveRuntimePolyfillPath())\n const templateIdent = meta.templatePath ? '__weapp_template__' : undefined\n const styleIdent = meta.stylePath ? '__weapp_style__' : undefined\n\n if (meta.templatePath && templateIdent) {\n imports.push(`import ${templateIdent} from '${toRelativeImport(cleanId, meta.templatePath)}'`)\n }\n\n if (meta.stylePath && styleIdent) {\n imports.push(`import ${styleIdent} from '${appendInlineQuery(toRelativeImport(cleanId, meta.stylePath))}'`)\n }\n\n const registerImports = new Set<string>()\n\n traverse(ast, {\n CallExpression(path: NodePath<CallExpression>) {\n if (!t.isIdentifier(path.node.callee)) {\n return\n }\n const name = path.node.callee.name\n if (name === mapRegisterIdentifier(meta.kind)) {\n registerImports.add(registerName)\n overwriteCall(path, meta, registerName, templateIdent, styleIdent, s)\n transformed = true\n }\n },\n })\n\n if (!transformed) {\n return null\n }\n\n if (registerImports.size > 0) {\n imports.unshift(`import { ${Array.from(registerImports).join(', ')} } from '${runtimePolyfillId}'`)\n }\n\n const prefix = `${imports.join('\\n')}\\n`\n s.prepend(prefix)\n\n if (enableHmr) {\n s.append(`\\nif (import.meta.hot) { import.meta.hot.accept() }\\n`)\n }\n\n return {\n code: s.toString(),\n map: s.generateMap({\n hires: true,\n }),\n }\n}\n"],"mappings":";;;;;;;AAkBA,MAAM,2BAAgC;CACpC,MAAM,MAAW;CACjB,IAAI,OAAO,QAAQ,YACjB,OAAO;CAET,IAAI,KAAK,WAAW,OAAO,IAAI,YAAY,YACzC,OAAO,IAAI;CAEb,IAAI,KAAK,YAAY,OAAO,IAAI,aAAa,YAC3C,OAAO,IAAI;AAGf,EAAC,CAAE;AAEH,IAAI,OAAO,sBAAsB,YAC/B,MAAM,IAAI,UAAU,6DAA6D;AAGnF,MAAM,WAA6B;AAEnC,SAAS,sBAAsB,MAA0B;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,EAAE,EAAE;CAG/F,IAAI,KAAK,aAAa,YACpB,QAAQ,KAAK,UAAU,WAAW,SAAS,kBAAkB,iBAAiB,SAAS,KAAK,SAAS,CAAC,EAAE,EAAE;CAG5G,MAAM,kCAAkB,IAAI,IAAY;CAExC,SAAS,KAAK,EACZ,eAAe,MAAgC;EAC7C,IAAI,CAAC,EAAE,aAAa,KAAK,KAAK,MAAM,GAClC;EAGF,IADa,KAAK,KAAK,OAAO,SACjB,sBAAsB,KAAK,IAAI,GAAG;GAC7C,gBAAgB,IAAI,YAAY;GAChC,cAAc,MAAM,MAAM,cAAc,eAAe,YAAY,CAAC;GACpE,cAAc;EAChB;CACF,EACF,CAAC;CAED,IAAI,CAAC,aACH,OAAO;CAGT,IAAI,gBAAgB,OAAO,GACzB,QAAQ,QAAQ,YAAY,MAAM,KAAK,eAAe,CAAC,CAAC,KAAK,IAAI,EAAE,WAAW,kBAAkB,EAAE;CAGpG,MAAM,SAAS,GAAG,QAAQ,KAAK,IAAI,EAAE;CACrC,EAAE,QAAQ,MAAM;CAEhB,IAAI,WACF,EAAE,OAAO,uDAAuD;CAGlE,OAAO;EACL,MAAM,EAAE,SAAS;EACjB,KAAK,EAAE,YAAY,EACjB,OAAO,KACT,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"register.mjs","names":[],"sources":["../../src/plugin/register.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse'\nimport type { CallExpression } from '@babel/types'\nimport type { SourceMap } from 'magic-string'\n\nimport type { ModuleMeta } from './types'\nimport { parse } from '@babel/parser'\nimport _babelTraverse from '@babel/traverse'\nimport * as t from '@babel/types'\n\nimport MagicString from 'magic-string'\nimport { appendInlineQuery, resolveRuntimePolyfillPath, toRelativeImport, toViteFsImport } from './path'\n\ntype TraverseFunction = typeof _babelTraverse extends (...args: any[]) => any\n ? typeof _babelTraverse\n : typeof _babelTraverse extends { default: infer D }\n ? D\n : typeof _babelTraverse\n\nconst traverseCandidate: any = (() => {\n const mod: any = _babelTraverse\n if (typeof mod === 'function') {\n return mod\n }\n if (mod?.default && typeof mod.default === 'function') {\n return mod.default\n }\n if (mod?.traverse && typeof mod.traverse === 'function') {\n return mod.traverse\n }\n return undefined\n})()\n\nif (typeof traverseCandidate !== 'function') {\n throw new TypeError('[@weapp-vite/web] Failed to resolve @babel/traverse export.')\n}\n\nconst traverse: TraverseFunction = traverseCandidate\n\nfunction mapRegisterIdentifier(kind: ModuleMeta['kind']) {\n if (kind === 'page') {\n return 'Page'\n }\n if (kind === 'component') {\n return 'Component'\n }\n if (kind === 'app') {\n return 'App'\n }\n return ''\n}\n\nfunction getRegisterName(kind: ModuleMeta['kind']) {\n if (kind === 'page') {\n return 'registerPage'\n }\n if (kind === 'component') {\n return 'registerComponent'\n }\n if (kind === 'app') {\n return 'registerApp'\n }\n return undefined\n}\n\nfunction overwriteCall(\n path: NodePath<CallExpression>,\n meta: ModuleMeta,\n registerName: string,\n templateIdent: string | undefined,\n styleIdent: string | undefined,\n s: MagicString,\n) {\n const node = path.node\n const callee = node.callee\n if (!t.isIdentifier(callee)) {\n return\n }\n const end = node.end!\n const insertPosition = end - 1\n const metaParts: string[] = [`id: ${JSON.stringify(meta.id)}`]\n if (templateIdent) {\n metaParts.push(`template: ${templateIdent}`)\n }\n if (styleIdent) {\n metaParts.push(`style: ${styleIdent}`)\n }\n const metaCode = `{ ${metaParts.join(', ')} }`\n s.overwrite(callee.start!, callee.end!, registerName)\n s.appendLeft(insertPosition, `, ${metaCode}`)\n}\n\ninterface TransformScriptModuleOptions {\n code: string\n cleanId: string\n meta: ModuleMeta\n enableHmr: boolean\n runtimeModuleId?: string\n hmrAcceptCode?: string\n}\n\nexport function transformScriptModule({\n code,\n cleanId,\n meta,\n enableHmr,\n runtimeModuleId,\n hmrAcceptCode,\n}: TransformScriptModuleOptions): null | { code: string, map: SourceMap } {\n const registerName = getRegisterName(meta.kind)\n if (!registerName) {\n return null\n }\n\n let ast: ReturnType<typeof parse> | undefined\n try {\n ast = parse(code, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n errorRecovery: true,\n ranges: true,\n })\n }\n catch {\n return null\n }\n\n const s = new MagicString(code)\n let transformed = false\n\n const imports: string[] = []\n const runtimePolyfillId = runtimeModuleId ?? toViteFsImport(resolveRuntimePolyfillPath())\n const templateIdent = meta.templatePath ? '__weapp_template__' : undefined\n const styleIdent = meta.stylePath ? '__weapp_style__' : undefined\n\n if (meta.templatePath && templateIdent) {\n imports.push(`import ${templateIdent} from '${toRelativeImport(cleanId, meta.templatePath)}'`)\n }\n\n if (meta.stylePath && styleIdent) {\n imports.push(`import ${styleIdent} from '${appendInlineQuery(toRelativeImport(cleanId, meta.stylePath))}'`)\n }\n\n const registerImports = new Set<string>()\n\n traverse(ast, {\n CallExpression(path: NodePath<CallExpression>) {\n if (!t.isIdentifier(path.node.callee)) {\n return\n }\n const name = path.node.callee.name\n if (name === mapRegisterIdentifier(meta.kind)) {\n registerImports.add(registerName)\n overwriteCall(path, meta, registerName, templateIdent, styleIdent, s)\n transformed = true\n }\n },\n })\n\n if (!transformed) {\n return null\n }\n\n if (registerImports.size > 0) {\n imports.unshift(`import { ${Array.from(registerImports).join(', ')} } from '${runtimePolyfillId}'`)\n }\n\n const prefix = `${imports.join('\\n')}\\n`\n s.prepend(prefix)\n\n if (enableHmr && hmrAcceptCode) {\n s.append(`\\n${hmrAcceptCode}\\n`)\n }\n\n return {\n code: s.toString(),\n map: s.generateMap({\n hires: true,\n }),\n }\n}\n"],"mappings":";;;;;;;AAkBA,MAAM,2BAAgC;CACpC,MAAM,MAAW;CACjB,IAAI,OAAO,QAAQ,YACjB,OAAO;CAET,IAAI,KAAK,WAAW,OAAO,IAAI,YAAY,YACzC,OAAO,IAAI;CAEb,IAAI,KAAK,YAAY,OAAO,IAAI,aAAa,YAC3C,OAAO,IAAI;AAGf,EAAC,CAAE;AAEH,IAAI,OAAO,sBAAsB,YAC/B,MAAM,IAAI,UAAU,6DAA6D;AAGnF,MAAM,WAA6B;AAE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AK,UAAU,cAAc,SAAS,iBAAiB,SAAS,KAAK,YAAY,EAAE,EAAE;CAG/F,IAAI,KAAK,aAAa,YACpB,QAAQ,KAAK,UAAU,WAAW,SAAS,kBAAkB,iBAAiB,SAAS,KAAK,SAAS,CAAC,EAAE,EAAE;CAG5G,MAAM,kCAAkB,IAAI,IAAY;CAExC,SAAS,KAAK,EACZ,eAAe,MAAgC;EAC7C,IAAI,CAAC,EAAE,aAAa,KAAK,KAAK,MAAM,GAClC;EAGF,IADa,KAAK,KAAK,OAAO,SACjB,sBAAsB,KAAK,IAAI,GAAG;GAC7C,gBAAgB,IAAI,YAAY;GAChC,cAAc,MAAM,MAAM,cAAc,eAAe,YAAY,CAAC;GACpE,cAAc;EAChB;CACF,EACF,CAAC;CAED,IAAI,CAAC,aACH,OAAO;CAGT,IAAI,gBAAgB,OAAO,GACzB,QAAQ,QAAQ,YAAY,MAAM,KAAK,eAAe,CAAC,CAAC,KAAK,IAAI,EAAE,WAAW,kBAAkB,EAAE;CAGpG,MAAM,SAAS,GAAG,QAAQ,KAAK,IAAI,EAAE;CACrC,EAAE,QAAQ,MAAM;CAEhB,IAAI,aAAa,eACf,EAAE,OAAO,KAAK,cAAc,GAAG;CAGjC,OAAO;EACL,MAAM,EAAE,SAAS;EACjB,KAAK,EAAE,YAAY,EACjB,OAAO,KACT,CAAC;CACH;AACF"}
@@ -39,6 +39,15 @@ interface WeappWebPluginOptions {
39
39
  dedupe?: boolean;
40
40
  };
41
41
  };
42
+ /**
43
+ * weapp-vite runtime provider 注入的内部绑定。
44
+ *
45
+ * @internal
46
+ */
47
+ __runtimeProvider?: {
48
+ moduleId: string;
49
+ hmrAcceptCode?: string;
50
+ };
42
51
  }
43
52
  //#endregion
44
53
  export { WeappWebPluginOptions };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@weapp-vite/web",
3
3
  "type": "module",
4
- "version": "1.3.35",
4
+ "version": "1.3.37",
5
5
  "description": "Experimental web runtime for weapp-vite templates",
6
6
  "author": "ice breaker <1324318532@qq.com>",
7
7
  "license": "MIT",
@@ -54,12 +54,12 @@
54
54
  "domhandler": "^6.0.1",
55
55
  "htmlparser2": "^12.0.0",
56
56
  "lit": "^3.3.3",
57
- "magic-string": "^0.30.21",
57
+ "magic-string": "^1.0.0",
58
58
  "pathe": "^2.0.3",
59
59
  "rolldown": "1.1.5",
60
- "@weapp-core/constants": "0.1.13",
61
- "@weapp-core/shared": "3.0.5",
62
- "rolldown-require": "2.0.20"
60
+ "@weapp-core/constants": "0.1.14",
61
+ "@weapp-core/shared": "3.0.6",
62
+ "rolldown-require": "2.0.22"
63
63
  },
64
64
  "scripts": {
65
65
  "dev": "tsdown -w --sourcemap",