mini-three-adapter 0.1.0 → 0.1.2
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/AGENTS.md +85 -85
- package/README.md +159 -159
- package/dist/build/rollup.js +60 -9
- package/dist/build/rollup.js.map +1 -1
- package/dist/build/vite.js +60 -9
- package/dist/build/vite.js.map +1 -1
- package/dist/{chunk-MTBMOFAL.js → chunk-CQPWOYLA.js} +27 -14
- package/dist/chunk-CQPWOYLA.js.map +1 -0
- package/dist/{chunk-LB3WL24R.js → chunk-LRR4AEZM.js} +8 -4
- package/dist/chunk-LRR4AEZM.js.map +1 -0
- package/dist/{chunk-3UGQWFH3.js → chunk-MWGTYPGA.js} +87 -27
- package/dist/chunk-MWGTYPGA.js.map +1 -0
- package/dist/{chunk-4UEBRAK6.js → chunk-TMSB525P.js} +15 -6
- package/dist/chunk-TMSB525P.js.map +1 -0
- package/dist/{chunk-WLRQDTSZ.js → chunk-V2IGFCZV.js} +3 -3
- package/dist/{chunk-WLRQDTSZ.js.map → chunk-V2IGFCZV.js.map} +1 -1
- package/dist/{chunk-Z7AMDRN3.js → chunk-WB6MOHR3.js} +8 -5
- package/dist/chunk-WB6MOHR3.js.map +1 -0
- package/dist/core/index.d.ts +15 -5
- package/dist/core/index.js +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +6 -6
- package/dist/platforms/browser.d.ts +2 -2
- package/dist/platforms/browser.js +3 -3
- package/dist/platforms/wechat-game.d.ts +2 -2
- package/dist/platforms/wechat-game.js +4 -4
- package/dist/platforms/wechat-miniprogram.d.ts +2 -2
- package/dist/platforms/wechat-miniprogram.js +4 -4
- package/dist/polyfills/index.d.ts +8 -1
- package/dist/polyfills/index.js +1 -1
- package/dist/{runtime-7uUOoFhC.d.ts → runtime-DnEkKZjo.d.ts} +1 -1
- package/dist/scope.d.ts +1 -1
- package/dist/{types-BzK0LQMa.d.ts → types-X_5SJh4y.d.ts} +7 -0
- package/docs/02-architecture.md +126 -126
- package/docs/03-module-map.md +99 -99
- package/docs/04-api-reference.md +294 -291
- package/docs/05-build-plugin.md +33 -5
- package/docs/06-platform-notes.md +113 -108
- package/docs/07-integration-guide.md +13 -0
- package/docs/09-testing-and-release.md +208 -206
- package/docs/10-ai-playbook.md +140 -140
- package/docs/11-compat-matrix.md +95 -94
- package/docs/adr/0007-capability-probe-fallback.md +55 -0
- package/docs/adr/README.md +1 -0
- package/llms.txt +68 -65
- package/package.json +10 -4
- package/dist/chunk-3UGQWFH3.js.map +0 -1
- package/dist/chunk-4UEBRAK6.js.map +0 -1
- package/dist/chunk-LB3WL24R.js.map +0 -1
- package/dist/chunk-MTBMOFAL.js.map +0 -1
- package/dist/chunk-Z7AMDRN3.js.map +0 -1
package/dist/build/rollup.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/build/plugin-core.ts","../../src/build/scope-rewrite.ts","../../src/build/assets.ts","../../src/build/rollup.ts"],"sourcesContent":["/**\n * Rollup/Vite-compatible plugin core (zero hard dependency on either bundler).\n *\n * Responsibilities:\n * 1. Rewrite free browser globals inside third-party modules to scoped access.\n * 2. Handle `three/webgpu` (WebGPU is unavailable in WeChat mini games).\n * 3. Collect worker/wasm assets referenced by addons and emit them + a manifest.\n * 4. Produce a machine-readable build report for CI and AI-assisted iteration.\n */\nimport { promises as fs } from 'node:fs';\nimport {\n DEFAULT_FORCE_UNDEF,\n rewriteGlobals,\n type RewriteOptions,\n} from './scope-rewrite';\nimport {\n collectAssetReferences,\n collectAssets,\n type AssetManifest,\n type AssetOptions,\n} from './assets';\n\nexport interface MiniThreePluginOptions extends AssetOptions {\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\n include?: (id: string) => boolean;\n /** Modules to skip even when they match. */\n exclude?: (id: string) => boolean;\n /** Also transform application code (off by default). */\n includeUserCode?: boolean;\n /** Rewrite options (advanced). */\n rewrite?: RewriteOptions;\n /** How to handle `three/webgpu` imports. Default 'warn'. */\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\n /** Print a build report summary. Default true. */\n report?: boolean;\n /** Verbose per-module logs. */\n debug?: boolean;\n}\n\nexport interface BuildReport {\n modulesScanned: number;\n modulesRewritten: number;\n rewrites: number;\n globalsSeen: string[];\n assetReferences: string[];\n missingAssets: string[];\n webgpuWarnings: string[];\n parseFailures: string[];\n}\n\nexport interface PluginContext {\n warn(message: string): void;\n error(message: string): never;\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\n}\n\nexport interface MiniThreePlugin {\n name: string;\n enforce: 'pre';\n transform(this: PluginContext, code: string, id: string): { code: string; map: unknown } | null;\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\n api: {\n report(): BuildReport;\n };\n}\n\nconst DEFAULT_INCLUDE = (id: string): boolean => {\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\n return (\n normalized.includes('/node_modules/three/') ||\n normalized.includes('/node_modules/three-stdlib/') ||\n normalized.includes('/node_modules/@react-three/') ||\n normalized.includes('/node_modules/@tresjs/') ||\n normalized.includes('/node_modules/.vite/deps/three') ||\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\n );\n};\n\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n const include = options.include ?? DEFAULT_INCLUDE;\n const exclude = options.exclude ?? (() => false);\n const webgpuMode = options.webgpu ?? 'warn';\n const report: BuildReport = {\n modulesScanned: 0,\n modulesRewritten: 0,\n rewrites: 0,\n globalsSeen: [],\n assetReferences: [],\n missingAssets: [],\n webgpuWarnings: [],\n parseFailures: [],\n };\n const seenGlobals = new Set<string>();\n const assetRefs = new Set<string>();\n let manifest: AssetManifest | null = null;\n let filesToEmit = new Map<string, string>();\n\n const note = (ctx: PluginContext, message: string): void => {\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\n };\n\n return {\n name: 'mini-three-adapter',\n enforce: 'pre',\n\n transform(this: PluginContext, code: string, id: string) {\n const normalized = id.replace(/\\\\/g, '/');\n const shouldTransform = options.includeUserCode\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\n : include(normalized) && !exclude(normalized);\n if (!shouldTransform) return null;\n\n report.modulesScanned++;\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\n\n let currentCode = code;\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\n report.webgpuWarnings.push(message);\n if (webgpuMode === 'error') this.error(message);\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\n if (webgpuMode === 'rewrite') {\n currentCode = currentCode\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\n }\n }\n\n const result = rewriteGlobals(currentCode, normalized, {\n ...options.rewrite,\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\n });\n if (result && 'error' in result) {\n report.parseFailures.push(result.error);\n this.warn(`[mini-three] ${result.error}`);\n return null;\n }\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\n\n report.modulesRewritten++;\n report.rewrites += result.count;\n for (const name of result.seen) seenGlobals.add(name);\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\n return { code: result.code, map: result.map };\n },\n\n async generateBundle(this: PluginContext, bundleOptions) {\n const refs = Array.from(assetRefs);\n report.assetReferences = refs;\n report.globalsSeen = Array.from(seenGlobals).sort();\n\n if (refs.length > 0) {\n const collected = await collectAssets(refs, {\n cwd: options.cwd,\n roots: options.roots,\n outputDir: options.outputDir,\n brotli: options.brotli,\n manifest: options.manifest,\n });\n manifest = collected.manifest;\n filesToEmit = collected.files;\n report.missingAssets = collected.missing;\n for (const missing of collected.missing) {\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\n }\n for (const [destination, source] of filesToEmit) {\n try {\n const content = await fs.readFile(source);\n this.emitFile({ type: 'asset', fileName: destination, source: content });\n } catch (error) {\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\n }\n }\n } else {\n manifest = {\n generatedBy: 'mini-three-adapter',\n outputDir: options.outputDir ?? 'assets/three',\n entries: [],\n gameJsonSuggestion: {},\n decoderPaths: {},\n };\n }\n\n if (options.manifest !== false) {\n this.emitFile({\n type: 'asset',\n fileName: 'mini-three-assets.json',\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\n });\n }\n if (options.report !== false) {\n this.warn(\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\n );\n }\n },\n\n api: {\n report: () => ({\n ...report,\n globalsSeen: Array.from(seenGlobals).sort(),\n assetReferences: Array.from(assetRefs),\n webgpuWarnings: [...report.webgpuWarnings],\n parseFailures: [...report.parseFailures],\n }),\n },\n };\n}\n","/**\n * AST-based global-to-scope rewriting.\n *\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\n * `typeof window` feature detection. Here we parse with @babel/parser and use\n * Babel's scope binding information, so ONLY free (unbound) references to\n * browser globals are rewritten — application code is never touched.\n */\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport MagicString from 'magic-string';\nimport type { NodePath } from '@babel/traverse';\nimport type { Identifier } from '@babel/types';\nimport type { Node } from '@babel/types';\n\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\nconst traverse = (typeof _traverse === 'function'\n ? _traverse\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\n\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\n];\n\n/** Globals that must remain `undefined` in the mini game scope. */\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\n\nexport interface RewriteOptions {\n /** Extra global identifiers to rewrite. */\n extraGlobals?: string[];\n /** Replace the default global list instead of extending it. */\n globals?: string[];\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\n forceUndef?: string[];\n /** Name of the injected scope accessor. Default `__m3`. */\n accessor?: string;\n /** Module specifier that exports `getActiveScope`. */\n scopeModule?: string;\n}\n\nexport interface RewriteResult {\n code: string;\n map: { toString(): string } | null;\n /** Number of rewritten references. */\n count: number;\n /** Globals actually seen (useful for the build report). */\n seen: string[];\n}\n\nexport interface RewriteFailure {\n code: string;\n error: string;\n}\n\nexport const SCOPE_IMPORT = (accessor: string, module: string): string =>\n `import { getActiveScope as ${accessor} } from '${module}';\\n`;\n\nfunction isNonComputedKey(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent) return false;\n const self: unknown = path.node;\n if (parent.isObjectProperty() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isObjectMethod() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isClassProperty() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isClassMethod() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isMemberExpression() && !parent.node.computed && (parent.node.property as unknown) === self) return true;\n return false;\n}\n\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\nexport function rewriteGlobals(\n code: string,\n id: string,\n options: RewriteOptions = {},\n): RewriteResult | RewriteFailure | null {\n const names = new Set<string>([\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\n ...(options.extraGlobals ?? []),\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\n ]);\n const accessor = options.accessor ?? '__m3';\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\n\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'unambiguous',\n errorRecovery: true,\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\n });\n } catch (error) {\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\n }\n\n const ms = new MagicString(code);\n const seen = new Set<string>();\n let count = 0;\n\n traverse(ast, {\n ReferencedIdentifier(path: NodePath<Node>) {\n const node = path.node as Identifier;\n const name = node.name;\n if (!name || !names.has(name)) return;\n if (node.start == null || node.end == null) return;\n if (isNonComputedKey(path)) return;\n // Babel scope knows about imports, function params, local declarations,\n // catch bindings and block-scoped shadowing. This is the critical check\n // that a regex-based replacement cannot perform.\n if (path.scope.hasBinding(name, true)) return;\n // `typeof window` stays correct: `typeof __m3().window` === 'object'.\n seen.add(name);\n ms.overwrite(node.start, node.end, `${accessor}().${name}`);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(accessor, scopeModule));\n return {\n code: ms.toString(),\n map: ms.generateMap({ source: id, includeContent: true, hires: true }) as unknown as { toString(): string },\n count,\n seen: Array.from(seen).sort(),\n };\n}\n","/**\n * Worker / WASM asset collection for three.js addons.\n *\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\n * `.js` and `.wasm` files by string path. In a mini game those files are not\n * reachable via HTTP; they must be copied into the code package (ideally a\n * subpackage) and `setDecoderPath` must point at the copied location.\n *\n * The plugin scans transformed modules, resolves each referenced basename in a\n * small set of known directories, copies it, and emits a manifest plus a\n * `game.json` suggestion. No global state, no hidden writes.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface AssetOptions {\n /** Extra directories to search (besides three's jsm/libs). */\n roots?: string[];\n /** Output directory relative to the bundle root. Default 'assets/three'. */\n outputDir?: string;\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\n brotli?: boolean;\n /** Emit `mini-three-assets.json`. Default true. */\n manifest?: boolean;\n /** Working directory used to resolve roots. Default process.cwd(). */\n cwd?: string;\n}\n\nexport interface AssetEntry {\n /** Original string found in the module. */\n reference: string;\n /** Resolved absolute source path. */\n source: string;\n /** Relative destination inside the bundle. */\n destination: string;\n kind: 'worker' | 'wasm' | 'data';\n}\n\nexport interface AssetManifest {\n generatedBy: 'mini-three-adapter';\n outputDir: string;\n entries: AssetEntry[];\n /** Paste into game.json (adjust subpackage names to your project). */\n gameJsonSuggestion: Record<string, unknown>;\n /** Decoder paths to feed to loaders at runtime. */\n decoderPaths: Record<string, string>;\n}\n\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\nconst DECODER_KEYWORDS = [\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\n];\n\nexport function collectAssetReferences(code: string): string[] {\n const found = new Set<string>();\n let match: RegExpExecArray | null;\n ASSET_PATTERN.lastIndex = 0;\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\n const value = match[2] ?? '';\n const lower = value.toLowerCase();\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\n }\n return Array.from(found);\n}\n\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > maxDepth) return;\n let entries;\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\n catch { return; }\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) await walk(full, depth + 1);\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\n }\n };\n await walk(root, 0);\n return index;\n}\n\nfunction classify(name: string): AssetEntry['kind'] {\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\n if (name.endsWith('.js')) return 'worker';\n return 'data';\n}\n\nexport function defaultRoots(cwd: string): string[] {\n return [\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\n path.join(cwd, 'node_modules/three/examples/jsm'),\n path.join(cwd, 'node_modules/three-stdlib'),\n path.join(cwd, 'public'),\n path.join(cwd, 'static'),\n ];\n}\n\nexport interface CollectResult {\n manifest: AssetManifest;\n /** Files to write: destination (relative) -> absolute source. */\n files: Map<string, string>;\n missing: string[];\n}\n\n/** Resolve references against known roots without copying anything. */\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\n const cwd = options.cwd ?? process.cwd();\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\n const find = (name: string): string | undefined => {\n for (const index of indexes) {\n const hit = index.get(name);\n if (hit) return hit;\n }\n return undefined;\n };\n\n const entries: AssetEntry[] = [];\n const files = new Map<string, string>();\n const missing: string[] = [];\n\n for (const reference of references) {\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\n const source = find(base);\n if (!source) { missing.push(reference); continue; }\n const entry: AssetEntry = {\n reference,\n source,\n destination: `${outputDir}/${base}`,\n kind: classify(base),\n };\n entries.push(entry);\n files.set(entry.destination, source);\n if (options.brotli !== false && entry.kind === 'wasm') {\n const br = find(`${base}.br`);\n if (br) {\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\n files.set(`${outputDir}/${base}.br`, br);\n }\n }\n }\n\n const decoderPaths: Record<string, string> = {};\n for (const entry of entries) {\n const name = path.posix.basename(entry.destination).toLowerCase();\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\n }\n }\n\n const manifest: AssetManifest = {\n generatedBy: 'mini-three-adapter',\n outputDir,\n entries,\n gameJsonSuggestion: {\n workers: { path: `${outputDir}`, isSubpackage: true },\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\n },\n decoderPaths,\n };\n return { manifest, files, missing };\n}\n\n/** Copy resolved files into `outDir`. */\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\n let written = 0;\n for (const [destination, source] of files) {\n const target = path.join(outDir, destination);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n written++;\n }\n return written;\n}\n","/** Rollup entry: `import { miniThree } from 'mini-three-adapter/rollup'`. */\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\n\nexport function miniThree(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n return miniThreePlugin(options);\n}\n\nexport default miniThree;\nexport { miniThreePlugin } from './plugin-core';\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\nexport { DEFAULT_GLOBAL_NAMES, DEFAULT_FORCE_UNDEF, rewriteGlobals } from './scope-rewrite';\nexport type { RewriteOptions, RewriteResult } from './scope-rewrite';\nexport { collectAssetReferences, collectAssets, copyAssets } from './assets';\nexport type { AssetOptions, AssetManifest, AssetEntry } from './assets';\n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UACV,QAAQ,KAAK,UAAU,EAAE,GAAG,UAAU,OAAO,QAAQ,QAAQ,cAAc,OAAO,cAAc,QAAQ,GAAG,GAAG,MAAM,CAAC;AAAA,QACvH,CAAC;AAAA,MACH;AACA,UAAI,QAAQ,WAAW,OAAO;AAC5B,aAAK;AAAA,UACH,8BAA8B,OAAO,cAAc,uBAC9C,OAAO,gBAAgB,eAAe,OAAO,QAAQ,2BACrD,YAAY,IAAI,sBAAsB,OAAO,cAAc,MAAM;AAAA,QACxE;AAAA,MACF;AAAA,IACF;AAAA,IAEA,KAAK;AAAA,MACH,QAAQ,OAAO;AAAA,QACb,GAAG;AAAA,QACH,aAAa,MAAM,KAAK,WAAW,EAAE,KAAK;AAAA,QAC1C,iBAAiB,MAAM,KAAK,SAAS;AAAA,QACrC,gBAAgB,CAAC,GAAG,OAAO,cAAc;AAAA,QACzC,eAAe,CAAC,GAAG,OAAO,aAAa;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;;;AGhNO,SAAS,UAAU,UAAkC,CAAC,GAAoB;AAC/E,SAAO,gBAAgB,OAAO;AAChC;AAEA,IAAO,iBAAQ;","names":["fs","path","fs"]}
|
|
1
|
+
{"version":3,"sources":["../../src/build/plugin-core.ts","../../src/build/scope-rewrite.ts","../../src/build/assets.ts","../../src/build/rollup.ts"],"sourcesContent":["/**\n * Rollup/Vite-compatible plugin core (zero hard dependency on either bundler).\n *\n * Responsibilities:\n * 1. Rewrite free browser globals inside third-party modules to scoped access.\n * 2. Handle `three/webgpu` (WebGPU is unavailable in WeChat mini games).\n * 3. Collect worker/wasm assets referenced by addons and emit them + a manifest.\n * 4. Produce a machine-readable build report for CI and AI-assisted iteration.\n */\nimport { promises as fs } from 'node:fs';\nimport {\n DEFAULT_FORCE_UNDEF,\n rewriteGlobals,\n type RewriteOptions,\n} from './scope-rewrite';\nimport {\n collectAssetReferences,\n collectAssets,\n type AssetManifest,\n type AssetOptions,\n} from './assets';\n\nexport interface MiniThreePluginOptions extends AssetOptions {\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\n include?: (id: string) => boolean;\n /** Modules to skip even when they match. */\n exclude?: (id: string) => boolean;\n /** Also transform application code (off by default). */\n includeUserCode?: boolean;\n /** Rewrite options (advanced). */\n rewrite?: RewriteOptions;\n /** How to handle `three/webgpu` imports. Default 'warn'. */\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\n /** Print a build report summary. Default true. */\n report?: boolean;\n /** Verbose per-module logs. */\n debug?: boolean;\n}\n\nexport interface BuildReport {\n modulesScanned: number;\n modulesRewritten: number;\n rewrites: number;\n globalsSeen: string[];\n assetReferences: string[];\n missingAssets: string[];\n webgpuWarnings: string[];\n parseFailures: string[];\n}\n\nexport interface PluginContext {\n warn(message: string): void;\n error(message: string): never;\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\n}\n\nexport interface MiniThreePlugin {\n name: string;\n enforce: 'pre';\n transform(this: PluginContext, code: string, id: string): { code: string; map: unknown } | null;\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\n api: {\n report(): BuildReport;\n };\n}\n\nconst DEFAULT_INCLUDE = (id: string): boolean => {\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\n return (\n normalized.includes('/node_modules/three/') ||\n normalized.includes('/node_modules/three-stdlib/') ||\n normalized.includes('/node_modules/@react-three/') ||\n normalized.includes('/node_modules/@tresjs/') ||\n normalized.includes('/node_modules/.vite/deps/three') ||\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\n );\n};\n\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n const include = options.include ?? DEFAULT_INCLUDE;\n const exclude = options.exclude ?? (() => false);\n const webgpuMode = options.webgpu ?? 'warn';\n const report: BuildReport = {\n modulesScanned: 0,\n modulesRewritten: 0,\n rewrites: 0,\n globalsSeen: [],\n assetReferences: [],\n missingAssets: [],\n webgpuWarnings: [],\n parseFailures: [],\n };\n const seenGlobals = new Set<string>();\n const assetRefs = new Set<string>();\n let manifest: AssetManifest | null = null;\n let filesToEmit = new Map<string, string>();\n\n const note = (ctx: PluginContext, message: string): void => {\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\n };\n\n return {\n name: 'mini-three-adapter',\n enforce: 'pre',\n\n transform(this: PluginContext, code: string, id: string) {\n const normalized = id.replace(/\\\\/g, '/');\n const shouldTransform = options.includeUserCode\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\n : include(normalized) && !exclude(normalized);\n if (!shouldTransform) return null;\n\n report.modulesScanned++;\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\n\n let currentCode = code;\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\n report.webgpuWarnings.push(message);\n if (webgpuMode === 'error') this.error(message);\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\n if (webgpuMode === 'rewrite') {\n currentCode = currentCode\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\n }\n }\n\n const result = rewriteGlobals(currentCode, normalized, {\n ...options.rewrite,\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\n });\n if (result && 'error' in result) {\n report.parseFailures.push(result.error);\n this.warn(`[mini-three] ${result.error}`);\n return null;\n }\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\n\n report.modulesRewritten++;\n report.rewrites += result.count;\n for (const name of result.seen) seenGlobals.add(name);\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\n return { code: result.code, map: result.map };\n },\n\n async generateBundle(this: PluginContext, bundleOptions) {\n const refs = Array.from(assetRefs);\n report.assetReferences = refs;\n report.globalsSeen = Array.from(seenGlobals).sort();\n\n if (refs.length > 0) {\n const collected = await collectAssets(refs, {\n cwd: options.cwd,\n roots: options.roots,\n outputDir: options.outputDir,\n brotli: options.brotli,\n manifest: options.manifest,\n });\n manifest = collected.manifest;\n filesToEmit = collected.files;\n report.missingAssets = collected.missing;\n for (const missing of collected.missing) {\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\n }\n for (const [destination, source] of filesToEmit) {\n try {\n const content = await fs.readFile(source);\n this.emitFile({ type: 'asset', fileName: destination, source: content });\n } catch (error) {\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\n }\n }\n } else {\n manifest = {\n generatedBy: 'mini-three-adapter',\n outputDir: options.outputDir ?? 'assets/three',\n entries: [],\n gameJsonSuggestion: {},\n decoderPaths: {},\n };\n }\n\n if (options.manifest !== false) {\n this.emitFile({\n type: 'asset',\n fileName: 'mini-three-assets.json',\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\n });\n }\n if (options.report !== false) {\n this.warn(\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\n );\n }\n },\n\n api: {\n report: () => ({\n ...report,\n globalsSeen: Array.from(seenGlobals).sort(),\n assetReferences: Array.from(assetRefs),\n webgpuWarnings: [...report.webgpuWarnings],\n parseFailures: [...report.parseFailures],\n }),\n },\n };\n}\n","/**\n * AST-based global-to-scope rewriting.\n *\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\n * `typeof window` feature detection. Here we parse with @babel/parser and use\n * Babel's scope binding information, so ONLY free (unbound) references to\n * browser globals are rewritten — application code is never touched.\n */\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport MagicString from 'magic-string';\nimport type { NodePath } from '@babel/traverse';\nimport type { Identifier } from '@babel/types';\nimport type { Node } from '@babel/types';\n\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\nconst traverse = (typeof _traverse === 'function'\n ? _traverse\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\n\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\n];\n\n/** Globals that must remain `undefined` in the mini game scope. */\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\n\nexport interface RewriteOptions {\n /** Extra global identifiers to rewrite. */\n extraGlobals?: string[];\n /** Replace the default global list instead of extending it. */\n globals?: string[];\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\n forceUndef?: string[];\n /** Name of the injected scope accessor. Default `__m3`. */\n accessor?: string;\n /** Module specifier that exports `getActiveScope`. */\n scopeModule?: string;\n}\n\nexport interface RewriteResult {\n code: string;\n map: { toString(): string } | null;\n /** Number of rewritten references. */\n count: number;\n /** Globals actually seen (useful for the build report). */\n seen: string[];\n}\n\nexport interface RewriteFailure {\n code: string;\n error: string;\n}\n\nexport const SCOPE_IMPORT = (\n accessor: string,\n module: string,\n extraSpecifiers: readonly string[] = [],\n): string => {\n const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(', ');\n return `import { ${specifiers} } from '${module}';\\n`;\n};\n\n/**\n * Reference or range equality. `@babel/parser` emits TWO distinct `Identifier`\n * nodes with identical `[start, end]` for a shorthand property (`{ X }`: one for\n * `key`, one for `value`), so reference equality alone is not enough to tell\n * \"this identifier is an object key\".\n */\nfunction sameNode(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const x = a as { start?: number | null; end?: number | null } | null | undefined;\n const y = b as { start?: number | null; end?: number | null } | null | undefined;\n return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);\n}\n\nfunction isNonComputedKey(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent) return false;\n const self: unknown = path.node;\n if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;\n return false;\n}\n\n/**\n * `{ X }`: the value node shares its range with the key, so it cannot be\n * rewritten in place — it must be expanded to `{ X: <expr> }`.\n */\nfunction isShorthandValue(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent?.isObjectProperty()) return false;\n if (!parent.node.shorthand || parent.node.computed) return false;\n if (parent.node.value !== path.node) return false;\n // `const { X } = obj` destructures a binding, never a global reference. Babel\n // already treats it as a binding, this guard keeps the two paths disjoint.\n return !parent.parentPath?.isObjectPattern();\n}\n\n/**\n * Is this identifier the left-most link of a `new X` / `new X.Y.Z` callee chain?\n *\n * `new f().g()` parses as `(new f()).g()`, so rewriting `X` to a *call*\n * (`__m3().X`) without parentheses silently turns `new X()` into\n * `(new __m3()).X()` — the scope object gets constructed and the class is then\n * invoked as a plain function. Wrapping only the chain root is enough:\n * `new (a().b).c` parses as `new ((a().b).c)`.\n */\nfunction isNewCalleeRoot(path: NodePath): boolean {\n let cur: NodePath = path;\n let parent = cur.parentPath;\n while (parent?.isMemberExpression() && parent.node.object === cur.node) {\n cur = parent;\n parent = parent.parentPath;\n }\n return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);\n}\n\n/** `typeof X` must never throw: `typeof a.b` is legal even when `a` is unbound. */\nfunction isDirectTypeofOperand(path: NodePath): boolean {\n const parent = path.parentPath;\n return Boolean(\n parent?.isUnaryExpression() &&\n parent.node.operator === 'typeof' &&\n parent.node.argument === path.node,\n );\n}\n\n/**\n * Globals that `getActiveScope()` resolves to itself even before a runtime\n * exists, so `typeof window` is already `'object'` and needs no guard.\n */\nconst ALWAYS_OBJECT_GLOBALS: ReadonlySet<string> = new Set(['window', 'self', 'globalThis']);\n\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\nexport function rewriteGlobals(\n code: string,\n id: string,\n options: RewriteOptions = {},\n): RewriteResult | RewriteFailure | null {\n const names = new Set<string>([\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\n ...(options.extraGlobals ?? []),\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\n ]);\n const accessor = options.accessor ?? '__m3';\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\n\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'unambiguous',\n errorRecovery: true,\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\n });\n } catch (error) {\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\n }\n\n const ms = new MagicString(code);\n const seen = new Set<string>();\n const hasAccessor = `${accessor}Has`;\n let count = 0;\n let needsHasGuard = false;\n\n traverse(ast, {\n ReferencedIdentifier(path: NodePath<Node>) {\n const node = path.node as Identifier;\n const name = node.name;\n if (!name || !names.has(name)) return;\n if (node.start == null || node.end == null) return;\n // Babel scope knows about imports, function params, local declarations,\n // catch bindings and block-scoped shadowing. This is the critical check\n // that a regex-based replacement cannot perform.\n if (path.scope.hasBinding(name, true)) return;\n\n const ref = `${accessor}().${name}`;\n\n // 1) Shorthand must be handled before the key check: once `isNonComputedKey`\n // compares ranges, `{ X }`'s value looks like a key too and would be\n // silently skipped (leaving an undefined global behind).\n if (isShorthandValue(path)) {\n seen.add(name);\n ms.overwrite(node.start, node.end, `${name}: (${ref})`);\n count++;\n return;\n }\n\n // 2) Object keys / member property names are not references.\n if (isNonComputedKey(path)) return;\n\n seen.add(name);\n if (isDirectTypeofOperand(path) && !ALWAYS_OBJECT_GLOBALS.has(name)) {\n // `typeof X` must never throw, but an uninitialized scope throws for\n // everything except window/self/globalThis. Guard it so feature\n // detection at module top level sees 'undefined' instead of exploding.\n ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);\n needsHasGuard = true;\n count++;\n return;\n }\n ms.overwrite(node.start, node.end, isNewCalleeRoot(path) ? `(${ref})` : ref);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(\n accessor,\n scopeModule,\n needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : [],\n ));\n return {\n code: ms.toString(),\n map: ms.generateMap({ source: id, includeContent: true, hires: true }) as unknown as { toString(): string },\n count,\n seen: Array.from(seen).sort(),\n };\n}\n","/**\n * Worker / WASM asset collection for three.js addons.\n *\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\n * `.js` and `.wasm` files by string path. In a mini game those files are not\n * reachable via HTTP; they must be copied into the code package (ideally a\n * subpackage) and `setDecoderPath` must point at the copied location.\n *\n * The plugin scans transformed modules, resolves each referenced basename in a\n * small set of known directories, copies it, and emits a manifest plus a\n * `game.json` suggestion. No global state, no hidden writes.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface AssetOptions {\n /** Extra directories to search (besides three's jsm/libs). */\n roots?: string[];\n /** Output directory relative to the bundle root. Default 'assets/three'. */\n outputDir?: string;\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\n brotli?: boolean;\n /** Emit `mini-three-assets.json`. Default true. */\n manifest?: boolean;\n /** Working directory used to resolve roots. Default process.cwd(). */\n cwd?: string;\n}\n\nexport interface AssetEntry {\n /** Original string found in the module. */\n reference: string;\n /** Resolved absolute source path. */\n source: string;\n /** Relative destination inside the bundle. */\n destination: string;\n kind: 'worker' | 'wasm' | 'data';\n}\n\nexport interface AssetManifest {\n generatedBy: 'mini-three-adapter';\n outputDir: string;\n entries: AssetEntry[];\n /** Paste into game.json (adjust subpackage names to your project). */\n gameJsonSuggestion: Record<string, unknown>;\n /** Decoder paths to feed to loaders at runtime. */\n decoderPaths: Record<string, string>;\n}\n\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\nconst DECODER_KEYWORDS = [\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\n];\n\nexport function collectAssetReferences(code: string): string[] {\n const found = new Set<string>();\n let match: RegExpExecArray | null;\n ASSET_PATTERN.lastIndex = 0;\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\n const value = match[2] ?? '';\n const lower = value.toLowerCase();\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\n }\n return Array.from(found);\n}\n\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > maxDepth) return;\n let entries;\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\n catch { return; }\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) await walk(full, depth + 1);\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\n }\n };\n await walk(root, 0);\n return index;\n}\n\nfunction classify(name: string): AssetEntry['kind'] {\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\n if (name.endsWith('.js')) return 'worker';\n return 'data';\n}\n\nexport function defaultRoots(cwd: string): string[] {\n return [\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\n path.join(cwd, 'node_modules/three/examples/jsm'),\n path.join(cwd, 'node_modules/three-stdlib'),\n path.join(cwd, 'public'),\n path.join(cwd, 'static'),\n ];\n}\n\nexport interface CollectResult {\n manifest: AssetManifest;\n /** Files to write: destination (relative) -> absolute source. */\n files: Map<string, string>;\n missing: string[];\n}\n\n/** Resolve references against known roots without copying anything. */\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\n const cwd = options.cwd ?? process.cwd();\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\n const find = (name: string): string | undefined => {\n for (const index of indexes) {\n const hit = index.get(name);\n if (hit) return hit;\n }\n return undefined;\n };\n\n const entries: AssetEntry[] = [];\n const files = new Map<string, string>();\n const missing: string[] = [];\n\n for (const reference of references) {\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\n const source = find(base);\n if (!source) { missing.push(reference); continue; }\n const entry: AssetEntry = {\n reference,\n source,\n destination: `${outputDir}/${base}`,\n kind: classify(base),\n };\n entries.push(entry);\n files.set(entry.destination, source);\n if (options.brotli !== false && entry.kind === 'wasm') {\n const br = find(`${base}.br`);\n if (br) {\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\n files.set(`${outputDir}/${base}.br`, br);\n }\n }\n }\n\n const decoderPaths: Record<string, string> = {};\n for (const entry of entries) {\n const name = path.posix.basename(entry.destination).toLowerCase();\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\n }\n }\n\n const manifest: AssetManifest = {\n generatedBy: 'mini-three-adapter',\n outputDir,\n entries,\n gameJsonSuggestion: {\n workers: { path: `${outputDir}`, isSubpackage: true },\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\n },\n decoderPaths,\n };\n return { manifest, files, missing };\n}\n\n/** Copy resolved files into `outDir`. */\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\n let written = 0;\n for (const [destination, source] of files) {\n const target = path.join(outDir, destination);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n written++;\n }\n return written;\n}\n","/** Rollup entry: `import { miniThree } from 'mini-three-adapter/rollup'`. */\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\n\nexport function miniThree(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n return miniThreePlugin(options);\n}\n\nexport default miniThree;\nexport { miniThreePlugin } from './plugin-core';\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\nexport { DEFAULT_GLOBAL_NAMES, DEFAULT_FORCE_UNDEF, rewriteGlobals } from './scope-rewrite';\nexport type { RewriteOptions, RewriteResult } from './scope-rewrite';\nexport { collectAssetReferences, collectAssets, copyAssets } from './assets';\nexport type { AssetOptions, AssetManifest, AssetEntry } from './assets';\n"],"mappings":";AASA,SAAS,YAAYA,WAAU;;;ACA/B,SAAS,aAAa;AACtB,OAAO,eAAe;AACtB,OAAO,iBAAiB;AAMxB,IAAM,WAAY,OAAO,cAAc,aACnC,YACC,UAAuD;AAErD,IAAM,uBAA0C;AAAA,EACrD;AAAA,EAAU;AAAA,EAAQ;AAAA,EAAY;AAAA,EAAa;AAAA,EAAU;AAAA,EACrD;AAAA,EAAc;AAAA,EAAe;AAAA,EAAc;AAAA,EAC3C;AAAA,EAAoB;AAAA,EAAe;AAAA,EACnC;AAAA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AAAA,UACZ,MAAM;AAAA,UACN,UAAU;AAAA,UACV,QAAQ,KAAK,UAAU,EAAE,GAAG,UAAU,OAAO,QAAQ,QAAQ,cAAc,OAAO,cAAc,QAAQ,GAAG,GAAG,MAAM,CAAC;AAAA,QACvH,CAAC;AAAA,MACH;AACA,UAAI,QAAQ,WAAW,OAAO;AAC5B,aAAK;AAAA,UACH,8BAA8B,OAAO,cAAc,uBAC9C,OAAO,gBAAgB,eAAe,OAAO,QAAQ,2BACrD,YAAY,IAAI,sBAAsB,OAAO,cAAc,MAAM;AAAA,QACxE;AAAA,MACF;AAAA,IACF;AAAA,IAEA,KAAK;AAAA,MACH,QAAQ,OAAO;AAAA,QACb,GAAG;AAAA,QACH,aAAa,MAAM,KAAK,WAAW,EAAE,KAAK;AAAA,QAC1C,iBAAiB,MAAM,KAAK,SAAS;AAAA,QACrC,gBAAgB,CAAC,GAAG,OAAO,cAAc;AAAA,QACzC,eAAe,CAAC,GAAG,OAAO,aAAa;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;;;AGhNO,SAAS,UAAU,UAAkC,CAAC,GAAoB;AAC/E,SAAO,gBAAgB,OAAO;AAChC;AAEA,IAAO,iBAAQ;","names":["fs","path","fs"]}
|
package/dist/build/vite.js
CHANGED
|
@@ -65,19 +65,51 @@ var DEFAULT_GLOBAL_NAMES = [
|
|
|
65
65
|
"ResizeObserver"
|
|
66
66
|
];
|
|
67
67
|
var DEFAULT_FORCE_UNDEF = ["createImageBitmap"];
|
|
68
|
-
var SCOPE_IMPORT = (accessor, module
|
|
68
|
+
var SCOPE_IMPORT = (accessor, module, extraSpecifiers = []) => {
|
|
69
|
+
const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(", ");
|
|
70
|
+
return `import { ${specifiers} } from '${module}';
|
|
69
71
|
`;
|
|
72
|
+
};
|
|
73
|
+
function sameNode(a, b) {
|
|
74
|
+
if (a === b) return true;
|
|
75
|
+
const x = a;
|
|
76
|
+
const y = b;
|
|
77
|
+
return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);
|
|
78
|
+
}
|
|
70
79
|
function isNonComputedKey(path2) {
|
|
71
80
|
const parent = path2.parentPath;
|
|
72
81
|
if (!parent) return false;
|
|
73
82
|
const self = path2.node;
|
|
74
|
-
if (parent.isObjectProperty() && !parent.node.computed && parent.node.key
|
|
75
|
-
if (parent.isObjectMethod() && !parent.node.computed && parent.node.key
|
|
76
|
-
if (parent.isClassProperty() && !parent.node.computed && parent.node.key
|
|
77
|
-
if (parent.isClassMethod() && !parent.node.computed && parent.node.key
|
|
78
|
-
if (parent.isMemberExpression() && !parent.node.computed && parent.node.property
|
|
83
|
+
if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;
|
|
84
|
+
if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;
|
|
85
|
+
if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;
|
|
86
|
+
if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;
|
|
87
|
+
if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;
|
|
79
88
|
return false;
|
|
80
89
|
}
|
|
90
|
+
function isShorthandValue(path2) {
|
|
91
|
+
const parent = path2.parentPath;
|
|
92
|
+
if (!parent?.isObjectProperty()) return false;
|
|
93
|
+
if (!parent.node.shorthand || parent.node.computed) return false;
|
|
94
|
+
if (parent.node.value !== path2.node) return false;
|
|
95
|
+
return !parent.parentPath?.isObjectPattern();
|
|
96
|
+
}
|
|
97
|
+
function isNewCalleeRoot(path2) {
|
|
98
|
+
let cur = path2;
|
|
99
|
+
let parent = cur.parentPath;
|
|
100
|
+
while (parent?.isMemberExpression() && parent.node.object === cur.node) {
|
|
101
|
+
cur = parent;
|
|
102
|
+
parent = parent.parentPath;
|
|
103
|
+
}
|
|
104
|
+
return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);
|
|
105
|
+
}
|
|
106
|
+
function isDirectTypeofOperand(path2) {
|
|
107
|
+
const parent = path2.parentPath;
|
|
108
|
+
return Boolean(
|
|
109
|
+
parent?.isUnaryExpression() && parent.node.operator === "typeof" && parent.node.argument === path2.node
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
var ALWAYS_OBJECT_GLOBALS = /* @__PURE__ */ new Set(["window", "self", "globalThis"]);
|
|
81
113
|
function rewriteGlobals(code, id, options = {}) {
|
|
82
114
|
const names = /* @__PURE__ */ new Set([
|
|
83
115
|
...options.globals ?? DEFAULT_GLOBAL_NAMES,
|
|
@@ -98,22 +130,41 @@ function rewriteGlobals(code, id, options = {}) {
|
|
|
98
130
|
}
|
|
99
131
|
const ms = new MagicString(code);
|
|
100
132
|
const seen = /* @__PURE__ */ new Set();
|
|
133
|
+
const hasAccessor = `${accessor}Has`;
|
|
101
134
|
let count = 0;
|
|
135
|
+
let needsHasGuard = false;
|
|
102
136
|
traverse(ast, {
|
|
103
137
|
ReferencedIdentifier(path2) {
|
|
104
138
|
const node = path2.node;
|
|
105
139
|
const name = node.name;
|
|
106
140
|
if (!name || !names.has(name)) return;
|
|
107
141
|
if (node.start == null || node.end == null) return;
|
|
108
|
-
if (isNonComputedKey(path2)) return;
|
|
109
142
|
if (path2.scope.hasBinding(name, true)) return;
|
|
143
|
+
const ref = `${accessor}().${name}`;
|
|
144
|
+
if (isShorthandValue(path2)) {
|
|
145
|
+
seen.add(name);
|
|
146
|
+
ms.overwrite(node.start, node.end, `${name}: (${ref})`);
|
|
147
|
+
count++;
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (isNonComputedKey(path2)) return;
|
|
110
151
|
seen.add(name);
|
|
111
|
-
|
|
152
|
+
if (isDirectTypeofOperand(path2) && !ALWAYS_OBJECT_GLOBALS.has(name)) {
|
|
153
|
+
ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);
|
|
154
|
+
needsHasGuard = true;
|
|
155
|
+
count++;
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
ms.overwrite(node.start, node.end, isNewCalleeRoot(path2) ? `(${ref})` : ref);
|
|
112
159
|
count++;
|
|
113
160
|
}
|
|
114
161
|
});
|
|
115
162
|
if (count === 0) return null;
|
|
116
|
-
ms.prepend(SCOPE_IMPORT(
|
|
163
|
+
ms.prepend(SCOPE_IMPORT(
|
|
164
|
+
accessor,
|
|
165
|
+
scopeModule,
|
|
166
|
+
needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : []
|
|
167
|
+
));
|
|
117
168
|
return {
|
|
118
169
|
code: ms.toString(),
|
|
119
170
|
map: ms.generateMap({ source: id, includeContent: true, hires: true }),
|
package/dist/build/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/build/plugin-core.ts","../../src/build/scope-rewrite.ts","../../src/build/assets.ts","../../src/build/vite.ts"],"sourcesContent":["/**\n * Rollup/Vite-compatible plugin core (zero hard dependency on either bundler).\n *\n * Responsibilities:\n * 1. Rewrite free browser globals inside third-party modules to scoped access.\n * 2. Handle `three/webgpu` (WebGPU is unavailable in WeChat mini games).\n * 3. Collect worker/wasm assets referenced by addons and emit them + a manifest.\n * 4. Produce a machine-readable build report for CI and AI-assisted iteration.\n */\nimport { promises as fs } from 'node:fs';\nimport {\n DEFAULT_FORCE_UNDEF,\n rewriteGlobals,\n type RewriteOptions,\n} from './scope-rewrite';\nimport {\n collectAssetReferences,\n collectAssets,\n type AssetManifest,\n type AssetOptions,\n} from './assets';\n\nexport interface MiniThreePluginOptions extends AssetOptions {\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\n include?: (id: string) => boolean;\n /** Modules to skip even when they match. */\n exclude?: (id: string) => boolean;\n /** Also transform application code (off by default). */\n includeUserCode?: boolean;\n /** Rewrite options (advanced). */\n rewrite?: RewriteOptions;\n /** How to handle `three/webgpu` imports. Default 'warn'. */\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\n /** Print a build report summary. Default true. */\n report?: boolean;\n /** Verbose per-module logs. */\n debug?: boolean;\n}\n\nexport interface BuildReport {\n modulesScanned: number;\n modulesRewritten: number;\n rewrites: number;\n globalsSeen: string[];\n assetReferences: string[];\n missingAssets: string[];\n webgpuWarnings: string[];\n parseFailures: string[];\n}\n\nexport interface PluginContext {\n warn(message: string): void;\n error(message: string): never;\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\n}\n\nexport interface MiniThreePlugin {\n name: string;\n enforce: 'pre';\n transform(this: PluginContext, code: string, id: string): { code: string; map: unknown } | null;\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\n api: {\n report(): BuildReport;\n };\n}\n\nconst DEFAULT_INCLUDE = (id: string): boolean => {\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\n return (\n normalized.includes('/node_modules/three/') ||\n normalized.includes('/node_modules/three-stdlib/') ||\n normalized.includes('/node_modules/@react-three/') ||\n normalized.includes('/node_modules/@tresjs/') ||\n normalized.includes('/node_modules/.vite/deps/three') ||\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\n );\n};\n\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n const include = options.include ?? DEFAULT_INCLUDE;\n const exclude = options.exclude ?? (() => false);\n const webgpuMode = options.webgpu ?? 'warn';\n const report: BuildReport = {\n modulesScanned: 0,\n modulesRewritten: 0,\n rewrites: 0,\n globalsSeen: [],\n assetReferences: [],\n missingAssets: [],\n webgpuWarnings: [],\n parseFailures: [],\n };\n const seenGlobals = new Set<string>();\n const assetRefs = new Set<string>();\n let manifest: AssetManifest | null = null;\n let filesToEmit = new Map<string, string>();\n\n const note = (ctx: PluginContext, message: string): void => {\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\n };\n\n return {\n name: 'mini-three-adapter',\n enforce: 'pre',\n\n transform(this: PluginContext, code: string, id: string) {\n const normalized = id.replace(/\\\\/g, '/');\n const shouldTransform = options.includeUserCode\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\n : include(normalized) && !exclude(normalized);\n if (!shouldTransform) return null;\n\n report.modulesScanned++;\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\n\n let currentCode = code;\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\n report.webgpuWarnings.push(message);\n if (webgpuMode === 'error') this.error(message);\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\n if (webgpuMode === 'rewrite') {\n currentCode = currentCode\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\n }\n }\n\n const result = rewriteGlobals(currentCode, normalized, {\n ...options.rewrite,\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\n });\n if (result && 'error' in result) {\n report.parseFailures.push(result.error);\n this.warn(`[mini-three] ${result.error}`);\n return null;\n }\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\n\n report.modulesRewritten++;\n report.rewrites += result.count;\n for (const name of result.seen) seenGlobals.add(name);\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\n return { code: result.code, map: result.map };\n },\n\n async generateBundle(this: PluginContext, bundleOptions) {\n const refs = Array.from(assetRefs);\n report.assetReferences = refs;\n report.globalsSeen = Array.from(seenGlobals).sort();\n\n if (refs.length > 0) {\n const collected = await collectAssets(refs, {\n cwd: options.cwd,\n roots: options.roots,\n outputDir: options.outputDir,\n brotli: options.brotli,\n manifest: options.manifest,\n });\n manifest = collected.manifest;\n filesToEmit = collected.files;\n report.missingAssets = collected.missing;\n for (const missing of collected.missing) {\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\n }\n for (const [destination, source] of filesToEmit) {\n try {\n const content = await fs.readFile(source);\n this.emitFile({ type: 'asset', fileName: destination, source: content });\n } catch (error) {\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\n }\n }\n } else {\n manifest = {\n generatedBy: 'mini-three-adapter',\n outputDir: options.outputDir ?? 'assets/three',\n entries: [],\n gameJsonSuggestion: {},\n decoderPaths: {},\n };\n }\n\n if (options.manifest !== false) {\n this.emitFile({\n type: 'asset',\n fileName: 'mini-three-assets.json',\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\n });\n }\n if (options.report !== false) {\n this.warn(\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\n );\n }\n },\n\n api: {\n report: () => ({\n ...report,\n globalsSeen: Array.from(seenGlobals).sort(),\n assetReferences: Array.from(assetRefs),\n webgpuWarnings: [...report.webgpuWarnings],\n parseFailures: [...report.parseFailures],\n }),\n },\n };\n}\n","/**\n * AST-based global-to-scope rewriting.\n *\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\n * `typeof window` feature detection. Here we parse with @babel/parser and use\n * Babel's scope binding information, so ONLY free (unbound) references to\n * browser globals are rewritten — application code is never touched.\n */\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport MagicString from 'magic-string';\nimport type { NodePath } from '@babel/traverse';\nimport type { Identifier } from '@babel/types';\nimport type { Node } from '@babel/types';\n\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\nconst traverse = (typeof _traverse === 'function'\n ? _traverse\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\n\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\n];\n\n/** Globals that must remain `undefined` in the mini game scope. */\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\n\nexport interface RewriteOptions {\n /** Extra global identifiers to rewrite. */\n extraGlobals?: string[];\n /** Replace the default global list instead of extending it. */\n globals?: string[];\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\n forceUndef?: string[];\n /** Name of the injected scope accessor. Default `__m3`. */\n accessor?: string;\n /** Module specifier that exports `getActiveScope`. */\n scopeModule?: string;\n}\n\nexport interface RewriteResult {\n code: string;\n map: { toString(): string } | null;\n /** Number of rewritten references. */\n count: number;\n /** Globals actually seen (useful for the build report). */\n seen: string[];\n}\n\nexport interface RewriteFailure {\n code: string;\n error: string;\n}\n\nexport const SCOPE_IMPORT = (accessor: string, module: string): string =>\n `import { getActiveScope as ${accessor} } from '${module}';\\n`;\n\nfunction isNonComputedKey(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent) return false;\n const self: unknown = path.node;\n if (parent.isObjectProperty() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isObjectMethod() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isClassProperty() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isClassMethod() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isMemberExpression() && !parent.node.computed && (parent.node.property as unknown) === self) return true;\n return false;\n}\n\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\nexport function rewriteGlobals(\n code: string,\n id: string,\n options: RewriteOptions = {},\n): RewriteResult | RewriteFailure | null {\n const names = new Set<string>([\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\n ...(options.extraGlobals ?? []),\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\n ]);\n const accessor = options.accessor ?? '__m3';\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\n\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'unambiguous',\n errorRecovery: true,\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\n });\n } catch (error) {\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\n }\n\n const ms = new MagicString(code);\n const seen = new Set<string>();\n let count = 0;\n\n traverse(ast, {\n ReferencedIdentifier(path: NodePath<Node>) {\n const node = path.node as Identifier;\n const name = node.name;\n if (!name || !names.has(name)) return;\n if (node.start == null || node.end == null) return;\n if (isNonComputedKey(path)) return;\n // Babel scope knows about imports, function params, local declarations,\n // catch bindings and block-scoped shadowing. This is the critical check\n // that a regex-based replacement cannot perform.\n if (path.scope.hasBinding(name, true)) return;\n // `typeof window` stays correct: `typeof __m3().window` === 'object'.\n seen.add(name);\n ms.overwrite(node.start, node.end, `${accessor}().${name}`);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(accessor, scopeModule));\n return {\n code: ms.toString(),\n map: ms.generateMap({ source: id, includeContent: true, hires: true }) as unknown as { toString(): string },\n count,\n seen: Array.from(seen).sort(),\n };\n}\n","/**\n * Worker / WASM asset collection for three.js addons.\n *\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\n * `.js` and `.wasm` files by string path. In a mini game those files are not\n * reachable via HTTP; they must be copied into the code package (ideally a\n * subpackage) and `setDecoderPath` must point at the copied location.\n *\n * The plugin scans transformed modules, resolves each referenced basename in a\n * small set of known directories, copies it, and emits a manifest plus a\n * `game.json` suggestion. No global state, no hidden writes.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface AssetOptions {\n /** Extra directories to search (besides three's jsm/libs). */\n roots?: string[];\n /** Output directory relative to the bundle root. Default 'assets/three'. */\n outputDir?: string;\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\n brotli?: boolean;\n /** Emit `mini-three-assets.json`. Default true. */\n manifest?: boolean;\n /** Working directory used to resolve roots. Default process.cwd(). */\n cwd?: string;\n}\n\nexport interface AssetEntry {\n /** Original string found in the module. */\n reference: string;\n /** Resolved absolute source path. */\n source: string;\n /** Relative destination inside the bundle. */\n destination: string;\n kind: 'worker' | 'wasm' | 'data';\n}\n\nexport interface AssetManifest {\n generatedBy: 'mini-three-adapter';\n outputDir: string;\n entries: AssetEntry[];\n /** Paste into game.json (adjust subpackage names to your project). */\n gameJsonSuggestion: Record<string, unknown>;\n /** Decoder paths to feed to loaders at runtime. */\n decoderPaths: Record<string, string>;\n}\n\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\nconst DECODER_KEYWORDS = [\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\n];\n\nexport function collectAssetReferences(code: string): string[] {\n const found = new Set<string>();\n let match: RegExpExecArray | null;\n ASSET_PATTERN.lastIndex = 0;\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\n const value = match[2] ?? '';\n const lower = value.toLowerCase();\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\n }\n return Array.from(found);\n}\n\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > maxDepth) return;\n let entries;\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\n catch { return; }\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) await walk(full, depth + 1);\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\n }\n };\n await walk(root, 0);\n return index;\n}\n\nfunction classify(name: string): AssetEntry['kind'] {\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\n if (name.endsWith('.js')) return 'worker';\n return 'data';\n}\n\nexport function defaultRoots(cwd: string): string[] {\n return [\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\n path.join(cwd, 'node_modules/three/examples/jsm'),\n path.join(cwd, 'node_modules/three-stdlib'),\n path.join(cwd, 'public'),\n path.join(cwd, 'static'),\n ];\n}\n\nexport interface CollectResult {\n manifest: AssetManifest;\n /** Files to write: destination (relative) -> absolute source. */\n files: Map<string, string>;\n missing: string[];\n}\n\n/** Resolve references against known roots without copying anything. */\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\n const cwd = options.cwd ?? process.cwd();\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\n const find = (name: string): string | undefined => {\n for (const index of indexes) {\n const hit = index.get(name);\n if (hit) return hit;\n }\n return undefined;\n };\n\n const entries: AssetEntry[] = [];\n const files = new Map<string, string>();\n const missing: string[] = [];\n\n for (const reference of references) {\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\n const source = find(base);\n if (!source) { missing.push(reference); continue; }\n const entry: AssetEntry = {\n reference,\n source,\n destination: `${outputDir}/${base}`,\n kind: classify(base),\n };\n entries.push(entry);\n files.set(entry.destination, source);\n if (options.brotli !== false && entry.kind === 'wasm') {\n const br = find(`${base}.br`);\n if (br) {\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\n files.set(`${outputDir}/${base}.br`, br);\n }\n }\n }\n\n const decoderPaths: Record<string, string> = {};\n for (const entry of entries) {\n const name = path.posix.basename(entry.destination).toLowerCase();\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\n }\n }\n\n const manifest: AssetManifest = {\n generatedBy: 'mini-three-adapter',\n outputDir,\n entries,\n gameJsonSuggestion: {\n workers: { path: `${outputDir}`, isSubpackage: true },\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\n },\n decoderPaths,\n };\n return { manifest, files, missing };\n}\n\n/** Copy resolved files into `outDir`. */\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\n let written = 0;\n for (const [destination, source] of files) {\n const target = path.join(outDir, destination);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n written++;\n }\n return written;\n}\n","/** Vite entry: `import miniThree from 'mini-three-adapter/vite'`. */\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\n\nexport interface ViteMiniThreePlugin extends MiniThreePlugin {\n config(): Record<string, unknown>;\n}\n\n/**\n * Vite plugin. `optimizeDeps.exclude` keeps three's ESM sources intact so the\n * AST rewrite sees the original module graph instead of a pre-bundled blob.\n */\nexport function miniThree(options: MiniThreePluginOptions = {}): ViteMiniThreePlugin {\n const core = miniThreePlugin(options);\n return {\n ...core,\n config() {\n return {\n optimizeDeps: {\n exclude: ['three', 'three-stdlib', 'three/examples/jsm'],\n },\n build: {\n commonjsOptions: { transformMixedEsModules: true },\n rollupOptions: {\n output: {\n manualChunks: undefined,\n },\n },\n },\n };\n },\n };\n}\n\nexport default mi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cAAc,uBAC9C,OAAO,gBAAgB,eAAe,OAAO,QAAQ,2BACrD,YAAY,IAAI,sBAAsB,OAAO,cAAc,MAAM;AAAA,QACxE;AAAA,MACF;AAAA,IACF;AAAA,IAEA,KAAK;AAAA,MACH,QAAQ,OAAO;AAAA,QACb,GAAG;AAAA,QACH,aAAa,MAAM,KAAK,WAAW,EAAE,KAAK;AAAA,QAC1C,iBAAiB,MAAM,KAAK,SAAS;AAAA,QACrC,gBAAgB,CAAC,GAAG,OAAO,cAAc;AAAA,QACzC,eAAe,CAAC,GAAG,OAAO,aAAa;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;;;AGxMO,SAAS,UAAU,UAAkC,CAAC,GAAwB;AACnF,QAAM,OAAO,gBAAgB,OAAO;AACpC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,SAAS;AACP,aAAO;AAAA,QACL,cAAc;AAAA,UACZ,SAAS,CAAC,SAAS,gBAAgB,oBAAoB;AAAA,QACzD;AAAA,QACA,OAAO;AAAA,UACL,iBAAiB,EAAE,yBAAyB,KAAK;AAAA,UACjD,eAAe;AAAA,YACb,QAAQ;AAAA,cACN,cAAc;AAAA,YAChB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,eAAQ;","names":["fs","path","fs"]}
|
|
1
|
+
{"version":3,"sources":["../../src/build/plugin-core.ts","../../src/build/scope-rewrite.ts","../../src/build/assets.ts","../../src/build/vite.ts"],"sourcesContent":["/**\n * Rollup/Vite-compatible plugin core (zero hard dependency on either bundler).\n *\n * Responsibilities:\n * 1. Rewrite free browser globals inside third-party modules to scoped access.\n * 2. Handle `three/webgpu` (WebGPU is unavailable in WeChat mini games).\n * 3. Collect worker/wasm assets referenced by addons and emit them + a manifest.\n * 4. Produce a machine-readable build report for CI and AI-assisted iteration.\n */\nimport { promises as fs } from 'node:fs';\nimport {\n DEFAULT_FORCE_UNDEF,\n rewriteGlobals,\n type RewriteOptions,\n} from './scope-rewrite';\nimport {\n collectAssetReferences,\n collectAssets,\n type AssetManifest,\n type AssetOptions,\n} from './assets';\n\nexport interface MiniThreePluginOptions extends AssetOptions {\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\n include?: (id: string) => boolean;\n /** Modules to skip even when they match. */\n exclude?: (id: string) => boolean;\n /** Also transform application code (off by default). */\n includeUserCode?: boolean;\n /** Rewrite options (advanced). */\n rewrite?: RewriteOptions;\n /** How to handle `three/webgpu` imports. Default 'warn'. */\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\n /** Print a build report summary. Default true. */\n report?: boolean;\n /** Verbose per-module logs. */\n debug?: boolean;\n}\n\nexport interface BuildReport {\n modulesScanned: number;\n modulesRewritten: number;\n rewrites: number;\n globalsSeen: string[];\n assetReferences: string[];\n missingAssets: string[];\n webgpuWarnings: string[];\n parseFailures: string[];\n}\n\nexport interface PluginContext {\n warn(message: string): void;\n error(message: string): never;\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\n}\n\nexport interface MiniThreePlugin {\n name: string;\n enforce: 'pre';\n transform(this: PluginContext, code: string, id: string): { code: string; map: unknown } | null;\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\n api: {\n report(): BuildReport;\n };\n}\n\nconst DEFAULT_INCLUDE = (id: string): boolean => {\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\n return (\n normalized.includes('/node_modules/three/') ||\n normalized.includes('/node_modules/three-stdlib/') ||\n normalized.includes('/node_modules/@react-three/') ||\n normalized.includes('/node_modules/@tresjs/') ||\n normalized.includes('/node_modules/.vite/deps/three') ||\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\n );\n};\n\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n const include = options.include ?? DEFAULT_INCLUDE;\n const exclude = options.exclude ?? (() => false);\n const webgpuMode = options.webgpu ?? 'warn';\n const report: BuildReport = {\n modulesScanned: 0,\n modulesRewritten: 0,\n rewrites: 0,\n globalsSeen: [],\n assetReferences: [],\n missingAssets: [],\n webgpuWarnings: [],\n parseFailures: [],\n };\n const seenGlobals = new Set<string>();\n const assetRefs = new Set<string>();\n let manifest: AssetManifest | null = null;\n let filesToEmit = new Map<string, string>();\n\n const note = (ctx: PluginContext, message: string): void => {\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\n };\n\n return {\n name: 'mini-three-adapter',\n enforce: 'pre',\n\n transform(this: PluginContext, code: string, id: string) {\n const normalized = id.replace(/\\\\/g, '/');\n const shouldTransform = options.includeUserCode\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\n : include(normalized) && !exclude(normalized);\n if (!shouldTransform) return null;\n\n report.modulesScanned++;\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\n\n let currentCode = code;\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\n report.webgpuWarnings.push(message);\n if (webgpuMode === 'error') this.error(message);\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\n if (webgpuMode === 'rewrite') {\n currentCode = currentCode\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\n }\n }\n\n const result = rewriteGlobals(currentCode, normalized, {\n ...options.rewrite,\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\n });\n if (result && 'error' in result) {\n report.parseFailures.push(result.error);\n this.warn(`[mini-three] ${result.error}`);\n return null;\n }\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\n\n report.modulesRewritten++;\n report.rewrites += result.count;\n for (const name of result.seen) seenGlobals.add(name);\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\n return { code: result.code, map: result.map };\n },\n\n async generateBundle(this: PluginContext, bundleOptions) {\n const refs = Array.from(assetRefs);\n report.assetReferences = refs;\n report.globalsSeen = Array.from(seenGlobals).sort();\n\n if (refs.length > 0) {\n const collected = await collectAssets(refs, {\n cwd: options.cwd,\n roots: options.roots,\n outputDir: options.outputDir,\n brotli: options.brotli,\n manifest: options.manifest,\n });\n manifest = collected.manifest;\n filesToEmit = collected.files;\n report.missingAssets = collected.missing;\n for (const missing of collected.missing) {\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\n }\n for (const [destination, source] of filesToEmit) {\n try {\n const content = await fs.readFile(source);\n this.emitFile({ type: 'asset', fileName: destination, source: content });\n } catch (error) {\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\n }\n }\n } else {\n manifest = {\n generatedBy: 'mini-three-adapter',\n outputDir: options.outputDir ?? 'assets/three',\n entries: [],\n gameJsonSuggestion: {},\n decoderPaths: {},\n };\n }\n\n if (options.manifest !== false) {\n this.emitFile({\n type: 'asset',\n fileName: 'mini-three-assets.json',\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\n });\n }\n if (options.report !== false) {\n this.warn(\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\n );\n }\n },\n\n api: {\n report: () => ({\n ...report,\n globalsSeen: Array.from(seenGlobals).sort(),\n assetReferences: Array.from(assetRefs),\n webgpuWarnings: [...report.webgpuWarnings],\n parseFailures: [...report.parseFailures],\n }),\n },\n };\n}\n","/**\n * AST-based global-to-scope rewriting.\n *\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\n * `typeof window` feature detection. Here we parse with @babel/parser and use\n * Babel's scope binding information, so ONLY free (unbound) references to\n * browser globals are rewritten — application code is never touched.\n */\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport MagicString from 'magic-string';\nimport type { NodePath } from '@babel/traverse';\nimport type { Identifier } from '@babel/types';\nimport type { Node } from '@babel/types';\n\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\nconst traverse = (typeof _traverse === 'function'\n ? _traverse\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\n\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\n];\n\n/** Globals that must remain `undefined` in the mini game scope. */\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\n\nexport interface RewriteOptions {\n /** Extra global identifiers to rewrite. */\n extraGlobals?: string[];\n /** Replace the default global list instead of extending it. */\n globals?: string[];\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\n forceUndef?: string[];\n /** Name of the injected scope accessor. Default `__m3`. */\n accessor?: string;\n /** Module specifier that exports `getActiveScope`. */\n scopeModule?: string;\n}\n\nexport interface RewriteResult {\n code: string;\n map: { toString(): string } | null;\n /** Number of rewritten references. */\n count: number;\n /** Globals actually seen (useful for the build report). */\n seen: string[];\n}\n\nexport interface RewriteFailure {\n code: string;\n error: string;\n}\n\nexport const SCOPE_IMPORT = (\n accessor: string,\n module: string,\n extraSpecifiers: readonly string[] = [],\n): string => {\n const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(', ');\n return `import { ${specifiers} } from '${module}';\\n`;\n};\n\n/**\n * Reference or range equality. `@babel/parser` emits TWO distinct `Identifier`\n * nodes with identical `[start, end]` for a shorthand property (`{ X }`: one for\n * `key`, one for `value`), so reference equality alone is not enough to tell\n * \"this identifier is an object key\".\n */\nfunction sameNode(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const x = a as { start?: number | null; end?: number | null } | null | undefined;\n const y = b as { start?: number | null; end?: number | null } | null | undefined;\n return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);\n}\n\nfunction isNonComputedKey(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent) return false;\n const self: unknown = path.node;\n if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;\n return false;\n}\n\n/**\n * `{ X }`: the value node shares its range with the key, so it cannot be\n * rewritten in place — it must be expanded to `{ X: <expr> }`.\n */\nfunction isShorthandValue(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent?.isObjectProperty()) return false;\n if (!parent.node.shorthand || parent.node.computed) return false;\n if (parent.node.value !== path.node) return false;\n // `const { X } = obj` destructures a binding, never a global reference. Babel\n // already treats it as a binding, this guard keeps the two paths disjoint.\n return !parent.parentPath?.isObjectPattern();\n}\n\n/**\n * Is this identifier the left-most link of a `new X` / `new X.Y.Z` callee chain?\n *\n * `new f().g()` parses as `(new f()).g()`, so rewriting `X` to a *call*\n * (`__m3().X`) without parentheses silently turns `new X()` into\n * `(new __m3()).X()` — the scope object gets constructed and the class is then\n * invoked as a plain function. Wrapping only the chain root is enough:\n * `new (a().b).c` parses as `new ((a().b).c)`.\n */\nfunction isNewCalleeRoot(path: NodePath): boolean {\n let cur: NodePath = path;\n let parent = cur.parentPath;\n while (parent?.isMemberExpression() && parent.node.object === cur.node) {\n cur = parent;\n parent = parent.parentPath;\n }\n return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);\n}\n\n/** `typeof X` must never throw: `typeof a.b` is legal even when `a` is unbound. */\nfunction isDirectTypeofOperand(path: NodePath): boolean {\n const parent = path.parentPath;\n return Boolean(\n parent?.isUnaryExpression() &&\n parent.node.operator === 'typeof' &&\n parent.node.argument === path.node,\n );\n}\n\n/**\n * Globals that `getActiveScope()` resolves to itself even before a runtime\n * exists, so `typeof window` is already `'object'` and needs no guard.\n */\nconst ALWAYS_OBJECT_GLOBALS: ReadonlySet<string> = new Set(['window', 'self', 'globalThis']);\n\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\nexport function rewriteGlobals(\n code: string,\n id: string,\n options: RewriteOptions = {},\n): RewriteResult | RewriteFailure | null {\n const names = new Set<string>([\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\n ...(options.extraGlobals ?? []),\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\n ]);\n const accessor = options.accessor ?? '__m3';\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\n\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'unambiguous',\n errorRecovery: true,\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\n });\n } catch (error) {\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\n }\n\n const ms = new MagicString(code);\n const seen = new Set<string>();\n const hasAccessor = `${accessor}Has`;\n let count = 0;\n let needsHasGuard = false;\n\n traverse(ast, {\n ReferencedIdentifier(path: NodePath<Node>) {\n const node = path.node as Identifier;\n const name = node.name;\n if (!name || !names.has(name)) return;\n if (node.start == null || node.end == null) return;\n // Babel scope knows about imports, function params, local declarations,\n // catch bindings and block-scoped shadowing. This is the critical check\n // that a regex-based replacement cannot perform.\n if (path.scope.hasBinding(name, true)) return;\n\n const ref = `${accessor}().${name}`;\n\n // 1) Shorthand must be handled before the key check: once `isNonComputedKey`\n // compares ranges, `{ X }`'s value looks like a key too and would be\n // silently skipped (leaving an undefined global behind).\n if (isShorthandValue(path)) {\n seen.add(name);\n ms.overwrite(node.start, node.end, `${name}: (${ref})`);\n count++;\n return;\n }\n\n // 2) Object keys / member property names are not references.\n if (isNonComputedKey(path)) return;\n\n seen.add(name);\n if (isDirectTypeofOperand(path) && !ALWAYS_OBJECT_GLOBALS.has(name)) {\n // `typeof X` must never throw, but an uninitialized scope throws for\n // everything except window/self/globalThis. Guard it so feature\n // detection at module top level sees 'undefined' instead of exploding.\n ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);\n needsHasGuard = true;\n count++;\n return;\n }\n ms.overwrite(node.start, node.end, isNewCalleeRoot(path) ? `(${ref})` : ref);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(\n accessor,\n scopeModule,\n needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : [],\n ));\n return {\n code: ms.toString(),\n map: ms.generateMap({ source: id, includeContent: true, hires: true }) as unknown as { toString(): string },\n count,\n seen: Array.from(seen).sort(),\n };\n}\n","/**\n * Worker / WASM asset collection for three.js addons.\n *\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\n * `.js` and `.wasm` files by string path. In a mini game those files are not\n * reachable via HTTP; they must be copied into the code package (ideally a\n * subpackage) and `setDecoderPath` must point at the copied location.\n *\n * The plugin scans transformed modules, resolves each referenced basename in a\n * small set of known directories, copies it, and emits a manifest plus a\n * `game.json` suggestion. No global state, no hidden writes.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface AssetOptions {\n /** Extra directories to search (besides three's jsm/libs). */\n roots?: string[];\n /** Output directory relative to the bundle root. Default 'assets/three'. */\n outputDir?: string;\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\n brotli?: boolean;\n /** Emit `mini-three-assets.json`. Default true. */\n manifest?: boolean;\n /** Working directory used to resolve roots. Default process.cwd(). */\n cwd?: string;\n}\n\nexport interface AssetEntry {\n /** Original string found in the module. */\n reference: string;\n /** Resolved absolute source path. */\n source: string;\n /** Relative destination inside the bundle. */\n destination: string;\n kind: 'worker' | 'wasm' | 'data';\n}\n\nexport interface AssetManifest {\n generatedBy: 'mini-three-adapter';\n outputDir: string;\n entries: AssetEntry[];\n /** Paste into game.json (adjust subpackage names to your project). */\n gameJsonSuggestion: Record<string, unknown>;\n /** Decoder paths to feed to loaders at runtime. */\n decoderPaths: Record<string, string>;\n}\n\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\nconst DECODER_KEYWORDS = [\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\n];\n\nexport function collectAssetReferences(code: string): string[] {\n const found = new Set<string>();\n let match: RegExpExecArray | null;\n ASSET_PATTERN.lastIndex = 0;\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\n const value = match[2] ?? '';\n const lower = value.toLowerCase();\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\n }\n return Array.from(found);\n}\n\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > maxDepth) return;\n let entries;\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\n catch { return; }\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) await walk(full, depth + 1);\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\n }\n };\n await walk(root, 0);\n return index;\n}\n\nfunction classify(name: string): AssetEntry['kind'] {\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\n if (name.endsWith('.js')) return 'worker';\n return 'data';\n}\n\nexport function defaultRoots(cwd: string): string[] {\n return [\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\n path.join(cwd, 'node_modules/three/examples/jsm'),\n path.join(cwd, 'node_modules/three-stdlib'),\n path.join(cwd, 'public'),\n path.join(cwd, 'static'),\n ];\n}\n\nexport interface CollectResult {\n manifest: AssetManifest;\n /** Files to write: destination (relative) -> absolute source. */\n files: Map<string, string>;\n missing: string[];\n}\n\n/** Resolve references against known roots without copying anything. */\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\n const cwd = options.cwd ?? process.cwd();\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\n const find = (name: string): string | undefined => {\n for (const index of indexes) {\n const hit = index.get(name);\n if (hit) return hit;\n }\n return undefined;\n };\n\n const entries: AssetEntry[] = [];\n const files = new Map<string, string>();\n const missing: string[] = [];\n\n for (const reference of references) {\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\n const source = find(base);\n if (!source) { missing.push(reference); continue; }\n const entry: AssetEntry = {\n reference,\n source,\n destination: `${outputDir}/${base}`,\n kind: classify(base),\n };\n entries.push(entry);\n files.set(entry.destination, source);\n if (options.brotli !== false && entry.kind === 'wasm') {\n const br = find(`${base}.br`);\n if (br) {\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\n files.set(`${outputDir}/${base}.br`, br);\n }\n }\n }\n\n const decoderPaths: Record<string, string> = {};\n for (const entry of entries) {\n const name = path.posix.basename(entry.destination).toLowerCase();\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\n }\n }\n\n const manifest: AssetManifest = {\n generatedBy: 'mini-three-adapter',\n outputDir,\n entries,\n gameJsonSuggestion: {\n workers: { path: `${outputDir}`, isSubpackage: true },\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\n },\n decoderPaths,\n };\n return { manifest, files, missing };\n}\n\n/** Copy resolved files into `outDir`. */\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\n let written = 0;\n for (const [destination, source] of files) {\n const target = path.join(outDir, destination);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n written++;\n }\n return written;\n}\n","/** Vite entry: `import miniThree from 'mini-three-adapter/vite'`. */\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\n\nexport interface ViteMiniThreePlugin extends MiniThreePlugin {\n config(): Record<string, unknown>;\n}\n\n/**\n * Vite plugin. `optimizeDeps.exclude` keeps three's ESM sources intact so the\n * AST rewrite sees the original module graph instead of a pre-bundled blob.\n */\nexport function miniThree(options: MiniThreePluginOptions = {}): ViteMiniThreePlugin {\n const core = miniThreePlugin(options);\n return {\n ...core,\n config() {\n return {\n optimizeDeps: {\n exclude: ['three', 'three-stdlib', 'three/examples/jsm'],\n },\n build: {\n commonjsOptions: { transformMixedEsModules: true },\n rollupOptions: {\n output: {\n manualChunks: undefined,\n },\n },\n },\n };\n },\n };\n}\n\nexport default miniThree;\nexport { miniThreePlugin } from './plugin-core';\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\n"],"mappings":";AASA,SAAS,YAAYA,WAAU;;;ACA/B,SAAS,aAAa;AACtB,OAAO,eAAe;AACtB,OAAO,iBAAiB;AAMxB,IAAM,WAAY,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AAK,UAAU,EAAE,GAAG,UAAU,OAAO,QAAQ,QAAQ,cAAc,OAAO,cAAc,QAAQ,GAAG,GAAG,MAAM,CAAC;AAAA,QACvH,CAAC;AAAA,MACH;AACA,UAAI,QAAQ,WAAW,OAAO;AAC5B,aAAK;AAAA,UACH,8BAA8B,OAAO,cAAc,uBAC9C,OAAO,gBAAgB,eAAe,OAAO,QAAQ,2BACrD,YAAY,IAAI,sBAAsB,OAAO,cAAc,MAAM;AAAA,QACxE;AAAA,MACF;AAAA,IACF;AAAA,IAEA,KAAK;AAAA,MACH,QAAQ,OAAO;AAAA,QACb,GAAG;AAAA,QACH,aAAa,MAAM,KAAK,WAAW,EAAE,KAAK;AAAA,QAC1C,iBAAiB,MAAM,KAAK,SAAS;AAAA,QACrC,gBAAgB,CAAC,GAAG,OAAO,cAAc;AAAA,QACzC,eAAe,CAAC,GAAG,OAAO,aAAa;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;;;AGxMO,SAAS,UAAU,UAAkC,CAAC,GAAwB;AACnF,QAAM,OAAO,gBAAgB,OAAO;AACpC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,SAAS;AACP,aAAO;AAAA,QACL,cAAc;AAAA,UACZ,SAAS,CAAC,SAAS,gBAAgB,oBAAoB;AAAA,QACzD;AAAA,QACA,OAAO;AAAA,UACL,iBAAiB,EAAE,yBAAyB,KAAK;AAAA,UACjD,eAAe;AAAA,YACb,QAAQ;AAAA,cACN,cAAc;AAAA,YAChB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,eAAQ;","names":["fs","path","fs"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createImageFactory } from './chunk-
|
|
1
|
+
import { createImageFactory } from './chunk-MWGTYPGA.js';
|
|
2
2
|
|
|
3
3
|
// src/platforms/wechat-common.ts
|
|
4
4
|
function createWechatImageFactory(wx, diagnostics) {
|
|
@@ -53,19 +53,32 @@ function watchWxVisibility(wx, handler) {
|
|
|
53
53
|
(_b2 = wx.offHide) == null ? void 0 : _b2.call(wx, onHide);
|
|
54
54
|
};
|
|
55
55
|
}
|
|
56
|
-
function
|
|
56
|
+
function probeRawContext(raw, type) {
|
|
57
57
|
var _a, _b;
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
58
|
+
const ctx = raw.getContext(type);
|
|
59
|
+
if (!ctx) return false;
|
|
60
|
+
const lose = ctx.getExtension;
|
|
61
|
+
(_b = (_a = lose == null ? void 0 : lose.call(ctx, "WEBGL_lose_context")) == null ? void 0 : _a.loseContext) == null ? void 0 : _b.call(_a);
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
function probeContext(wx, type, options = {}) {
|
|
65
|
+
let offscreen;
|
|
66
|
+
if (typeof wx.createOffscreenCanvas === "function") {
|
|
67
|
+
try {
|
|
68
|
+
offscreen = probeRawContext(wx.createOffscreenCanvas({ width: 1, height: 1, type }), type);
|
|
69
|
+
} catch {
|
|
70
|
+
offscreen = void 0;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (offscreen === true) return true;
|
|
74
|
+
if (options.allowCanvasFallback && typeof wx.createCanvas === "function") {
|
|
75
|
+
try {
|
|
76
|
+
return probeRawContext(wx.createCanvas(), type);
|
|
77
|
+
} catch {
|
|
78
|
+
return void 0;
|
|
79
|
+
}
|
|
68
80
|
}
|
|
81
|
+
return offscreen;
|
|
69
82
|
}
|
|
70
83
|
function createOffscreenCanvasRaw(wx, width, height, type, diagnostics) {
|
|
71
84
|
if (typeof wx.createOffscreenCanvas === "function") {
|
|
@@ -128,5 +141,5 @@ function resolveWx(injected) {
|
|
|
128
141
|
}
|
|
129
142
|
|
|
130
143
|
export { createNow, createOffscreenCanvasRaw, createRafPair, createWechatImageFactory, probeContext, rectFromSelectorResult, rectFromWindowInfo, resolveWx, watchWxTouch, watchWxVisibility };
|
|
131
|
-
//# sourceMappingURL=chunk-
|
|
132
|
-
//# sourceMappingURL=chunk-
|
|
144
|
+
//# sourceMappingURL=chunk-CQPWOYLA.js.map
|
|
145
|
+
//# sourceMappingURL=chunk-CQPWOYLA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/platforms/wechat-common.ts","../src/platforms/wx-types.ts"],"names":["_a","_b","raw"],"mappings":";;;AAMO,SAAS,wBAAA,CAAyB,IAAY,WAAA,EAAyC;AAC5F,EAAA,OAAO,kBAAA,CAAmB,IAAI,WAAW,CAAA;AAC3C;AAGO,SAAS,aAAA,CACd,IACA,MAAA,EAC2E;AAd7E,EAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA;AAeE,EAAA,MAAM,IAAA,GAAO,UAAA;AAIb,EAAA,MAAM,SAAA,GAAA,CAAY,EAAA,GAAA,MAAA,IAAA,IAAA,GAAA,MAAA,GAAA,MAAA,CAAQ,qBAAA,KAAR,IAAA,GAAA,MAAA,GAAA,EAAA,CAA+B,IAAA,CAAK,MAAA,CAAA;AACtD,EAAA,MAAM,SAAA,GAAA,CAAY,EAAA,GAAA,MAAA,IAAA,IAAA,GAAA,MAAA,GAAA,MAAA,CAAQ,oBAAA,KAAR,IAAA,GAAA,MAAA,GAAA,EAAA,CAA8B,IAAA,CAAK,MAAA,CAAA;AACrD,EAAA,MAAM,WAAU,EAAA,GAAA,SAAA,IAAA,IAAA,GAAA,SAAA,GAAA,CAAa,EAAA,GAAA,IAAA,CAAK,qBAAA,KAAL,IAAA,GAAA,MAAA,GAAA,EAAA,CAA4B,KAAK,IAAA,CAAA,KAA9C,IAAA,GAAA,EAAA,IACb,CAAC,EAAA,KAA+B,WAAW,MAAM,EAAA,CAAG,KAAK,GAAA,EAAK,GAAG,EAAE,CAAA,CAAA;AACtE,EAAA,MAAM,MAAA,GAAA,CAAS,E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AA,GACjC;AACF;;;ACvCO,SAAS,UAAU,QAAA,EAA2B;AACnD,EAAA,IAAI,UAAU,OAAO,QAAA;AACrB,EAAA,MAAM,IAAA,GAAO,UAAA;AACb,EAAA,MAAM,KAAK,IAAA,CAAK,EAAA;AAChB,EAAA,IAAI,CAAC,EAAA,EAAI;AACP,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,OAAO,EAAA;AACT","file":"chunk-CQPWOYLA.js","sourcesContent":["/** Shared WeChat plumbing used by both mini game and mini program bindings. */\nimport type { ContextType, Disposer, Rect, TouchLikeEvent } from '../types';\nimport type { WxCanvas, WxLike, WxTouchEvent } from './wx-types';\nimport { createImageFactory, type ImageFactory } from '../core/image';\nimport type { Diagnostics } from '../core/diagnostics';\n\nexport function createWechatImageFactory(wx: WxLike, diagnostics?: Diagnostics): ImageFactory {\n return createImageFactory(wx, diagnostics);\n}\n\n/** rAF comes from the global in mini games, from the canvas node in mini programs. */\nexport function createRafPair(\n wx: WxLike,\n canvas?: WxCanvas,\n): { request(cb: (time: number) => void): number; cancel(id: number): void } {\n const host = globalThis as unknown as {\n requestAnimationFrame?: (cb: (time: number) => void) => number;\n cancelAnimationFrame?: (id: number) => void;\n };\n const canvasRaf = canvas?.requestAnimationFrame?.bind(canvas);\n const canvasCaf = canvas?.cancelAnimationFrame?.bind(canvas);\n const request = canvasRaf ?? host.requestAnimationFrame?.bind(host) ??\n ((cb: (time: number) => void) => setTimeout(() => cb(Date.now()), 16) as unknown as number);\n const cancel = canvasCaf ?? host.cancelAnimationFrame?.bind(host) ??\n ((id: number) => clearTimeout(id as unknown as ReturnType<typeof setTimeout>));\n void wx;\n return { request, cancel };\n}\n\nexport function createNow(wx: WxLike): () => number {\n const perf = wx.getPerformance?.();\n if (perf && typeof perf.now === 'function') return () => perf.now();\n const host = globalThis as unknown as { performance?: { now(): number } };\n const hostPerf = host.performance;\n if (hostPerf && typeof hostPerf.now === 'function') return () => hostPerf.now();\n const start = Date.now();\n return () => Date.now() - start;\n}\n\n/** Subscribe to mini game touch events. Mini programs use WXML bindings instead. */\nexport function watchWxTouch(wx: WxLike, handler: (event: TouchLikeEvent) => void): Disposer {\n const methods = ['onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'] as const;\n const offs = ['offTouchStart', 'offTouchMove', 'offTouchEnd', 'offTouchCancel'] as const;\n const attached: Array<[string, (event: WxTouchEvent) => void]> = [];\n methods.forEach((name, index) => {\n const attach = wx[name];\n if (typeof attach !== 'function') return;\n const listener = (event: WxTouchEvent): void => handler(event as TouchLikeEvent);\n attach.call(wx, listener);\n attached.push([offs[index] as string, listener]);\n });\n return () => {\n for (const [off, listener] of attached) {\n const fn = (wx as Record<string, unknown>)[off];\n if (typeof fn === 'function') (fn as (l: unknown) => void).call(wx, listener);\n }\n };\n}\n\nexport function watchWxVisibility(wx: WxLike, handler: (visible: boolean) => void): Disposer {\n const onShow = (): void => handler(true);\n const onHide = (): void => handler(false);\n wx.onShow?.(onShow);\n wx.onHide?.(onHide);\n return () => {\n wx.offShow?.(onShow);\n wx.offHide?.(onHide);\n };\n}\n\nexport interface ProbeContextOptions {\n /**\n * Allow falling back to a *second* `wx.createCanvas()` when the offscreen\n * probe cannot answer. This is only safe AFTER the on-screen canvas has been\n * taken, because WeChat then guarantees every later `createCanvas()` returns\n * an off-screen canvas. Callers must opt in explicitly (see ADR-0007).\n */\n allowCanvasFallback?: boolean;\n}\n\n/** Try one canvas; returns `false` when the context is simply unavailable. */\nfunction probeRawContext(raw: WxCanvas, type: ContextType): boolean {\n const ctx = raw.getContext(type);\n if (!ctx) return false;\n // Release GPU resources as soon as possible on constrained devices.\n const lose = (ctx as { getExtension?: (name: string) => { loseContext?: () => void } | null }).getExtension;\n lose?.call(ctx, 'WEBGL_lose_context')?.loseContext?.();\n return true;\n}\n\n/**\n * WebGL2 / WebGL1 capability probe.\n *\n * The offscreen canvas is preferred because it has no side effects on the\n * on-screen canvas. But offscreen support is NOT the same capability as\n * on-screen support: a base library can render WebGL2 on the screen canvas while\n * `createOffscreenCanvas` is missing or cannot create a WebGL2 context. So when\n * the offscreen answer is missing or negative and the caller allows it, we ask\n * the real canvas type as well.\n *\n * Returns `undefined` when the host cannot answer — callers must treat that as\n * \"unknown\", never as \"unsupported\".\n */\nexport function probeContext(\n wx: WxLike,\n type: ContextType,\n options: ProbeContextOptions = {},\n): boolean | undefined {\n let offscreen: boolean | undefined;\n if (typeof wx.createOffscreenCanvas === 'function') {\n try {\n offscreen = probeRawContext(wx.createOffscreenCanvas({ width: 1, height: 1, type }), type);\n } catch {\n // Some base libraries expose the API but throw for webgl2; keep probing.\n offscreen = undefined;\n }\n }\n if (offscreen === true) return true;\n if (options.allowCanvasFallback && typeof wx.createCanvas === 'function') {\n try {\n return probeRawContext(wx.createCanvas(), type);\n } catch {\n return undefined;\n }\n }\n return offscreen;\n}\n\nexport function createOffscreenCanvasRaw(\n wx: WxLike,\n width: number,\n height: number,\n type: ContextType,\n diagnostics?: Diagnostics,\n): WxCanvas {\n if (typeof wx.createOffscreenCanvas === 'function') {\n try {\n const raw = wx.createOffscreenCanvas({ width, height, type });\n raw.width = width;\n raw.height = height;\n return raw;\n } catch (error) {\n diagnostics?.warn(`createOffscreenCanvas(${type}) failed, falling back to 2d`, error);\n }\n }\n // Last resort for old base libraries: createCanvas() after the first call is\n // guaranteed to be off-screen, but it still counts against the canvas budget.\n if (typeof wx.createCanvas !== 'function') {\n throw new Error('[mini-three-adapter] no canvas creation API available');\n }\n const raw = wx.createCanvas();\n raw.width = width;\n raw.height = height;\n return raw;\n}\n\nexport function rectFromWindowInfo(wx: WxLike): Rect {\n const info = wx.getWindowInfo?.() ?? wx.getSystemInfoSync?.() ??\n { windowWidth: 0, windowHeight: 0, pixelRatio: 1 };\n return {\n left: 0,\n top: 0,\n width: info.windowWidth,\n height: info.windowHeight,\n right: info.windowWidth,\n bottom: info.windowHeight,\n };\n}\n\nexport function rectFromSelectorResult(result: {\n width?: number; height?: number; top?: number; left?: number; right?: number; bottom?: number;\n}): Rect {\n const width = result.width ?? 0;\n const height = result.height ?? 0;\n const left = result.left ?? 0;\n const top = result.top ?? 0;\n return {\n width, height, left, top,\n right: result.right ?? left + width,\n bottom: result.bottom ?? top + height,\n };\n}\n","/**\n * Hand-written, minimal structural types for the WeChat runtime.\n *\n * Why not `minigame-api-typings`? Because consuming the official typings forces\n * a global `wx` declaration onto every consumer (including browser builds and\n * Node tests) and couples us to a specific version. Structural interfaces let\n * the adapter work with a real `wx`, a mock in tests, or a future platform.\n */\n\nexport interface WxCanvas {\n width: number;\n height: number;\n getContext(type: string, attributes?: Record<string, unknown>): unknown;\n toDataURL?(type?: string, quality?: number): string;\n createImage?(): WxImage;\n requestAnimationFrame?(callback: (time: number) => void): number;\n cancelAnimationFrame?(id: number): void;\n [key: string]: unknown;\n}\n\nexport interface WxImage {\n width: number;\n height: number;\n src: string;\n onload?: ((event?: unknown) => void) | null;\n onerror?: ((error?: unknown) => void) | null;\n complete?: boolean;\n [key: string]: unknown;\n}\n\nexport interface WxRect {\n top: number;\n left: number;\n width: number;\n height: number;\n right: number;\n bottom: number;\n}\n\nexport interface WxWindowInfo {\n windowWidth: number;\n windowHeight: number;\n pixelRatio: number;\n screenWidth?: number;\n screenHeight?: number;\n safeArea?: WxRect;\n}\n\nexport interface WxTouchPoint {\n identifier?: number;\n clientX?: number;\n clientY?: number;\n pageX?: number;\n pageY?: number;\n x?: number;\n y?: number;\n force?: number;\n}\n\nexport interface WxTouchEvent {\n type: string;\n touches?: ArrayLike<WxTouchPoint>;\n changedTouches?: ArrayLike<WxTouchPoint>;\n timeStamp?: number;\n}\n\nexport interface WxRequestResult {\n statusCode: number;\n data: string | ArrayBuffer | Record<string, unknown>;\n header?: Record<string, string>;\n errMsg?: string;\n}\n\nexport interface WxRequestOptions {\n url: string;\n method?: string;\n data?: unknown;\n header?: Record<string, string>;\n responseType?: 'text' | 'arraybuffer';\n timeout?: number;\n success?: (result: WxRequestResult) => void;\n fail?: (error: { errMsg?: string; [key: string]: unknown }) => void;\n}\n\nexport interface WxSelectorQueryResult {\n node?: WxCanvas;\n width?: number;\n height?: number;\n top?: number;\n left?: number;\n right?: number;\n bottom?: number;\n}\n\nexport interface WxSelectorQuery {\n select(selector: string): WxSelectorQuery;\n fields(fields: Record<string, boolean>): WxSelectorQuery;\n exec(callback: (results: (WxSelectorQueryResult | null)[]) => void): void;\n}\n\n/** The subset of `wx` the adapter touches. All members are optional so the\n * same interface can describe a mini game, a mini program or a test mock. */\nexport interface WxLike {\n createCanvas?(): WxCanvas;\n createOffscreenCanvas?(options?: {\n width?: number;\n height?: number;\n type?: '2d' | 'webgl' | 'webgl2';\n }): WxCanvas;\n createImage?(): WxImage;\n createImageData?(width: number, height: number): unknown;\n getWindowInfo?(): WxWindowInfo;\n getSystemInfoSync?(): WxWindowInfo;\n onWindowResize?(listener: (res: { windowWidth: number; windowHeight: number }) => void): void;\n offWindowResize?(listener: (res: { windowWidth: number; windowHeight: number }) => void): void;\n\n onTouchStart?(listener: (event: WxTouchEvent) => void): void;\n onTouchMove?(listener: (event: WxTouchEvent) => void): void;\n onTouchEnd?(listener: (event: WxTouchEvent) => void): void;\n onTouchCancel?(listener: (event: WxTouchEvent) => void): void;\n offTouchStart?(listener: (event: WxTouchEvent) => void): void;\n offTouchMove?(listener: (event: WxTouchEvent) => void): void;\n offTouchEnd?(listener: (event: WxTouchEvent) => void): void;\n offTouchCancel?(listener: (event: WxTouchEvent) => void): void;\n\n onShow?(listener: () => void): void;\n onHide?(listener: () => void): void;\n offShow?(listener: () => void): void;\n offHide?(listener: () => void): void;\n\n request?(options: WxRequestOptions): { abort?(): void };\n createSelectorQuery?(): WxSelectorQuery;\n getPerformance?(): { now(): number };\n setPreferredFramesPerSecond?(fps: number): void;\n triggerGC?(): void;\n createWorker?(path: string, options?: unknown): unknown;\n env?: { USER_DATA_PATH?: string; [key: string]: unknown };\n getSystemInfo?(options: { success?: (info: WxWindowInfo & { SDKVersion?: string }) => void }): void;\n [key: string]: unknown;\n}\n\n/** Resolve `wx` from an explicit injection or from the host global. */\nexport function resolveWx(injected?: WxLike): WxLike {\n if (injected) return injected;\n const host = globalThis as unknown as Record<string, unknown>;\n const wx = host.wx as WxLike | undefined;\n if (!wx) {\n throw new Error(\n '[mini-three-adapter] `wx` is not available. Pass `{ wx }` in options when running outside WeChat (e.g. in Node tests).',\n );\n }\n return wx;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { resolveWx, probeContext, createWechatImageFactory, createRafPair, createNow, rectFromSelectorResult, createOffscreenCanvasRaw, watchWxVisibility } from './chunk-
|
|
2
|
-
import { createDiagnostics, detectCapabilities, createRuntime } from './chunk-
|
|
1
|
+
import { resolveWx, probeContext, createWechatImageFactory, createRafPair, createNow, rectFromSelectorResult, createOffscreenCanvasRaw, watchWxVisibility } from './chunk-CQPWOYLA.js';
|
|
2
|
+
import { createDiagnostics, detectCapabilities, createRuntime } from './chunk-MWGTYPGA.js';
|
|
3
3
|
|
|
4
4
|
// src/platforms/wechat-miniprogram.ts
|
|
5
5
|
function queryNode(ctx, selector, delay) {
|
|
@@ -39,6 +39,10 @@ async function createWeChatMiniProgramBinding(options) {
|
|
|
39
39
|
const rawCanvas = node;
|
|
40
40
|
const capabilities = detectCapabilities(wx, "wechat-miniprogram", {
|
|
41
41
|
overrides: options.capabilities,
|
|
42
|
+
diagnostics,
|
|
43
|
+
// No createCanvas() fallback here: the canvas node comes from a selector
|
|
44
|
+
// query and probing it directly would create the real GL context with
|
|
45
|
+
// default attributes before three.js asks for its own.
|
|
42
46
|
probeContext: (type) => probeContext(wx, type)
|
|
43
47
|
});
|
|
44
48
|
const imageFactory = createWechatImageFactory(wx, diagnostics);
|
|
@@ -87,5 +91,5 @@ function createWeChatMiniProgramRuntime(options) {
|
|
|
87
91
|
}
|
|
88
92
|
|
|
89
93
|
export { createWeChatMiniProgramBinding, createWeChatMiniProgramRuntime };
|
|
90
|
-
//# sourceMappingURL=chunk-
|
|
91
|
-
//# sourceMappingURL=chunk-
|
|
94
|
+
//# sourceMappingURL=chunk-LRR4AEZM.js.map
|
|
95
|
+
//# sourceMappingURL=chunk-LRR4AEZM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/platforms/wechat-miniprogram.ts"],"names":[],"mappings":";;;;AAiCA,SAAS,SAAA,CACP,GAAA,EACA,QAAA,EACA,KAAA,EAC4D;AAC5D,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,MAAM,MAAM,MAAY;AACtB,MAAA,IAAI;AACF,QAAA,MAAM,SAAS,GAAA,CAAI,mBAAA;AACnB,QAAA,IAAI,OAAO,WAAW,UAAA,EAAY;AAChC,UAAA,MAAA,CAAO,IAAI,KAAA,CAAM,mFAAmF,CAAC,CAAA;AACrG,UAAA;AAAA,QACF;AACA,QAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA;AAC7B,QAAA,KAAA,CACG,OAAO,QAAQ,CAAA,CACf,MAAA,CAAO,EAAE,MAAM,IAAA,EAAM,EAAA,EAAI,IAAA,EAAM,IAAA,EAAM,MAAM,IAAA,EAAM,IAAA,EAAM,CAAA,CACvD,IAAA,CAAK,CAAC,OAAA,KAAY;AACjB,UAAA,MAAM,SAAS,OAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,OAAA,CAAU,CAAA,CAAA;AACzB,UAAA,IAAI,EAAC,iCAAQ,IAAA,CAAA,EAAM;AACjB,YAAA,MAAA,CAAO,IAAI,KAAA;AAAA,cACT,kCAAkC,QAAQ,CAAA,uGAAA;AAAA,aAE3C,CAAA;AACD,YAAA;AAAA,UACF;AACA,UAAA,OAAA,CAAQ,EAAE,IAAA,EAAM,MAAA,CAAO,IAAA,EAAM,QAAQ,CAAA;AAAA,QACvC,CAAC,CAAA;AAAA,MACL,SAAS,KAAA,EAAO;AACd,QAAA,M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AA;AAE/F,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,oBAAA;AAAA,IACN,EAAA;AAAA,IACA,SAAA;AAAA,IACA,YAAA;AAAA,IACA,YAAA;AAAA,IACA,aAAA;AAAA,IACA,qBAAA,EAAuB,CAAC,KAAA,EAAe,MAAA,EAAgB,IAAA,KACrD,yBAAyB,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,IAAA,EAAM,WAAW,CAAA;AAAA;AAAA;AAAA,IAG/D,UAAA,EAAY,CAAC,QAAA,KAAwD,MAAM,MAAA;AAAA,IAC3E,eAAA;AAAA,IACA,uBAAuB,GAAA,CAAI,OAAA;AAAA,IAC3B,sBAAsB,GAAA,CAAI,MAAA;AAAA,IAC1B,GAAA;AAAA,IACA,OAAA,EAAS,MAAM,WAAA,CAAY,KAAA,CAAM,qCAAqC;AAAA,GACxE;AACF;AAIO,SAAS,+BACd,OAAA,EAC2B;AAC3B,EAAA,OAAO,aAAA,CAAc,MAAM,8BAAA,CAA+B,OAAO,GAAG,OAAO,CAAA;AAC7E","file":"chunk-LRR4AEZM.js","sourcesContent":["/** WeChat Mini Program (小程序, canvas type=\"webgl2\") platform binding. */\nimport type { Capabilities, ContextType, Disposer, Rect, TouchLikeEvent } from '../types';\nimport type { PlatformBinding } from '../core/platform';\nimport { createRuntime, type MiniThreeRuntime, type RuntimeOptions } from '../core/runtime';\nimport { detectCapabilities } from '../core/capabilities';\nimport { createDiagnostics, type Diagnostics } from '../core/diagnostics';\nimport {\n createNow,\n createOffscreenCanvasRaw,\n createRafPair,\n createWechatImageFactory,\n probeContext,\n rectFromSelectorResult,\n watchWxVisibility,\n} from './wechat-common';\nimport { resolveWx, type WxCanvas, type WxLike, type WxSelectorQuery, type WxSelectorQueryResult } from './wx-types';\n\nexport interface SelectorCtx {\n createSelectorQuery(): WxSelectorQuery;\n}\n\nexport interface WeChatMiniProgramOptions {\n wx?: WxLike;\n /** CSS selector of the `<canvas type=\"webgl2\">` node. */\n selector: string;\n /** Inside a custom component, pass `this` so the query is scoped correctly. */\n selectorCtx?: SelectorCtx;\n /** Milliseconds to wait for layout before querying (uni-app needs a tick). */\n queryDelay?: number;\n capabilities?: Partial<Capabilities>;\n diagnostics?: Diagnostics;\n}\n\nfunction queryNode(\n ctx: SelectorCtx | WxLike,\n selector: string,\n delay: number,\n): Promise<{ node: WxCanvas; result: WxSelectorQueryResult }> {\n return new Promise((resolve, reject) => {\n const run = (): void => {\n try {\n const create = ctx.createSelectorQuery;\n if (typeof create !== 'function') {\n reject(new Error('[mini-three-adapter] createSelectorQuery is unavailable; pass a valid selectorCtx'));\n return;\n }\n const query = create.call(ctx);\n query\n .select(selector)\n .fields({ node: true, id: true, rect: true, size: true })\n .exec((results) => {\n const result = results?.[0];\n if (!result?.node) {\n reject(new Error(\n `[mini-three-adapter] selector \"${selector}\" returned no canvas node. ` +\n 'Ensure <canvas type=\"webgl2\" id=\"...\"> exists and the component is rendered.',\n ));\n return;\n }\n resolve({ node: result.node, result });\n });\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)));\n }\n };\n if (delay > 0) setTimeout(run, delay);\n else run();\n });\n}\n\nexport async function createWeChatMiniProgramBinding(\n options: WeChatMiniProgramOptions,\n): Promise<PlatformBinding> {\n const wx = resolveWx(options.wx);\n const diagnostics = options.diagnostics ?? createDiagnostics('warn');\n const ctx = options.selectorCtx ?? wx;\n const { node, result } = await queryNode(ctx, options.selector, options.queryDelay ?? 0);\n const rawCanvas = node;\n const capabilities = detectCapabilities(wx, 'wechat-miniprogram', {\n overrides: options.capabilities,\n diagnostics,\n // No createCanvas() fallback here: the canvas node comes from a selector\n // query and probing it directly would create the real GL context with\n // default attributes before three.js asks for its own.\n probeContext: (type) => probeContext(wx, type),\n });\n const imageFactory = createWechatImageFactory(wx, diagnostics);\n const raf = createRafPair(wx, rawCanvas);\n const now = createNow(wx);\n let lastRect = rectFromSelectorResult(result);\n\n const getCanvasRect = async (): Promise<Rect> => {\n const fresh = await queryNode(ctx, options.selector, 0);\n lastRect = rectFromSelectorResult(fresh.result);\n return lastRect;\n };\n\n const watchVisibility = (handler: (visible: boolean) => void): Disposer => {\n const host = wx as Record<string, unknown>;\n const onShow = (): void => handler(true);\n const onHide = (): void => handler(false);\n if (typeof host.onAppShow === 'function') (host.onAppShow as (l: () => void) => void).call(wx, onShow);\n if (typeof host.onAppHide === 'function') (host.onAppHide as (l: () => void) => void).call(wx, onHide);\n const fallback = watchWxVisibility(wx, handler);\n return () => {\n if (typeof host.offAppShow === 'function') (host.offAppShow as (l: () => void) => void).call(wx, onShow);\n if (typeof host.offAppHide === 'function') (host.offAppHide as (l: () => void) => void).call(wx, onHide);\n fallback();\n };\n };\n\n diagnostics.info('mini program canvas resolved', { selector: options.selector, rect: lastRect });\n\n return {\n kind: 'wechat-miniprogram',\n wx,\n rawCanvas,\n capabilities,\n imageFactory,\n getCanvasRect,\n createOffscreenCanvas: (width: number, height: number, type: ContextType) =>\n createOffscreenCanvasRaw(wx, width, height, type, diagnostics),\n // Mini programs deliver touch events through WXML bindings, not wx.onTouch*.\n // The app must forward them: <canvas @touchstart=\"runtime.handleTouch\" ... />\n watchTouch: (_handler: (event: TouchLikeEvent) => void): Disposer => () => undefined,\n watchVisibility,\n requestAnimationFrame: raf.request,\n cancelAnimationFrame: raf.cancel,\n now,\n dispose: () => diagnostics.debug('wechat-miniprogram binding disposed'),\n };\n}\n\nexport type WeChatMiniProgramRuntimeOptions = WeChatMiniProgramOptions & RuntimeOptions;\n\nexport function createWeChatMiniProgramRuntime(\n options: WeChatMiniProgramRuntimeOptions,\n): Promise<MiniThreeRuntime> {\n return createRuntime(() => createWeChatMiniProgramBinding(options), options);\n}\n"]}
|