@drincs/pixi-vn 1.9.2 → 1.9.4

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.
Files changed (59) hide show
  1. package/README.md +1 -1
  2. package/dist/{ContainerMemory-BpDgacyr.d.cts → ContainerMemory-DNqSVzLY.d.cts} +12 -116
  3. package/dist/{ContainerMemory-BpDgacyr.d.ts → ContainerMemory-DNqSVzLY.d.ts} +12 -116
  4. package/dist/canvas.cjs +2 -2
  5. package/dist/canvas.d.cts +1279 -551
  6. package/dist/canvas.d.ts +1279 -551
  7. package/dist/canvas.mjs +2 -2
  8. package/dist/characters.cjs +1 -1
  9. package/dist/characters.mjs +1 -1
  10. package/dist/{chunk-6GLWL3NH.mjs → chunk-5MVDNAT4.mjs} +1 -1
  11. package/dist/chunk-6OABTG5R.mjs +1 -0
  12. package/dist/chunk-AW5XWF24.mjs +1 -0
  13. package/dist/chunk-LXIKP2K5.mjs +1 -0
  14. package/dist/chunk-S7HZUIEI.mjs +1 -0
  15. package/dist/core.cjs +1 -1
  16. package/dist/core.d.cts +61 -5
  17. package/dist/core.d.ts +61 -5
  18. package/dist/core.mjs +1 -1
  19. package/dist/filters.cjs +1 -0
  20. package/dist/filters.d.cts +182 -0
  21. package/dist/filters.d.ts +182 -0
  22. package/dist/filters.mjs +1 -0
  23. package/dist/history.cjs +1 -1
  24. package/dist/history.d.cts +2 -2
  25. package/dist/history.d.ts +2 -2
  26. package/dist/history.mjs +1 -1
  27. package/dist/index.cjs +2 -2
  28. package/dist/index.d.cts +43 -3
  29. package/dist/index.d.ts +43 -3
  30. package/dist/index.mjs +2 -2
  31. package/dist/motion.cjs +1 -1
  32. package/dist/motion.d.cts +30 -8
  33. package/dist/motion.d.ts +30 -8
  34. package/dist/motion.mjs +1 -1
  35. package/dist/narration.cjs +1 -1
  36. package/dist/narration.d.cts +2 -1
  37. package/dist/narration.d.ts +2 -1
  38. package/dist/narration.mjs +1 -1
  39. package/dist/pixi/browser.js +170 -169
  40. package/dist/sound.mjs +1 -1
  41. package/dist/storage.cjs +1 -1
  42. package/dist/storage.d.cts +1 -1
  43. package/dist/storage.d.ts +1 -1
  44. package/dist/storage.mjs +1 -1
  45. package/dist/tickers.cjs +1 -0
  46. package/dist/tickers.d.cts +555 -0
  47. package/dist/tickers.d.ts +555 -0
  48. package/dist/tickers.mjs +1 -0
  49. package/dist/vite.cjs +6 -4
  50. package/dist/vite.d.cts +64 -0
  51. package/dist/vite.d.ts +64 -0
  52. package/dist/vite.mjs +6 -4
  53. package/dist/worker.cjs +1 -0
  54. package/dist/worker.d.cts +153 -0
  55. package/dist/worker.d.ts +153 -0
  56. package/dist/worker.mjs +1 -0
  57. package/package.json +28 -1
  58. package/dist/chunk-HQQ5WH6C.mjs +0 -1
  59. package/dist/chunk-I7DOUH5V.mjs +0 -1
