@puzzmo/sdk 1.0.82 → 1.0.83

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.
@@ -0,0 +1,48 @@
1
+ import type { Plugin } from "vite";
2
+ /** What a bundle's build holds it to, as each bundle runs somewhere different */
3
+ export type BundleLimits = {
4
+ /** Where the bundle loads, finishing "over the limit for a bundle loaded on ..." */
5
+ loadedOn?: string;
6
+ /** Warns past this many bytes */
7
+ warnBytes?: number;
8
+ /** Fails the build past this many bytes */
9
+ maxBytes?: number;
10
+ /** Packages that fail the build when any of their modules is bundled */
11
+ bannedPackages?: string[];
12
+ };
13
+ /** What `checkBundle` reads from a finished build */
14
+ export type BundleFacts = {
15
+ /** The bundle's file as messages name it */
16
+ fileName: string;
17
+ /** The bundle's final code */
18
+ code: string;
19
+ /** Each bundled module by id: its rendered bytes, and its code before minifying */
20
+ modules: Record<string, {
21
+ size: number;
22
+ code: string | null;
23
+ }>;
24
+ /** The imports leading from the entry to each module, entry first */
25
+ chains: Map<string, string[]>;
26
+ /** Paths in messages are relative to this */
27
+ root: string;
28
+ };
29
+ /** The limits for a bundle Puzzmo loads into its own pages, where every byte is on a player's page load */
30
+ export declare const pageBundleLimits: (loadedOn: string) => BundleLimits;
31
+ /**
32
+ * Checks a built bundle: errors fail the build (too big, or a banned package), warnings flag likely mistakes (Node
33
+ * globals, which browsers and isolates don't have).
34
+ */
35
+ export declare const checkBundle: (facts: BundleFacts, limits: BundleLimits) => {
36
+ errors: string[];
37
+ warnings: string[];
38
+ };
39
+ /**
40
+ * Runs `checkBundle` inside a bundle's own build. Warnings go to the build's logger, and errors fail it, kept on
41
+ * `api.failure` so the caller can report them without the bundler's stack.
42
+ */
43
+ export declare const bundleChecks: (fileName: string, limits: BundleLimits) => Plugin & {
44
+ api: {
45
+ failure?: string;
46
+ };
47
+ };
48
+ //# sourceMappingURL=bundleChecks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundleChecks.d.ts","sources":["../src/bundleChecks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAElC,iFAAiF;AACjF,MAAM,MAAM,YAAY,GAAG;IACzB,oFAAoF;IACpF,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,iCAAiC;IACjC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,2CAA2C;IAC3C,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,wEAAwE;IACxE,cAAc,CAAC,EAAE,MAAM,EAAE,CAAA;CAC1B,CAAA;AAED,qDAAqD;AACrD,MAAM,MAAM,WAAW,GAAG;IACxB,4CAA4C;IAC5C,QAAQ,EAAE,MAAM,CAAA;IAChB,8BAA8B;IAC9B,IAAI,EAAE,MAAM,CAAA;IACZ,mFAAmF;IACnF,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAAA;IAC9D,qEAAqE;IACrE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAA;IAC7B,6CAA6C;IAC7C,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAID,2GAA2G;AAC3G,eAAO,MAAM,gBAAgB,aAAc,MAAM,KAAG,YAKlD,CAAA;AAEF;;;GAGG;AACH,eAAO,MAAM,WAAW,UAAW,WAAW,UAAU,YAAY;;;CA4CnE,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,YAAY,aAAc,MAAM,UAAU,YAAY,KAAG,MAAM,GAAG;IAAE,GAAG,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAyBzG,CAAA"}
package/dist/vite.cjs CHANGED
@@ -1,9 +1,13 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-350yNsax.cjs`),t=require(`./objectWithoutProperties-CL_8JSCP.cjs`),n=require(`./objectSpread2-BU9HzoRm.cjs`),r=require(`./asyncToGenerator-Tjg_Hpik.cjs`),i=require(`./lua-C5r7UXeR.cjs`);let a=require(`vite`),o=require(`path`);o=e.n(o);let s=require(`fs`);s=e.n(s);let c=require(`child_process`);function l(e,t={}){var n;let r;if(t.cart)r=o.default.resolve(e,t.cart);else{let t=o.default.join(e,`cart`),n=s.default.existsSync(t)?s.default.readdirSync(t).filter(e=>e.endsWith(`.p8`)):[];if(n.length>1)throw Error(`[puzzmo-pico8] found ${n.length} carts in ${t}, pick one with the \`cart\` option`);n.length===1&&(r=o.default.join(t,n[0]))}if(!r||!s.default.existsSync(r))return null;let i=o.default.basename(r,`.p8`),a=o.default.resolve(e,(n=t.exportDir)==null?`export`:n);return{dir:e,cart:r,name:i,exportHTML:o.default.join(a,`${i}.html`),exportJS:o.default.join(a,`${i}.js`)}}function u(e,t,n){let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=RegExp(`((?:\\.src\\s*=\\s*|\\ssrc=)["'])[^"']*${r}\\.js(["'])`);if(!i.test(e))throw Error(`[puzzmo-pico8] couldn't find where PICO-8's page loads ${t}.js`);e=e.replace(i,`$1./${t}.js$2`),e=e.replace(/var\s+p8_autoplay\s*=\s*false/,`var p8_autoplay = true`),/var\s+pico8_gpio\s*=/.test(e)||(e=e.replace(/<head>/i,`<head>
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-350yNsax.cjs`),t=require(`./objectWithoutProperties-CL_8JSCP.cjs`),n=require(`./objectSpread2-BU9HzoRm.cjs`),r=require(`./asyncToGenerator-Tjg_Hpik.cjs`),i=require(`./lua-C5r7UXeR.cjs`);let a=require(`vite`),o=require(`path`);o=e.n(o);let s=require(`fs`);s=e.n(s);let c=require(`child_process`);var l=1024;const u=e=>({loadedOn:e,warnBytes:200*l,maxBytes:500*l,bannedPackages:[`react`,`react-dom`,`scheduler`,`redux`,`react-redux`,`@reduxjs/toolkit`]}),d=(e,t)=>{var n;let r=[],i=[],a=_(e),o=Buffer.byteLength(e.code),s=t.maxBytes!==void 0&&o>t.maxBytes,c=t.warnBytes!==void 0&&o>t.warnBytes;if(s||c){let n=s?t.maxBytes:t.warnBytes,c=t.loadedOn?` for a bundle loaded on ${t.loadedOn}`:``,l=Object.entries(e.modules).sort(([,e],[,t])=>t.size-e.size).slice(0,5).map(([e,{size:t}])=>` ${y(t).padStart(7)} ${a.module(e)}\n ${a.chain(e)}`),u=`${e.fileName} is ${y(o)}, over the ${y(n)} limit${c}. Its largest modules:\n${l.join(`
2
+ `)}`;(s?r:i).push(u)}let l=new Set((n=t.bannedPackages)==null?[]:n),u=new Set;for(let t of Object.keys(e.modules)){let n=v(t);!n||!l.has(n)||u.has(n)||(u.add(n),r.push(`${n} can't be in ${e.fileName}, as Puzzmo calls it for strings and data. Imported by:\n ${a.chain(t)}`))}let d=m(e.code,e.modules);if(d.length){let t=d.map(({usage:e,count:t,moduleID:n})=>{let r=t>1?` (x${t})`:``;return n?` ${e}${r} in ${a.module(n)}\n ${a.chain(n)}`:` ${e}${r}`});i.push(`${e.fileName} uses Node globals, which don't exist where Puzzmo runs it, so each throws if reached:\n${t.join(`
3
+ `)}`)}return{errors:r,warnings:i}},f=(e,t)=>{let n=process.cwd(),r={};return{name:`puzzmo-bundle-checks`,api:r,configResolved(e){n=e.root},generateBundle(i,a){let o=Object.values(a).find(e=>e.type===`chunk`&&e.isEntry);if((o==null?void 0:o.type)!==`chunk`||!o.facadeModuleId)return;let s=Object.fromEntries(Object.entries(o.modules).map(([e,t])=>[e,{size:t.renderedLength,code:t.code}])),c=g(o.facadeModuleId,e=>this.getModuleInfo(e)),{errors:l,warnings:u}=d({fileName:e,code:o.code,modules:s,chains:c,root:n},t);for(let e of u)this.warn(e);l.length&&(r.failure=l.join(`
4
+
5
+ `),this.error(r.failure))}}};var p=RegExp(`(?<![\\w$.])(?:(?:process|global|Buffer)(?:\\.[\\w$]+){1,2}|require\\s*\\(|new\\s+Buffer\\s*\\(|__dirname\\b|__filename\\b)`,`g`),m=(e,t)=>{let n=h(e),r=[];for(let[e,i]of Object.entries(t))if(i.code)for(let[t,a]of h(i.code))n.has(t)&&r.push({usage:t,count:a,moduleID:e});let i=new Set(r.map(({usage:e})=>e));for(let[e,t]of n)i.has(e)||r.push({usage:e,count:t});return r},h=e=>{let t=new Map;for(let r of e.matchAll(p)){var n;let i=r[0].match(/process|global|Buffer|require|__dirname|__filename/)[0],a=e.slice(Math.max(0,r.index-200),r.index);if(/typeof\s+$/.test(a)||RegExp(`typeof\\s+${i}\\b`).test(a))continue;let o=r[0].replace(/\s*\($/,`(`).replace(/\s+/g,` `);t.set(o,((n=t.get(o))==null?0:n)+1)}return t},g=(e,t)=>{let n=new Map([[e,[e]]]),r=[e];for(let e=0;e<r.length;e++){let i=t(r[e]);if(i)for(let t of[...i.importedIds,...i.dynamicallyImportedIds])n.has(t)||(n.set(t,[...n.get(r[e]),t]),r.push(t))}return n},_=({root:e,chains:t})=>{let n=t=>{let n=t.replace(/^\0/,``).replace(/\?.*$/,``),r=b(n.split(`/node_modules/`));return r===n?o.default.isAbsolute(n)?o.default.relative(e,n):n:r};return{module:n,chain:e=>{var r;return((r=t.get(e))==null?[e]:r).map(n).join(` > `)}}},v=e=>{let t=e.split(`/node_modules/`);if(t.length<2)return;let n=b(t).split(`/`);return n[0].startsWith(`@`)?`${n[0]}/${n[1]}`:n[0]},y=e=>`${Math.round(e/l)}KB`,b=e=>e[e.length-1];function x(e,t={}){var n;let r;if(t.cart)r=o.default.resolve(e,t.cart);else{let t=o.default.join(e,`cart`),n=s.default.existsSync(t)?s.default.readdirSync(t).filter(e=>e.endsWith(`.p8`)):[];if(n.length>1)throw Error(`[puzzmo-pico8] found ${n.length} carts in ${t}, pick one with the \`cart\` option`);n.length===1&&(r=o.default.join(t,n[0]))}if(!r||!s.default.existsSync(r))return null;let i=o.default.basename(r,`.p8`),a=o.default.resolve(e,(n=t.exportDir)==null?`export`:n);return{dir:e,cart:r,name:i,exportHTML:o.default.join(a,`${i}.html`),exportJS:o.default.join(a,`${i}.js`)}}function S(e,t,n){let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=RegExp(`((?:\\.src\\s*=\\s*|\\ssrc=)["'])[^"']*${r}\\.js(["'])`);if(!i.test(e))throw Error(`[puzzmo-pico8] couldn't find where PICO-8's page loads ${t}.js`);e=e.replace(i,`$1./${t}.js$2`),e=e.replace(/var\s+p8_autoplay\s*=\s*false/,`var p8_autoplay = true`),/var\s+pico8_gpio\s*=/.test(e)||(e=e.replace(/<head>/i,`<head>
2
6
  <script>var pico8_gpio = new Array(128)<\/script>`)),e=e.replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/gi,(e,t,n,r)=>t+n.replace(/<!--|-->/g,``).replace(/^[ \t]*-repeat[^;\n]*;[ \t]*$/gm,``)+r),e=e.replace(/&nbsp(?!;)/g,`&nbsp;`);let a=e.lastIndexOf(`</body>`);if(a===-1)throw Error(`[puzzmo-pico8] that doesn't look like a PICO-8 export, it has no </body>`);return e.slice(0,a)+n.join(`
3
7
  `)+`
4
- `+e.slice(a)}var d=[`/Applications/PICO-8.app/Contents/MacOS/pico8`,`C:\\Program Files (x86)\\PICO-8\\pico8.exe`,`C:\\Program Files\\PICO-8\\pico8.exe`],f=e=>{var t,n;if(e.includes(`/`)||e.includes(`\\`))return s.default.existsSync(e)?e:null;for(let n of((t=process.env.PATH)==null?``:t).split(o.default.delimiter))for(let t of process.platform===`win32`?[`.exe`,`.cmd`,``]:[``]){let r=o.default.join(n,e+t);if(s.default.existsSync(r))return r}return e===`pico8`?(n=d.find(e=>s.default.existsSync(e)))==null?null:n:null},p=e=>s.default.existsSync(e)?s.default.statSync(e).mtimeMs:0;function m(e={}){var t,n;let r,a=new Map,d=e.pico8===!1?null:(t=(n=e.pico8)==null?process.env.PICO8:n)==null?`pico8`:t,m=e=>r.logger.info(`\x1b[33m\x1b[1m PICO-8 \x1b[22m\x1b[39m${e}`),h=t=>{if(e.writeLua===!1)return;let n=o.default.join(o.default.dirname(t.cart),`puzzmo.lua`);s.default.existsSync(n)&&s.default.readFileSync(n,`utf8`)===i.t||(s.default.writeFileSync(n,i.t),m(`wrote ${o.default.relative(r.root,n)}`))},g=e=>{let t=o.default.dirname(e.cart),n=Math.max(...s.default.readdirSync(t).filter(e=>/\.(p8|lua)$/.test(e)).map(e=>p(o.default.join(t,e))));if(s.default.existsSync(e.exportJS)&&p(e.exportJS)>=n)return;let i=d?f(d):null;if(!i){if(s.default.existsSync(e.exportHTML)){r.logger.warn(`[puzzmo-pico8] ${o.default.relative(r.root,e.cart)} is newer than its export, and PICO-8 isn't around to re-export it. Using the old export.`);return}throw Error(`[puzzmo-pico8] there's no export of ${o.default.relative(r.root,e.cart)} yet, and PICO-8 isn't on your PATH to make one.\nExport it inside PICO-8 with EXPORT ${e.name}.html into ${o.default.relative(r.root,o.default.dirname(e.exportHTML))}/, or set PICO8=/path/to/pico8.`)}s.default.mkdirSync(o.default.dirname(e.exportHTML),{recursive:!0});let a=p(e.exportJS),l=``;try{l=(0,c.execFileSync)(i,[e.cart,`-export`,e.exportHTML],{encoding:`utf8`,timeout:6e4,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){var u;l=String((u=e.stdout)==null?e:u)}if(p(e.exportJS)===a){let t=/label/i.test(l)?`
5
- HTML exports need a label: run the cart in PICO-8, press CTRL-7, and save.`:``;throw Error(`[puzzmo-pico8] PICO-8 didn't export ${o.default.relative(r.root,e.cart)}:\n${l.trim()}${t}`)}m(`exported ${o.default.relative(r.root,e.cart)}`)},_=t=>{let n=o.default.dirname(t);if(!a.has(n)){let t=l(n,e);if(!t)return null;a.set(n,t)}return a.get(n)};return{name:`puzzmo-pico8`,config(){var t;let n=(t=e.exportDir)==null?`export`:t;return{server:{watch:{ignored:[e=>/\.(html|js)$/.test(e)&&o.default.basename(o.default.dirname(e))===o.default.basename(n)&&s.default.existsSync(o.default.join(o.default.dirname(o.default.dirname(e)),`cart`))]}}}},configResolved(e){r=e},transformIndexHtml:{order:`pre`,handler(e,t){var n;let r=_(t.filename);if(!r)return;h(r),g(r);let i=(n=e.match(/<script\b[^>]*type=["']module["'][^>]*>[\s\S]*?<\/script>/gi))==null?[]:n;return u(s.default.readFileSync(r.exportHTML,`utf8`),r.name,i)}},configureServer(e){e.middlewares.use((e,t,n)=>{var i;let c=decodeURIComponent(((i=e.url)==null?``:i).split(`?`)[0]);if(!c.endsWith(`.js`))return n();let l=[...a.values()].find(e=>c===`/`+o.default.relative(r.root,o.default.join(e.dir,`${e.name}.js`)).split(o.default.sep).join(`/`));if(!l||!s.default.existsSync(l.exportJS))return n();t.setHeader(`Content-Type`,`text/javascript`),t.end(s.default.readFileSync(l.exportJS))}),e.watcher.on(`change`,t=>{let n=[...a.values()].find(e=>o.default.dirname(t)===o.default.dirname(e.cart)&&/\.(p8|lua)$/.test(t));if(!(!n||o.default.basename(t)===`puzzmo.lua`))try{g(n),e.ws.send({type:`full-reload`})}catch(t){let n=t instanceof Error?t.message:String(t);r.logger.error(n),e.ws.send({type:`error`,err:{message:n,stack:``}})}})},generateBundle(){for(let e of a.values()){let t=o.default.relative(r.root,o.default.join(e.dir,`${e.name}.js`)).split(o.default.sep).join(`/`);this.emitFile({type:`asset`,fileName:t,source:s.default.readFileSync(e.exportJS)})}}}}var h=[`fixturesGlob`,`viewFactories`],g=`/@puzzmo-simulator-init.js`,_=`virtual:puzzmo-simulator`;function v(e){let t=new Map,n=M(e,3);s.default.existsSync(o.default.join(e,`puzzmo.json`))&&n.unshift(e);for(let i of n)try{var r;let n=JSON.parse(s.default.readFileSync(o.default.join(i,`puzzmo.json`),`utf-8`));if(!(!(n==null||(r=n.game)==null)&&r.slug))continue;let a=n.integrations&&typeof n.integrations==`object`?n.integrations:void 0;t.set(n.game.slug,{dir:i,slug:n.game.slug,displayName:n.game.displayName,appBundlePath:w(e,T(i,`src/appBundle`)),pmmgBundlePath:w(e,T(i,`src/pmmgBundle`)),integrations:a})}catch(e){}return t}function y(e,t,n){if(e)try{let r=new URL(e).pathname;for(let e of t.values()){let t=`/`+o.default.relative(n,e.dir).split(o.default.sep).join(`/`);if(r.startsWith(t+`/`)||r===t)return e}}catch(e){}if(t.size===1)return t.values().next().value}function b(e,r){let{fixturesGlob:i,viewFactories:a}=e,o=t.t(e,h),s=i===!1?null:i==null?`/fixtures/puzzles/**/*.{json,toml}`:i,c=[`import { createSimulator } from "@puzzmo/sdk/simulator"`];for(let e of a==null?[]:a)c.push(`import { ${e.export} } from ${JSON.stringify(e.module)}`);s&&c.push(`const fixtures = import.meta.glob(${JSON.stringify(s)}, { query: "?raw", import: "default", eager: true })`),r!=null&&r.appBundlePath&&(c.push(`import(${JSON.stringify(r.appBundlePath)}).then(m => {`),c.push(` if (m.renderThumbnail) globalThis.renderThumbnail = m.renderThumbnail`),c.push(` if (m.getShareString) globalThis.getShareString = m.getShareString`),c.push(`}).catch(() => {})`));let l=n.t(n.t(n.t({},o),r!=null&&r.slug?{slug:r.slug}:{}),r!=null&&r.integrations?{integrations:r.integrations}:{}),u=Object.entries(l).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}: ${JSON.stringify(t)}`);return s&&u.push(`fixtures`),r!=null&&r.pmmgBundlePath&&u.push(`pmmgBundle: () => import(${JSON.stringify(r.pmmgBundlePath)})`),a!=null&&a.length&&u.push(`views: [${a.map(e=>`${e.export}()`).join(`, `)}]`),c.push(`createSimulator({ ${u.join(`, `)} })`),c.join(`
6
- `)}function x(e={}){let t=new Map,n;return{name:`puzzmo-simulator`,apply:`serve`,configResolved(e){if(n=e.root,t=v(n),t.size===0)e.logger.info(`\x1B[33m\x1B[1m PUZZMO \x1B[22m\x1B[39m\x1B[2m no puzzmo.json files found\x1B[22m`);else{let n=[...t.values()].map(e=>`\x1b[36m${e.slug}\x1b[39m`),r=t.size===1?`game`:`games`;e.logger.info(`\x1b[33m\x1b[1m PUZZMO \x1b[22m\x1b[39m found ${t.size} ${r}: ${n.join(`\x1B[2m, \x1B[22m`)}`)}},resolveId(e){if(e===_||e.startsWith(_+`?`))return`\0`+e},load(n){if(!n.startsWith(`\0`+_))return;let r=new URLSearchParams(n.split(`?`)[1]||``).get(`game`);return b(e,r?t.get(r):t.size===1?t.values().next().value:void 0)},configureServer(e){for(let n of t.values())e.watcher.add(o.default.join(n.dir,`puzzmo.json`));e.watcher.on(`change`,r=>{if(o.default.basename(r)===`puzzmo.json`){t=v(n);for(let t of e.moduleGraph.idToModuleMap.values()){var i;(i=t.id)!=null&&i.startsWith(`\0`+_)&&e.moduleGraph.invalidateModule(t)}e.ws.send({type:`full-reload`})}}),e.middlewares.use(`/oauth/callback`,(e,t)=>{t.setHeader(`Content-Type`,`text/html`),t.end(`<!DOCTYPE html>
8
+ `+e.slice(a)}var C=[`/Applications/PICO-8.app/Contents/MacOS/pico8`,`C:\\Program Files (x86)\\PICO-8\\pico8.exe`,`C:\\Program Files\\PICO-8\\pico8.exe`],w=e=>{var t,n;if(e.includes(`/`)||e.includes(`\\`))return s.default.existsSync(e)?e:null;for(let n of((t=process.env.PATH)==null?``:t).split(o.default.delimiter))for(let t of process.platform===`win32`?[`.exe`,`.cmd`,``]:[``]){let r=o.default.join(n,e+t);if(s.default.existsSync(r))return r}return e===`pico8`?(n=C.find(e=>s.default.existsSync(e)))==null?null:n:null},T=e=>s.default.existsSync(e)?s.default.statSync(e).mtimeMs:0;function E(e={}){var t,n;let r,a=new Map,l=e.pico8===!1?null:(t=(n=e.pico8)==null?process.env.PICO8:n)==null?`pico8`:t,u=e=>r.logger.info(`\x1b[33m\x1b[1m PICO-8 \x1b[22m\x1b[39m${e}`),d=t=>{if(e.writeLua===!1)return;let n=o.default.join(o.default.dirname(t.cart),`puzzmo.lua`);s.default.existsSync(n)&&s.default.readFileSync(n,`utf8`)===i.t||(s.default.writeFileSync(n,i.t),u(`wrote ${o.default.relative(r.root,n)}`))},f=e=>{let t=o.default.dirname(e.cart),n=Math.max(...s.default.readdirSync(t).filter(e=>/\.(p8|lua)$/.test(e)).map(e=>T(o.default.join(t,e))));if(s.default.existsSync(e.exportJS)&&T(e.exportJS)>=n)return;let i=l?w(l):null;if(!i){if(s.default.existsSync(e.exportHTML)){r.logger.warn(`[puzzmo-pico8] ${o.default.relative(r.root,e.cart)} is newer than its export, and PICO-8 isn't around to re-export it. Using the old export.`);return}throw Error(`[puzzmo-pico8] there's no export of ${o.default.relative(r.root,e.cart)} yet, and PICO-8 isn't on your PATH to make one.\nExport it inside PICO-8 with EXPORT ${e.name}.html into ${o.default.relative(r.root,o.default.dirname(e.exportHTML))}/, or set PICO8=/path/to/pico8.`)}s.default.mkdirSync(o.default.dirname(e.exportHTML),{recursive:!0});let a=T(e.exportJS),d=``;try{d=(0,c.execFileSync)(i,[e.cart,`-export`,e.exportHTML],{encoding:`utf8`,timeout:6e4,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){var f;d=String((f=e.stdout)==null?e:f)}if(T(e.exportJS)===a){let t=/label/i.test(d)?`
9
+ HTML exports need a label: run the cart in PICO-8, press CTRL-7, and save.`:``;throw Error(`[puzzmo-pico8] PICO-8 didn't export ${o.default.relative(r.root,e.cart)}:\n${d.trim()}${t}`)}u(`exported ${o.default.relative(r.root,e.cart)}`)},p=t=>{let n=o.default.dirname(t);if(!a.has(n)){let t=x(n,e);if(!t)return null;a.set(n,t)}return a.get(n)};return{name:`puzzmo-pico8`,config(){var t;let n=(t=e.exportDir)==null?`export`:t;return{server:{watch:{ignored:[e=>/\.(html|js)$/.test(e)&&o.default.basename(o.default.dirname(e))===o.default.basename(n)&&s.default.existsSync(o.default.join(o.default.dirname(o.default.dirname(e)),`cart`))]}}}},configResolved(e){r=e},transformIndexHtml:{order:`pre`,handler(e,t){var n;let r=p(t.filename);if(!r)return;d(r),f(r);let i=(n=e.match(/<script\b[^>]*type=["']module["'][^>]*>[\s\S]*?<\/script>/gi))==null?[]:n;return S(s.default.readFileSync(r.exportHTML,`utf8`),r.name,i)}},configureServer(e){e.middlewares.use((e,t,n)=>{var i;let c=decodeURIComponent(((i=e.url)==null?``:i).split(`?`)[0]);if(!c.endsWith(`.js`))return n();let l=[...a.values()].find(e=>c===`/`+o.default.relative(r.root,o.default.join(e.dir,`${e.name}.js`)).split(o.default.sep).join(`/`));if(!l||!s.default.existsSync(l.exportJS))return n();t.setHeader(`Content-Type`,`text/javascript`),t.end(s.default.readFileSync(l.exportJS))}),e.watcher.on(`change`,t=>{let n=[...a.values()].find(e=>o.default.dirname(t)===o.default.dirname(e.cart)&&/\.(p8|lua)$/.test(t));if(!(!n||o.default.basename(t)===`puzzmo.lua`))try{f(n),e.ws.send({type:`full-reload`})}catch(t){let n=t instanceof Error?t.message:String(t);r.logger.error(n),e.ws.send({type:`error`,err:{message:n,stack:``}})}})},generateBundle(){for(let e of a.values()){let t=o.default.relative(r.root,o.default.join(e.dir,`${e.name}.js`)).split(o.default.sep).join(`/`);this.emitFile({type:`asset`,fileName:t,source:s.default.readFileSync(e.exportJS)})}}}}var D=[`fixturesGlob`,`viewFactories`],O=`/@puzzmo-simulator-init.js`,k=`virtual:puzzmo-simulator`;function A(e){let t=new Map,n=W(e,3);s.default.existsSync(o.default.join(e,`puzzmo.json`))&&n.unshift(e);for(let i of n)try{var r;let n=JSON.parse(s.default.readFileSync(o.default.join(i,`puzzmo.json`),`utf-8`));if(!(!(n==null||(r=n.game)==null)&&r.slug))continue;let a=n.integrations&&typeof n.integrations==`object`?n.integrations:void 0;t.set(n.game.slug,{dir:i,slug:n.game.slug,displayName:n.game.displayName,appBundlePath:I(e,L(i,`src/appBundle`)),pmmgBundlePath:I(e,L(i,`src/pmmgBundle`)),integrations:a})}catch(e){}return t}function j(e,t,n){if(e)try{let r=new URL(e).pathname;for(let e of t.values()){let t=`/`+o.default.relative(n,e.dir).split(o.default.sep).join(`/`);if(r.startsWith(t+`/`)||r===t)return e}}catch(e){}if(t.size===1)return t.values().next().value}function M(e,r){let{fixturesGlob:i,viewFactories:a}=e,o=t.t(e,D),s=i===!1?null:i==null?`/fixtures/puzzles/**/*.{json,toml}`:i,c=[`import { createSimulator } from "@puzzmo/sdk/simulator"`];for(let e of a==null?[]:a)c.push(`import { ${e.export} } from ${JSON.stringify(e.module)}`);s&&c.push(`const fixtures = import.meta.glob(${JSON.stringify(s)}, { query: "?raw", import: "default", eager: true })`),r!=null&&r.appBundlePath&&(c.push(`import(${JSON.stringify(r.appBundlePath)}).then(m => {`),c.push(` if (m.renderThumbnail) globalThis.renderThumbnail = m.renderThumbnail`),c.push(` if (m.getShareString) globalThis.getShareString = m.getShareString`),c.push(`}).catch(() => {})`));let l=n.t(n.t(n.t({},o),r!=null&&r.slug?{slug:r.slug}:{}),r!=null&&r.integrations?{integrations:r.integrations}:{}),u=Object.entries(l).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}: ${JSON.stringify(t)}`);return s&&u.push(`fixtures`),r!=null&&r.pmmgBundlePath&&u.push(`pmmgBundle: () => import(${JSON.stringify(r.pmmgBundlePath)})`),a!=null&&a.length&&u.push(`views: [${a.map(e=>`${e.export}()`).join(`, `)}]`),c.push(`createSimulator({ ${u.join(`, `)} })`),c.join(`
10
+ `)}function N(e={}){let t=new Map,n;return{name:`puzzmo-simulator`,apply:`serve`,configResolved(e){if(n=e.root,t=A(n),t.size===0)e.logger.info(`\x1B[33m\x1B[1m PUZZMO \x1B[22m\x1B[39m\x1B[2m no puzzmo.json files found\x1B[22m`);else{let n=[...t.values()].map(e=>`\x1b[36m${e.slug}\x1b[39m`),r=t.size===1?`game`:`games`;e.logger.info(`\x1b[33m\x1b[1m PUZZMO \x1b[22m\x1b[39m found ${t.size} ${r}: ${n.join(`\x1B[2m, \x1B[22m`)}`)}},resolveId(e){if(e===k||e.startsWith(k+`?`))return`\0`+e},load(n){if(!n.startsWith(`\0`+k))return;let r=new URLSearchParams(n.split(`?`)[1]||``).get(`game`);return M(e,r?t.get(r):t.size===1?t.values().next().value:void 0)},configureServer(e){for(let n of t.values())e.watcher.add(o.default.join(n.dir,`puzzmo.json`));e.watcher.on(`change`,r=>{if(o.default.basename(r)===`puzzmo.json`){t=A(n);for(let t of e.moduleGraph.idToModuleMap.values()){var i;(i=t.id)!=null&&i.startsWith(`\0`+k)&&e.moduleGraph.invalidateModule(t)}e.ws.send({type:`full-reload`})}}),e.middlewares.use(`/oauth/callback`,(e,t)=>{t.setHeader(`Content-Type`,`text/html`),t.end(`<!DOCTYPE html>
7
11
  <html><head><title>Puzzmo OAuth</title></head>
8
12
  <body><script>
9
13
  var params = new URLSearchParams(window.location.search);
@@ -11,5 +15,5 @@ var returnUrl = sessionStorage.getItem("oauth_return_url") || "/";
11
15
  var url = new URL(returnUrl);
12
16
  params.forEach(function(v, k) { url.searchParams.set(k, v); });
13
17
  window.location.href = url.toString();
14
- <\/script></body></html>`)}),e.middlewares.use(function(){var i=r.t(function*(r,i,a){var o;if(((o=r.url)==null?void 0:o.split(`?`)[0])!==g)return a();let s=y(r.headers.referer,t,n),c=_+(s?`?game=${s.slug}`:``),l=yield e.transformRequest(c);if(!l)return a();i.setHeader(`Content-Type`,`application/javascript`),i.end(l.code)});return function(e,t,n){return i.apply(this,arguments)}}())},transformIndexHtml(){return[{tag:`script`,attrs:{type:`module`,src:g},injectTo:`head`}]}}}function S(e,t){return(i={})=>{let{entry:s,outputFile:c,outDir:l}=n.t(n.t({},t),i);return{name:e,apply:`build`,closeBundle(){return r.t(function*(){var t;let n=i.entry?o.default.isAbsolute(s)?s:o.default.resolve(process.cwd(),s):(t=T(process.cwd(),C(s)))==null?o.default.resolve(process.cwd(),s):t;try{yield(0,a.build)({configFile:!1,logLevel:`warn`,build:{lib:{entry:n,formats:[`es`],fileName:()=>c},outDir:l,emptyOutDir:!1}})}catch(t){throw console.error(`[${e}] build failed:`,t),t}})()}}}}var C=e=>e.replace(/\.[jt]sx?$/i,``),w=(e,t)=>t?`/`+o.default.relative(e,t).split(o.default.sep).join(`/`):null,T=(e,t)=>{for(let n of[`.js`,`.ts`,`.tsx`,`.jsx`]){let r=o.default.join(e,t+n);if(s.default.existsSync(r))return r}return null};const E=S(`app-bundle`,{entry:`src/appBundle.js`,outputFile:`app-bundle.js`,outDir:`dist`}),D=S(`server-bundle`,{entry:`src/serverBundle.js`,outputFile:`server-bundle.js`,outDir:`dist-server`});var O=S(`pmmg-bundle`,{entry:`src/pmmgBundle.js`,outputFile:`pmmg-bundle.js`,outDir:`dist`});const k=(e={})=>[O(e),{name:`pmmg-bundle-dev`,apply:`serve`,configureServer(t){let n;t.middlewares.use((r,i,a)=>{var s;if(!/^\/pmmg-bundle\.js(?:\?.*)?$/.test(r.url||``))return a();let c=(s=e.entry)==null?T(t.config.root,`src/pmmgBundle`):s;if(!c)return a();n!=null||(n=A(o.default.resolve(t.config.root,c)).finally(()=>n=void 0)),n.then(e=>{i.setHeader(`Content-Type`,`text/javascript`),i.setHeader(`Access-Control-Allow-Origin`,`*`),i.setHeader(`Cache-Control`,`no-store`),i.end(e)},e=>{var n;t.config.logger.error(`[pmmg-bundle] build failed: ${(n=e==null?void 0:e.message)==null?e:n}`),i.statusCode=500,i.end()})})}}],A=function(){var e=r.t(function*(e){let t=yield(0,a.build)({configFile:!1,logLevel:`warn`,build:{write:!1,copyPublicDir:!1,minify:!1,sourcemap:`inline`,lib:{entry:e,formats:[`es`],fileName:()=>`pmmg-bundle.js`},rolldownOptions:{output:{codeSplitting:!1}}}}),n=(Array.isArray(t)?t:`output`in t?[t]:[]).flatMap(e=>e.output).find(e=>e.type===`chunk`&&e.isEntry);if(!n||n.type!==`chunk`)throw Error(`Building ${e} made no bundle`);return n.code});return function(t){return e.apply(this,arguments)}}(),j=S(`editor-bundle`,{entry:`src/editorBundle.js`,outputFile:`editor-bundle.js`,outDir:`dist`}),M=(e,t,n=0)=>{if(n>=t)return[];let r=[],i;try{i=s.default.readdirSync(e,{withFileTypes:!0})}catch(e){return r}for(let a of i){if(!a.isDirectory()||a.name.startsWith(`.`)||a.name===`node_modules`)continue;let i=o.default.join(e,a.name);s.default.existsSync(o.default.join(i,`puzzmo.json`))&&r.push(i),r.push(...M(i,t,n+1))}return r};exports.appBundlePlugin=E,exports.buildPmmgBundleSource=A,exports.discoverGames=v,exports.editorBundlePlugin=j,exports.findPuzzmoJsonDirs=M,exports.generateSimulatorCode=b,exports.pmmgBundlePlugin=k,exports.puzzmoPico8=m,exports.puzzmoSimulator=x,exports.resolveGameFromReferer=y,exports.serverBundlePlugin=D;
18
+ <\/script></body></html>`)}),e.middlewares.use(function(){var i=r.t(function*(r,i,a){var o;if(((o=r.url)==null?void 0:o.split(`?`)[0])!==O)return a();let s=j(r.headers.referer,t,n),c=k+(s?`?game=${s.slug}`:``),l=yield e.transformRequest(c);if(!l)return a();i.setHeader(`Content-Type`,`application/javascript`),i.end(l.code)});return function(e,t,n){return i.apply(this,arguments)}}())},transformIndexHtml(){return[{tag:`script`,attrs:{type:`module`,src:O},injectTo:`head`}]}}}function P(e,t,i={}){return(s={})=>{let{entry:c,outputFile:l,outDir:u}=n.t(n.t({},t),s),d=o.default.relative(process.cwd(),o.default.resolve(u,l));return{name:e,apply:`build`,closeBundle(){return r.t(function*(){var t;let n=s.entry?o.default.isAbsolute(c)?c:o.default.resolve(process.cwd(),c):(t=L(process.cwd(),F(c)))==null?o.default.resolve(process.cwd(),c):t,r=f(d,i);try{yield(0,a.build)({configFile:!1,logLevel:`warn`,define:G,plugins:[r],build:{lib:{entry:n,formats:[`es`],fileName:()=>l},outDir:u,emptyOutDir:!1}})}catch(t){throw r.api.failure?K(`[${e}] ${r.api.failure}`):(console.error(`[${e}] build failed:`,t),t)}})()}}}}var F=e=>e.replace(/\.[jt]sx?$/i,``),I=(e,t)=>t?`/`+o.default.relative(e,t).split(o.default.sep).join(`/`):null,L=(e,t)=>{for(let n of[`.js`,`.ts`,`.tsx`,`.jsx`]){let r=o.default.join(e,t+n);if(s.default.existsSync(r))return r}return null};const R=P(`app-bundle`,{entry:`src/appBundle.js`,outputFile:`app-bundle.js`,outDir:`dist`},u(`Puzzmo's pages wherever the game's thumbnails show`)),z=P(`server-bundle`,{entry:`src/serverBundle.js`,outputFile:`server-bundle.js`,outDir:`dist-server`});var B=P(`pmmg-bundle`,{entry:`src/pmmgBundle.js`,outputFile:`pmmg-bundle.js`,outDir:`dist`},u(`Puzzmo's pages for every board at the table`));const V=(e={})=>[B(e),{name:`pmmg-bundle-dev`,apply:`serve`,configureServer(t){let n;t.middlewares.use((r,i,a)=>{var s;if(!/^\/pmmg-bundle\.js(?:\?.*)?$/.test(r.url||``))return a();let c=(s=e.entry)==null?L(t.config.root,`src/pmmgBundle`):s;if(!c)return a();n!=null||(n=H(o.default.resolve(t.config.root,c)).finally(()=>n=void 0)),n.then(e=>{i.setHeader(`Content-Type`,`text/javascript`),i.setHeader(`Access-Control-Allow-Origin`,`*`),i.setHeader(`Cache-Control`,`no-store`),i.end(e)},e=>{var n;t.config.logger.error(`[pmmg-bundle] build failed: ${(n=e==null?void 0:e.message)==null?e:n}`),i.statusCode=500,i.end()})})}}],H=function(){var e=r.t(function*(e){let t=yield(0,a.build)({configFile:!1,logLevel:`warn`,define:G,build:{write:!1,copyPublicDir:!1,minify:!1,sourcemap:`inline`,lib:{entry:e,formats:[`es`],fileName:()=>`pmmg-bundle.js`},rolldownOptions:{output:{codeSplitting:!1}}}}),n=(Array.isArray(t)?t:`output`in t?[t]:[]).flatMap(e=>e.output).find(e=>e.type===`chunk`&&e.isEntry);if(!n||n.type!==`chunk`)throw Error(`Building ${e} made no bundle`);return n.code});return function(t){return e.apply(this,arguments)}}(),U=P(`editor-bundle`,{entry:`src/editorBundle.js`,outputFile:`editor-bundle.js`,outDir:`dist`}),W=(e,t,n=0)=>{if(n>=t)return[];let r=[],i;try{i=s.default.readdirSync(e,{withFileTypes:!0})}catch(e){return r}for(let a of i){if(!a.isDirectory()||a.name.startsWith(`.`)||a.name===`node_modules`)continue;let i=o.default.join(e,a.name);s.default.existsSync(o.default.join(i,`puzzmo.json`))&&r.push(i),r.push(...W(i,t,n+1))}return r};var G={"process.env.NODE_ENV":JSON.stringify(`production`)},K=e=>Object.assign(Error(e),{stack:e});exports.appBundlePlugin=R,exports.buildPmmgBundleSource=H,exports.discoverGames=A,exports.editorBundlePlugin=U,exports.findPuzzmoJsonDirs=W,exports.generateSimulatorCode=M,exports.pmmgBundlePlugin=V,exports.puzzmoPico8=E,exports.puzzmoSimulator=N,exports.resolveGameFromReferer=j,exports.serverBundlePlugin=z;
15
19
  //# sourceMappingURL=vite.cjs.map
package/dist/vite.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"vite.cjs","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":"mYAiCA,SAAgB,EAAc,EAAa,EAAoC,EAAE,CAAoB,OACnG,IAAI,EACJ,GAAI,EAAQ,KAAM,EAAO,EAAA,QAAK,QAAQ,EAAK,EAAQ,KAAK,KACnD,CACH,IAAM,EAAU,EAAA,QAAK,KAAK,EAAK,OAAO,CAChC,EAAQ,EAAA,QAAG,WAAW,EA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QAAK,KAAK,EAAM,EAAM,KAAK,CACnC,EAAA,QAAG,WAAW,EAAA,QAAK,KAAK,EAAK,cAAc,CAAC,EAC9C,EAAQ,KAAK,EAAI,CAEnB,EAAQ,KAAK,GAAG,EAAmB,EAAK,EAAU,EAAQ,EAAE,CAAC,CAE/D,OAAO"}
1
+ {"version":3,"file":"vite.cjs","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":"mYA6BA,IAAM,EAAK,KAGX,MAAa,EAAoB,IAAoC,CACnE,WACA,UAAW,IAAM,EACjB,SAAU,IAAM,EAChB,eAAgB,CAAC,QAAS,YAAa,YAAa,QAAS,cAAe,mBAAmB,CAChG,EAMY,GAAe,EAAoB,IAAyB,OACvE,IAAM,EAAmB,EAAE,CACrB,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eAAO,MAAM,kBAAkB,SAAU,MAAM,YAAY,MAAM,qBAAc,MAAM,EAkBpF,CAAA"}
package/dist/vite.js CHANGED
@@ -6,8 +6,121 @@ import { build as i } from "vite";
6
6
  import a from "path";
7
7
  import o from "fs";
8
8
  import { execFileSync as s } from "child_process";
9
+ var c = 1024;
10
+ /** The limits for a bundle Puzzmo loads into its own pages, where every byte is on a player's page load */
11
+ const l = (e) => ({
12
+ loadedOn: e,
13
+ warnBytes: 200 * c,
14
+ maxBytes: 500 * c,
15
+ bannedPackages: [
16
+ "react",
17
+ "react-dom",
18
+ "scheduler",
19
+ "redux",
20
+ "react-redux",
21
+ "@reduxjs/toolkit"
22
+ ]
23
+ }), u = (e, t) => {
24
+ var n;
25
+ let r = [], i = [], a = g(e), o = Buffer.byteLength(e.code), s = t.maxBytes !== void 0 && o > t.maxBytes, c = t.warnBytes !== void 0 && o > t.warnBytes;
26
+ if (s || c) {
27
+ let n = s ? t.maxBytes : t.warnBytes, c = t.loadedOn ? ` for a bundle loaded on ${t.loadedOn}` : "", l = Object.entries(e.modules).sort(([, e], [, t]) => t.size - e.size).slice(0, 5).map(([e, { size: t }]) => ` ${v(t).padStart(7)} ${a.module(e)}\n ${a.chain(e)}`), u = `${e.fileName} is ${v(o)}, over the ${v(n)} limit${c}. Its largest modules:\n${l.join("\n")}`;
28
+ (s ? r : i).push(u);
29
+ }
30
+ let l = new Set((n = t.bannedPackages) == null ? [] : n), u = /* @__PURE__ */ new Set();
31
+ for (let t of Object.keys(e.modules)) {
32
+ let n = _(t);
33
+ !n || !l.has(n) || u.has(n) || (u.add(n), r.push(`${n} can't be in ${e.fileName}, as Puzzmo calls it for strings and data. Imported by:\n ${a.chain(t)}`));
34
+ }
35
+ let d = p(e.code, e.modules);
36
+ if (d.length) {
37
+ let t = d.map(({ usage: e, count: t, moduleID: n }) => {
38
+ let r = t > 1 ? ` (x${t})` : "";
39
+ return n ? ` ${e}${r} in ${a.module(n)}\n ${a.chain(n)}` : ` ${e}${r}`;
40
+ });
41
+ i.push(`${e.fileName} uses Node globals, which don't exist where Puzzmo runs it, so each throws if reached:\n${t.join("\n")}`);
42
+ }
43
+ return {
44
+ errors: r,
45
+ warnings: i
46
+ };
47
+ }, d = (e, t) => {
48
+ let n = process.cwd(), r = {};
49
+ return {
50
+ name: "puzzmo-bundle-checks",
51
+ api: r,
52
+ configResolved(e) {
53
+ n = e.root;
54
+ },
55
+ generateBundle(i, a) {
56
+ let o = Object.values(a).find((e) => e.type === "chunk" && e.isEntry);
57
+ if ((o == null ? void 0 : o.type) !== "chunk" || !o.facadeModuleId) return;
58
+ let s = Object.fromEntries(Object.entries(o.modules).map(([e, t]) => [e, {
59
+ size: t.renderedLength,
60
+ code: t.code
61
+ }])), c = h(o.facadeModuleId, (e) => this.getModuleInfo(e)), { errors: l, warnings: d } = u({
62
+ fileName: e,
63
+ code: o.code,
64
+ modules: s,
65
+ chains: c,
66
+ root: n
67
+ }, t);
68
+ for (let e of d) this.warn(e);
69
+ l.length && (r.failure = l.join("\n\n"), this.error(r.failure));
70
+ }
71
+ };
72
+ };
73
+ /** A Node-only global in use: `process.env.X`, `Buffer.from`, `require(`, never `obj.process.x` or `__require(` */
74
+ var f = /* @__PURE__ */ RegExp("(?<![\\w$.])(?:(?:process|global|Buffer)(?:\\.[\\w$]+){1,2}|require\\s*\\(|new\\s+Buffer\\s*\\(|__dirname\\b|__filename\\b)", "g"), p = (e, t) => {
75
+ let n = m(e), r = [];
76
+ for (let [e, i] of Object.entries(t)) if (i.code) for (let [t, a] of m(i.code)) n.has(t) && r.push({
77
+ usage: t,
78
+ count: a,
79
+ moduleID: e
80
+ });
81
+ let i = new Set(r.map(({ usage: e }) => e));
82
+ for (let [e, t] of n) i.has(e) || r.push({
83
+ usage: e,
84
+ count: t
85
+ });
86
+ return r;
87
+ }, m = (e) => {
88
+ let t = /* @__PURE__ */ new Map();
89
+ for (let r of e.matchAll(f)) {
90
+ var n;
91
+ let i = r[0].match(/process|global|Buffer|require|__dirname|__filename/)[0], a = e.slice(Math.max(0, r.index - 200), r.index);
92
+ if (/typeof\s+$/.test(a) || RegExp(`typeof\\s+${i}\\b`).test(a)) continue;
93
+ let o = r[0].replace(/\s*\($/, "(").replace(/\s+/g, " ");
94
+ t.set(o, ((n = t.get(o)) == null ? 0 : n) + 1);
95
+ }
96
+ return t;
97
+ }, h = (e, t) => {
98
+ let n = new Map([[e, [e]]]), r = [e];
99
+ for (let e = 0; e < r.length; e++) {
100
+ let i = t(r[e]);
101
+ if (i) for (let t of [...i.importedIds, ...i.dynamicallyImportedIds]) n.has(t) || (n.set(t, [...n.get(r[e]), t]), r.push(t));
102
+ }
103
+ return n;
104
+ }, g = ({ root: e, chains: t }) => {
105
+ let n = (t) => {
106
+ let n = t.replace(/^\0/, "").replace(/\?.*$/, ""), r = y(n.split("/node_modules/"));
107
+ return r === n ? a.isAbsolute(n) ? a.relative(e, n) : n : r;
108
+ };
109
+ return {
110
+ module: n,
111
+ chain: (e) => {
112
+ var r;
113
+ return ((r = t.get(e)) == null ? [e] : r).map(n).join(" > ");
114
+ }
115
+ };
116
+ }, _ = (e) => {
117
+ let t = e.split("/node_modules/");
118
+ if (t.length < 2) return;
119
+ let n = y(t).split("/");
120
+ return n[0].startsWith("@") ? `${n[0]}/${n[1]}` : n[0];
121
+ }, v = (e) => `${Math.round(e / c)}KB`, y = (e) => e[e.length - 1];
9
122
  /** @internal Finds the PICO-8 game served by the page in `dir`, if there is one. */
10
- function c(e, t = {}) {
123
+ function b(e, t = {}) {
11
124
  var n;
12
125
  let r;
13
126
  if (t.cart) r = a.resolve(e, t.cart);
@@ -31,7 +144,7 @@ function c(e, t = {}) {
31
144
  * Turns PICO-8's exported page into a Puzzmo game's page. PICO-8's shell is a thousand lines of globals and handlers
32
145
  * its runtime expects to find, and it changes between versions, so rather than keep a copy we adjust theirs.
33
146
  */
34
- function l(e, t, n) {
147
+ function x(e, t, n) {
35
148
  let r = t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), i = RegExp(`((?:\\.src\\s*=\\s*|\\ssrc=)["'])[^"']*${r}\\.js(["'])`);
36
149
  if (!i.test(e)) throw Error(`[puzzmo-pico8] couldn't find where PICO-8's page loads ${t}.js`);
37
150
  e = e.replace(i, `$1./${t}.js$2`), e = e.replace(/var\s+p8_autoplay\s*=\s*false/, "var p8_autoplay = true"), /var\s+pico8_gpio\s*=/.test(e) || (e = e.replace(/<head>/i, "<head>\n<script>var pico8_gpio = new Array(128)<\/script>")), e = e.replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/gi, (e, t, n, r) => t + n.replace(/<!--|-->/g, "").replace(/^[ \t]*-repeat[^;\n]*;[ \t]*$/gm, "") + r), e = e.replace(/&nbsp(?!;)/g, "&nbsp;");
@@ -40,11 +153,11 @@ function l(e, t, n) {
40
153
  return e.slice(0, a) + n.join("\n") + "\n" + e.slice(a);
41
154
  }
42
155
  /** Where PICO-8's own installers put it, for people who never added it to their PATH. */
43
- var u = [
156
+ var S = [
44
157
  "/Applications/PICO-8.app/Contents/MacOS/pico8",
45
158
  "C:\\Program Files (x86)\\PICO-8\\pico8.exe",
46
159
  "C:\\Program Files\\PICO-8\\pico8.exe"
47
- ], d = (e) => {
160
+ ], C = (e) => {
48
161
  var t, n;
49
162
  if (e.includes("/") || e.includes("\\")) return o.existsSync(e) ? e : null;
50
163
  for (let n of ((t = process.env.PATH) == null ? "" : t).split(a.delimiter)) for (let t of process.platform === "win32" ? [
@@ -55,8 +168,8 @@ var u = [
55
168
  let r = a.join(n, e + t);
56
169
  if (o.existsSync(r)) return r;
57
170
  }
58
- return e === "pico8" ? (n = u.find((e) => o.existsSync(e))) == null ? null : n : null;
59
- }, f = (e) => o.existsSync(e) ? o.statSync(e).mtimeMs : 0;
171
+ return e === "pico8" ? (n = S.find((e) => o.existsSync(e))) == null ? null : n : null;
172
+ }, w = (e) => o.existsSync(e) ? o.statSync(e).mtimeMs : 0;
60
173
  /**
61
174
  * Vite plugin for games written as PICO-8 carts. Your `index.html` only needs your own script tag, the plugin swaps
62
175
  * in PICO-8's exported page around it, serves the PICO-8 runtime next to it, and copies it into the build.
@@ -64,16 +177,16 @@ var u = [
64
177
  * When PICO-8 is installed it also re-exports the cart whenever it (or a `.lua` file next to it) changes, and reloads
65
178
  * the page, so saving in PICO-8 is enough to see the change in the simulator.
66
179
  */
67
- function p(e = {}) {
180
+ function T(e = {}) {
68
181
  var t, n;
69
- let i, u = /* @__PURE__ */ new Map(), p = e.pico8 === !1 ? null : (t = (n = e.pico8) == null ? process.env.PICO8 : n) == null ? "pico8" : t, m = (e) => i.logger.info(`\x1b[33m\x1b[1m PICO-8 \x1b[22m\x1b[39m${e}`), h = (t) => {
182
+ let i, c = /* @__PURE__ */ new Map(), l = e.pico8 === !1 ? null : (t = (n = e.pico8) == null ? process.env.PICO8 : n) == null ? "pico8" : t, u = (e) => i.logger.info(`\x1b[33m\x1b[1m PICO-8 \x1b[22m\x1b[39m${e}`), d = (t) => {
70
183
  if (e.writeLua === !1) return;
71
184
  let n = a.join(a.dirname(t.cart), "puzzmo.lua");
72
- o.existsSync(n) && o.readFileSync(n, "utf8") === r || (o.writeFileSync(n, r), m(`wrote ${a.relative(i.root, n)}`));
73
- }, g = (e) => {
74
- let t = a.dirname(e.cart), n = Math.max(...o.readdirSync(t).filter((e) => /\.(p8|lua)$/.test(e)).map((e) => f(a.join(t, e))));
75
- if (o.existsSync(e.exportJS) && f(e.exportJS) >= n) return;
76
- let r = p ? d(p) : null;
185
+ o.existsSync(n) && o.readFileSync(n, "utf8") === r || (o.writeFileSync(n, r), u(`wrote ${a.relative(i.root, n)}`));
186
+ }, f = (e) => {
187
+ let t = a.dirname(e.cart), n = Math.max(...o.readdirSync(t).filter((e) => /\.(p8|lua)$/.test(e)).map((e) => w(a.join(t, e))));
188
+ if (o.existsSync(e.exportJS) && w(e.exportJS) >= n) return;
189
+ let r = l ? C(l) : null;
77
190
  if (!r) {
78
191
  if (o.existsSync(e.exportHTML)) {
79
192
  i.logger.warn(`[puzzmo-pico8] ${a.relative(i.root, e.cart)} is newer than its export, and PICO-8 isn't around to re-export it. Using the old export.`);
@@ -82,9 +195,9 @@ function p(e = {}) {
82
195
  throw Error(`[puzzmo-pico8] there's no export of ${a.relative(i.root, e.cart)} yet, and PICO-8 isn't on your PATH to make one.\nExport it inside PICO-8 with EXPORT ${e.name}.html into ${a.relative(i.root, a.dirname(e.exportHTML))}/, or set PICO8=/path/to/pico8.`);
83
196
  }
84
197
  o.mkdirSync(a.dirname(e.exportHTML), { recursive: !0 });
85
- let c = f(e.exportJS), l = "";
198
+ let c = w(e.exportJS), d = "";
86
199
  try {
87
- l = s(r, [
200
+ d = s(r, [
88
201
  e.cart,
89
202
  "-export",
90
203
  e.exportHTML
@@ -98,22 +211,22 @@ function p(e = {}) {
98
211
  ]
99
212
  });
100
213
  } catch (e) {
101
- var u;
102
- l = String((u = e.stdout) == null ? e : u);
214
+ var f;
215
+ d = String((f = e.stdout) == null ? e : f);
103
216
  }
104
- if (f(e.exportJS) === c) {
105
- let t = /label/i.test(l) ? "\nHTML exports need a label: run the cart in PICO-8, press CTRL-7, and save." : "";
106
- throw Error(`[puzzmo-pico8] PICO-8 didn't export ${a.relative(i.root, e.cart)}:\n${l.trim()}${t}`);
217
+ if (w(e.exportJS) === c) {
218
+ let t = /label/i.test(d) ? "\nHTML exports need a label: run the cart in PICO-8, press CTRL-7, and save." : "";
219
+ throw Error(`[puzzmo-pico8] PICO-8 didn't export ${a.relative(i.root, e.cart)}:\n${d.trim()}${t}`);
107
220
  }
108
- m(`exported ${a.relative(i.root, e.cart)}`);
109
- }, _ = (t) => {
221
+ u(`exported ${a.relative(i.root, e.cart)}`);
222
+ }, p = (t) => {
110
223
  let n = a.dirname(t);
111
- if (!u.has(n)) {
112
- let t = c(n, e);
224
+ if (!c.has(n)) {
225
+ let t = b(n, e);
113
226
  if (!t) return null;
114
- u.set(n, t);
227
+ c.set(n, t);
115
228
  }
116
- return u.get(n);
229
+ return c.get(n);
117
230
  };
118
231
  return {
119
232
  name: "puzzmo-pico8",
@@ -129,11 +242,11 @@ function p(e = {}) {
129
242
  order: "pre",
130
243
  handler(e, t) {
131
244
  var n;
132
- let r = _(t.filename);
245
+ let r = p(t.filename);
133
246
  if (!r) return;
134
- h(r), g(r);
247
+ d(r), f(r);
135
248
  let i = (n = e.match(/<script\b[^>]*type=["']module["'][^>]*>[\s\S]*?<\/script>/gi)) == null ? [] : n;
136
- return l(o.readFileSync(r.exportHTML, "utf8"), r.name, i);
249
+ return x(o.readFileSync(r.exportHTML, "utf8"), r.name, i);
137
250
  }
138
251
  },
139
252
  configureServer(e) {
@@ -141,13 +254,13 @@ function p(e = {}) {
141
254
  var r;
142
255
  let s = decodeURIComponent(((r = e.url) == null ? "" : r).split("?")[0]);
143
256
  if (!s.endsWith(".js")) return n();
144
- let c = [...u.values()].find((e) => s === "/" + a.relative(i.root, a.join(e.dir, `${e.name}.js`)).split(a.sep).join("/"));
145
- if (!c || !o.existsSync(c.exportJS)) return n();
146
- t.setHeader("Content-Type", "text/javascript"), t.end(o.readFileSync(c.exportJS));
257
+ let l = [...c.values()].find((e) => s === "/" + a.relative(i.root, a.join(e.dir, `${e.name}.js`)).split(a.sep).join("/"));
258
+ if (!l || !o.existsSync(l.exportJS)) return n();
259
+ t.setHeader("Content-Type", "text/javascript"), t.end(o.readFileSync(l.exportJS));
147
260
  }), e.watcher.on("change", (t) => {
148
- let n = [...u.values()].find((e) => a.dirname(t) === a.dirname(e.cart) && /\.(p8|lua)$/.test(t));
261
+ let n = [...c.values()].find((e) => a.dirname(t) === a.dirname(e.cart) && /\.(p8|lua)$/.test(t));
149
262
  if (!(!n || a.basename(t) === "puzzmo.lua")) try {
150
- g(n), e.ws.send({ type: "full-reload" });
263
+ f(n), e.ws.send({ type: "full-reload" });
151
264
  } catch (t) {
152
265
  let n = t instanceof Error ? t.message : String(t);
153
266
  i.logger.error(n), e.ws.send({
@@ -161,7 +274,7 @@ function p(e = {}) {
161
274
  });
162
275
  },
163
276
  generateBundle() {
164
- for (let e of u.values()) {
277
+ for (let e of c.values()) {
165
278
  let t = a.relative(i.root, a.join(e.dir, `${e.name}.js`)).split(a.sep).join("/");
166
279
  this.emitFile({
167
280
  type: "asset",
@@ -172,14 +285,14 @@ function p(e = {}) {
172
285
  }
173
286
  };
174
287
  }
175
- var m = ["fixturesGlob", "viewFactories"], h = "/@puzzmo-simulator-init.js", g = "virtual:puzzmo-simulator";
288
+ var E = ["fixturesGlob", "viewFactories"], D = "/@puzzmo-simulator-init.js", O = "virtual:puzzmo-simulator";
176
289
  /**
177
290
  * Discover all games from puzzmo.json files under a root directory.
178
291
  *
179
292
  * @internal
180
293
  */
181
- function _(e) {
182
- let t = /* @__PURE__ */ new Map(), n = j(e, 3);
294
+ function k(e) {
295
+ let t = /* @__PURE__ */ new Map(), n = U(e, 3);
183
296
  o.existsSync(a.join(e, "puzzmo.json")) && n.unshift(e);
184
297
  for (let i of n) try {
185
298
  var r;
@@ -190,8 +303,8 @@ function _(e) {
190
303
  dir: i,
191
304
  slug: n.game.slug,
192
305
  displayName: n.game.displayName,
193
- appBundlePath: C(e, w(i, "src/appBundle")),
194
- pmmgBundlePath: C(e, w(i, "src/pmmgBundle")),
306
+ appBundlePath: F(e, I(i, "src/appBundle")),
307
+ pmmgBundlePath: F(e, I(i, "src/pmmgBundle")),
195
308
  integrations: s
196
309
  });
197
310
  } catch (e) {}
@@ -202,7 +315,7 @@ function _(e) {
202
315
  *
203
316
  * @internal
204
317
  */
205
- function v(e, t, n) {
318
+ function A(e, t, n) {
206
319
  if (e) try {
207
320
  let r = new URL(e).pathname;
208
321
  for (let e of t.values()) {
@@ -217,42 +330,42 @@ function v(e, t, n) {
217
330
  *
218
331
  * @internal
219
332
  */
220
- function y(n, r) {
221
- let { fixturesGlob: i, viewFactories: a } = n, o = e(n, m), s = i === !1 ? null : i == null ? "/fixtures/puzzles/**/*.{json,toml}" : i, c = ["import { createSimulator } from \"@puzzmo/sdk/simulator\""];
333
+ function j(n, r) {
334
+ let { fixturesGlob: i, viewFactories: a } = n, o = e(n, E), s = i === !1 ? null : i == null ? "/fixtures/puzzles/**/*.{json,toml}" : i, c = ["import { createSimulator } from \"@puzzmo/sdk/simulator\""];
222
335
  for (let e of a == null ? [] : a) c.push(`import { ${e.export} } from ${JSON.stringify(e.module)}`);
223
336
  s && c.push(`const fixtures = import.meta.glob(${JSON.stringify(s)}, { query: "?raw", import: "default", eager: true })`), r != null && r.appBundlePath && (c.push(`import(${JSON.stringify(r.appBundlePath)}).then(m => {`), c.push(" if (m.renderThumbnail) globalThis.renderThumbnail = m.renderThumbnail"), c.push(" if (m.getShareString) globalThis.getShareString = m.getShareString"), c.push("}).catch(() => {})"));
224
337
  let l = t(t(t({}, o), r != null && r.slug ? { slug: r.slug } : {}), r != null && r.integrations ? { integrations: r.integrations } : {}), u = Object.entries(l).filter(([, e]) => e !== void 0).map(([e, t]) => `${e}: ${JSON.stringify(t)}`);
225
338
  return s && u.push("fixtures"), r != null && r.pmmgBundlePath && u.push(`pmmgBundle: () => import(${JSON.stringify(r.pmmgBundlePath)})`), a != null && a.length && u.push(`views: [${a.map((e) => `${e.export}()`).join(", ")}]`), c.push(`createSimulator({ ${u.join(", ")} })`), c.join("\n");
226
339
  }
227
340
  /** Vite plugin that injects the Puzzmo simulator in dev mode and handles OAuth callbacks. */
228
- function b(e = {}) {
341
+ function M(e = {}) {
229
342
  let t = /* @__PURE__ */ new Map(), r;
230
343
  return {
231
344
  name: "puzzmo-simulator",
232
345
  apply: "serve",
233
346
  configResolved(e) {
234
- if (r = e.root, t = _(r), t.size === 0) e.logger.info("\x1B[33m\x1B[1m PUZZMO \x1B[22m\x1B[39m\x1B[2m no puzzmo.json files found\x1B[22m");
347
+ if (r = e.root, t = k(r), t.size === 0) e.logger.info("\x1B[33m\x1B[1m PUZZMO \x1B[22m\x1B[39m\x1B[2m no puzzmo.json files found\x1B[22m");
235
348
  else {
236
349
  let n = [...t.values()].map((e) => `\x1b[36m${e.slug}\x1b[39m`), r = t.size === 1 ? "game" : "games";
237
350
  e.logger.info(`\x1b[33m\x1b[1m PUZZMO \x1b[22m\x1b[39m found ${t.size} ${r}: ${n.join("\x1B[2m, \x1B[22m")}`);
238
351
  }
239
352
  },
240
353
  resolveId(e) {
241
- if (e === g || e.startsWith(g + "?")) return "\0" + e;
354
+ if (e === O || e.startsWith(O + "?")) return "\0" + e;
242
355
  },
243
356
  load(n) {
244
- if (!n.startsWith("\0" + g)) return;
357
+ if (!n.startsWith("\0" + O)) return;
245
358
  let r = new URLSearchParams(n.split("?")[1] || "").get("game");
246
- return y(e, r ? t.get(r) : t.size === 1 ? t.values().next().value : void 0);
359
+ return j(e, r ? t.get(r) : t.size === 1 ? t.values().next().value : void 0);
247
360
  },
248
361
  configureServer(e) {
249
362
  for (let n of t.values()) e.watcher.add(a.join(n.dir, "puzzmo.json"));
250
363
  e.watcher.on("change", (n) => {
251
364
  if (a.basename(n) === "puzzmo.json") {
252
- t = _(r);
365
+ t = k(r);
253
366
  for (let t of e.moduleGraph.idToModuleMap.values()) {
254
367
  var i;
255
- (i = t.id) != null && i.startsWith("\0" + g) && e.moduleGraph.invalidateModule(t);
368
+ (i = t.id) != null && i.startsWith("\0" + O) && e.moduleGraph.invalidateModule(t);
256
369
  }
257
370
  e.ws.send({ type: "full-reload" });
258
371
  }
@@ -261,8 +374,8 @@ function b(e = {}) {
261
374
  }), e.middlewares.use(function() {
262
375
  var i = n(function* (n, i, a) {
263
376
  var o;
264
- if (((o = n.url) == null ? void 0 : o.split("?")[0]) !== h) return a();
265
- let s = v(n.headers.referer, t, r), c = g + (s ? `?game=${s.slug}` : ""), l = yield e.transformRequest(c);
377
+ if (((o = n.url) == null ? void 0 : o.split("?")[0]) !== D) return a();
378
+ let s = A(n.headers.referer, t, r), c = O + (s ? `?game=${s.slug}` : ""), l = yield e.transformRequest(c);
266
379
  if (!l) return a();
267
380
  i.setHeader("Content-Type", "application/javascript"), i.end(l.code);
268
381
  });
@@ -276,39 +389,41 @@ function b(e = {}) {
276
389
  tag: "script",
277
390
  attrs: {
278
391
  type: "module",
279
- src: h
392
+ src: D
280
393
  },
281
394
  injectTo: "head"
282
395
  }];
283
396
  }
284
397
  };
285
398
  }
286
- function x(e, r) {
287
- return (o = {}) => {
288
- let { entry: s, outputFile: c, outDir: l } = t(t({}, r), o);
399
+ function N(e, r, o = {}) {
400
+ return (s = {}) => {
401
+ let { entry: c, outputFile: l, outDir: u } = t(t({}, r), s), f = a.relative(process.cwd(), a.resolve(u, l));
289
402
  return {
290
403
  name: e,
291
404
  apply: "build",
292
405
  closeBundle() {
293
406
  return n(function* () {
294
407
  var t;
295
- let n = o.entry ? a.isAbsolute(s) ? s : a.resolve(process.cwd(), s) : (t = w(process.cwd(), S(s))) == null ? a.resolve(process.cwd(), s) : t;
408
+ let n = s.entry ? a.isAbsolute(c) ? c : a.resolve(process.cwd(), c) : (t = I(process.cwd(), P(c))) == null ? a.resolve(process.cwd(), c) : t, r = d(f, o);
296
409
  try {
297
410
  yield i({
298
411
  configFile: !1,
299
412
  logLevel: "warn",
413
+ define: W,
414
+ plugins: [r],
300
415
  build: {
301
416
  lib: {
302
417
  entry: n,
303
418
  formats: ["es"],
304
- fileName: () => c
419
+ fileName: () => l
305
420
  },
306
- outDir: l,
421
+ outDir: u,
307
422
  emptyOutDir: !1
308
423
  }
309
424
  });
310
425
  } catch (t) {
311
- throw console.error(`[${e}] build failed:`, t), t;
426
+ throw r.api.failure ? G(`[${e}] ${r.api.failure}`) : (console.error(`[${e}] build failed:`, t), t);
312
427
  }
313
428
  })();
314
429
  }
@@ -316,7 +431,7 @@ function x(e, r) {
316
431
  };
317
432
  }
318
433
  /** Strip the trailing extension from a default entry path so we can probe siblings. */
319
- var S = (e) => e.replace(/\.[jt]sx?$/i, ""), C = (e, t) => t ? "/" + a.relative(e, t).split(a.sep).join("/") : null, w = (e, t) => {
434
+ var P = (e) => e.replace(/\.[jt]sx?$/i, ""), F = (e, t) => t ? "/" + a.relative(e, t).split(a.sep).join("/") : null, I = (e, t) => {
320
435
  for (let n of [
321
436
  ".js",
322
437
  ".ts",
@@ -335,20 +450,20 @@ var S = (e) => e.replace(/\.[jt]sx?$/i, ""), C = (e, t) => t ? "/" + a.relative(
335
450
  * returning the SVG and its dimensions (`{ svg, width, height }`), used by the Puzzmo
336
451
  * platform for puzzle previews.
337
452
  */
338
- const T = x("app-bundle", {
453
+ const L = N("app-bundle", {
339
454
  entry: "src/appBundle.js",
340
455
  outputFile: "app-bundle.js",
341
456
  outDir: "dist"
342
- }), E = x("server-bundle", {
457
+ }, l("Puzzmo's pages wherever the game's thumbnails show")), R = N("server-bundle", {
343
458
  entry: "src/serverBundle.js",
344
459
  outputFile: "server-bundle.js",
345
460
  outDir: "dist-server"
346
461
  });
347
- var D = x("pmmg-bundle", {
462
+ var z = N("pmmg-bundle", {
348
463
  entry: "src/pmmgBundle.js",
349
464
  outputFile: "pmmg-bundle.js",
350
465
  outDir: "dist"
351
- });
466
+ }, l("Puzzmo's pages for every board at the table"));
352
467
  /**
353
468
  * Vite plugins for the game's pmmg bundle (see `PmmgBundle`), such as its boards at the table. After the main build
354
469
  * they produce dist/pmmg-bundle.js, which is public and served with the rest of `dist`. In dev, `/pmmg-bundle.js` on
@@ -358,7 +473,7 @@ var D = x("pmmg-bundle", {
358
473
  * Puzzmo imports it from an opaque-origin sandbox, so that one response answers any origin. It's a whole build rather
359
474
  * than the dev server's modules, since letting `Origin: null` read those would let any page read the game's source.
360
475
  */
361
- const O = (e = {}) => [D(e), {
476
+ const B = (e = {}) => [z(e), {
362
477
  name: "pmmg-bundle-dev",
363
478
  apply: "serve",
364
479
  configureServer(t) {
@@ -366,9 +481,9 @@ const O = (e = {}) => [D(e), {
366
481
  t.middlewares.use((r, i, o) => {
367
482
  var s;
368
483
  if (!/^\/pmmg-bundle\.js(?:\?.*)?$/.test(r.url || "")) return o();
369
- let c = (s = e.entry) == null ? w(t.config.root, "src/pmmgBundle") : s;
484
+ let c = (s = e.entry) == null ? I(t.config.root, "src/pmmgBundle") : s;
370
485
  if (!c) return o();
371
- n != null || (n = k(a.resolve(t.config.root, c)).finally(() => n = void 0)), n.then((e) => {
486
+ n != null || (n = V(a.resolve(t.config.root, c)).finally(() => n = void 0)), n.then((e) => {
372
487
  i.setHeader("Content-Type", "text/javascript"), i.setHeader("Access-Control-Allow-Origin", "*"), i.setHeader("Cache-Control", "no-store"), i.end(e);
373
488
  }, (e) => {
374
489
  var n;
@@ -376,11 +491,12 @@ const O = (e = {}) => [D(e), {
376
491
  });
377
492
  });
378
493
  }
379
- }], k = function() {
494
+ }], V = function() {
380
495
  var e = n(function* (e) {
381
496
  let t = yield i({
382
497
  configFile: !1,
383
498
  logLevel: "warn",
499
+ define: W,
384
500
  build: {
385
501
  write: !1,
386
502
  copyPublicDir: !1,
@@ -400,11 +516,11 @@ const O = (e = {}) => [D(e), {
400
516
  return function(t) {
401
517
  return e.apply(this, arguments);
402
518
  };
403
- }(), A = x("editor-bundle", {
519
+ }(), H = N("editor-bundle", {
404
520
  entry: "src/editorBundle.js",
405
521
  outputFile: "editor-bundle.js",
406
522
  outDir: "dist"
407
- }), j = (e, t, n = 0) => {
523
+ }), U = (e, t, n = 0) => {
408
524
  if (n >= t) return [];
409
525
  let r = [], i;
410
526
  try {
@@ -415,10 +531,15 @@ const O = (e = {}) => [D(e), {
415
531
  for (let s of i) {
416
532
  if (!s.isDirectory() || s.name.startsWith(".") || s.name === "node_modules") continue;
417
533
  let i = a.join(e, s.name);
418
- o.existsSync(a.join(i, "puzzmo.json")) && r.push(i), r.push(...j(i, t, n + 1));
534
+ o.existsSync(a.join(i, "puzzmo.json")) && r.push(i), r.push(...U(i, t, n + 1));
419
535
  }
420
536
  return r;
421
537
  };
422
- export { T as appBundlePlugin, k as buildPmmgBundleSource, _ as discoverGames, A as editorBundlePlugin, j as findPuzzmoJsonDirs, y as generateSimulatorCode, O as pmmgBundlePlugin, p as puzzmoPico8, b as puzzmoSimulator, v as resolveGameFromReferer, E as serverBundlePlugin };
538
+ /**
539
+ * Lib mode leaves `process.env.*` for a consumer's bundler to replace, but these bundles are run as-is in browsers and
540
+ * isolates with no `process`, so a dependency's `NODE_ENV` check (immer, reselect, React) would throw on load
541
+ */
542
+ var W = { "process.env.NODE_ENV": JSON.stringify("production") }, G = (e) => Object.assign(Error(e), { stack: e });
543
+ export { L as appBundlePlugin, V as buildPmmgBundleSource, k as discoverGames, H as editorBundlePlugin, U as findPuzzmoJsonDirs, j as generateSimulatorCode, B as pmmgBundlePlugin, T as puzzmoPico8, M as puzzmoSimulator, A as resolveGameFromReferer, R as serverBundlePlugin };
423
544
 
424
545
  //# sourceMappingURL=vite.js.map
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,IAA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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,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
4
4
  "description": "Puzzmo runtime SDK for game developers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",