-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMEC_ScriptCache.js
More file actions
179 lines (167 loc) · 6.1 KB
/
MEC_ScriptCache.js
File metadata and controls
179 lines (167 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/*:
* @target MZ
* @plugindesc 🧩 Minto Engine Core ScriptCache v0.9β — JSファイルをIndexedDBにキャッシュ&即eval by MintoSoft
* @author MintoSoft
* @orderAfter MEC_Core
* @help
* -------------------------------------------------------
* Minto Engine Core ScriptCache (MEC_ScriptCache)
* -------------------------------------------------------
* これは「MEC_WorkerLoader」と同様の技術で、
* js/plugins 内の .js ファイルを IndexedDB にキャッシュします。
*
* ✅ 初回起動:ファイルをWorker経由でfetch→DB保存
* ✅ 2回目以降:DBから即eval(ディスク読み込みなし)
*
* ⚠️ 注意
* - MZコアファイル(js/rmmz_*.js)はキャッシュ対象外
* - プラグインが大量でも安定動作
* - eval()使用につき、外部改変防止のため署名検証を追加予定
*
* 💬 開発中ショートカット
* Ctrl + F10 : キャッシュ一覧を出力
* Ctrl + F11 : キャッシュ全削除
*
* -------------------------------------------------------
* © MintoSoft
* -------------------------------------------------------
*/
(() => {
const MEC = window.MEC || (window.MEC = {});
MEC.ScriptCache = MEC.ScriptCache || {};
const log = (...a) => console.log("%c[M.E.C.ScriptCache]", "color:#7fffd4", ...a);
const DB_NAME = "MEC_ScriptCacheDB";
const STORE_NAME = "scripts";
const DB_VERSION = 1;
const CACHE_TTL_MS = 1000 * 60 * 60 * 24 * 7; // 7日
let dbPromise = null;
function openDB() {
if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = e => {
const db = e.target.result;
if (!db.objectStoreNames.contains(STORE_NAME))
db.createObjectStore(STORE_NAME, { keyPath: "url" });
};
req.onsuccess = e => resolve(e.target.result);
req.onerror = () => reject(req.error);
});
return dbPromise;
}
async function getCache(url) {
const db = await openDB();
return new Promise(resolve => {
const tx = db.transaction(STORE_NAME, "readonly");
const store = tx.objectStore(STORE_NAME);
const req = store.get(url);
req.onsuccess = () => {
const e = req.result;
if (!e) return resolve(null);
const expired = Date.now() - e.time > CACHE_TTL_MS;
resolve(expired ? null : e);
};
req.onerror = () => resolve(null);
});
}
async function setCache(url, code) {
const db = await openDB();
return new Promise(resolve => {
const tx = db.transaction(STORE_NAME, "readwrite");
const store = tx.objectStore(STORE_NAME);
store.put({ url, code, time: Date.now() });
tx.oncomplete = resolve;
});
}
async function clearCache() {
const db = await openDB();
return new Promise(resolve => {
const tx = db.transaction(STORE_NAME, "readwrite");
tx.objectStore(STORE_NAME).clear();
tx.oncomplete = () => { log("All script cache cleared."); resolve(); };
});
}
// Workerを生成してfetchを分離
const workerCode = `
self.onmessage = async e => {
const url = e.data;
try {
const res = await fetch(url);
const code = await res.text();
postMessage({ url, code });
} catch(err) {
postMessage({ url, error: err.toString() });
}
};
`;
const blob = new Blob([workerCode], { type: "application/javascript" });
const workerUrl = URL.createObjectURL(blob);
const worker = new Worker(workerUrl);
const pending = new Map();
worker.onmessage = e => {
const { url, code, error } = e.data;
const task = pending.get(url);
if (task) {
if (error) task.reject(error);
else task.resolve(code);
pending.delete(url);
}
};
async function workerLoad(url) {
const cached = await getCache(url);
if (cached) {
log("Cache hit:", url);
try { eval(cached.code); } catch(e){ console.warn("Eval failed:", url, e); }
return;
}
const code = await new Promise((resolve, reject) => {
pending.set(url, { resolve, reject });
worker.postMessage(url);
});
await setCache(url, code);
log("Cache store:", url);
try { eval(code); } catch(e){ console.warn("Eval failed:", url, e); }
}
// ===== Pluginロード検出 =====
const _Scene_Boot_start = Scene_Boot.prototype.start;
Scene_Boot.prototype.start = function() {
if (!_Scene_Boot_start._mec_scriptcache_done) {
_Scene_Boot_start._mec_scriptcache_done = true;
const pluginList = window.$plugins?.map(p => p.description || p.name || p.filename) || [];
log("Booting ScriptCache. Plugins:", pluginList.length);
// data/plugins.jsを見て順にキャッシュ
const urls = pluginList
.map(p => (p && p.filename ? `js/plugins/${p.filename}` : null))
.filter(u => u && !u.includes("MEC_")); // 自分自身は除外
(async () => {
for (const url of urls) {
await workerLoad(url);
}
log("All plugin scripts loaded via ScriptCache.");
})();
}
_Scene_Boot_start.call(this);
};
// ===== Debug keys =====
const _updateMap = Scene_Map.prototype.update;
Scene_Map.prototype.update = function() {
_updateMap.call(this);
// F10: 一覧 / F11: 全削除
if (Input.isPressed("control") && Input.isTriggered("f10")) {
openDB().then(db => {
const tx = db.transaction(STORE_NAME, "readonly");
const store = tx.objectStore(STORE_NAME);
const req = store.getAll();
req.onsuccess = () => {
console.table(req.result.map(e => ({
url: e.url,
age: Math.floor((Date.now() - e.time) / 1000) + "s",
size: (e.code.length / 1024).toFixed(1) + " KB"
})));
};
});
}
if (Input.isPressed("control") && Input.isTriggered("f11")) clearCache();
};
log("Loaded Minto Engine Core ScriptCache v0.9β");
})();