package/dist/vite.d.cts CHANGED
@@ -74,6 +74,61 @@ interface VitePluginPixivnOptions {
74
74
  * @example "./src/pixi-vn.keys.gen.ts"
75
75
  */
76
76
  typeFilePath?: string;
77
+ /**
78
+ * Path to an auto-generated Worker entry file that hands every message it receives to
79
+ * `handleGameWorkerMessage` from `@drincs/pixi-vn/worker` — the file a project needs to make
80
+ * `Game.worker.register(...)` (see that function's doc comment) actually do something,
81
+ * without having to hand-write and maintain that file itself.
82
+ *
83
+ * Written once, when the plugin's config resolves (its content never changes, so unlike
84
+ * {@link typeFilePath} there's nothing to regenerate on content reload). Wire it up with
85
+ * Vite's own `?worker` import:
86
+ *
87
+ * ```ts
88
+ * // vite.config.ts
89
+ * vitePluginPixivn({ workerFilePath: "./src/pixi-vn.worker.gen.ts" })
90
+ *
91
+ * // wherever the app calls Game.init(...)
92
+ * import { Game } from "@drincs/pixi-vn";
93
+ * import PixivnWorker from "./pixi-vn.worker.gen?worker";
94
+ * Game.worker.register(new PixivnWorker());
95
+ * ```
96
+ *
97
+ * Purely a convenience: a project that wants a different worker setup (e.g. combining this
98
+ * with its own message types on the same worker) can just write the file by hand instead and
99
+ * skip this option entirely - `Game.worker.register` doesn't care which side created the file.
100
+ *
101
+ * The path may be absolute or relative to Vite `root`.
102
+ *
103
+ * @example "./src/pixi-vn.worker.gen.ts"
104
+ */
105
+ workerFilePath?: string;
106
+ /**
107
+ * Auto-registers the worker generated by {@link VitePluginPixivnOptions.workerFilePath} by
108
+ * injecting a small module into `index.html` that creates it and calls
109
+ * `Game.worker.register(...)` on page load - no app code required for this part, mirroring
110
+ * how {@link VitePluginPixivnOptions.testing} auto-injects its own bridge.
111
+ *
112
+ * Unlike `testing`, this **is** injected during `vite build` too - the worker offloads real
113
+ * runtime work (`back()`, save/export diffing), not a dev-only hook, so shipping without it
114
+ * would silently lose the optimization in production.
115
+ *
116
+ * Requires {@link VitePluginPixivnOptions.workerFilePath} to also be set; a project that needs
117
+ * more control over the worker's lifecycle (e.g. combining it with its own message types)
118
+ * should keep calling `Game.worker.register(new PixivnWorker())` by hand instead and leave
119
+ * this option unset - don't do both, the second registration would just replace the first.
120
+ *
121
+ * @default false
122
+ * @example
123
+ * ```ts
124
+ * // vite.config.ts — the entire worker setup, no app code needed
125
+ * vitePluginPixivn({
126
+ * workerFilePath: "./src/pixi-vn.worker.gen.ts",
127
+ * autoRegisterWorker: true,
128
+ * })
129
+ * ```
130
+ */
131
+ autoRegisterWorker?: boolean;
77
132
  /**
78
133
  * A PIXI.js {@link AssetsManifest} describing all asset bundles and their aliases — or a
79
134
  * function that resolves one, for manifests that aren't known synchronously at
@@ -180,6 +235,15 @@ interface VitePluginPixivnOptions {
180
235
  * The file is regenerated whenever the character or label set changes (content reload or
181
236
  * external-label updates). It is **excluded from HMR** so regenerating it never triggers a page reload.
182
237
  *
238
+ * **Auto-generated worker file**
239
+ *
240
+ * When {@link VitePluginPixivnOptions.workerFilePath} is provided, the plugin writes a Worker
241
+ * entry file wired to `handleGameWorkerMessage` from `@drincs/pixi-vn/worker` - see that option's
242
+ * doc comment for what it's for (`Game.worker.register(...)`) and how to import it. Written once
243
+ * (its content never changes), not regenerated on the triggers above. Add
244
+ * {@link VitePluginPixivnOptions.autoRegisterWorker} to also skip the manual
245
+ * `Game.worker.register(...)` call - the plugin creates and registers the worker itself.
246
+ *
183
247
  * **Auto-generated list file**
184
248
  *
185
249
  * When {@link VitePluginPixivnOptions.listFilePath} is provided, the plugin writes a
package/dist/vite.d.ts CHANGED
@@ -74,6 +74,61 @@ interface VitePluginPixivnOptions {
74
74
  * @example "./src/pixi-vn.keys.gen.ts"
75
75
  */
76
76
  typeFilePath?: string;
77
+ /**
78
+ * Path to an auto-generated Worker entry file that hands every message it receives to
79
+ * `handleGameWorkerMessage` from `@drincs/pixi-vn/worker` — the file a project needs to make
80
+ * `Game.worker.register(...)` (see that function's doc comment) actually do something,
81
+ * without having to hand-write and maintain that file itself.
82
+ *
83
+ * Written once, when the plugin's config resolves (its content never changes, so unlike
84
+ * {@link typeFilePath} there's nothing to regenerate on content reload). Wire it up with
85
+ * Vite's own `?worker` import:
86
+ *
87
+ * ```ts
88
+ * // vite.config.ts
89
+ * vitePluginPixivn({ workerFilePath: "./src/pixi-vn.worker.gen.ts" })
90
+ *
91
+ * // wherever the app calls Game.init(...)
92
+ * import { Game } from "@drincs/pixi-vn";
93
+ * import PixivnWorker from "./pixi-vn.worker.gen?worker";
94
+ * Game.worker.register(new PixivnWorker());
95
+ * ```
96
+ *
97
+ * Purely a convenience: a project that wants a different worker setup (e.g. combining this
98
+ * with its own message types on the same worker) can just write the file by hand instead and
99
+ * skip this option entirely - `Game.worker.register` doesn't care which side created the file.
100
+ *
101
+ * The path may be absolute or relative to Vite `root`.
102
+ *
103
+ * @example "./src/pixi-vn.worker.gen.ts"
104
+ */
105
+ workerFilePath?: string;
106
+ /**
107
+ * Auto-registers the worker generated by {@link VitePluginPixivnOptions.workerFilePath} by
108
+ * injecting a small module into `index.html` that creates it and calls
109
+ * `Game.worker.register(...)` on page load - no app code required for this part, mirroring
110
+ * how {@link VitePluginPixivnOptions.testing} auto-injects its own bridge.
111
+ *
112
+ * Unlike `testing`, this **is** injected during `vite build` too - the worker offloads real
113
+ * runtime work (`back()`, save/export diffing), not a dev-only hook, so shipping without it
114
+ * would silently lose the optimization in production.
115
+ *
116
+ * Requires {@link VitePluginPixivnOptions.workerFilePath} to also be set; a project that needs
117
+ * more control over the worker's lifecycle (e.g. combining it with its own message types)
118
+ * should keep calling `Game.worker.register(new PixivnWorker())` by hand instead and leave
119
+ * this option unset - don't do both, the second registration would just replace the first.
120
+ *
121
+ * @default false
122
+ * @example
123
+ * ```ts
124
+ * // vite.config.ts — the entire worker setup, no app code needed
125
+ * vitePluginPixivn({
126
+ * workerFilePath: "./src/pixi-vn.worker.gen.ts",
127
+ * autoRegisterWorker: true,
128
+ * })
129
+ * ```
130
+ */
131
+ autoRegisterWorker?: boolean;
77
132
  /**
78
133
  * A PIXI.js {@link AssetsManifest} describing all asset bundles and their aliases — or a
79
134
  * function that resolves one, for manifests that aren't known synchronously at
@@ -180,6 +235,15 @@ interface VitePluginPixivnOptions {
180
235
  * The file is regenerated whenever the character or label set changes (content reload or
181
236
  * external-label updates). It is **excluded from HMR** so regenerating it never triggers a page reload.
182
237
  *
238
+ * **Auto-generated worker file**
239
+ *
240
+ * When {@link VitePluginPixivnOptions.workerFilePath} is provided, the plugin writes a Worker
241
+ * entry file wired to `handleGameWorkerMessage` from `@drincs/pixi-vn/worker` - see that option's
242
+ * doc comment for what it's for (`Game.worker.register(...)`) and how to import it. Written once
243
+ * (its content never changes), not regenerated on the triggers above. Add
244
+ * {@link VitePluginPixivnOptions.autoRegisterWorker} to also skip the manual
245
+ * `Game.worker.register(...)` call - the plugin creates and registers the worker itself.
246
+ *
183
247
  * **Auto-generated list file**
184
248
  *
185
249
  * When {@link VitePluginPixivnOptions.listFilePath} is provided, the plugin writes a
package/dist/vite.mjs CHANGED
@@ -1,4 +1,6 @@
1
- import {a as a$1,b,c as c$1,d}from'./chunk-3BBZHKU4.mjs';export{c as PIXIVN_DEV_API_ASSETS_MANIFEST,d as PIXIVN_DEV_API_CANVAS_OPTIONS,a as PIXIVN_DEV_API_CHARACTERS,b as PIXIVN_DEV_API_LABELS}from'./chunk-3BBZHKU4.mjs';import {a,c}from'./chunk-K7JIC2F2.mjs';import {mkdirSync,writeFileSync,readFileSync}from'fs';import {isAbsolute,resolve,dirname}from'path';import {glob}from'tinyglobby';var G=a((me,R)=>{var A=process||{},D=A.argv||[],I=A.env||{},Z=!(I.NO_COLOR||D.includes("--no-color"))&&(!!I.FORCE_COLOR||D.includes("--color")||A.platform==="win32"||(A.stdout||{}).isTTY&&I.TERM!=="dumb"||!!I.CI),q=(r,e,u=r)=>m=>{let l=""+m,c=l.indexOf(e,r.length);return ~c?r+ee(l,e,u,c)+e:r+l+e},ee=(r,e,u,m)=>{let l="",c=0;do l+=r.substring(c,m)+u,c=m+e.length,m=r.indexOf(e,c);while(~m);return l+r.substring(c)},j=(r=Z)=>{let e=r?q:()=>String;return {isColorSupported:r,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};R.exports=j();R.exports.createColors=j;});var F=c(G(),1);var v=F.default.cyan("(pixi-vn)"),V="virtual:pixi-vn-testing",K=`\0${V}`;function x(r){return r?Array.isArray(r)?r:[r]:[]}function oe(r){return r?r.bundles.map(e=>e.name):[]}function ce(r){if(!r)return [];let e=new Set;for(let u of r.bundles){let m=u.assets;if(Array.isArray(m))for(let l of m){let c=l.alias;if(c)for(let g of Array.isArray(c)?c:[c])e.add(g);}else if(m&&typeof m=="object")for(let l of Object.keys(m))e.add(l);}return Array.from(e)}function le(r){let e=[],u=[];for(let m of r)try{let l=readFileSync(m,"utf-8"),c=/newLabel\(\s*["']([^"']+)["']/g,g;for(;(g=c.exec(l))!==null;)u.push(g[1]);let h=/new\s+\w*[Cc]haracter\(\s*["']([^"']+)["']/g;for(;(g=h.exec(l))!==null;)e.push(g[1]);}catch{}return {charIds:e,labelIds:u}}function de(r){let e,u,m=new Promise(t=>{u=t;}),l=[...x(r?.content),...x(r?.characters),...x(r?.labels)],c=[],g=[],h=new Set,L=[],w=typeof r?.assetsManifest=="function",H=r?.testing===false,$=typeof r?.testing=="object"?r.testing.windowKey:void 0,y=typeof r?.assetsManifest=="function"?void 0:r?.assetsManifest;async function P(t){if(typeof r?.assetsManifest=="function")try{let n=await r.assetsManifest(t);y=n,p.manifest=n??null;}catch(n){e?.logger.error(`${v} Failed to resolve the assets manifest.`,{error:n instanceof Error?n:new Error(String(n)),timestamp:true});}}let E=new Map;function B(){if(!r?.typeFilePath||!e)return null;let t=r.typeFilePath;return isAbsolute(t)?t:resolve(e.root,t)}function T(){let t=[...g,...Array.from(E.values()).flat()];return Array.from(new Set(t))}function U(t,n,s,i,f){mkdirSync(dirname(t),{recursive:true});let a=["/* eslint-disable */","// noinspection JSUnusedGlobalSymbols","// This file is auto-generated by @drincs/pixi-vn vite plugin. Do not edit manually."];if(n.length>0){a.push('declare module "@drincs/pixi-vn/characters" {'),a.push(" interface PixivnCharacterIds {");for(let o of n)a.push(` ${JSON.stringify(o)}: never;`);a.push(" }"),a.push("}");}if(s.length>0){a.push('declare module "@drincs/pixi-vn/narration" {'),a.push(" interface PixivnLabelIds {");for(let o of s)a.push(` ${JSON.stringify(o)}: never;`);a.push(" }"),a.push("}");}if(i.length>0||f.length>0){if(a.push('declare module "@drincs/pixi-vn/canvas" {'),i.length>0){a.push(" interface PixivnBundleIds {");for(let o of i)a.push(` ${JSON.stringify(o)}: never;`);a.push(" }");}if(f.length>0){a.push(" interface PixivnAssetAliasIds {");for(let o of f)a.push(` ${JSON.stringify(o)}: never;`);a.push(" }");}a.push("}");}a.push(`export const characterIds = ${JSON.stringify(n)} as const;`);{let o=Object.fromEntries(n.map(d=>[d,d]));a.push(`export const characterIdsEnum = ${JSON.stringify(o)} as const;`);}a.push(`export const labelIds = ${JSON.stringify(s)} as const;`);{let o=Object.fromEntries(s.map(d=>[d,d]));a.push(`export const labelIdsEnum = ${JSON.stringify(o)} as const;`);}a.push(`export const bundleIds = ${JSON.stringify(i)} as const;`);{let o=Object.fromEntries(i.map(d=>[d,d]));a.push(`export const bundleIdsEnum = ${JSON.stringify(o)} as const;`);}a.push(`export const assetAliasIds = ${JSON.stringify(f)} as const;`);{let o=Object.fromEntries(f.map(d=>[d,d]));a.push(`export const assetAliasIdsEnum = ${JSON.stringify(o)} as const;`);}a.push(""),writeFileSync(t,a.join(`
2
- `),"utf-8");}function z(){p.characters=c,p.labels=T();}function b$1(){z();let t=B();if(t)try{U(t,c.map(n=>n.id),T(),oe(y),ce(y));}catch(n){e?.logger.error(`${v} Failed to write keys file "${t}".`,{error:n instanceof Error?n:new Error(String(n)),timestamp:true});}}async function O(t,n=[]){try{c=(await t("@drincs/pixi-vn/characters")).RegisteredCharacters?.values()??[];}catch{c=[];}try{g=(await t("@drincs/pixi-vn/narration")).RegisteredLabels?.keys()??[];}catch{g=[];}if(n.length>0){let{charIds:i,labelIds:f}=le(n),a=new Set(c.map(d=>d.id)),o=new Set(g);for(let d of i)a.has(d)||c.push({id:d});for(let d of f)o.has(d)||g.push(d);}let s=c.map(i=>i.id).join(", ")||"none";e?.logger.info(`${v} ${F.default.dim(`${c.length} character(s): [${s}], ${g.length} label(s)`)}`,{timestamp:true});}async function J(t,n){let s=[],i=[...x(r?.characters),...x(r?.labels)],f=await glob(i,{cwd:n,absolute:true,onlyFiles:true});for(let o of f){h.add(o);try{await t(o);}catch{s.push(o);}}await O(t,s),b$1();let a=await glob(x(r?.content),{cwd:n,absolute:true,onlyFiles:true});for(let o of a){h.add(o);try{await t(o);}catch{s.push(o);}}return s}async function k(t,n){try{await t("@drincs/pixi-vn/characters");}catch{}try{await t("@drincs/pixi-vn/narration");}catch{}let s=await J(t,n);await O(t,s),await P(t),b$1(),u();}async function W(t){for(let s of h)for(let i of t.moduleGraph.getModulesByFile(s)??[])t.moduleGraph.invalidateModule(i);try{(await t.ssrLoadModule("@drincs/pixi-vn/characters")).RegisteredCharacters?.clear?.();}catch{}try{(await t.ssrLoadModule("@drincs/pixi-vn/narration")).RegisteredLabels?.clear?.();}catch{}let n=await J(s=>t.ssrLoadModule(s),e.root);await O(s=>t.ssrLoadModule(s),n),await P(s=>t.ssrLoadModule(s)),b$1();for(let s of L)s();}let p={characters:null,labels:null,manifest:y??null,canvasOptions:null};function S(t,n){return (s,i)=>{if(i.setHeader("Content-Type","application/json"),s.method==="GET"){let f=p[t];if(f===null){i.statusCode=404,i.end(JSON.stringify({error:`${n} not initialized`}));return}i.statusCode=200,i.end(JSON.stringify(f));return}if(s.method==="POST"){let f="";s.on("data",a=>{f+=a.toString();}),s.on("end",()=>{try{p[t]=JSON.parse(f),i.statusCode=201,i.end(JSON.stringify({message:`${n} updated successfully`}));}catch{i.statusCode=400,i.end(JSON.stringify({error:`Invalid JSON format for ${n}`}));}});}}}return {name:"vite-plugin-pixi-vn",enforce:"pre",api:{contentLoaded:m,get characters(){return c},onReload(t){L.push(t);},setExternalLabels(t,n){E.set(t,n),b$1();},clearExternalLabels(t){E.delete(t),b$1();},setAssetsManifest(t){y=t,p.manifest=t,b$1();}},resolveId(t){if(t===V)return K},load(t){if(t===K)return `import { Game } from "@drincs/pixi-vn";
3
- Game.testing.enable(${$?JSON.stringify({windowKey:$}):""});
4
- `},transformIndexHtml(){if(!(H||e?.command!=="serve"))return [{tag:"script",attrs:{type:"module",src:`/@id/${V}`},injectTo:"head-prepend"}]},config(t,n){if(n.command==="serve"&&l.length>0)return {ssr:{noExternal:["@drincs/pixi-vn"]}}},configResolved(t){e=t,l.length===0&&!w&&(b$1(),u());},async buildStart(){if(e?.command!=="build"||l.length===0&&!w)return;let{createServer:t}=await import('vite'),n=await t({root:e.root,configFile:false,resolve:e.resolve,server:{middlewareMode:true},appType:"custom",logLevel:"silent",optimizeDeps:{noDiscovery:true},ssr:{noExternal:["@drincs/pixi-vn"]}});try{await k(s=>n.ssrLoadModule(s),e.root);}catch{u();}finally{await n.close();}},configureServer(t){(l.length>0||w)&&k(n=>t.ssrLoadModule(n),e.root).catch(()=>{u();}),t.middlewares.use(a$1,S("characters","Characters")),t.middlewares.use(b,S("labels","Labels")),t.middlewares.use(c$1,S("manifest","Manifest")),t.middlewares.use(d,S("canvasOptions","Canvas options"));},async hotUpdate({file:t,server:n}){let s=B();if(s&&t===s)return [];if(l.length>0&&h.has(t)){try{await W(n);}catch(i){e?.logger.error(`${v} Failed to reload content.`,{error:i instanceof Error?i:new Error(String(i)),timestamp:true});}return []}if(w)try{await P(i=>n.ssrLoadModule(i)),b$1();}catch(i){e?.logger.error(`${v} Failed to refresh the assets manifest.`,{error:i instanceof Error?i:new Error(String(i)),timestamp:true});}}}}export{de as vitePluginPixivn};
1
+ import {a as a$1,b,c as c$1,d}from'./chunk-3BBZHKU4.mjs';export{c as PIXIVN_DEV_API_ASSETS_MANIFEST,d as PIXIVN_DEV_API_CANVAS_OPTIONS,a as PIXIVN_DEV_API_CHARACTERS,b as PIXIVN_DEV_API_LABELS}from'./chunk-3BBZHKU4.mjs';import {a,c}from'./chunk-K7JIC2F2.mjs';import {mkdirSync,writeFileSync,readFileSync}from'fs';import {isAbsolute,resolve,dirname}from'path';import {glob}from'tinyglobby';import {normalizePath}from'vite';var K=a((he,F)=>{var A=process||{},W=A.argv||[],P=A.env||{},ce=!(P.NO_COLOR||W.includes("--no-color"))&&(!!P.FORCE_COLOR||W.includes("--color")||A.platform==="win32"||(A.stdout||{}).isTTY&&P.TERM!=="dumb"||!!P.CI),le=(n,t,m=n)=>f=>{let u=""+f,l=u.indexOf(t,n.length);return ~l?n+ue(u,t,m,l)+t:n+u+t},ue=(n,t,m,f)=>{let u="",l=0;do u+=n.substring(l,f)+m,l=f+t.length,f=n.indexOf(t,l);while(~f);return u+n.substring(l)},X=(n=ce)=>{let t=n?le:()=>String;return {isColorSupported:n,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};F.exports=X();F.exports.createColors=X;});var T=c(K(),1);var h=T.default.cyan("(pixi-vn)"),V="virtual:pixi-vn-testing",q=`\0${V}`,$="virtual:pixi-vn-worker-register",ee=`\0${$}`;function y(n){return n?Array.isArray(n)?n:[n]:[]}function fe(n){return n?n.bundles.map(t=>t.name):[]}function me(n){if(!n)return [];let t=new Set;for(let m of n.bundles){let f=m.assets;if(Array.isArray(f))for(let u of f){let l=u.alias;if(l)for(let g of Array.isArray(l)?l:[l])t.add(g);}else if(f&&typeof f=="object")for(let u of Object.keys(f))t.add(u);}return Array.from(t)}function ge(n){let t=[],m=[];for(let f of n)try{let u=readFileSync(f,"utf-8"),l=/newLabel\(\s*["']([^"']+)["']/g,g;for(;(g=l.exec(u))!==null;)m.push(g[1]);let p=/new\s+\w*[Cc]haracter\(\s*["']([^"']+)["']/g;for(;(g=p.exec(u))!==null;)t.push(g[1]);}catch{}return {charIds:t,labelIds:m}}function be(n){let t,m,f=new Promise(e=>{m=e;}),u=[...y(n?.content),...y(n?.characters),...y(n?.labels)],l=[],g=[],p=new Set,L=[],w=typeof n?.assetsManifest=="function",te=n?.testing===false,B=typeof n?.testing=="object"?n.testing.windowKey:void 0,v=typeof n?.assetsManifest=="function"?void 0:n?.assetsManifest;async function O(e){if(typeof n?.assetsManifest=="function")try{let r=await n.assetsManifest(e);v=r,x.manifest=r??null;}catch(r){t?.logger.error(`${h} Failed to resolve the assets manifest.`,{error:r instanceof Error?r:new Error(String(r)),timestamp:true});}}let _=new Map;function J(){if(!n?.typeFilePath||!t)return null;let e=n.typeFilePath;return isAbsolute(e)?e:resolve(t.root,e)}function I(){if(!n?.workerFilePath||!t)return null;let e=n.workerFilePath;return isAbsolute(e)?e:resolve(t.root,e)}function re(){let e=I();if(e)try{mkdirSync(dirname(e),{recursive:!0}),writeFileSync(e,["/* eslint-disable */","// noinspection JSUnusedGlobalSymbols","// This file is auto-generated by @drincs/pixi-vn vite plugin. Do not edit manually.",'import { handleGameWorkerMessage } from "@drincs/pixi-vn/worker";',"","self.onmessage = async (event) => {"," const response = await handleGameWorkerMessage(event.data);"," if (response) self.postMessage(response);","};",""].join(`
2
+ `),"utf-8");}catch(r){t?.logger.error(`${h} Failed to write worker file "${e}".`,{error:r instanceof Error?r:new Error(String(r)),timestamp:true});}}function D(){let e=[...g,...Array.from(_.values()).flat()];return Array.from(new Set(e))}function ne(e,r,s,a,o){mkdirSync(dirname(e),{recursive:true});let i=["/* eslint-disable */","// noinspection JSUnusedGlobalSymbols","// This file is auto-generated by @drincs/pixi-vn vite plugin. Do not edit manually."];if(r.length>0){i.push('declare module "@drincs/pixi-vn/characters" {'),i.push(" interface PixivnCharacterIds {");for(let c of r)i.push(` ${JSON.stringify(c)}: never;`);i.push(" }"),i.push("}");}if(s.length>0){i.push('declare module "@drincs/pixi-vn/narration" {'),i.push(" interface PixivnLabelIds {");for(let c of s)i.push(` ${JSON.stringify(c)}: never;`);i.push(" }"),i.push("}");}if(a.length>0||o.length>0){if(i.push('declare module "@drincs/pixi-vn/canvas" {'),a.length>0){i.push(" interface PixivnBundleIds {");for(let c of a)i.push(` ${JSON.stringify(c)}: never;`);i.push(" }");}if(o.length>0){i.push(" interface PixivnAssetAliasIds {");for(let c of o)i.push(` ${JSON.stringify(c)}: never;`);i.push(" }");}i.push("}");}i.push(`export const characterIds = ${JSON.stringify(r)} as const;`);{let c=Object.fromEntries(r.map(d=>[d,d]));i.push(`export const characterIdsEnum = ${JSON.stringify(c)} as const;`);}i.push(`export const labelIds = ${JSON.stringify(s)} as const;`);{let c=Object.fromEntries(s.map(d=>[d,d]));i.push(`export const labelIdsEnum = ${JSON.stringify(c)} as const;`);}i.push(`export const bundleIds = ${JSON.stringify(a)} as const;`);{let c=Object.fromEntries(a.map(d=>[d,d]));i.push(`export const bundleIdsEnum = ${JSON.stringify(c)} as const;`);}i.push(`export const assetAliasIds = ${JSON.stringify(o)} as const;`);{let c=Object.fromEntries(o.map(d=>[d,d]));i.push(`export const assetAliasIdsEnum = ${JSON.stringify(c)} as const;`);}i.push(""),writeFileSync(e,i.join(`
3
+ `),"utf-8");}function se(){x.characters=l,x.labels=D();}function b$1(){se();let e=J();if(e)try{ne(e,l.map(r=>r.id),D(),fe(v),me(v));}catch(r){t?.logger.error(`${h} Failed to write keys file "${e}".`,{error:r instanceof Error?r:new Error(String(r)),timestamp:true});}}async function R(e,r=[]){try{l=(await e("@drincs/pixi-vn/characters")).RegisteredCharacters?.values()??[];}catch{l=[];}try{g=(await e("@drincs/pixi-vn/narration")).RegisteredLabels?.keys()??[];}catch{g=[];}if(r.length>0){let{charIds:a,labelIds:o}=ge(r),i=new Set(l.map(d=>d.id)),c=new Set(g);for(let d of a)i.has(d)||l.push({id:d});for(let d of o)c.has(d)||g.push(d);}let s=l.map(a=>a.id).join(", ")||"none";t?.logger.info(`${h} ${T.default.dim(`${l.length} character(s): [${s}], ${g.length} label(s)`)}`,{timestamp:true});}async function G(e,r){let s=[],a=[...y(n?.characters),...y(n?.labels)],o=await glob(a,{cwd:r,absolute:true,onlyFiles:true});for(let c of o){p.add(normalizePath(c));try{await e(c);}catch{s.push(c);}}await R(e,s),b$1();let i=await glob(y(n?.content),{cwd:r,absolute:true,onlyFiles:true});for(let c of i){p.add(normalizePath(c));try{await e(c);}catch{s.push(c);}}return s}async function j(e,r){try{await e("@drincs/pixi-vn/characters");}catch{}try{await e("@drincs/pixi-vn/narration");}catch{}let s=await G(e,r);await R(e,s),await O(e),b$1(),m();}async function ie(e){for(let s of p)for(let a of e.moduleGraph.getModulesByFile(s)??[])e.moduleGraph.invalidateModule(a);try{(await e.ssrLoadModule("@drincs/pixi-vn/characters")).RegisteredCharacters?.clear?.();}catch{}try{(await e.ssrLoadModule("@drincs/pixi-vn/narration")).RegisteredLabels?.clear?.();}catch{}let r=await G(s=>e.ssrLoadModule(s),t.root);await R(s=>e.ssrLoadModule(s),r),await O(s=>e.ssrLoadModule(s)),b$1();for(let s of L)s();}let x={characters:null,labels:null,manifest:v??null,canvasOptions:null};function S(e,r){return (s,a)=>{if(a.setHeader("Content-Type","application/json"),s.method==="GET"){let o=x[e];if(o===null){a.statusCode=404,a.end(JSON.stringify({error:`${r} not initialized`}));return}a.statusCode=200,a.end(JSON.stringify(o));return}if(s.method==="POST"){let o="";s.on("data",i=>{o+=i.toString();}),s.on("end",()=>{try{x[e]=JSON.parse(o),a.statusCode=201,a.end(JSON.stringify({message:`${r} updated successfully`}));}catch{a.statusCode=400,a.end(JSON.stringify({error:`Invalid JSON format for ${r}`}));}});}}}return {name:"vite-plugin-pixi-vn",enforce:"pre",api:{contentLoaded:f,get characters(){return l},onReload(e){L.push(e);},setExternalLabels(e,r){_.set(e,r),b$1();},clearExternalLabels(e){_.delete(e),b$1();},setAssetsManifest(e){v=e,x.manifest=e,b$1();}},resolveId(e){if(e===V)return q;if(e===$)return ee},load(e){if(e===q)return `import { Game } from "@drincs/pixi-vn";
4
+ Game.testing.enable(${B?JSON.stringify({windowKey:B}):""});
5
+ `;if(e===ee){let r=I();return r?['import { Game } from "@drincs/pixi-vn";',`import PixivnWorker from ${JSON.stringify(`${r}?worker`)};`,"Game.worker.register(new PixivnWorker());",""].join(`
6
+ `):""}},transformIndexHtml(){let e=[];return !te&&t?.command==="serve"&&e.push({tag:"script",attrs:{type:"module",src:`/@id/${V}`},injectTo:"head-prepend"}),n?.autoRegisterWorker&&I()&&e.push({tag:"script",attrs:{type:"module",src:`/@id/${$}`},injectTo:"head-prepend"}),e},config(e,r){if(r.command==="serve"&&u.length>0)return {ssr:{noExternal:["@drincs/pixi-vn"]}}},configResolved(e){t=e,re(),n?.autoRegisterWorker&&!I()&&t.logger.warn(`${h} "autoRegisterWorker" has no effect without "workerFilePath" - set both to auto-register the generated worker.`,{timestamp:true}),u.length===0&&!w&&(b$1(),m());},async buildStart(){if(t?.command!=="build"||u.length===0&&!w)return;let{createServer:e}=await import('vite'),r=await e({root:t.root,configFile:false,resolve:t.resolve,server:{middlewareMode:true},appType:"custom",logLevel:"silent",optimizeDeps:{noDiscovery:true},ssr:{noExternal:["@drincs/pixi-vn"]}});try{await j(s=>r.ssrLoadModule(s),t.root);}catch{m();}finally{await r.close();}},configureServer(e){(u.length>0||w)&&j(r=>e.ssrLoadModule(r),t.root).catch(()=>{m();}),e.middlewares.use(a$1,S("characters","Characters")),e.middlewares.use(b,S("labels","Labels")),e.middlewares.use(c$1,S("manifest","Manifest")),e.middlewares.use(d,S("canvasOptions","Canvas options"));},async hotUpdate({file:e,server:r}){let s=normalizePath(e),a=J();if(a&&s===normalizePath(a))return [];if(u.length>0&&p.has(s)){try{await ie(r);}catch(o){t?.logger.error(`${h} Failed to reload content.`,{error:o instanceof Error?o:new Error(String(o)),timestamp:true});}return []}if(w)try{await O(o=>r.ssrLoadModule(o)),b$1();}catch(o){t?.logger.error(`${h} Failed to refresh the assets manifest.`,{error:o instanceof Error?o:new Error(String(o)),timestamp:true});}}}}export{be as vitePluginPixivn};
@@ -0,0 +1 @@
1
+ 'use strict';var i=class extends Error{code;constructor(t,r,a,o,m){super(`[Pixi\u2019VN] ${r}`),this.code=t,a==="canvas"&&(this.canvasElementInfo=o,this.parent=m);}canvasElementInfo;parent};var n;(o=>(o.log=(m,...l)=>console.log(`[Pixi\u2019VN] ${m}`,...l),o.warn=(m,...l)=>console.warn(`[Pixi\u2019VN] ${m}`,...l),o.error=(m,...l)=>console.error(`[Pixi\u2019VN] ${m}`,...l),o.info=(m,...l)=>console.info(`[Pixi\u2019VN] ${m}`,...l)))(n||={});(class e{static init(t){t.navigate&&(e._navigate=t.navigate),e._getStepCounter=t.getStepCounter,e._setStepCounter=t.setStepCounter,e._getCurrentGameStepState=t.getCurrentGameStepState,e._restoreGameStepState=t.restoreGameStepState,e._getOpenedLabels=t.getOpenedLabels,e._processNavigationRequests=t.processNavigationRequests,e._getVariable=t.getVariable,e._setVariable=t.setVariable,e._removeVariable=t.removeVariable,e._getFlag=t.getFlag,e._setFlag=t.setFlag,t.onLabelClosing&&(e._onLabelClosing=t.onLabelClosing),e._addHistoryItem=t.addHistoryItem,e._getCharacter=t.getCharacter,e._animate=t.animate,e._animateFilter=t.animateFilter,e._removeCanvasComponent=t.removeCanvasComponent,e._canvasComponentExists=t.canvasComponentExists;}static _navigate=()=>{n.warn("Navigate function not initialized. You should add the navigate function in the Game.init() method.");};static get navigate(){return e._navigate}static set navigate(t){e._navigate=t;}static _getStepCounter=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static _setStepCounter=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get stepCounter(){return e._getStepCounter()}static set stepCounter(t){e._setStepCounter(t);}static _getCurrentGameStepState=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get currentGameStepState(){return e._getCurrentGameStepState()}static _restoreGameStepState=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get restoreGameStepState(){return e._restoreGameStepState}static _getOpenedLabels=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get openedLabels(){return e._getOpenedLabels()}static _onPreContinueHandlers=[];static addOnPreContinue(t){e._onPreContinueHandlers.push(t);}static removeOnPreContinue(t){e._onPreContinueHandlers=e._onPreContinueHandlers.filter(r=>r!==t);}static clearOnPreContinueHandlers(){e._onPreContinueHandlers=[];}static async runOnPreContinue(){let t=e._onPreContinueHandlers.slice();await Promise.all(t.map(r=>r()));}static get onPreContinue(){return e.runOnPreContinue}static navigationRequestsCount=0;static processNavigationLock=Promise.resolve();static get continueRequestsCount(){return e.navigationRequestsCount}static increaseContinueRequest(t=1){e.navigationRequestsCount+=t;}static get backRequestsCount(){return -1*e.navigationRequestsCount}static increaseBackRequest(t=1){e.navigationRequestsCount-=t;}static _processNavigationRequests=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static async processNavigationRequests(t){let r=e._processNavigationRequests(e.navigationRequestsCount,t);return e.navigationRequestsCount=r.newValue,await r.result}static _getVariable=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get getVariable(){return e._getVariable}static _setVariable=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get setVariable(){return e._setVariable}static _removeVariable=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get removeVariable(){return e._removeVariable}static _getFlag=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get getFlag(){return e._getFlag}static _setFlag=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get setFlag(){return e._setFlag}static _onLabelClosing=()=>{};static get onLabelClosing(){return e._onLabelClosing}static _addHistoryItem=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get addHistoryItem(){return e._addHistoryItem}static runningStepsCount=0;static _getCharacter=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented.")};static get getCharacter(){return e._getCharacter}static onEnd;static _onErrorHandlers=[];static addOnError(t){return e._onErrorHandlers.push(t),()=>e.removeOnError(t)}static removeOnError(t){e._onErrorHandlers=e._onErrorHandlers.filter(r=>r!==t);}static clearOnErrorHandlers(){e._onErrorHandlers.length=0;}static async runOnError(t,r){for(let a of e._onErrorHandlers.slice())try{await a(t,r);}catch(o){n.error("Error in onError handler",o);}}static _animate=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get animate(){return e._animate}static _animateFilter=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get animateFilter(){return e._animateFilter}static _removeCanvasComponent=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get removeCanvasComponent(){return e._removeCanvasComponent}static _canvasComponentExists=()=>{throw n.error("Method not implemented, you should initialize the Game: Game.init()"),new i("not_implemented","Method not implemented, you should initialize the Game: Game.init()")};static get canvasComponentExists(){return e._canvasComponentExists}});function y(e){try{if(typeof e>"u")return e;let t=JSON.stringify(e);return JSON.parse(t)}catch(t){throw n.error("Error creating exportable element",e,t),new i("not_json_serializable","Error creating exportable element")}}function h(e,t){let r=y(e);return t.length>1&&"type"in t[0]&&(t=t.slice().reverse()),t.forEach(a=>{k(r,a);}),r}function k(e,t){let r=e;t.path&&t.path.length>0?t.path.forEach((a,o)=>{if(t.path&&o===t.path.length-1)switch(t.type){case "CHANGE":case "REMOVE":r[a]=t.oldValue;break;case "CREATE":Array.isArray(r)&&typeof a=="number"?r.splice(a,1):delete r[a];break}else r=r[a];}):n.warn("No path found, skipping diff",t);}var w=["Date","RegExp","String","Number"],E=Object.getOwnPropertyNames(globalThis.Temporal||{});function c(e,t,r={cyclesFix:true},a=[]){let o=[],m=Array.isArray(e);for(let p in e){let s=e[p],v=m?+p:p;if(!(p in t)){o.push({type:"REMOVE",path:[v],oldValue:s});continue}let u=t[p],G=typeof s=="object"&&typeof u=="object"&&Array.isArray(s)===Array.isArray(u),g=G&&s?Object.getPrototypeOf(s)?.constructor?.name:void 0;if(s&&u&&G&&!w.includes(g)&&!E.includes(g)&&(!r.cyclesFix||!a.includes(s))){r.cyclesFix&&a.push(s);let S=c(s,u,r,a);r.cyclesFix&&a.pop();for(let C of S)C.path.unshift(v),o.push(C);}else Object.is(s,u)||E.includes(g)&&String(s)===String(u)||w.includes(g)&&(isNaN(s)?s+""==u+"":+s==+u)||o.push({path:[v],type:"CHANGE",value:u,oldValue:s});}let l=Array.isArray(t);for(let p in t)p in e||o.push({type:"CREATE",path:[l?+p:p],value:t[p]});return o}var b=new Map;function x(e,t){b.set(e,t);}function P(e){b.delete(e);}function T(e){return b.get(e)}async function M(e){try{switch(e.type){case "restore-diff":{let t=h(e.state,e.diff);return {id:e.id,type:"restore-diff-result",result:t}}case "diff":{let t=c(e.before,e.after);return {id:e.id,type:"diff-result",result:t}}case "clone":{let t=JSON.parse(JSON.stringify(e.value));return {id:e.id,type:"clone-result",result:t}}case "custom":{let t=T(e.kind);if(!t)throw new Error(`No game worker handler registered for kind "${e.kind}"`);let r=await t(e.payload);return {id:e.id,type:"custom-result",result:r}}}}catch(t){return {id:e.id,type:"error",error:t instanceof Error?t.message:String(t)}}}var d=class e{static _worker;static _pending=new Map;static _nextId=0;static get isAvailable(){return e._worker!==void 0}static register(t){e.unregister(),e._worker=t,t.addEventListener("message",e._handleMessage);}static unregister(){let t=e._worker;if(t){t.removeEventListener("message",e._handleMessage),e._worker=void 0;for(let{reject:r}of e._pending.values())r(new Error("Game worker was unregistered"));e._pending.clear();}}static _handleMessage=t=>{let r=e._pending.get(t.data.id);r&&(e._pending.delete(t.data.id),t.data.type==="error"?r.reject(new Error(t.data.error)):r.resolve(t.data.result));};static _request(t){let r=e._worker;if(!r)return Promise.reject(new Error("No game worker is registered"));let a=e._nextId++;return new Promise((o,m)=>{e._pending.set(a,{resolve:o,reject:m});try{r.postMessage({...t,id:a});}catch(l){e._pending.delete(a),n.error("Error posting message to game worker",l),m(l);}})}static async restoreDiff(t,r){return await e._request({type:"restore-diff",state:t,diff:r})}static async diff(t,r){return await e._request({type:"diff",before:t,after:r})}static async clone(t){return await e._request({type:"clone",value:t})}static async custom(t,r){return await e._request({type:"custom",kind:t,payload:r})}};async function R(e,t){if(d.isAvailable)try{return await d.restoreDiff(e,t)}catch(r){n.warn("Game worker failed to restore diff, falling back to the main thread",r);}return h(e,t)}async function O(e,t){if(d.isAvailable)try{return await d.diff(e,t)}catch(r){n.warn("Game worker failed to compute diff, falling back to the main thread",r);}return c(e,t)}async function H(e){if(d.isAvailable)try{return await d.clone(e)}catch(t){n.warn("Game worker failed to clone value, falling back to the main thread",t);}return y(e)}exports.GameWorkerManager=d;exports.cloneMaybeOffloaded=H;exports.diffMaybeOffloaded=O;exports.handleGameWorkerMessage=M;exports.registerGameWorkerHandler=x;exports.restoreDiffMaybeOffloaded=R;exports.unregisterGameWorkerHandler=P;
@@ -0,0 +1,153 @@
1
+ import { Difference } from 'microdiff';
2
+
3
+ /**
4
+ * Message protocol between the main thread and an optional {@link GameWorker}-registered
5
+ * Worker. Kept intentionally small: each request names one unit of work Pixi'VN (or a
6
+ * third-party library building on it, via `"custom"` - see `registerGameWorkerHandler`) knows
7
+ * how to hand off, and the worker replies with the same `id` so the caller can match the
8
+ * response.
9
+ *
10
+ * This protocol (and everything it carries) only ever deals with plain, structured-clone-safe
11
+ * data - never PixiJS/canvas/audio objects, which can't leave the main thread.
12
+ */
13
+ type GameWorkerRequest = {
14
+ id: number;
15
+ type: "restore-diff";
16
+ /** The base state to apply `diff` to (not mutated). */
17
+ state: object;
18
+ diff: Difference[];
19
+ } | {
20
+ id: number;
21
+ type: "diff";
22
+ /** The two states to compare (neither is mutated). */
23
+ before: object;
24
+ after: object;
25
+ } | {
26
+ id: number;
27
+ type: "clone";
28
+ /** The value to deep-clone. */
29
+ value: object;
30
+ } | {
31
+ id: number;
32
+ type: "custom";
33
+ /** Identifies which registered handler (see `registerGameWorkerHandler`) should run. */
34
+ kind: string;
35
+ payload: unknown;
36
+ };
37
+ type GameWorkerResponse = {
38
+ id: number;
39
+ type: "restore-diff-result";
40
+ result: object;
41
+ } | {
42
+ id: number;
43
+ type: "diff-result";
44
+ result: Difference[];
45
+ } | {
46
+ id: number;
47
+ type: "clone-result";
48
+ result: object;
49
+ } | {
50
+ id: number;
51
+ type: "custom-result";
52
+ result: unknown;
53
+ } | {
54
+ id: number;
55
+ type: "error";
56
+ error: string;
57
+ };
58
+
59
+ /**
60
+ * The worker-side half of the {@link GameWorkerManager} protocol. The game project creates its
61
+ * own Worker (so it controls the bundler-specific setup) and points its `message` handling here:
62
+ *
63
+ * ```ts
64
+ * // game-worker.ts, built as its own entry by the project's bundler
65
+ * import { handleGameWorkerMessage } from "@drincs/pixi-vn/worker";
66
+ *
67
+ * self.onmessage = async (event) => {
68
+ * const response = await handleGameWorkerMessage(event.data);
69
+ * if (response) self.postMessage(response);
70
+ * };
71
+ * ```
72
+ *
73
+ * A third-party library sharing this same worker (see `registerGameWorkerHandler`) just needs
74
+ * its own worker-side registration module imported alongside this one, in that same file.
75
+ *
76
+ * Everything this processes is plain, structured-clone-safe data by construction - it never
77
+ * touches PixiJS/canvas/audio, which only exist on the main thread.
78
+ */
79
+ declare function handleGameWorkerMessage(request: GameWorkerRequest): Promise<GameWorkerResponse>;
80
+
81
+ /**
82
+ * Optional integration point for offloading Pixi'VN's own heavy, pure (no DOM/PixiJS/audio)
83
+ * computations to a Worker the game project registers. Pixi'VN never creates a Worker itself
84
+ * and works exactly as before if none is registered - this is opt-in, not a requirement, so
85
+ * projects that can't or don't want to use Workers (SSR, certain embeds, ...) are unaffected.
86
+ *
87
+ * The game project owns the `Worker` instance (so it controls the bundler-specific `new
88
+ * Worker(new URL(...), { type: "module" })` call, any CSP/nonce concerns, and whether it exists
89
+ * at all) and just needs its `onmessage` wired to {@link handleGameWorkerMessage} - see that
90
+ * function's doc comment for the worker-side half of this.
91
+ */
92
+ declare class GameWorkerManager {
93
+ private static _worker;
94
+ private static _pending;
95
+ private static _nextId;
96
+ static get isAvailable(): boolean;
97
+ /**
98
+ * Registers the Worker Pixi'VN may use for eligible heavy computations. Replaces any
99
+ * previously registered worker (its still-pending requests are rejected, never left
100
+ * hanging).
101
+ */
102
+ static register(worker: Worker): void;
103
+ /** Stops using the registered worker (does not terminate it - the caller owns its lifecycle). */
104
+ static unregister(): void;
105
+ private static _handleMessage;
106
+ /**
107
+ * Sends one {@link GameWorkerRequest} and resolves with its matching response's `result`.
108
+ * Rejects if no worker is registered - callers are expected to fall back to computing the
109
+ * same result synchronously in that case (see {@link restoreDiff}/{@link diff}/{@link clone}'s
110
+ * own call sites), not to treat the worker as required.
111
+ */
112
+ private static _request;
113
+ /** Applies `diff` to `state` on the registered worker (see `restoreDiffChanges`). */
114
+ static restoreDiff<T extends object>(state: T, diff: Difference[]): Promise<T>;
115
+ /** Computes the `microdiff` difference between `before` and `after` on the registered worker. */
116
+ static diff(before: object, after: object): Promise<Difference[]>;
117
+ /** Deep-clones `value` (JSON round-trip, matching `createExportableElement`) on the registered worker. */
118
+ static clone<T extends object>(value: T): Promise<T>;
119
+ /**
120
+ * Runs the handler a third-party library registered for `kind` (see
121
+ * `registerGameWorkerHandler`) on the registered worker, passing it `payload`. Lets a
122
+ * library built on top of Pixi'VN share this same worker instead of needing one of its own -
123
+ * see that function's doc comment for the worker-side half of this.
124
+ */
125
+ static custom<TResult = unknown>(kind: string, payload: unknown): Promise<TResult>;
126
+ }
127
+
128
+ type GameWorkerHandler = (payload: unknown) => unknown | Promise<unknown>;
129
+ /** Registers (or replaces) the worker-side handler for `kind`. See this file's doc comment. */
130
+ declare function registerGameWorkerHandler(kind: string, handler: GameWorkerHandler): void;
131
+ /** Removes the worker-side handler previously registered for `kind`, if any. */
132
+ declare function unregisterGameWorkerHandler(kind: string): void;
133
+
134
+ /**
135
+ * Applies `stateDiff` to `state`, via the registered game worker if one is available (see
136
+ * `Game.worker`), falling back to computing it synchronously on the main thread otherwise -
137
+ * whether that's because no worker was registered, or because the worker call itself failed (the
138
+ * caller should never hard-fail just because the optional worker hiccuped).
139
+ */
140
+ declare function restoreDiffMaybeOffloaded<T extends object>(state: T, stateDiff: Difference[]): Promise<T>;
141
+ /**
142
+ * Computes the difference between `before` and `after`, via the registered game worker if
143
+ * available, falling back to the main thread otherwise. Mirrors
144
+ * {@link restoreDiffMaybeOffloaded} - same worker, opposite direction.
145
+ */
146
+ declare function diffMaybeOffloaded(before: object, after: object): Promise<Difference[]>;
147
+ /**
148
+ * Deep-clones `value` (matching `createExportableElement`'s JSON-round-trip semantics), via the
149
+ * registered game worker if available, falling back to the main thread otherwise.
150
+ */
151
+ declare function cloneMaybeOffloaded<T extends object>(value: T): Promise<T>;
152
+
153
+ export { type GameWorkerHandler, GameWorkerManager, type GameWorkerRequest, type GameWorkerResponse, cloneMaybeOffloaded, diffMaybeOffloaded, handleGameWorkerMessage, registerGameWorkerHandler, restoreDiffMaybeOffloaded, unregisterGameWorkerHandler };
@@ -0,0 +1,153 @@
1
+ import { Difference } from 'microdiff';
2
+
3
+ /**
4
+ * Message protocol between the main thread and an optional {@link GameWorker}-registered
5
+ * Worker. Kept intentionally small: each request names one unit of work Pixi'VN (or a
6
+ * third-party library building on it, via `"custom"` - see `registerGameWorkerHandler`) knows
7
+ * how to hand off, and the worker replies with the same `id` so the caller can match the
8
+ * response.
9
+ *
10
+ * This protocol (and everything it carries) only ever deals with plain, structured-clone-safe
11
+ * data - never PixiJS/canvas/audio objects, which can't leave the main thread.
12
+ */
13
+ type GameWorkerRequest = {
14
+ id: number;
15
+ type: "restore-diff";
16
+ /** The base state to apply `diff` to (not mutated). */
17
+ state: object;
18
+ diff: Difference[];
19
+ } | {
20
+ id: number;
21
+ type: "diff";
22
+ /** The two states to compare (neither is mutated). */
23
+ before: object;
24
+ after: object;
25
+ } | {
26
+ id: number;
27
+ type: "clone";
28
+ /** The value to deep-clone. */
29
+ value: object;
30
+ } | {
31
+ id: number;
32
+ type: "custom";
33
+ /** Identifies which registered handler (see `registerGameWorkerHandler`) should run. */
34
+ kind: string;
35
+ payload: unknown;
36
+ };
37
+ type GameWorkerResponse = {
38
+ id: number;
39
+ type: "restore-diff-result";
40
+ result: object;
41
+ } | {
42
+ id: number;
43
+ type: "diff-result";
44
+ result: Difference[];
45
+ } | {
46
+ id: number;
47
+ type: "clone-result";
48
+ result: object;
49
+ } | {
50
+ id: number;
51
+ type: "custom-result";
52
+ result: unknown;
53
+ } | {
54
+ id: number;
55
+ type: "error";
56
+ error: string;
57
+ };
58
+
59
+ /**
60
+ * The worker-side half of the {@link GameWorkerManager} protocol. The game project creates its
61
+ * own Worker (so it controls the bundler-specific setup) and points its `message` handling here:
62
+ *
63
+ * ```ts
64
+ * // game-worker.ts, built as its own entry by the project's bundler
65
+ * import { handleGameWorkerMessage } from "@drincs/pixi-vn/worker";
66
+ *
67
+ * self.onmessage = async (event) => {
68
+ * const response = await handleGameWorkerMessage(event.data);
69
+ * if (response) self.postMessage(response);
70
+ * };
71
+ * ```
72
+ *
73
+ * A third-party library sharing this same worker (see `registerGameWorkerHandler`) just needs
74
+ * its own worker-side registration module imported alongside this one, in that same file.
75
+ *
76
+ * Everything this processes is plain, structured-clone-safe data by construction - it never
77
+ * touches PixiJS/canvas/audio, which only exist on the main thread.
78
+ */
79
+ declare function handleGameWorkerMessage(request: GameWorkerRequest): Promise<GameWorkerResponse>;
80
+
81
+ /**
82
+ * Optional integration point for offloading Pixi'VN's own heavy, pure (no DOM/PixiJS/audio)
83
+ * computations to a Worker the game project registers. Pixi'VN never creates a Worker itself
84
+ * and works exactly as before if none is registered - this is opt-in, not a requirement, so
85
+ * projects that can't or don't want to use Workers (SSR, certain embeds, ...) are unaffected.
86
+ *
87
+ * The game project owns the `Worker` instance (so it controls the bundler-specific `new
88
+ * Worker(new URL(...), { type: "module" })` call, any CSP/nonce concerns, and whether it exists
89
+ * at all) and just needs its `onmessage` wired to {@link handleGameWorkerMessage} - see that
90
+ * function's doc comment for the worker-side half of this.
91
+ */
92
+ declare class GameWorkerManager {
93
+ private static _worker;
94
+ private static _pending;
95
+ private static _nextId;
96
+ static get isAvailable(): boolean;
97
+ /**
98
+ * Registers the Worker Pixi'VN may use for eligible heavy computations. Replaces any
99
+ * previously registered worker (its still-pending requests are rejected, never left
100
+ * hanging).
101
+ */
102
+ static register(worker: Worker): void;
103
+ /** Stops using the registered worker (does not terminate it - the caller owns its lifecycle). */
104
+ static unregister(): void;
105
+ private static _handleMessage;
106
+ /**
107
+ * Sends one {@link GameWorkerRequest} and resolves with its matching response's `result`.
108
+ * Rejects if no worker is registered - callers are expected to fall back to computing the
109
+ * same result synchronously in that case (see {@link restoreDiff}/{@link diff}/{@link clone}'s
110
+ * own call sites), not to treat the worker as required.
111
+ */
112
+ private static _request;
113
+ /** Applies `diff` to `state` on the registered worker (see `restoreDiffChanges`). */
114
+ static restoreDiff<T extends object>(state: T, diff: Difference[]): Promise<T>;
115
+ /** Computes the `microdiff` difference between `before` and `after` on the registered worker. */
116
+ static diff(before: object, after: object): Promise<Difference[]>;
117
+ /** Deep-clones `value` (JSON round-trip, matching `createExportableElement`) on the registered worker. */
118
+ static clone<T extends object>(value: T): Promise<T>;
119
+ /**
120
+ * Runs the handler a third-party library registered for `kind` (see
121
+ * `registerGameWorkerHandler`) on the registered worker, passing it `payload`. Lets a
122
+ * library built on top of Pixi'VN share this same worker instead of needing one of its own -
123
+ * see that function's doc comment for the worker-side half of this.
124
+ */
125
+ static custom<TResult = unknown>(kind: string, payload: unknown): Promise<TResult>;
126
+ }
127
+
128
+ type GameWorkerHandler = (payload: unknown) => unknown | Promise<unknown>;
129
+ /** Registers (or replaces) the worker-side handler for `kind`. See this file's doc comment. */
130
+ declare function registerGameWorkerHandler(kind: string, handler: GameWorkerHandler): void;
131
+ /** Removes the worker-side handler previously registered for `kind`, if any. */
132
+ declare function unregisterGameWorkerHandler(kind: string): void;
133
+
134
+ /**
135
+ * Applies `stateDiff` to `state`, via the registered game worker if one is available (see
136
+ * `Game.worker`), falling back to computing it synchronously on the main thread otherwise -
137
+ * whether that's because no worker was registered, or because the worker call itself failed (the
138
+ * caller should never hard-fail just because the optional worker hiccuped).
139
+ */
140
+ declare function restoreDiffMaybeOffloaded<T extends object>(state: T, stateDiff: Difference[]): Promise<T>;
141
+ /**
142
+ * Computes the difference between `before` and `after`, via the registered game worker if
143
+ * available, falling back to the main thread otherwise. Mirrors
144
+ * {@link restoreDiffMaybeOffloaded} - same worker, opposite direction.
145
+ */
146
+ declare function diffMaybeOffloaded(before: object, after: object): Promise<Difference[]>;
147
+ /**
148
+ * Deep-clones `value` (matching `createExportableElement`'s JSON-round-trip semantics), via the
149
+ * registered game worker if available, falling back to the main thread otherwise.
150
+ */
151
+ declare function cloneMaybeOffloaded<T extends object>(value: T): Promise<T>;
152
+
153
+ export { type GameWorkerHandler, GameWorkerManager, type GameWorkerRequest, type GameWorkerResponse, cloneMaybeOffloaded, diffMaybeOffloaded, handleGameWorkerMessage, registerGameWorkerHandler, restoreDiffMaybeOffloaded, unregisterGameWorkerHandler };
@@ -0,0 +1 @@
1
+ import {b,a as a$1}from'./chunk-LXIKP2K5.mjs';function u(r){try{if(typeof r>"u")return r;let e=JSON.stringify(r);return JSON.parse(e)}catch(e){throw b.error("Error creating exportable element",r,e),new a$1("not_json_serializable","Error creating exportable element")}}function g(r,e){let t=u(r);return e.length>1&&"type"in e[0]&&(e=e.slice().reverse()),e.forEach(o=>{W(t,o);}),t}function W(r,e){let t=r;e.path&&e.path.length>0?e.path.forEach((o,f)=>{if(e.path&&f===e.path.length-1)switch(e.type){case "CHANGE":case "REMOVE":t[o]=e.oldValue;break;case "CREATE":Array.isArray(t)&&typeof o=="number"?t.splice(o,1):delete t[o];break}else t=t[o];}):b.warn("No path found, skipping diff",e);}var x=["Date","RegExp","String","Number"],T=Object.getOwnPropertyNames(globalThis.Temporal||{});function l(r,e,t={cyclesFix:true},o=[]){let f=[],d=Array.isArray(r);for(let i in r){let n=r[i],y=d?+i:i;if(!(i in e)){f.push({type:"REMOVE",path:[y],oldValue:n});continue}let c=e[i],w=typeof n=="object"&&typeof c=="object"&&Array.isArray(n)===Array.isArray(c),m=w&&n?Object.getPrototypeOf(n)?.constructor?.name:void 0;if(n&&c&&w&&!x.includes(m)&&!T.includes(m)&&(!t.cyclesFix||!o.includes(n))){t.cyclesFix&&o.push(n);let G=l(n,c,t,o);t.cyclesFix&&o.pop();for(let h of G)h.path.unshift(y),f.push(h);}else Object.is(n,c)||T.includes(m)&&String(n)===String(c)||x.includes(m)&&(isNaN(n)?n+""==c+"":+n==+c)||f.push({path:[y],type:"CHANGE",value:c,oldValue:n});}let p=Array.isArray(e);for(let i in e)i in r||f.push({type:"CREATE",path:[p?+i:i],value:e[i]});return f}var k=new Map;function v(r,e){k.set(r,e);}function D(r){k.delete(r);}function E(r){return k.get(r)}async function M(r){try{switch(r.type){case "restore-diff":{let e=g(r.state,r.diff);return {id:r.id,type:"restore-diff-result",result:e}}case "diff":{let e=l(r.before,r.after);return {id:r.id,type:"diff-result",result:e}}case "clone":{let e=JSON.parse(JSON.stringify(r.value));return {id:r.id,type:"clone-result",result:e}}case "custom":{let e=E(r.kind);if(!e)throw new Error(`No game worker handler registered for kind "${r.kind}"`);let t=await e(r.payload);return {id:r.id,type:"custom-result",result:t}}}}catch(e){return {id:r.id,type:"error",error:e instanceof Error?e.message:String(e)}}}var a=class r{static _worker;static _pending=new Map;static _nextId=0;static get isAvailable(){return r._worker!==void 0}static register(e){r.unregister(),r._worker=e,e.addEventListener("message",r._handleMessage);}static unregister(){let e=r._worker;if(e){e.removeEventListener("message",r._handleMessage),r._worker=void 0;for(let{reject:t}of r._pending.values())t(new Error("Game worker was unregistered"));r._pending.clear();}}static _handleMessage=e=>{let t=r._pending.get(e.data.id);t&&(r._pending.delete(e.data.id),e.data.type==="error"?t.reject(new Error(e.data.error)):t.resolve(e.data.result));};static _request(e){let t=r._worker;if(!t)return Promise.reject(new Error("No game worker is registered"));let o=r._nextId++;return new Promise((f,d)=>{r._pending.set(o,{resolve:f,reject:d});try{t.postMessage({...e,id:o});}catch(p){r._pending.delete(o),b.error("Error posting message to game worker",p),d(p);}})}static async restoreDiff(e,t){return await r._request({type:"restore-diff",state:e,diff:t})}static async diff(e,t){return await r._request({type:"diff",before:e,after:t})}static async clone(e){return await r._request({type:"clone",value:e})}static async custom(e,t){return await r._request({type:"custom",kind:e,payload:t})}};async function A(r,e){if(a.isAvailable)try{return await a.restoreDiff(r,e)}catch(t){b.warn("Game worker failed to restore diff, falling back to the main thread",t);}return g(r,e)}async function O(r,e){if(a.isAvailable)try{return await a.diff(r,e)}catch(t){b.warn("Game worker failed to compute diff, falling back to the main thread",t);}return l(r,e)}async function j(r){if(a.isAvailable)try{return await a.clone(r)}catch(e){b.warn("Game worker failed to clone value, falling back to the main thread",e);}return u(r)}export{a as GameWorkerManager,j as cloneMaybeOffloaded,O as diffMaybeOffloaded,M as handleGameWorkerMessage,v as registerGameWorkerHandler,A as restoreDiffMaybeOffloaded,D as unregisterGameWorkerHandler};