@puzzmo/sdk 1.0.82 → 1.0.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"vite.js","names":[],"sources":["../src/pico8/vitePlugin.ts","../src/vite.ts"],"sourcesContent":["import type { Plugin, ResolvedConfig } from \"vite\"\nimport { execFileSync } from \"child_process\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport { puzzmoLua } from \"./lua\"\n\nexport type PuzzmoPico8PluginOptions = {\n /** The cart, relative to the page. Defaults to the only `.p8` file in `cart/`. */\n cart?: string\n /** Where PICO-8's HTML export lives, relative to the page. Defaults to `export`. Commit it, so builds don't need PICO-8. */\n exportDir?: string\n /**\n * The PICO-8 binary used to re-export the cart when it changes. Defaults to `$PICO8`, then `pico8` on your PATH,\n * then where PICO-8's installers put it. When it can't be found the committed export is used as-is. Pass false to\n * never export.\n */\n pico8?: string | false\n /** Keep `puzzmo.lua` next to the cart up to date. Defaults to true. */\n writeLua?: boolean\n}\n\n/** @internal */\nexport type Pico8Game = {\n /** The directory holding the page */\n dir: string\n cart: string\n /** The cart's name, which PICO-8 also uses for its export */\n name: string\n exportHTML: string\n exportJS: string\n}\n\n/** @internal Finds the PICO-8 game served by the page in `dir`, if there is one. */\nexport function findPico8Game(dir: string, options: PuzzmoPico8PluginOptions = {}): Pico8Game | null {\n let cart: string | undefined\n if (options.cart) cart = path.resolve(dir, options.cart)\n else {\n const cartDir = path.join(dir, \"cart\")\n const carts = fs.existsSync(cartDir) ? fs.readdirSync(cartDir).filter((f) => f.endsWith(\".p8\")) : []\n if (carts.length > 1) throw new Error(`[puzzmo-pico8] found ${carts.length} carts in ${cartDir}, pick one with the \\`cart\\` option`)\n if (carts.length === 1) cart = path.join(cartDir, carts[0])\n }\n if (!cart || !fs.existsSync(cart)) return null\n const name = path.basename(cart, \".p8\")\n const exportDir = path.resolve(dir, options.exportDir ?? \"export\")\n return { dir, cart, name, exportHTML: path.join(exportDir, `${name}.html`), exportJS: path.join(exportDir, `${name}.js`) }\n}\n\n/**\n * @internal\n * Turns PICO-8's exported page into a Puzzmo game's page. PICO-8's shell is a thousand lines of globals and handlers\n * its runtime expects to find, and it changes between versions, so rather than keep a copy we adjust theirs.\n */\nexport function patchPico8Export(html: string, name: string, scripts: string[]): string {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\n // PICO-8 loads its runtime from a script element it builds itself. Point it at the copy we serve next to the page,\n // relative because Puzzmo serves games from a subfolder.\n const runtime = new RegExp(`((?:\\\\.src\\\\s*=\\\\s*|\\\\ssrc=)[\"'])[^\"']*${escaped}\\\\.js([\"'])`)\n if (!runtime.test(html)) throw new Error(`[puzzmo-pico8] couldn't find where PICO-8's page loads ${name}.js`)\n html = html.replace(runtime, `$1./${name}.js$2`)\n\n // Boot straight away. Otherwise the cart waits for a click on PICO-8's play button and the host never hears that\n // the game loaded. (Browsers which need a tap before audio can start, like iOS Safari, still show the button.)\n html = html.replace(/var\\s+p8_autoplay\\s*=\\s*false/, \"var p8_autoplay = true\")\n\n // The GPIO array, for shells old enough not to declare it themselves.\n if (!/var\\s+pico8_gpio\\s*=/.test(html)) html = html.replace(/<head>/i, \"<head>\\n<script>var pico8_gpio = new Array(128)</script>\")\n\n // Things a browser shrugs off and Vite doesn't: an HTML comment wrapped around the stylesheet, a stray\n // `-repeat center;` in it, and an `&nbsp` without its semicolon.\n html = html.replace(\n /(<style[^>]*>)([\\s\\S]*?)(<\\/style>)/gi,\n (_, open: string, css: string, close: string) =>\n open + css.replace(/<!--|-->/g, \"\").replace(/^[ \\t]*-repeat[^;\\n]*;[ \\t]*$/gm, \"\") + close,\n )\n html = html.replace(/&nbsp(?!;)/g, \"&nbsp;\")\n\n const bodyEnd = html.lastIndexOf(\"</body>\")\n if (bodyEnd === -1) throw new Error(\"[puzzmo-pico8] that doesn't look like a PICO-8 export, it has no </body>\")\n return html.slice(0, bodyEnd) + scripts.join(\"\\n\") + \"\\n\" + html.slice(bodyEnd)\n}\n\n/** Where PICO-8's own installers put it, for people who never added it to their PATH. */\nconst usualPico8Locations = [\n \"/Applications/PICO-8.app/Contents/MacOS/pico8\",\n \"C:\\\\Program Files (x86)\\\\PICO-8\\\\pico8.exe\",\n \"C:\\\\Program Files\\\\PICO-8\\\\pico8.exe\",\n]\n\n/** Finds an executable on the PATH without running it: `pico8` with no export arguments opens the whole app. */\nconst findExecutable = (bin: string): string | null => {\n if (bin.includes(\"/\") || bin.includes(\"\\\\\")) return fs.existsSync(bin) ? bin : null\n for (const dir of (process.env.PATH ?? \"\").split(path.delimiter)) {\n for (const ext of process.platform === \"win32\" ? [\".exe\", \".cmd\", \"\"] : [\"\"]) {\n const candidate = path.join(dir, bin + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n }\n if (bin === \"pico8\") return usualPico8Locations.find((p) => fs.existsSync(p)) ?? null\n return null\n}\n\nconst mtime = (file: string) => (fs.existsSync(file) ? fs.statSync(file).mtimeMs : 0)\n\n/**\n * Vite plugin for games written as PICO-8 carts. Your `index.html` only needs your own script tag, the plugin swaps\n * in PICO-8's exported page around it, serves the PICO-8 runtime next to it, and copies it into the build.\n *\n * When PICO-8 is installed it also re-exports the cart whenever it (or a `.lua` file next to it) changes, and reloads\n * the page, so saving in PICO-8 is enough to see the change in the simulator.\n */\nexport function puzzmoPico8(options: PuzzmoPico8PluginOptions = {}): Plugin {\n let config: ResolvedConfig\n const games = new Map<string, Pico8Game>()\n const binary = options.pico8 === false ? null : (options.pico8 ?? process.env.PICO8 ?? \"pico8\")\n\n const log = (message: string) => config.logger.info(`\\x1b[33m\\x1b[1m PICO-8 \\x1b[22m\\x1b[39m${message}`)\n\n const writeLua = (game: Pico8Game) => {\n if (options.writeLua === false) return\n const file = path.join(path.dirname(game.cart), \"puzzmo.lua\")\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === puzzmoLua) return\n fs.writeFileSync(file, puzzmoLua)\n log(`wrote ${path.relative(config.root, file)}`)\n }\n\n /** Re-exports the cart when it's newer than the export and PICO-8 is around to do it. */\n const exportIfStale = (game: Pico8Game) => {\n const cartDir = path.dirname(game.cart)\n const newest = Math.max(\n ...fs\n .readdirSync(cartDir)\n .filter((f) => /\\.(p8|lua)$/.test(f))\n .map((f) => mtime(path.join(cartDir, f))),\n )\n if (fs.existsSync(game.exportJS) && mtime(game.exportJS) >= newest) return\n\n const pico8 = binary ? findExecutable(binary) : null\n if (!pico8) {\n if (fs.existsSync(game.exportHTML)) {\n config.logger.warn(\n `[puzzmo-pico8] ${path.relative(config.root, game.cart)} is newer than its export, and PICO-8 isn't around to re-export it. Using the old export.`,\n )\n return\n }\n throw new Error(\n `[puzzmo-pico8] there's no export of ${path.relative(config.root, game.cart)} yet, and PICO-8 isn't on your PATH to make one.\\n` +\n `Export it inside PICO-8 with EXPORT ${game.name}.html into ${path.relative(config.root, path.dirname(game.exportHTML))}/, or set PICO8=/path/to/pico8.`,\n )\n }\n\n fs.mkdirSync(path.dirname(game.exportHTML), { recursive: true })\n const before = mtime(game.exportJS)\n let output = \"\"\n try {\n output = execFileSync(pico8, [game.cart, \"-export\", game.exportHTML], {\n encoding: \"utf8\",\n timeout: 60_000,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (error) {\n output = String((error as { stdout?: string }).stdout ?? error)\n }\n if (mtime(game.exportJS) === before) {\n const hint = /label/i.test(output) ? \"\\nHTML exports need a label: run the cart in PICO-8, press CTRL-7, and save.\" : \"\"\n throw new Error(`[puzzmo-pico8] PICO-8 didn't export ${path.relative(config.root, game.cart)}:\\n${output.trim()}${hint}`)\n }\n log(`exported ${path.relative(config.root, game.cart)}`)\n }\n\n const gameForPage = (htmlFile: string) => {\n const dir = path.dirname(htmlFile)\n if (!games.has(dir)) {\n const game = findPico8Game(dir, options)\n if (!game) return null\n games.set(dir, game)\n }\n return games.get(dir)!\n }\n\n return {\n name: \"puzzmo-pico8\",\n\n config() {\n // The export is rewritten on every save, and Vite reloads the page for any .html it sees change. The plugin\n // reloads once the export is done, so Vite reloading too would boot the cart twice.\n const exportDir = options.exportDir ?? \"export\"\n const isExport = (file: string) =>\n /\\.(html|js)$/.test(file) &&\n path.basename(path.dirname(file)) === path.basename(exportDir) &&\n fs.existsSync(path.join(path.dirname(path.dirname(file)), \"cart\"))\n return { server: { watch: { ignored: [isExport] } } }\n },\n\n configResolved(resolved) {\n config = resolved\n },\n\n transformIndexHtml: {\n order: \"pre\",\n handler(html, ctx) {\n const game = gameForPage(ctx.filename)\n if (!game) return\n writeLua(game)\n exportIfStale(game)\n // Keep the page's own module scripts: that's the game code.\n const scripts = html.match(/<script\\b[^>]*type=[\"']module[\"'][^>]*>[\\s\\S]*?<\\/script>/gi) ?? []\n return patchPico8Export(fs.readFileSync(game.exportHTML, \"utf8\"), game.name, scripts)\n },\n },\n\n configureServer(devServer) {\n // Serve the runtime next to the page, untouched by Vite's transforms: it is a megabyte of emscripten output\n // which only works exactly as PICO-8 wrote it.\n devServer.middlewares.use((req, res, next) => {\n const url = decodeURIComponent((req.url ?? \"\").split(\"?\")[0])\n if (!url.endsWith(\".js\")) return next()\n const game = [...games.values()].find(\n (g) =>\n url ===\n \"/\" +\n path\n .relative(config.root, path.join(g.dir, `${g.name}.js`))\n .split(path.sep)\n .join(\"/\"),\n )\n if (!game || !fs.existsSync(game.exportJS)) return next()\n res.setHeader(\"Content-Type\", \"text/javascript\")\n res.end(fs.readFileSync(game.exportJS))\n })\n\n // Saving the cart in PICO-8 re-exports it and reloads the page.\n devServer.watcher.on(\"change\", (file) => {\n const game = [...games.values()].find((g) => path.dirname(file) === path.dirname(g.cart) && /\\.(p8|lua)$/.test(file))\n if (!game || path.basename(file) === \"puzzmo.lua\") return\n try {\n exportIfStale(game)\n devServer.ws.send({ type: \"full-reload\" })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n config.logger.error(message)\n devServer.ws.send({ type: \"error\", err: { message, stack: \"\" } })\n }\n })\n },\n\n generateBundle() {\n for (const game of games.values()) {\n const fileName = path\n .relative(config.root, path.join(game.dir, `${game.name}.js`))\n .split(path.sep)\n .join(\"/\")\n this.emitFile({ type: \"asset\", fileName, source: fs.readFileSync(game.exportJS) })\n }\n },\n }\n}\n","import type { Plugin, ResolvedConfig } from \"vite\"\nimport { build } from \"vite\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport type { HostContext } from \"./types\"\nimport type { HostContextPreset, SimulatorIntegrations } from \"./simulator/types\"\n\nexport { puzzmoPico8, type PuzzmoPico8PluginOptions } from \"./pico8/vitePlugin\"\n\nexport type PuzzmoSimulatorPluginOptions = {\n /** Whether to auto-start the game after READY (default: true) */\n autoStart?: boolean\n /** Initial collapsed state (default: true) */\n collapsed?: boolean\n /**\n * Glob pattern for fixture files, passed to import.meta.glob which is relative to the closest puzzmo.json. Defaults\n * to `\"/fixtures/puzzles/**\\/*.{json,toml}\"`. Fixtures are loaded as raw strings (any text format works — JSON,\n * TOML, or a custom format) and delivered to the game verbatim, so the game parses them itself. Pass false to disable.\n */\n fixturesGlob?: string | false\n /**\n * Whether READY_DATA carries a play session (default: true). Set to false to run the game the way\n * a host will for a mode with no puzzle. Ignored for games built on an SDK from before runtime contract \"1.1\".\n */\n session?: boolean\n /**\n * The `hostContext` array the simulator sends in READY_DATA, so host-context-dependent features\n * (embed settings, sandbox mode, mobile layout, …) can be exercised locally. Must be\n * JSON-serializable. Defaults to a single desktop \"app\" context; the simulator's Host tab can\n * override it at runtime (persisted per-browser, applied on restart).\n *\n * @internal\n */\n hostContext?: HostContext[]\n /**\n * Extra named `hostContext` presets for the simulator's Host tab, alongside the generic\n * built-ins — how a game ships its own scenarios (e.g. crossword's partner-embed toolbar\n * settings). Must be JSON-serializable.\n *\n * @internal\n */\n hostContextPresets?: HostContextPreset[]\n /**\n * Plugin-provided simulator tabs, named rather than passed directly because this config is\n * serialized into a virtual module. Each entry is imported and called with no arguments, so the\n * export must be a `() => SimulatorView` factory — e.g.\n * `{ module: \"@puzzmo-com/shared/sdkPlugins\", export: \"createCollabSimulatorView\" }`.\n */\n viewFactories?: { module: string; export: string }[]\n}\n\nconst simulatorURL = \"/@puzzmo-simulator-init.js\"\nconst virtualID = \"virtual:puzzmo-simulator\"\n\n/** @internal */\nexport type GameInfo = {\n /** Directory containing the puzzmo.json */\n dir: string\n slug: string\n displayName: string\n /** Vite-root-relative path to app bundle entry, if it exists */\n appBundlePath: string | null\n /** Vite-root-relative path to the pmmg bundle entry, if it exists, for the simulator's Pmmg tab */\n pmmgBundlePath?: string | null\n /** `integrations` from the puzzmo.json, passed to simulator tabs that preview them */\n integrations?: SimulatorIntegrations\n}\n\n/**\n * Discover all games from puzzmo.json files under a root directory.\n *\n * @internal\n */\nexport function discoverGames(viteRoot: string): Map<string, GameInfo> {\n const games = new Map<string, GameInfo>()\n const candidates = findPuzzmoJsonDirs(viteRoot, 3)\n if (fs.existsSync(path.join(viteRoot, \"puzzmo.json\"))) {\n candidates.unshift(viteRoot)\n }\n for (const dir of candidates) {\n try {\n const data = JSON.parse(fs.readFileSync(path.join(dir, \"puzzmo.json\"), \"utf-8\"))\n if (!data?.game?.slug) continue\n const integrations = data.integrations && typeof data.integrations === \"object\" ? data.integrations : undefined\n games.set(data.game.slug, {\n dir,\n slug: data.game.slug,\n displayName: data.game.displayName,\n appBundlePath: viteRootPath(viteRoot, resolveBundleEntry(dir, \"src/appBundle\")),\n pmmgBundlePath: viteRootPath(viteRoot, resolveBundleEntry(dir, \"src/pmmgBundle\")),\n integrations,\n })\n } catch {\n // skip invalid files\n }\n }\n return games\n}\n\n/**\n * Resolve which game a request belongs to using the referer URL.\n *\n * @internal\n */\nexport function resolveGameFromReferer(referer: string | undefined, games: Map<string, GameInfo>, viteRoot: string): GameInfo | undefined {\n if (referer) {\n try {\n const refPath = new URL(referer).pathname\n for (const g of games.values()) {\n const relDir = \"/\" + path.relative(viteRoot, g.dir).split(path.sep).join(\"/\")\n if (refPath.startsWith(relDir + \"/\") || refPath === relDir) return g\n }\n } catch {\n // ignore malformed referer\n }\n }\n if (games.size === 1) return games.values().next().value\n return undefined\n}\n\n/**\n * Generate the virtual module code for the simulator.\n *\n * @internal\n */\nexport function generateSimulatorCode(options: PuzzmoSimulatorPluginOptions, game: GameInfo | undefined): string {\n const { fixturesGlob: fixturesOpt, viewFactories, ...config } = options\n const fixturesGlob = fixturesOpt === false ? null : (fixturesOpt ?? \"/fixtures/puzzles/**/*.{json,toml}\")\n\n const lines = [`import { createSimulator } from \"@puzzmo/sdk/simulator\"`]\n for (const view of viewFactories ?? []) {\n lines.push(`import { ${view.export} } from ${JSON.stringify(view.module)}`)\n }\n\n // Load fixtures as raw strings so any text format reaches the game verbatim; the game does its own parsing.\n if (fixturesGlob) {\n lines.push(`const fixtures = import.meta.glob(${JSON.stringify(fixturesGlob)}, { query: \"?raw\", import: \"default\", eager: true })`)\n }\n\n if (game?.appBundlePath) {\n lines.push(`import(${JSON.stringify(game.appBundlePath)}).then(m => {`)\n lines.push(` if (m.renderThumbnail) globalThis.renderThumbnail = m.renderThumbnail`)\n lines.push(` if (m.getShareString) globalThis.getShareString = m.getShareString`)\n lines.push(`}).catch(() => {})`)\n }\n\n const simConfig = {\n ...config,\n ...(game?.slug ? { slug: game.slug } : {}),\n ...(game?.integrations ? { integrations: game.integrations } : {}),\n }\n const configEntries = Object.entries(simConfig).filter(([, v]) => v !== undefined)\n const configParts = configEntries.map(([k, v]) => `${k}: ${JSON.stringify(v)}`)\n if (fixturesGlob) configParts.push(\"fixtures\")\n // Loaded when the Pmmg tab opens, so a game page that never looks at it never imports it\n if (game?.pmmgBundlePath) configParts.push(`pmmgBundle: () => import(${JSON.stringify(game.pmmgBundlePath)})`)\n if (viewFactories?.length) configParts.push(`views: [${viewFactories.map((v) => `${v.export}()`).join(\", \")}]`)\n\n lines.push(`createSimulator({ ${configParts.join(\", \")} })`)\n\n return lines.join(\"\\n\")\n}\n\n/** Vite plugin that injects the Puzzmo simulator in dev mode and handles OAuth callbacks. */\nexport function puzzmoSimulator(options: PuzzmoSimulatorPluginOptions = {}): Plugin {\n let games = new Map<string, GameInfo>()\n let viteRoot: string\n\n return {\n name: \"puzzmo-simulator\",\n apply: \"serve\",\n\n configResolved(config: ResolvedConfig) {\n viteRoot = config.root\n games = discoverGames(viteRoot)\n\n if (games.size === 0) {\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m\\x1b[2m no puzzmo.json files found\\x1b[22m`)\n } else {\n const names = [...games.values()].map((g) => `\\x1b[36m${g.slug}\\x1b[39m`)\n const label = games.size === 1 ? \"game\" : \"games\"\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m found ${games.size} ${label}: ${names.join(\"\\x1b[2m, \\x1b[22m\")}`)\n }\n },\n\n resolveId(id) {\n if (id === virtualID || id.startsWith(virtualID + \"?\")) return \"\\0\" + id\n },\n\n load(id) {\n if (!id.startsWith(\"\\0\" + virtualID)) return\n const params = new URLSearchParams(id.split(\"?\")[1] || \"\")\n const gameSlug = params.get(\"game\")\n const game = gameSlug ? games.get(gameSlug) : games.size === 1 ? games.values().next().value : undefined\n return generateSimulatorCode(options, game)\n },\n\n configureServer(server) {\n // Re-read puzzmo.json on edit and reload the page so the simulator picks up its changes\n for (const g of games.values()) server.watcher.add(path.join(g.dir, \"puzzmo.json\"))\n server.watcher.on(\"change\", (file) => {\n if (path.basename(file) !== \"puzzmo.json\") return\n games = discoverGames(viteRoot)\n for (const mod of server.moduleGraph.idToModuleMap.values()) {\n if (mod.id?.startsWith(\"\\0\" + virtualID)) server.moduleGraph.invalidateModule(mod)\n }\n server.ws.send({ type: \"full-reload\" })\n })\n\n server.middlewares.use(\"/oauth/callback\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"text/html\")\n res.end(`<!DOCTYPE html>\n<html><head><title>Puzzmo OAuth</title></head>\n<body><script>\nvar params = new URLSearchParams(window.location.search);\nvar returnUrl = sessionStorage.getItem(\"oauth_return_url\") || \"/\";\nvar url = new URL(returnUrl);\nparams.forEach(function(v, k) { url.searchParams.set(k, v); });\nwindow.location.href = url.toString();\n</script></body></html>`)\n })\n\n // Serve the simulator init module, resolving the game from the referer\n server.middlewares.use(async (req, res, next) => {\n if (req.url?.split(\"?\")[0] !== simulatorURL) return next()\n\n const game = resolveGameFromReferer(req.headers.referer, games, viteRoot)\n const moduleID = virtualID + (game ? `?game=${game.slug}` : \"\")\n const result = await server.transformRequest(moduleID)\n if (!result) return next()\n res.setHeader(\"Content-Type\", \"application/javascript\")\n res.end(result.code)\n })\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: { type: \"module\", src: simulatorURL },\n injectTo: \"head\",\n },\n ]\n },\n }\n}\n\ntype BundlePluginOptions = {\n /** Entry file for the bundle */\n entry: string\n /** Output file name */\n outputFile: string\n /** Folder the bundle is written to */\n outDir: string\n}\n\nfunction createBundlePlugin(pluginName: string, defaults: BundlePluginOptions) {\n return (options: Partial<BundlePluginOptions> = {}): Plugin => {\n const { entry, outputFile, outDir } = { ...defaults, ...options }\n return {\n name: pluginName,\n apply: \"build\",\n async closeBundle() {\n // If the caller overrode `entry`, honor it as-is. Otherwise try `.js` first, then `.ts`.\n const resolvedEntry = options.entry\n ? path.isAbsolute(entry)\n ? entry\n : path.resolve(process.cwd(), entry)\n : (resolveBundleEntry(process.cwd(), stripBundleExt(entry)) ?? path.resolve(process.cwd(), entry))\n try {\n await build({\n configFile: false,\n logLevel: \"warn\",\n build: {\n lib: {\n entry: resolvedEntry,\n formats: [\"es\"],\n fileName: () => outputFile,\n },\n outDir,\n emptyOutDir: false,\n },\n })\n } catch (error) {\n console.error(`[${pluginName}] build failed:`, error)\n throw error\n }\n },\n }\n }\n}\n\n/** Strip the trailing extension from a default entry path so we can probe siblings. */\nconst stripBundleExt = (p: string) => p.replace(/\\.[jt]sx?$/i, \"\")\n\n/** An absolute file as the path the dev server serves it at, or null for no file */\nconst viteRootPath = (viteRoot: string, file: string | null) =>\n file ? \"/\" + path.relative(viteRoot, file).split(path.sep).join(\"/\") : null\n\n/** Returns the absolute path to the first matching extension under `dir`, or null. */\nconst resolveBundleEntry = (dir: string, baseRelative: string): string | null => {\n // JSX last: a bundle written as JSX still needs the plain entry to win if both somehow exist.\n for (const ext of [\".js\", \".ts\", \".tsx\", \".jsx\"]) {\n const candidate = path.join(dir, baseRelative + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n return null\n}\n\nexport type AppBundlePluginOptions = {\n /** Entry file for the app bundle (default: `src/appBundle.js`) */\n entry?: string\n /** Output file name (default: `app-bundle.js`) */\n outputFile?: string\n}\n\n/**\n * Vite plugin that produces dist/app-bundle.js after the main build for app-level integrations.\n *\n * The bundle exports `renderThumbnail(puzzleString, inputString?, config?)` — a pure renderer\n * returning the SVG and its dimensions (`{ svg, width, height }`), used by the Puzzmo\n * platform for puzzle previews.\n */\nexport const appBundlePlugin = createBundlePlugin(\"app-bundle\", { entry: \"src/appBundle.js\", outputFile: \"app-bundle.js\", outDir: \"dist\" })\n\nexport type ServerBundlePluginOptions = {\n /** Entry file for the server bundle (default: `src/serverBundle.js`, or `.ts`) */\n entry?: string\n /** Output file name (default: `server-bundle.js`) */\n outputFile?: string\n}\n\n/**\n * Vite plugin that produces dist-server/server-bundle.js after the main build: the game's private\n * server bundle (see `ServerBundle`). It goes in its own folder, never `dist`, so it can't be served to\n * players by mistake; `puzzmo games upload` finds it there and sends it to Puzzmo privately. A repo that\n * builds several games gives each its own `outputFile` and names it in that game's puzzmo.json as\n * `output.serverBundle`, since uploads refuse to send one file for more than one game.\n */\nexport const serverBundlePlugin = createBundlePlugin(\"server-bundle\", {\n entry: \"src/serverBundle.js\",\n outputFile: \"server-bundle.js\",\n outDir: \"dist-server\",\n})\n\nexport type PmmgBundlePluginOptions = {\n /** Entry file for the pmmg bundle (default: `src/pmmgBundle.js`, or `.ts`) */\n entry?: string\n /** Output file name (default: `pmmg-bundle.js`) */\n outputFile?: string\n}\n\nconst buildPmmgBundle = createBundlePlugin(\"pmmg-bundle\", { entry: \"src/pmmgBundle.js\", outputFile: \"pmmg-bundle.js\", outDir: \"dist\" })\n\n/**\n * Vite plugins for the game's pmmg bundle (see `PmmgBundle`), such as its boards at the table. After the main build\n * they produce dist/pmmg-bundle.js, which is public and served with the rest of `dist`. In dev, `/pmmg-bundle.js` on\n * the game's dev server is built from source on each request, so a Puzzmo page running with `?dev` draws boards from\n * the code being worked on.\n *\n * Puzzmo imports it from an opaque-origin sandbox, so that one response answers any origin. It's a whole build rather\n * than the dev server's modules, since letting `Origin: null` read those would let any page read the game's source.\n */\nexport const pmmgBundlePlugin = (options: PmmgBundlePluginOptions = {}): Plugin[] => [\n buildPmmgBundle(options),\n {\n name: \"pmmg-bundle-dev\",\n apply: \"serve\",\n configureServer(server) {\n // Requests that arrive while a build runs share it\n let building: Promise<string> | undefined\n server.middlewares.use((req, res, next) => {\n if (!/^\\/pmmg-bundle\\.js(?:\\?.*)?$/.test(req.url || \"\")) return next()\n const entry = options.entry ?? resolveBundleEntry(server.config.root, \"src/pmmgBundle\")\n if (!entry) return next()\n building ??= buildPmmgBundleSource(path.resolve(server.config.root, entry)).finally(() => (building = undefined))\n building.then(\n (code) => {\n res.setHeader(\"Content-Type\", \"text/javascript\")\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\")\n res.setHeader(\"Cache-Control\", \"no-store\")\n res.end(code)\n },\n (error) => {\n server.config.logger.error(`[pmmg-bundle] build failed: ${error?.message ?? error}`)\n res.statusCode = 500\n res.end()\n },\n )\n })\n },\n },\n]\n\n/** The pmmg bundle built as production builds it, as one file's source for the dev route */\nexport const buildPmmgBundleSource = async (entry: string): Promise<string> => {\n const result = await build({\n configFile: false,\n logLevel: \"warn\",\n build: {\n write: false,\n copyPublicDir: false,\n minify: false,\n sourcemap: \"inline\",\n lib: { entry, formats: [\"es\"], fileName: () => \"pmmg-bundle.js\" },\n // One file, as the route serves only the one\n rolldownOptions: { output: { codeSplitting: false } },\n },\n })\n const outputs = Array.isArray(result) ? result : \"output\" in result ? [result] : []\n const chunk = outputs.flatMap((output) => output.output).find((file) => file.type === \"chunk\" && file.isEntry)\n if (!chunk || chunk.type !== \"chunk\") throw new Error(`Building ${entry} made no bundle`)\n return chunk.code\n}\n\nexport type EditorBundlePluginOptions = {\n /** Entry file for the editor bundle (default: `src/editorBundle.js`) */\n entry?: string\n /** Output file name (default: `editor-bundle.js`) */\n outputFile?: string\n}\n\n/** Vite plugin that produces dist/editor-bundle.js after the main build for editor-level integrations. */\nexport const editorBundlePlugin = createBundlePlugin(\"editor-bundle\", {\n entry: \"src/editorBundle.js\",\n outputFile: \"editor-bundle.js\",\n outDir: \"dist\",\n})\n\n/**\n * Recursively find directories containing puzzmo.json, up to `maxDepth` levels deep.\n *\n * @internal\n */\nexport const findPuzzmoJsonDirs = (root: string, maxDepth: number, depth = 0): string[] => {\n if (depth >= maxDepth) return []\n const results: string[] = []\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(root, { withFileTypes: true })\n } catch {\n return results\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue\n const dir = path.join(root, entry.name)\n if (fs.existsSync(path.join(dir, \"puzzmo.json\"))) {\n results.push(dir)\n }\n results.push(...findPuzzmoJsonDirs(dir, maxDepth, depth + 1))\n }\n return results\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAgB,EAAc,GAAa,IAAoC,EAAE,EAAoB;;CACnG,IAAI;AACJ,KAAI,EAAQ,KAAM,KAAO,EAAK,QAAQ,GAAK,EAAQ,KAAK;MACnD;EACH,IAAM,IAAU,EAAK,KAAK,GAAK,OAAO,EAChC,IAAQ,EAAG,WAAW,EAAQ,GAAG,EAAG,YAAY,EAAQ,CAAC,QAAQ,MAAM,EAAE,SAAS,MAAM,CAAC,GAAG,EAAE;AACpG,MAAI,EAAM,SAAS,EAAG,OAAU,MAAM,wBAAwB,EAAM,OAAO,YAAY,EAAQ,qC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AAO,SAAS,CAAC,KAAK;KAAE,gBAAgB;KAAkB;IAEjE,iBAAiB,EAAE,QAAQ,EAAE,eAAe,IAAO,EAAE;IACtD;GACF,CAAC,EAEI,KADU,MAAM,QAAQ,EAAO,GAAG,IAAS,YAAY,IAAS,CAAC,EAAO,GAAG,EAAE,EAC7D,SAAS,MAAW,EAAO,OAAO,CAAC,MAAM,MAAS,EAAK,SAAS,WAAW,EAAK,QAAQ;AAC9G,MAAI,CAAC,KAAS,EAAM,SAAS,QAAS,OAAU,MAAM,YAAY,EAAM,iBAAiB;AACzF,SAAO,EAAM;;iBAjB6B,GAAA;;;KA4B/B,IAAqB,EAAmB,iBAAiB;CACpE,OAAO;CACP,YAAY;CACZ,QAAQ;CACT,CAAC,EAOW,KAAsB,GAAc,GAAkB,IAAQ,MAAgB;AACzF,KAAI,KAAS,EAAU,QAAO,EAAE;CAChC,IAAM,IAAoB,EAAE,EACxB;AACJ,KAAI;AACF,MAAU,EAAG,YAAY,GAAM,EAAE,eAAe,IAAM,CAAC;aACjD;AACN,SAAO;;AAET,MAAK,IAAM,KAAS,GAAS;AAC3B,MAAI,CAAC,EAAM,aAAa,IAAI,EAAM,KAAK,WAAW,IAAI,IAAI,EAAM,SAAS,eAAgB;EACzF,IAAM,IAAM,EAAK,KAAK,GAAM,EAAM,KAAK;AAIvC,EAHI,EAAG,WAAW,EAAK,KAAK,GAAK,cAAc,CAAC,IAC9C,EAAQ,KAAK,EAAI,EAEnB,EAAQ,KAAK,GAAG,EAAmB,GAAK,GAAU,IAAQ,EAAE,CAAC;;AAE/D,QAAO"}
1
+ {"version":3,"file":"vite.js","names":[],"sources":["../src/bundleChecks.ts","../src/pico8/vitePlugin.ts","../src/vite.ts"],"sourcesContent":["import path from \"path\"\nimport type { Plugin } from \"vite\"\n\n/** What a bundle's build holds it to, as each bundle runs somewhere different */\nexport type BundleLimits = {\n /** Where the bundle loads, finishing \"over the limit for a bundle loaded on ...\" */\n loadedOn?: string\n /** Warns past this many bytes */\n warnBytes?: number\n /** Fails the build past this many bytes */\n maxBytes?: number\n /** Packages that fail the build when any of their modules is bundled */\n bannedPackages?: string[]\n}\n\n/** What `checkBundle` reads from a finished build */\nexport type BundleFacts = {\n /** The bundle's file as messages name it */\n fileName: string\n /** The bundle's final code */\n code: string\n /** Each bundled module by id: its rendered bytes, and its code before minifying */\n modules: Record<string, { size: number; code: string | null }>\n /** The imports leading from the entry to each module, entry first */\n chains: Map<string, string[]>\n /** Paths in messages are relative to this */\n root: string\n}\n\nconst KB = 1024\n\n/** The limits for a bundle Puzzmo loads into its own pages, where every byte is on a player's page load */\nexport const pageBundleLimits = (loadedOn: string): BundleLimits => ({\n loadedOn,\n warnBytes: 200 * KB,\n maxBytes: 500 * KB,\n bannedPackages: [\"react\", \"react-dom\", \"scheduler\", \"redux\", \"react-redux\", \"@reduxjs/toolkit\"],\n})\n\n/**\n * Checks a built bundle: errors fail the build (too big, or a banned package), warnings flag likely mistakes (Node\n * globals, which browsers and isolates don't have).\n */\nexport const checkBundle = (facts: BundleFacts, limits: BundleLimits) => {\n const errors: string[] = []\n const warnings: string[] = []\n const describe = describer(facts)\n\n const size = Buffer.byteLength(facts.code)\n const overMax = limits.maxBytes !== undefined && size > limits.maxBytes\n const overWarn = limits.warnBytes !== undefined && size > limits.warnBytes\n if (overMax || overWarn) {\n const limit = overMax ? limits.maxBytes! : limits.warnBytes!\n const where = limits.loadedOn ? ` for a bundle loaded on ${limits.loadedOn}` : \"\"\n const largest = Object.entries(facts.modules)\n .sort(([, a], [, b]) => b.size - a.size)\n .slice(0, 5)\n .map(\n ([moduleID, { size }]) => ` ${formatKB(size).padStart(7)} ${describe.module(moduleID)}\\n ${describe.chain(moduleID)}`,\n )\n const message = `${facts.fileName} is ${formatKB(size)}, over the ${formatKB(limit)} limit${where}. Its largest modules:\\n${largest.join(\"\\n\")}`\n ;(overMax ? errors : warnings).push(message)\n }\n\n const banned = new Set(limits.bannedPackages ?? [])\n const reported = new Set<string>()\n for (const moduleID of Object.keys(facts.modules)) {\n const pkg = packageName(moduleID)\n if (!pkg || !banned.has(pkg) || reported.has(pkg)) continue\n reported.add(pkg)\n errors.push(\n `${pkg} can't be in ${facts.fileName}, as Puzzmo calls it for strings and data. Imported by:\\n ${describe.chain(moduleID)}`,\n )\n }\n\n const globals = findNodeGlobals(facts.code, facts.modules)\n if (globals.length) {\n const lines = globals.map(({ usage, count, moduleID }) => {\n const times = count > 1 ? ` (x${count})` : \"\"\n return moduleID ? ` ${usage}${times} in ${describe.module(moduleID)}\\n ${describe.chain(moduleID)}` : ` ${usage}${times}`\n })\n warnings.push(\n `${facts.fileName} uses Node globals, which don't exist where Puzzmo runs it, so each throws if reached:\\n${lines.join(\"\\n\")}`,\n )\n }\n\n return { errors, warnings }\n}\n\n/**\n * Runs `checkBundle` inside a bundle's own build. Warnings go to the build's logger, and errors fail it, kept on\n * `api.failure` so the caller can report them without the bundler's stack.\n */\nexport const bundleChecks = (fileName: string, limits: BundleLimits): Plugin & { api: { failure?: string } } => {\n let root = process.cwd()\n const api: { failure?: string } = {}\n return {\n name: \"puzzmo-bundle-checks\",\n api,\n configResolved(config) {\n root = config.root\n },\n generateBundle(_, bundle) {\n const chunk = Object.values(bundle).find((file) => file.type === \"chunk\" && file.isEntry)\n if (chunk?.type !== \"chunk\" || !chunk.facadeModuleId) return\n\n const modules = Object.fromEntries(\n Object.entries(chunk.modules).map(([moduleID, info]) => [moduleID, { size: info.renderedLength, code: info.code }]),\n )\n const chains = importChains(chunk.facadeModuleId, (moduleID) => this.getModuleInfo(moduleID))\n const { errors, warnings } = checkBundle({ fileName, code: chunk.code, modules, chains, root }, limits)\n\n for (const warning of warnings) this.warn(warning)\n if (!errors.length) return\n api.failure = errors.join(\"\\n\\n\")\n this.error(api.failure)\n },\n }\n}\n\n/** A Node-only global in use: `process.env.X`, `Buffer.from`, `require(`, never `obj.process.x` or `__require(` */\nconst nodeGlobalPattern =\n /(?<![\\w$.])(?:(?:process|global|Buffer)(?:\\.[\\w$]+){1,2}|require\\s*\\(|new\\s+Buffer\\s*\\(|__dirname\\b|__filename\\b)/g\n\n/**\n * The Node global usages that survive into the final code, by the module they're in. Each module's own code says\n * where they came from, as globals keep their names through minifying, while the final code says which outlived\n * dead-code removal.\n */\nconst findNodeGlobals = (code: string, modules: BundleFacts[\"modules\"]) => {\n const inBundle = unguardedNodeGlobals(code)\n const found: { usage: string; count: number; moduleID?: string }[] = []\n for (const [moduleID, module] of Object.entries(modules)) {\n if (!module.code) continue\n for (const [usage, count] of unguardedNodeGlobals(module.code)) if (inBundle.has(usage)) found.push({ usage, count, moduleID })\n }\n const attributed = new Set(found.map(({ usage }) => usage))\n for (const [usage, count] of inBundle) if (!attributed.has(usage)) found.push({ usage, count })\n return found\n}\n\n/** Counts each Node global usage, skipping any behind a `typeof` check like lodash's `typeof global == \"object\" && global.Object` */\nconst unguardedNodeGlobals = (code: string) => {\n const counts = new Map<string, number>()\n for (const match of code.matchAll(nodeGlobalPattern)) {\n const name = match[0].match(/process|global|Buffer|require|__dirname|__filename/)![0]\n const before = code.slice(Math.max(0, match.index! - 200), match.index)\n if (/typeof\\s+$/.test(before) || new RegExp(`typeof\\\\s+${name}\\\\b`).test(before)) continue\n const usage = match[0].replace(/\\s*\\($/, \"(\").replace(/\\s+/g, \" \")\n counts.set(usage, (counts.get(usage) ?? 0) + 1)\n }\n return counts\n}\n\n/** The shortest import path from the entry to every module it reaches */\nconst importChains = (\n entryID: string,\n getModuleInfo: (moduleID: string) => { importedIds: readonly string[]; dynamicallyImportedIds: readonly string[] } | null,\n) => {\n const chains = new Map([[entryID, [entryID]]])\n const queue = [entryID]\n for (let i = 0; i < queue.length; i++) {\n const info = getModuleInfo(queue[i])\n if (!info) continue\n for (const next of [...info.importedIds, ...info.dynamicallyImportedIds]) {\n if (chains.has(next)) continue\n chains.set(next, [...chains.get(queue[i])!, next])\n queue.push(next)\n }\n }\n return chains\n}\n\n/** Shortens module ids for messages: packages from node_modules by name, everything else relative to the root */\nconst describer = ({ root, chains }: BundleFacts) => {\n const module = (moduleID: string) => {\n const clean = moduleID.replace(/^\\0/, \"\").replace(/\\?.*$/, \"\")\n const afterNodeModules = lastOf(clean.split(\"/node_modules/\"))\n if (afterNodeModules !== clean) return afterNodeModules\n return path.isAbsolute(clean) ? path.relative(root, clean) : clean\n }\n return {\n module,\n chain: (moduleID: string) => (chains.get(moduleID) ?? [moduleID]).map(module).join(\" > \"),\n }\n}\n\n/** The npm package a module id comes from, or undefined outside node_modules */\nconst packageName = (moduleID: string) => {\n const parts = moduleID.split(\"/node_modules/\")\n if (parts.length < 2) return undefined\n const segments = lastOf(parts).split(\"/\")\n return segments[0].startsWith(\"@\") ? `${segments[0]}/${segments[1]}` : segments[0]\n}\n\nconst formatKB = (bytes: number) => `${Math.round(bytes / KB)}KB`\n\n/** The SDK targets ES2020, before `Array#at` */\nconst lastOf = (items: string[]) => items[items.length - 1]\n","import type { Plugin, ResolvedConfig } from \"vite\"\nimport { execFileSync } from \"child_process\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport { puzzmoLua } from \"./lua\"\n\nexport type PuzzmoPico8PluginOptions = {\n /** The cart, relative to the page. Defaults to the only `.p8` file in `cart/`. */\n cart?: string\n /** Where PICO-8's HTML export lives, relative to the page. Defaults to `export`. Commit it, so builds don't need PICO-8. */\n exportDir?: string\n /**\n * The PICO-8 binary used to re-export the cart when it changes. Defaults to `$PICO8`, then `pico8` on your PATH,\n * then where PICO-8's installers put it. When it can't be found the committed export is used as-is. Pass false to\n * never export.\n */\n pico8?: string | false\n /** Keep `puzzmo.lua` next to the cart up to date. Defaults to true. */\n writeLua?: boolean\n}\n\n/** @internal */\nexport type Pico8Game = {\n /** The directory holding the page */\n dir: string\n cart: string\n /** The cart's name, which PICO-8 also uses for its export */\n name: string\n exportHTML: string\n exportJS: string\n}\n\n/** @internal Finds the PICO-8 game served by the page in `dir`, if there is one. */\nexport function findPico8Game(dir: string, options: PuzzmoPico8PluginOptions = {}): Pico8Game | null {\n let cart: string | undefined\n if (options.cart) cart = path.resolve(dir, options.cart)\n else {\n const cartDir = path.join(dir, \"cart\")\n const carts = fs.existsSync(cartDir) ? fs.readdirSync(cartDir).filter((f) => f.endsWith(\".p8\")) : []\n if (carts.length > 1) throw new Error(`[puzzmo-pico8] found ${carts.length} carts in ${cartDir}, pick one with the \\`cart\\` option`)\n if (carts.length === 1) cart = path.join(cartDir, carts[0])\n }\n if (!cart || !fs.existsSync(cart)) return null\n const name = path.basename(cart, \".p8\")\n const exportDir = path.resolve(dir, options.exportDir ?? \"export\")\n return { dir, cart, name, exportHTML: path.join(exportDir, `${name}.html`), exportJS: path.join(exportDir, `${name}.js`) }\n}\n\n/**\n * @internal\n * Turns PICO-8's exported page into a Puzzmo game's page. PICO-8's shell is a thousand lines of globals and handlers\n * its runtime expects to find, and it changes between versions, so rather than keep a copy we adjust theirs.\n */\nexport function patchPico8Export(html: string, name: string, scripts: string[]): string {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\n // PICO-8 loads its runtime from a script element it builds itself. Point it at the copy we serve next to the page,\n // relative because Puzzmo serves games from a subfolder.\n const runtime = new RegExp(`((?:\\\\.src\\\\s*=\\\\s*|\\\\ssrc=)[\"'])[^\"']*${escaped}\\\\.js([\"'])`)\n if (!runtime.test(html)) throw new Error(`[puzzmo-pico8] couldn't find where PICO-8's page loads ${name}.js`)\n html = html.replace(runtime, `$1./${name}.js$2`)\n\n // Boot straight away. Otherwise the cart waits for a click on PICO-8's play button and the host never hears that\n // the game loaded. (Browsers which need a tap before audio can start, like iOS Safari, still show the button.)\n html = html.replace(/var\\s+p8_autoplay\\s*=\\s*false/, \"var p8_autoplay = true\")\n\n // The GPIO array, for shells old enough not to declare it themselves.\n if (!/var\\s+pico8_gpio\\s*=/.test(html)) html = html.replace(/<head>/i, \"<head>\\n<script>var pico8_gpio = new Array(128)</script>\")\n\n // Things a browser shrugs off and Vite doesn't: an HTML comment wrapped around the stylesheet, a stray\n // `-repeat center;` in it, and an `&nbsp` without its semicolon.\n html = html.replace(\n /(<style[^>]*>)([\\s\\S]*?)(<\\/style>)/gi,\n (_, open: string, css: string, close: string) =>\n open + css.replace(/<!--|-->/g, \"\").replace(/^[ \\t]*-repeat[^;\\n]*;[ \\t]*$/gm, \"\") + close,\n )\n html = html.replace(/&nbsp(?!;)/g, \"&nbsp;\")\n\n const bodyEnd = html.lastIndexOf(\"</body>\")\n if (bodyEnd === -1) throw new Error(\"[puzzmo-pico8] that doesn't look like a PICO-8 export, it has no </body>\")\n return html.slice(0, bodyEnd) + scripts.join(\"\\n\") + \"\\n\" + html.slice(bodyEnd)\n}\n\n/** Where PICO-8's own installers put it, for people who never added it to their PATH. */\nconst usualPico8Locations = [\n \"/Applications/PICO-8.app/Contents/MacOS/pico8\",\n \"C:\\\\Program Files (x86)\\\\PICO-8\\\\pico8.exe\",\n \"C:\\\\Program Files\\\\PICO-8\\\\pico8.exe\",\n]\n\n/** Finds an executable on the PATH without running it: `pico8` with no export arguments opens the whole app. */\nconst findExecutable = (bin: string): string | null => {\n if (bin.includes(\"/\") || bin.includes(\"\\\\\")) return fs.existsSync(bin) ? bin : null\n for (const dir of (process.env.PATH ?? \"\").split(path.delimiter)) {\n for (const ext of process.platform === \"win32\" ? [\".exe\", \".cmd\", \"\"] : [\"\"]) {\n const candidate = path.join(dir, bin + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n }\n if (bin === \"pico8\") return usualPico8Locations.find((p) => fs.existsSync(p)) ?? null\n return null\n}\n\nconst mtime = (file: string) => (fs.existsSync(file) ? fs.statSync(file).mtimeMs : 0)\n\n/**\n * Vite plugin for games written as PICO-8 carts. Your `index.html` only needs your own script tag, the plugin swaps\n * in PICO-8's exported page around it, serves the PICO-8 runtime next to it, and copies it into the build.\n *\n * When PICO-8 is installed it also re-exports the cart whenever it (or a `.lua` file next to it) changes, and reloads\n * the page, so saving in PICO-8 is enough to see the change in the simulator.\n */\nexport function puzzmoPico8(options: PuzzmoPico8PluginOptions = {}): Plugin {\n let config: ResolvedConfig\n const games = new Map<string, Pico8Game>()\n const binary = options.pico8 === false ? null : (options.pico8 ?? process.env.PICO8 ?? \"pico8\")\n\n const log = (message: string) => config.logger.info(`\\x1b[33m\\x1b[1m PICO-8 \\x1b[22m\\x1b[39m${message}`)\n\n const writeLua = (game: Pico8Game) => {\n if (options.writeLua === false) return\n const file = path.join(path.dirname(game.cart), \"puzzmo.lua\")\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === puzzmoLua) return\n fs.writeFileSync(file, puzzmoLua)\n log(`wrote ${path.relative(config.root, file)}`)\n }\n\n /** Re-exports the cart when it's newer than the export and PICO-8 is around to do it. */\n const exportIfStale = (game: Pico8Game) => {\n const cartDir = path.dirname(game.cart)\n const newest = Math.max(\n ...fs\n .readdirSync(cartDir)\n .filter((f) => /\\.(p8|lua)$/.test(f))\n .map((f) => mtime(path.join(cartDir, f))),\n )\n if (fs.existsSync(game.exportJS) && mtime(game.exportJS) >= newest) return\n\n const pico8 = binary ? findExecutable(binary) : null\n if (!pico8) {\n if (fs.existsSync(game.exportHTML)) {\n config.logger.warn(\n `[puzzmo-pico8] ${path.relative(config.root, game.cart)} is newer than its export, and PICO-8 isn't around to re-export it. Using the old export.`,\n )\n return\n }\n throw new Error(\n `[puzzmo-pico8] there's no export of ${path.relative(config.root, game.cart)} yet, and PICO-8 isn't on your PATH to make one.\\n` +\n `Export it inside PICO-8 with EXPORT ${game.name}.html into ${path.relative(config.root, path.dirname(game.exportHTML))}/, or set PICO8=/path/to/pico8.`,\n )\n }\n\n fs.mkdirSync(path.dirname(game.exportHTML), { recursive: true })\n const before = mtime(game.exportJS)\n let output = \"\"\n try {\n output = execFileSync(pico8, [game.cart, \"-export\", game.exportHTML], {\n encoding: \"utf8\",\n timeout: 60_000,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (error) {\n output = String((error as { stdout?: string }).stdout ?? error)\n }\n if (mtime(game.exportJS) === before) {\n const hint = /label/i.test(output) ? \"\\nHTML exports need a label: run the cart in PICO-8, press CTRL-7, and save.\" : \"\"\n throw new Error(`[puzzmo-pico8] PICO-8 didn't export ${path.relative(config.root, game.cart)}:\\n${output.trim()}${hint}`)\n }\n log(`exported ${path.relative(config.root, game.cart)}`)\n }\n\n const gameForPage = (htmlFile: string) => {\n const dir = path.dirname(htmlFile)\n if (!games.has(dir)) {\n const game = findPico8Game(dir, options)\n if (!game) return null\n games.set(dir, game)\n }\n return games.get(dir)!\n }\n\n return {\n name: \"puzzmo-pico8\",\n\n config() {\n // The export is rewritten on every save, and Vite reloads the page for any .html it sees change. The plugin\n // reloads once the export is done, so Vite reloading too would boot the cart twice.\n const exportDir = options.exportDir ?? \"export\"\n const isExport = (file: string) =>\n /\\.(html|js)$/.test(file) &&\n path.basename(path.dirname(file)) === path.basename(exportDir) &&\n fs.existsSync(path.join(path.dirname(path.dirname(file)), \"cart\"))\n return { server: { watch: { ignored: [isExport] } } }\n },\n\n configResolved(resolved) {\n config = resolved\n },\n\n transformIndexHtml: {\n order: \"pre\",\n handler(html, ctx) {\n const game = gameForPage(ctx.filename)\n if (!game) return\n writeLua(game)\n exportIfStale(game)\n // Keep the page's own module scripts: that's the game code.\n const scripts = html.match(/<script\\b[^>]*type=[\"']module[\"'][^>]*>[\\s\\S]*?<\\/script>/gi) ?? []\n return patchPico8Export(fs.readFileSync(game.exportHTML, \"utf8\"), game.name, scripts)\n },\n },\n\n configureServer(devServer) {\n // Serve the runtime next to the page, untouched by Vite's transforms: it is a megabyte of emscripten output\n // which only works exactly as PICO-8 wrote it.\n devServer.middlewares.use((req, res, next) => {\n const url = decodeURIComponent((req.url ?? \"\").split(\"?\")[0])\n if (!url.endsWith(\".js\")) return next()\n const game = [...games.values()].find(\n (g) =>\n url ===\n \"/\" +\n path\n .relative(config.root, path.join(g.dir, `${g.name}.js`))\n .split(path.sep)\n .join(\"/\"),\n )\n if (!game || !fs.existsSync(game.exportJS)) return next()\n res.setHeader(\"Content-Type\", \"text/javascript\")\n res.end(fs.readFileSync(game.exportJS))\n })\n\n // Saving the cart in PICO-8 re-exports it and reloads the page.\n devServer.watcher.on(\"change\", (file) => {\n const game = [...games.values()].find((g) => path.dirname(file) === path.dirname(g.cart) && /\\.(p8|lua)$/.test(file))\n if (!game || path.basename(file) === \"puzzmo.lua\") return\n try {\n exportIfStale(game)\n devServer.ws.send({ type: \"full-reload\" })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n config.logger.error(message)\n devServer.ws.send({ type: \"error\", err: { message, stack: \"\" } })\n }\n })\n },\n\n generateBundle() {\n for (const game of games.values()) {\n const fileName = path\n .relative(config.root, path.join(game.dir, `${game.name}.js`))\n .split(path.sep)\n .join(\"/\")\n this.emitFile({ type: \"asset\", fileName, source: fs.readFileSync(game.exportJS) })\n }\n },\n }\n}\n","import type { Plugin, ResolvedConfig } from \"vite\"\nimport { build } from \"vite\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport { bundleChecks, pageBundleLimits, type BundleLimits } from \"./bundleChecks\"\nimport type { HostContext } from \"./types\"\nimport type { HostContextPreset, SimulatorIntegrations } from \"./simulator/types\"\n\nexport { puzzmoPico8, type PuzzmoPico8PluginOptions } from \"./pico8/vitePlugin\"\n\nexport type PuzzmoSimulatorPluginOptions = {\n /** Whether to auto-start the game after READY (default: true) */\n autoStart?: boolean\n /** Initial collapsed state (default: true) */\n collapsed?: boolean\n /**\n * Glob pattern for fixture files, passed to import.meta.glob which is relative to the closest puzzmo.json. Defaults\n * to `\"/fixtures/puzzles/**\\/*.{json,toml}\"`. Fixtures are loaded as raw strings (any text format works — JSON,\n * TOML, or a custom format) and delivered to the game verbatim, so the game parses them itself. Pass false to disable.\n */\n fixturesGlob?: string | false\n /**\n * Whether READY_DATA carries a play session (default: true). Set to false to run the game the way\n * a host will for a mode with no puzzle. Ignored for games built on an SDK from before runtime contract \"1.1\".\n */\n session?: boolean\n /**\n * The `hostContext` array the simulator sends in READY_DATA, so host-context-dependent features\n * (embed settings, sandbox mode, mobile layout, …) can be exercised locally. Must be\n * JSON-serializable. Defaults to a single desktop \"app\" context; the simulator's Host tab can\n * override it at runtime (persisted per-browser, applied on restart).\n *\n * @internal\n */\n hostContext?: HostContext[]\n /**\n * Extra named `hostContext` presets for the simulator's Host tab, alongside the generic\n * built-ins — how a game ships its own scenarios (e.g. crossword's partner-embed toolbar\n * settings). Must be JSON-serializable.\n *\n * @internal\n */\n hostContextPresets?: HostContextPreset[]\n /**\n * Plugin-provided simulator tabs, named rather than passed directly because this config is\n * serialized into a virtual module. Each entry is imported and called with no arguments, so the\n * export must be a `() => SimulatorView` factory — e.g.\n * `{ module: \"@puzzmo-com/shared/sdkPlugins\", export: \"createCollabSimulatorView\" }`.\n */\n viewFactories?: { module: string; export: string }[]\n}\n\nconst simulatorURL = \"/@puzzmo-simulator-init.js\"\nconst virtualID = \"virtual:puzzmo-simulator\"\n\n/** @internal */\nexport type GameInfo = {\n /** Directory containing the puzzmo.json */\n dir: string\n slug: string\n displayName: string\n /** Vite-root-relative path to app bundle entry, if it exists */\n appBundlePath: string | null\n /** Vite-root-relative path to the pmmg bundle entry, if it exists, for the simulator's Pmmg tab */\n pmmgBundlePath?: string | null\n /** `integrations` from the puzzmo.json, passed to simulator tabs that preview them */\n integrations?: SimulatorIntegrations\n}\n\n/**\n * Discover all games from puzzmo.json files under a root directory.\n *\n * @internal\n */\nexport function discoverGames(viteRoot: string): Map<string, GameInfo> {\n const games = new Map<string, GameInfo>()\n const candidates = findPuzzmoJsonDirs(viteRoot, 3)\n if (fs.existsSync(path.join(viteRoot, \"puzzmo.json\"))) {\n candidates.unshift(viteRoot)\n }\n for (const dir of candidates) {\n try {\n const data = JSON.parse(fs.readFileSync(path.join(dir, \"puzzmo.json\"), \"utf-8\"))\n if (!data?.game?.slug) continue\n const integrations = data.integrations && typeof data.integrations === \"object\" ? data.integrations : undefined\n games.set(data.game.slug, {\n dir,\n slug: data.game.slug,\n displayName: data.game.displayName,\n appBundlePath: viteRootPath(viteRoot, resolveBundleEntry(dir, \"src/appBundle\")),\n pmmgBundlePath: viteRootPath(viteRoot, resolveBundleEntry(dir, \"src/pmmgBundle\")),\n integrations,\n })\n } catch {\n // skip invalid files\n }\n }\n return games\n}\n\n/**\n * Resolve which game a request belongs to using the referer URL.\n *\n * @internal\n */\nexport function resolveGameFromReferer(referer: string | undefined, games: Map<string, GameInfo>, viteRoot: string): GameInfo | undefined {\n if (referer) {\n try {\n const refPath = new URL(referer).pathname\n for (const g of games.values()) {\n const relDir = \"/\" + path.relative(viteRoot, g.dir).split(path.sep).join(\"/\")\n if (refPath.startsWith(relDir + \"/\") || refPath === relDir) return g\n }\n } catch {\n // ignore malformed referer\n }\n }\n if (games.size === 1) return games.values().next().value\n return undefined\n}\n\n/**\n * Generate the virtual module code for the simulator.\n *\n * @internal\n */\nexport function generateSimulatorCode(options: PuzzmoSimulatorPluginOptions, game: GameInfo | undefined): string {\n const { fixturesGlob: fixturesOpt, viewFactories, ...config } = options\n const fixturesGlob = fixturesOpt === false ? null : (fixturesOpt ?? \"/fixtures/puzzles/**/*.{json,toml}\")\n\n const lines = [`import { createSimulator } from \"@puzzmo/sdk/simulator\"`]\n for (const view of viewFactories ?? []) {\n lines.push(`import { ${view.export} } from ${JSON.stringify(view.module)}`)\n }\n\n // Load fixtures as raw strings so any text format reaches the game verbatim; the game does its own parsing.\n if (fixturesGlob) {\n lines.push(`const fixtures = import.meta.glob(${JSON.stringify(fixturesGlob)}, { query: \"?raw\", import: \"default\", eager: true })`)\n }\n\n if (game?.appBundlePath) {\n lines.push(`import(${JSON.stringify(game.appBundlePath)}).then(m => {`)\n lines.push(` if (m.renderThumbnail) globalThis.renderThumbnail = m.renderThumbnail`)\n lines.push(` if (m.getShareString) globalThis.getShareString = m.getShareString`)\n lines.push(`}).catch(() => {})`)\n }\n\n const simConfig = {\n ...config,\n ...(game?.slug ? { slug: game.slug } : {}),\n ...(game?.integrations ? { integrations: game.integrations } : {}),\n }\n const configEntries = Object.entries(simConfig).filter(([, v]) => v !== undefined)\n const configParts = configEntries.map(([k, v]) => `${k}: ${JSON.stringify(v)}`)\n if (fixturesGlob) configParts.push(\"fixtures\")\n // Loaded when the Pmmg tab opens, so a game page that never looks at it never imports it\n if (game?.pmmgBundlePath) configParts.push(`pmmgBundle: () => import(${JSON.stringify(game.pmmgBundlePath)})`)\n if (viewFactories?.length) configParts.push(`views: [${viewFactories.map((v) => `${v.export}()`).join(\", \")}]`)\n\n lines.push(`createSimulator({ ${configParts.join(\", \")} })`)\n\n return lines.join(\"\\n\")\n}\n\n/** Vite plugin that injects the Puzzmo simulator in dev mode and handles OAuth callbacks. */\nexport function puzzmoSimulator(options: PuzzmoSimulatorPluginOptions = {}): Plugin {\n let games = new Map<string, GameInfo>()\n let viteRoot: string\n\n return {\n name: \"puzzmo-simulator\",\n apply: \"serve\",\n\n configResolved(config: ResolvedConfig) {\n viteRoot = config.root\n games = discoverGames(viteRoot)\n\n if (games.size === 0) {\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m\\x1b[2m no puzzmo.json files found\\x1b[22m`)\n } else {\n const names = [...games.values()].map((g) => `\\x1b[36m${g.slug}\\x1b[39m`)\n const label = games.size === 1 ? \"game\" : \"games\"\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m found ${games.size} ${label}: ${names.join(\"\\x1b[2m, \\x1b[22m\")}`)\n }\n },\n\n resolveId(id) {\n if (id === virtualID || id.startsWith(virtualID + \"?\")) return \"\\0\" + id\n },\n\n load(id) {\n if (!id.startsWith(\"\\0\" + virtualID)) return\n const params = new URLSearchParams(id.split(\"?\")[1] || \"\")\n const gameSlug = params.get(\"game\")\n const game = gameSlug ? games.get(gameSlug) : games.size === 1 ? games.values().next().value : undefined\n return generateSimulatorCode(options, game)\n },\n\n configureServer(server) {\n // Re-read puzzmo.json on edit and reload the page so the simulator picks up its changes\n for (const g of games.values()) server.watcher.add(path.join(g.dir, \"puzzmo.json\"))\n server.watcher.on(\"change\", (file) => {\n if (path.basename(file) !== \"puzzmo.json\") return\n games = discoverGames(viteRoot)\n for (const mod of server.moduleGraph.idToModuleMap.values()) {\n if (mod.id?.startsWith(\"\\0\" + virtualID)) server.moduleGraph.invalidateModule(mod)\n }\n server.ws.send({ type: \"full-reload\" })\n })\n\n server.middlewares.use(\"/oauth/callback\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"text/html\")\n res.end(`<!DOCTYPE html>\n<html><head><title>Puzzmo OAuth</title></head>\n<body><script>\nvar params = new URLSearchParams(window.location.search);\nvar returnUrl = sessionStorage.getItem(\"oauth_return_url\") || \"/\";\nvar url = new URL(returnUrl);\nparams.forEach(function(v, k) { url.searchParams.set(k, v); });\nwindow.location.href = url.toString();\n</script></body></html>`)\n })\n\n // Serve the simulator init module, resolving the game from the referer\n server.middlewares.use(async (req, res, next) => {\n if (req.url?.split(\"?\")[0] !== simulatorURL) return next()\n\n const game = resolveGameFromReferer(req.headers.referer, games, viteRoot)\n const moduleID = virtualID + (game ? `?game=${game.slug}` : \"\")\n const result = await server.transformRequest(moduleID)\n if (!result) return next()\n res.setHeader(\"Content-Type\", \"application/javascript\")\n res.end(result.code)\n })\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: { type: \"module\", src: simulatorURL },\n injectTo: \"head\",\n },\n ]\n },\n }\n}\n\ntype BundlePluginOptions = {\n /** Entry file for the bundle */\n entry: string\n /** Output file name */\n outputFile: string\n /** Folder the bundle is written to */\n outDir: string\n}\n\nfunction createBundlePlugin(pluginName: string, defaults: BundlePluginOptions, limits: BundleLimits = {}) {\n return (options: Partial<BundlePluginOptions> = {}): Plugin => {\n const { entry, outputFile, outDir } = { ...defaults, ...options }\n const fileName = path.relative(process.cwd(), path.resolve(outDir, outputFile))\n return {\n name: pluginName,\n apply: \"build\",\n async closeBundle() {\n // If the caller overrode `entry`, honor it as-is. Otherwise try `.js` first, then `.ts`.\n const resolvedEntry = options.entry\n ? path.isAbsolute(entry)\n ? entry\n : path.resolve(process.cwd(), entry)\n : (resolveBundleEntry(process.cwd(), stripBundleExt(entry)) ?? path.resolve(process.cwd(), entry))\n const checks = bundleChecks(fileName, limits)\n try {\n await build({\n configFile: false,\n logLevel: \"warn\",\n define: bundleDefine,\n plugins: [checks],\n build: {\n lib: {\n entry: resolvedEntry,\n formats: [\"es\"],\n fileName: () => outputFile,\n },\n outDir,\n emptyOutDir: false,\n },\n })\n } catch (error) {\n // A failed check explains itself, so it goes up alone rather than inside rolldown's stack\n if (checks.api.failure) throw messageOnlyError(`[${pluginName}] ${checks.api.failure}`)\n console.error(`[${pluginName}] build failed:`, error)\n throw error\n }\n },\n }\n }\n}\n\n/** Strip the trailing extension from a default entry path so we can probe siblings. */\nconst stripBundleExt = (p: string) => p.replace(/\\.[jt]sx?$/i, \"\")\n\n/** An absolute file as the path the dev server serves it at, or null for no file */\nconst viteRootPath = (viteRoot: string, file: string | null) =>\n file ? \"/\" + path.relative(viteRoot, file).split(path.sep).join(\"/\") : null\n\n/** Returns the absolute path to the first matching extension under `dir`, or null. */\nconst resolveBundleEntry = (dir: string, baseRelative: string): string | null => {\n // JSX last: a bundle written as JSX still needs the plain entry to win if both somehow exist.\n for (const ext of [\".js\", \".ts\", \".tsx\", \".jsx\"]) {\n const candidate = path.join(dir, baseRelative + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n return null\n}\n\nexport type AppBundlePluginOptions = {\n /** Entry file for the app bundle (default: `src/appBundle.js`) */\n entry?: string\n /** Output file name (default: `app-bundle.js`) */\n outputFile?: string\n}\n\n/**\n * Vite plugin that produces dist/app-bundle.js after the main build for app-level integrations.\n *\n * The bundle exports `renderThumbnail(puzzleString, inputString?, config?)` — a pure renderer\n * returning the SVG and its dimensions (`{ svg, width, height }`), used by the Puzzmo\n * platform for puzzle previews.\n */\nexport const appBundlePlugin = createBundlePlugin(\n \"app-bundle\",\n { entry: \"src/appBundle.js\", outputFile: \"app-bundle.js\", outDir: \"dist\" },\n pageBundleLimits(\"Puzzmo's pages wherever the game's thumbnails show\"),\n)\n\nexport type ServerBundlePluginOptions = {\n /** Entry file for the server bundle (default: `src/serverBundle.js`, or `.ts`) */\n entry?: string\n /** Output file name (default: `server-bundle.js`) */\n outputFile?: string\n}\n\n/**\n * Vite plugin that produces dist-server/server-bundle.js after the main build: the game's private\n * server bundle (see `ServerBundle`). It goes in its own folder, never `dist`, so it can't be served to\n * players by mistake; `puzzmo games upload` finds it there and sends it to Puzzmo privately. A repo that\n * builds several games gives each its own `outputFile` and names it in that game's puzzmo.json as\n * `output.serverBundle`, since uploads refuse to send one file for more than one game.\n */\nexport const serverBundlePlugin = createBundlePlugin(\"server-bundle\", {\n entry: \"src/serverBundle.js\",\n outputFile: \"server-bundle.js\",\n outDir: \"dist-server\",\n})\n\nexport type PmmgBundlePluginOptions = {\n /** Entry file for the pmmg bundle (default: `src/pmmgBundle.js`, or `.ts`) */\n entry?: string\n /** Output file name (default: `pmmg-bundle.js`) */\n outputFile?: string\n}\n\nconst buildPmmgBundle = createBundlePlugin(\n \"pmmg-bundle\",\n { entry: \"src/pmmgBundle.js\", outputFile: \"pmmg-bundle.js\", outDir: \"dist\" },\n pageBundleLimits(\"Puzzmo's pages for every board at the table\"),\n)\n\n/**\n * Vite plugins for the game's pmmg bundle (see `PmmgBundle`), such as its boards at the table. After the main build\n * they produce dist/pmmg-bundle.js, which is public and served with the rest of `dist`. In dev, `/pmmg-bundle.js` on\n * the game's dev server is built from source on each request, so a Puzzmo page running with `?dev` draws boards from\n * the code being worked on.\n *\n * Puzzmo imports it from an opaque-origin sandbox, so that one response answers any origin. It's a whole build rather\n * than the dev server's modules, since letting `Origin: null` read those would let any page read the game's source.\n */\nexport const pmmgBundlePlugin = (options: PmmgBundlePluginOptions = {}): Plugin[] => [\n buildPmmgBundle(options),\n {\n name: \"pmmg-bundle-dev\",\n apply: \"serve\",\n configureServer(server) {\n // Requests that arrive while a build runs share it\n let building: Promise<string> | undefined\n server.middlewares.use((req, res, next) => {\n if (!/^\\/pmmg-bundle\\.js(?:\\?.*)?$/.test(req.url || \"\")) return next()\n const entry = options.entry ?? resolveBundleEntry(server.config.root, \"src/pmmgBundle\")\n if (!entry) return next()\n building ??= buildPmmgBundleSource(path.resolve(server.config.root, entry)).finally(() => (building = undefined))\n building.then(\n (code) => {\n res.setHeader(\"Content-Type\", \"text/javascript\")\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\")\n res.setHeader(\"Cache-Control\", \"no-store\")\n res.end(code)\n },\n (error) => {\n server.config.logger.error(`[pmmg-bundle] build failed: ${error?.message ?? error}`)\n res.statusCode = 500\n res.end()\n },\n )\n })\n },\n },\n]\n\n/** The pmmg bundle built as production builds it, as one file's source for the dev route */\nexport const buildPmmgBundleSource = async (entry: string): Promise<string> => {\n const result = await build({\n configFile: false,\n logLevel: \"warn\",\n define: bundleDefine,\n build: {\n write: false,\n copyPublicDir: false,\n minify: false,\n sourcemap: \"inline\",\n lib: { entry, formats: [\"es\"], fileName: () => \"pmmg-bundle.js\" },\n // One file, as the route serves only the one\n rolldownOptions: { output: { codeSplitting: false } },\n },\n })\n const outputs = Array.isArray(result) ? result : \"output\" in result ? [result] : []\n const chunk = outputs.flatMap((output) => output.output).find((file) => file.type === \"chunk\" && file.isEntry)\n if (!chunk || chunk.type !== \"chunk\") throw new Error(`Building ${entry} made no bundle`)\n return chunk.code\n}\n\nexport type EditorBundlePluginOptions = {\n /** Entry file for the editor bundle (default: `src/editorBundle.js`) */\n entry?: string\n /** Output file name (default: `editor-bundle.js`) */\n outputFile?: string\n}\n\n/** Vite plugin that produces dist/editor-bundle.js after the main build for editor-level integrations. */\nexport const editorBundlePlugin = createBundlePlugin(\"editor-bundle\", {\n entry: \"src/editorBundle.js\",\n outputFile: \"editor-bundle.js\",\n outDir: \"dist\",\n})\n\n/**\n * Recursively find directories containing puzzmo.json, up to `maxDepth` levels deep.\n *\n * @internal\n */\nexport const findPuzzmoJsonDirs = (root: string, maxDepth: number, depth = 0): string[] => {\n if (depth >= maxDepth) return []\n const results: string[] = []\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(root, { withFileTypes: true })\n } catch {\n return results\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue\n const dir = path.join(root, entry.name)\n if (fs.existsSync(path.join(dir, \"puzzmo.json\"))) {\n results.push(dir)\n }\n results.push(...findPuzzmoJsonDirs(dir, maxDepth, depth + 1))\n }\n return results\n}\n\n/**\n * Lib mode leaves `process.env.*` for a consumer's bundler to replace, but these bundles are run as-is in browsers and\n * isolates with no `process`, so a dependency's `NODE_ENV` check (immer, reselect, React) would throw on load\n */\nconst bundleDefine = { \"process.env.NODE_ENV\": JSON.stringify(\"production\") }\n\n/** An error whose stack is only its message, for a failure the bundler's internals add nothing to */\nconst messageOnlyError = (message: string) => Object.assign(new Error(message), { stack: message })\n"],"mappings":";;;;;;;;AA6BA,IAAM,IAAK;;AAGX,MAAa,KAAoB,OAAoC;CACnE;CACA,WAAW,MAAM;CACjB,UAAU,MAAM;CAChB,gBAAgB;EAAC;EAAS;EAAa;EAAa;EAAS;EAAe;EAAmB;CAChG,GAMY,KAAe,GAAoB,MAAyB;;CACvE,IAAM,IAAmB,EAAE,EACrB,IAAqB,EAAE,EACvB,IAAW,EAAU,EAAM,EAE3B,IAAO,OAAO,WAAW,EAAM,KAAK,EACpC,IAAU,EAAO,aAAa,KAAA,KAAa,IAAO,EAAO,UACzD,IAAW,EAAO,cAAc,KAAA,KAAa,IAAO,EAAO;AACjE,KAAI,KAAW,GAAU;EACvB,IAAM,IAAQ,IAAU,EAAO,WAAY,EAAO,WAC5C,IAAQ,EAAO,WAAW,2BAA2B,EAAO,aAAa,IACzE,IAAU,OAAO,QAAQ,EAAM,QAAQ,CAC1C,MAAM,GAAG,IAAI,GAAG,OAAO,EAAE,OAAO,EAAE,KAAK,CACvC,MAAM,GAAG,EAAE,CACX,KACE,CAAC,GAAU,EAAE,eA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AS,EAAM,SAAS,QAAS,OAAU,MAAM,YAAY,EAAM,iBAAiB;AACzF,SAAO,EAAM;;iBAlB6B,GAAA;;;KA6B/B,IAAqB,EAAmB,iBAAiB;CACpE,OAAO;CACP,YAAY;CACZ,QAAQ;CACT,CAAC,EAOW,KAAsB,GAAc,GAAkB,IAAQ,MAAgB;AACzF,KAAI,KAAS,EAAU,QAAO,EAAE;CAChC,IAAM,IAAoB,EAAE,EACxB;AACJ,KAAI;AACF,MAAU,EAAG,YAAY,GAAM,EAAE,eAAe,IAAM,CAAC;aACjD;AACN,SAAO;;AAET,MAAK,IAAM,KAAS,GAAS;AAC3B,MAAI,CAAC,EAAM,aAAa,IAAI,EAAM,KAAK,WAAW,IAAI,IAAI,EAAM,SAAS,eAAgB;EACzF,IAAM,IAAM,EAAK,KAAK,GAAM,EAAM,KAAK;AAIvC,EAHI,EAAG,WAAW,EAAK,KAAK,GAAK,cAAc,CAAC,IAC9C,EAAQ,KAAK,EAAI,EAEnB,EAAQ,KAAK,GAAG,EAAmB,GAAK,GAAU,IAAQ,EAAE,CAAC;;AAE/D,QAAO;;;;;;AAOT,IAAM,IAAe,EAAE,wBAAwB,KAAK,UAAU,aAAa,EAAE,EAGvE,KAAoB,MAAoB,OAAO,OAAW,MAAM,EAAQ,EAAE,EAAE,OAAO,GAAS,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@puzzmo/sdk",
3
- "version": "1.0.82",
3
+ "version": "1.0.84",
4
4
  "description": "Puzzmo runtime SDK for game developers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",