@shuo-li/i18n 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mp/index.js CHANGED
@@ -2,11 +2,10 @@ import {
2
2
  I18N_RESOURCES_UPDATED_EVENT,
3
3
  createI18nManager,
4
4
  emitI18nResourcesUpdated
5
- } from "../chunk-IWP4252C.js";
5
+ } from "../chunk-X6D2MZ7M.js";
6
6
 
7
7
  // src/storage/wx-sqlite.ts
8
8
  var DB_NAME = "i18n_cache";
9
- var SCHEMA_VERSION = 2;
10
9
  function resourceTable(name) {
11
10
  return `i18n_resources_${name}`;
12
11
  }
@@ -40,40 +39,17 @@ function exec(db, sql, args = []) {
40
39
  });
41
40
  }
42
41
  var WxSQLiteAdapter = class {
43
- async ensureSchemaVersion(stores) {
44
- const db = await getDB();
45
- await exec(db, `
46
- CREATE TABLE IF NOT EXISTS i18n_meta (
47
- key TEXT PRIMARY KEY,
48
- value TEXT NOT NULL
49
- )
50
- `);
51
- const stored = await this.getMeta("schema_version");
52
- const storedVersion = Number(stored ?? 0);
53
- if (storedVersion === 0) {
54
- await this.createTables(stores);
55
- await this.setMeta("schema_version", String(SCHEMA_VERSION));
56
- } else if (storedVersion < SCHEMA_VERSION) {
57
- for (const store of stores) {
58
- await exec(db, `DROP TABLE IF EXISTS ${resourceTable(store.name)}`);
59
- }
60
- await this.createTables(stores);
61
- await this.setMeta("schema_version", String(SCHEMA_VERSION));
62
- } else if (storedVersion > SCHEMA_VERSION) {
63
- throw new Error(`[i18n] wx.openDatabase schema version ${storedVersion} > current ${SCHEMA_VERSION}`);
64
- }
65
- }
66
- async createTables(stores) {
42
+ async ensureStores(stores) {
67
43
  const db = await getDB();
68
44
  for (const store of stores) {
69
45
  const table = resourceTable(store.name);
70
46
  await exec(db, `
71
47
  CREATE TABLE IF NOT EXISTS ${table} (
72
- key TEXT PRIMARY KEY,
48
+ key TEXT PRIMARY KEY,
73
49
  module_code TEXT NOT NULL,
74
- lang_code TEXT NOT NULL,
75
- version INTEGER NOT NULL DEFAULT 0,
76
- resources TEXT NOT NULL
50
+ lang_code TEXT NOT NULL,
51
+ version INTEGER NOT NULL DEFAULT 0,
52
+ resources TEXT NOT NULL
77
53
  )
78
54
  `);
79
55
  await exec(
@@ -129,23 +105,13 @@ var WxSQLiteAdapter = class {
129
105
  const db = await getDB();
130
106
  await exec(db, `DELETE FROM ${resourceTable(storeName)}`);
131
107
  }
132
- async getMeta(key) {
133
- const db = await getDB();
134
- const result = await exec(db, "SELECT value FROM i18n_meta WHERE key = ?", [key]);
135
- if (result.rows.length === 0) return null;
136
- return result.rows.item(0).value;
137
- }
138
- async setMeta(key, value) {
139
- const db = await getDB();
140
- await exec(db, "INSERT OR REPLACE INTO i18n_meta (key, value) VALUES (?, ?)", [key, value]);
141
- }
142
108
  async hasLoginResources(stores) {
143
109
  const db = await getDB();
144
110
  for (const store of stores) {
145
111
  const result = await exec(
146
112
  db,
147
113
  `SELECT key FROM ${resourceTable(store.name)}
148
- WHERE key NOT LIKE 'UNLOGIN_%' LIMIT 1`
114
+ WHERE key NOT LIKE 'UNLOGIN_%' AND key NOT LIKE '__meta__:%' LIMIT 1`
149
115
  );
150
116
  if (result.rows.length > 0) return true;
151
117
  }
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
2
 
3
3
 
4
4
 
@@ -7,7 +7,7 @@ var _chunkAJJKJPNBcjs = require('../chunk-AJJKJPNB.cjs');
7
7
 
8
8
 
9
9
 
10
- var _chunkK5VX3COHcjs = require('../chunk-K5VX3COH.cjs');
10
+ var _chunkJPKSBSEOcjs = require('../chunk-JPKSBSEO.cjs');
11
11
 
12
12
  // src/native/index.ts
13
13
  var _i18next = require('i18next'); var _i18next2 = _interopRequireDefault(_i18next);
@@ -15,7 +15,6 @@ var _reacti18next = require('react-i18next');
15
15
 
16
16
  // src/storage/sqlite.ts
17
17
  var DB_NAME = "i18n_cache";
18
- var SCHEMA_VERSION = 2;
19
18
  function resourceTable(name) {
20
19
  return `i18n_resources_${name}`;
21
20
  }
@@ -31,38 +30,16 @@ async function execute(sql, params = []) {
31
30
  return db.executeAsync(sql, params);
32
31
  }
33
32
  var SQLiteAdapter = class {
34
- async ensureSchemaVersion(stores) {
35
- await execute(`
36
- CREATE TABLE IF NOT EXISTS i18n_meta (
37
- key TEXT PRIMARY KEY,
38
- value TEXT NOT NULL
39
- )
40
- `);
41
- const stored = await this.getMeta("schema_version");
42
- const storedVersion = Number(_nullishCoalesce(stored, () => ( 0)));
43
- if (storedVersion === 0) {
44
- await this.createTables(stores);
45
- await this.setMeta("schema_version", String(SCHEMA_VERSION));
46
- } else if (storedVersion < SCHEMA_VERSION) {
47
- for (const store of stores) {
48
- await execute(`DROP TABLE IF EXISTS ${resourceTable(store.name)}`);
49
- }
50
- await this.createTables(stores);
51
- await this.setMeta("schema_version", String(SCHEMA_VERSION));
52
- } else if (storedVersion > SCHEMA_VERSION) {
53
- throw new Error(`[i18n] SQLite schema version ${storedVersion} > current ${SCHEMA_VERSION}`);
54
- }
55
- }
56
- async createTables(stores) {
33
+ async ensureStores(stores) {
57
34
  for (const store of stores) {
58
35
  const table = resourceTable(store.name);
59
36
  await execute(`
60
37
  CREATE TABLE IF NOT EXISTS ${table} (
61
- key TEXT PRIMARY KEY,
38
+ key TEXT PRIMARY KEY,
62
39
  module_code TEXT NOT NULL,
63
- lang_code TEXT NOT NULL,
64
- version INTEGER NOT NULL DEFAULT 0,
65
- resources TEXT NOT NULL
40
+ lang_code TEXT NOT NULL,
41
+ version INTEGER NOT NULL DEFAULT 0,
42
+ resources TEXT NOT NULL
66
43
  )
67
44
  `);
68
45
  await execute(
@@ -105,22 +82,11 @@ var SQLiteAdapter = class {
105
82
  async clearStore(storeName) {
106
83
  await execute(`DELETE FROM ${resourceTable(storeName)}`);
107
84
  }
108
- async getMeta(key) {
109
- const { rows } = await execute("SELECT value FROM i18n_meta WHERE key = ?", [key]);
110
- if (!rows.length) return null;
111
- return rows[0].value;
112
- }
113
- async setMeta(key, value) {
114
- await execute(
115
- "INSERT OR REPLACE INTO i18n_meta (key, value) VALUES (?, ?)",
116
- [key, value]
117
- );
118
- }
119
85
  async hasLoginResources(stores) {
120
86
  for (const store of stores) {
121
87
  const { rows } = await execute(
122
88
  `SELECT key FROM ${resourceTable(store.name)}
123
- WHERE key NOT LIKE 'UNLOGIN_%' LIMIT 1`
89
+ WHERE key NOT LIKE 'UNLOGIN_%' AND key NOT LIKE '__meta__:%' LIMIT 1`
124
90
  );
125
91
  if (rows.length > 0) return true;
126
92
  }
@@ -155,7 +121,7 @@ if (!_i18next2.default.isInitialized) {
155
121
  }
156
122
  });
157
123
  }
158
- var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } = _chunkK5VX3COHcjs.createI18nManager.call(void 0, {
124
+ var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } = _chunkJPKSBSEOcjs.createI18nManager.call(void 0, {
159
125
  storage: new SQLiteAdapter(),
160
126
  // Hermes Worker(RN 0.71+),API 与 Web Worker 一致
161
127
  createWorker: () => new (0, _chunkAJJKJPNBcjs.WebWorkerAdapter)(
@@ -172,4 +138,4 @@ var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } =
172
138
 
173
139
 
174
140
 
175
- exports.I18N_RESOURCES_UPDATED_EVENT = _chunkK5VX3COHcjs.I18N_RESOURCES_UPDATED_EVENT; exports.closeSSE = closeSSE; exports.emitI18nResourcesUpdated = _chunkK5VX3COHcjs.emitI18nResourcesUpdated; exports.ensureModules = ensureModules; exports.getAllRecordsByModule = getAllRecordsByModule; exports.getResource = getResource; exports.initI18n = initI18n; exports.useDict = _chunkAJJKJPNBcjs.useDict; exports.useTranslation = _chunkAJJKJPNBcjs.useTranslation;
141
+ exports.I18N_RESOURCES_UPDATED_EVENT = _chunkJPKSBSEOcjs.I18N_RESOURCES_UPDATED_EVENT; exports.closeSSE = closeSSE; exports.emitI18nResourcesUpdated = _chunkJPKSBSEOcjs.emitI18nResourcesUpdated; exports.ensureModules = ensureModules; exports.getAllRecordsByModule = getAllRecordsByModule; exports.getResource = getResource; exports.initI18n = initI18n; exports.useDict = _chunkAJJKJPNBcjs.useDict; exports.useTranslation = _chunkAJJKJPNBcjs.useTranslation;
@@ -1,5 +1,5 @@
1
- import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-CDBRPnHU.cjs';
2
- export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-CDBRPnHU.cjs';
1
+ import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-CSwgzbob.cjs';
2
+ export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-CSwgzbob.cjs';
3
3
  export { u as useDict } from '../hooks-ClO29Chr.cjs';
4
4
  export { useTranslation } from 'react-i18next';
5
5
 
@@ -1,5 +1,5 @@
1
- import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-CDBRPnHU.js';
2
- export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-CDBRPnHU.js';
1
+ import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-CSwgzbob.js';
2
+ export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-CSwgzbob.js';
3
3
  export { u as useDict } from '../hooks-ClO29Chr.js';
4
4
  export { useTranslation } from 'react-i18next';
5
5
 
@@ -7,7 +7,7 @@ import {
7
7
  I18N_RESOURCES_UPDATED_EVENT,
8
8
  createI18nManager,
9
9
  emitI18nResourcesUpdated
10
- } from "../chunk-IWP4252C.js";
10
+ } from "../chunk-X6D2MZ7M.js";
11
11
 
12
12
  // src/native/index.ts
13
13
  import i18n from "i18next";
@@ -15,7 +15,6 @@ import { initReactI18next } from "react-i18next";
15
15
 
16
16
  // src/storage/sqlite.ts
17
17
  var DB_NAME = "i18n_cache";
18
- var SCHEMA_VERSION = 2;
19
18
  function resourceTable(name) {
20
19
  return `i18n_resources_${name}`;
21
20
  }
@@ -31,38 +30,16 @@ async function execute(sql, params = []) {
31
30
  return db.executeAsync(sql, params);
32
31
  }
33
32
  var SQLiteAdapter = class {
34
- async ensureSchemaVersion(stores) {
35
- await execute(`
36
- CREATE TABLE IF NOT EXISTS i18n_meta (
37
- key TEXT PRIMARY KEY,
38
- value TEXT NOT NULL
39
- )
40
- `);
41
- const stored = await this.getMeta("schema_version");
42
- const storedVersion = Number(stored ?? 0);
43
- if (storedVersion === 0) {
44
- await this.createTables(stores);
45
- await this.setMeta("schema_version", String(SCHEMA_VERSION));
46
- } else if (storedVersion < SCHEMA_VERSION) {
47
- for (const store of stores) {
48
- await execute(`DROP TABLE IF EXISTS ${resourceTable(store.name)}`);
49
- }
50
- await this.createTables(stores);
51
- await this.setMeta("schema_version", String(SCHEMA_VERSION));
52
- } else if (storedVersion > SCHEMA_VERSION) {
53
- throw new Error(`[i18n] SQLite schema version ${storedVersion} > current ${SCHEMA_VERSION}`);
54
- }
55
- }
56
- async createTables(stores) {
33
+ async ensureStores(stores) {
57
34
  for (const store of stores) {
58
35
  const table = resourceTable(store.name);
59
36
  await execute(`
60
37
  CREATE TABLE IF NOT EXISTS ${table} (
61
- key TEXT PRIMARY KEY,
38
+ key TEXT PRIMARY KEY,
62
39
  module_code TEXT NOT NULL,
63
- lang_code TEXT NOT NULL,
64
- version INTEGER NOT NULL DEFAULT 0,
65
- resources TEXT NOT NULL
40
+ lang_code TEXT NOT NULL,
41
+ version INTEGER NOT NULL DEFAULT 0,
42
+ resources TEXT NOT NULL
66
43
  )
67
44
  `);
68
45
  await execute(
@@ -105,22 +82,11 @@ var SQLiteAdapter = class {
105
82
  async clearStore(storeName) {
106
83
  await execute(`DELETE FROM ${resourceTable(storeName)}`);
107
84
  }
108
- async getMeta(key) {
109
- const { rows } = await execute("SELECT value FROM i18n_meta WHERE key = ?", [key]);
110
- if (!rows.length) return null;
111
- return rows[0].value;
112
- }
113
- async setMeta(key, value) {
114
- await execute(
115
- "INSERT OR REPLACE INTO i18n_meta (key, value) VALUES (?, ?)",
116
- [key, value]
117
- );
118
- }
119
85
  async hasLoginResources(stores) {
120
86
  for (const store of stores) {
121
87
  const { rows } = await execute(
122
88
  `SELECT key FROM ${resourceTable(store.name)}
123
- WHERE key NOT LIKE 'UNLOGIN_%' LIMIT 1`
89
+ WHERE key NOT LIKE 'UNLOGIN_%' AND key NOT LIKE '__meta__:%' LIMIT 1`
124
90
  );
125
91
  if (rows.length > 0) return true;
126
92
  }
@@ -1,40 +1,18 @@
1
1
  "use strict"; function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/workers/preload-worker-rn.ts
2
- function flatToNested(flat) {
3
- const result = {};
4
- for (const [key, value] of Object.entries(flat)) {
5
- const parts = key.split(".");
6
- let cur = result;
7
- for (let i = 0; i < parts.length - 1; i++) {
8
- const part = parts[i];
9
- if (typeof cur[part] !== "object" || cur[part] === null) cur[part] = {};
10
- cur = cur[part];
11
- }
12
- cur[parts[parts.length - 1]] = value;
13
- }
14
- return result;
15
- }
16
- function parseI18nValues(values) {
17
- const result = {};
18
- for (const { termCode, langValue } of values) {
19
- if (termCode && langValue !== void 0) result[termCode] = _nullishCoalesce(langValue, () => ( ""));
20
- }
21
- return result;
22
- }
23
- function buildKey(moduleCode, langCode, store) {
24
- return store.cacheGroupKey ? `${moduleCode}_${langCode}_${store.cacheGroupKey}` : `${moduleCode}_${langCode}`;
25
- }
26
2
  function toQueryString(params) {
27
3
  return new URLSearchParams(
28
4
  Object.entries(params).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])
29
5
  ).toString();
30
6
  }
31
7
  async function processTask(task, payload) {
32
- const { baseURL, headers, pullPath, pullMethod, stores } = payload;
33
- const params = {};
34
- if (task.storeName) params["storeName"] = task.storeName;
35
- if (task.langCode) params["langCode"] = task.langCode;
36
- if (task.moduleCode) params["moduleCode"] = task.moduleCode;
37
- if (task.version != null) params["version"] = String(task.version);
8
+ const { baseURL, headers, pullPath, pullMethod } = payload;
9
+ const params = _nullishCoalesce(task.params, () => ( {}));
10
+ if (!task.params) {
11
+ if (task.storeName) params["storeName"] = task.storeName;
12
+ if (task.langCode) params["langCode"] = task.langCode;
13
+ if (task.moduleCode) params["moduleCode"] = task.moduleCode;
14
+ if (task.version != null) params["version"] = task.version;
15
+ }
38
16
  const url = baseURL + pullPath;
39
17
  let res;
40
18
  if (pullMethod === "POST") {
@@ -44,33 +22,12 @@ async function processTask(task, payload) {
44
22
  body: JSON.stringify(params)
45
23
  });
46
24
  } else {
47
- res = await fetch(`${url}?${toQueryString(params)}`, { headers });
25
+ const qs = toQueryString(params);
26
+ res = await fetch(qs ? `${url}?${qs}` : url, { headers });
48
27
  }
49
28
  if (!res.ok) throw new Error(`[i18n rn-worker] fetch failed: ${res.status}`);
50
- const blocks = await res.json();
51
- for (const block of blocks) {
52
- for (const mod of _nullishCoalesce(block.modules, () => ( []))) {
53
- const store = stores.find((s) => s.name === task.storeName);
54
- if (!store) continue;
55
- const storeIndex = stores.indexOf(store);
56
- const key = buildKey(mod.moduleCode, block.langCode, store);
57
- const parsed = parseI18nValues(_nullishCoalesce(mod.i18nValues, () => ( [])));
58
- const resources = storeIndex === 0 ? flatToNested(parsed) : parsed;
59
- self.postMessage({
60
- type: "dataReady",
61
- storeName: store.name,
62
- storeIndex,
63
- record: {
64
- key,
65
- moduleCode: mod.moduleCode,
66
- langCode: block.langCode,
67
- version: mod.version,
68
- resources
69
- },
70
- task
71
- });
72
- }
73
- }
29
+ const raw = await res.json();
30
+ self.postMessage({ type: "rawData", task, raw });
74
31
  }
75
32
  self.onmessage = async (event) => {
76
33
  if (event.data.type !== "start") return;
@@ -1,40 +1,18 @@
1
1
  // src/workers/preload-worker-rn.ts
2
- function flatToNested(flat) {
3
- const result = {};
4
- for (const [key, value] of Object.entries(flat)) {
5
- const parts = key.split(".");
6
- let cur = result;
7
- for (let i = 0; i < parts.length - 1; i++) {
8
- const part = parts[i];
9
- if (typeof cur[part] !== "object" || cur[part] === null) cur[part] = {};
10
- cur = cur[part];
11
- }
12
- cur[parts[parts.length - 1]] = value;
13
- }
14
- return result;
15
- }
16
- function parseI18nValues(values) {
17
- const result = {};
18
- for (const { termCode, langValue } of values) {
19
- if (termCode && langValue !== void 0) result[termCode] = langValue ?? "";
20
- }
21
- return result;
22
- }
23
- function buildKey(moduleCode, langCode, store) {
24
- return store.cacheGroupKey ? `${moduleCode}_${langCode}_${store.cacheGroupKey}` : `${moduleCode}_${langCode}`;
25
- }
26
2
  function toQueryString(params) {
27
3
  return new URLSearchParams(
28
4
  Object.entries(params).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])
29
5
  ).toString();
30
6
  }
31
7
  async function processTask(task, payload) {
32
- const { baseURL, headers, pullPath, pullMethod, stores } = payload;
33
- const params = {};
34
- if (task.storeName) params["storeName"] = task.storeName;
35
- if (task.langCode) params["langCode"] = task.langCode;
36
- if (task.moduleCode) params["moduleCode"] = task.moduleCode;
37
- if (task.version != null) params["version"] = String(task.version);
8
+ const { baseURL, headers, pullPath, pullMethod } = payload;
9
+ const params = task.params ?? {};
10
+ if (!task.params) {
11
+ if (task.storeName) params["storeName"] = task.storeName;
12
+ if (task.langCode) params["langCode"] = task.langCode;
13
+ if (task.moduleCode) params["moduleCode"] = task.moduleCode;
14
+ if (task.version != null) params["version"] = task.version;
15
+ }
38
16
  const url = baseURL + pullPath;
39
17
  let res;
40
18
  if (pullMethod === "POST") {
@@ -44,33 +22,12 @@ async function processTask(task, payload) {
44
22
  body: JSON.stringify(params)
45
23
  });
46
24
  } else {
47
- res = await fetch(`${url}?${toQueryString(params)}`, { headers });
25
+ const qs = toQueryString(params);
26
+ res = await fetch(qs ? `${url}?${qs}` : url, { headers });
48
27
  }
49
28
  if (!res.ok) throw new Error(`[i18n rn-worker] fetch failed: ${res.status}`);
50
- const blocks = await res.json();
51
- for (const block of blocks) {
52
- for (const mod of block.modules ?? []) {
53
- const store = stores.find((s) => s.name === task.storeName);
54
- if (!store) continue;
55
- const storeIndex = stores.indexOf(store);
56
- const key = buildKey(mod.moduleCode, block.langCode, store);
57
- const parsed = parseI18nValues(mod.i18nValues ?? []);
58
- const resources = storeIndex === 0 ? flatToNested(parsed) : parsed;
59
- self.postMessage({
60
- type: "dataReady",
61
- storeName: store.name,
62
- storeIndex,
63
- record: {
64
- key,
65
- moduleCode: mod.moduleCode,
66
- langCode: block.langCode,
67
- version: mod.version,
68
- resources
69
- },
70
- task
71
- });
72
- }
73
- }
29
+ const raw = await res.json();
30
+ self.postMessage({ type: "rawData", task, raw });
74
31
  }
75
32
  self.onmessage = async (event) => {
76
33
  if (event.data.type !== "start") return;
@@ -1,85 +1,11 @@
1
- "use strict"; function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/workers/preload-worker.ts
2
- function flatToNested(flat) {
3
- const result = {};
4
- for (const [key, value] of Object.entries(flat)) {
5
- const parts = key.split(".");
6
- let cur = result;
7
- for (let i = 0; i < parts.length - 1; i++) {
8
- const part = parts[i];
9
- if (typeof cur[part] !== "object" || cur[part] === null) cur[part] = {};
10
- cur = cur[part];
11
- }
12
- cur[parts[parts.length - 1]] = value;
13
- }
14
- return result;
15
- }
16
- function deepMerge(target, source) {
17
- const result = { ...target };
18
- for (const [key, sv] of Object.entries(source)) {
19
- const tv = result[key];
20
- if (sv !== null && typeof sv === "object" && !Array.isArray(sv) && tv !== null && typeof tv === "object" && !Array.isArray(tv)) {
21
- result[key] = deepMerge(tv, sv);
22
- } else {
23
- result[key] = sv;
24
- }
25
- }
26
- return result;
27
- }
28
- function parseI18nValues(values) {
29
- const result = {};
30
- for (const { termCode, langValue } of values) {
31
- if (termCode && langValue !== void 0) result[termCode] = _nullishCoalesce(langValue, () => ( ""));
32
- }
33
- return result;
34
- }
35
- function buildKey(moduleCode, langCode, store) {
36
- return store.cacheGroupKey ? `${moduleCode}_${langCode}_${store.cacheGroupKey}` : `${moduleCode}_${langCode}`;
37
- }
1
+ "use strict"; function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/workers/preload-worker.ts
38
2
  function toQueryString(params) {
39
3
  return new URLSearchParams(
40
4
  Object.entries(params).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])
41
5
  ).toString();
42
6
  }
43
- var db = null;
44
- function openDB(dbName, storeNames) {
45
- return new Promise((resolve, reject) => {
46
- const req = indexedDB.open(dbName, 2);
47
- req.onupgradeneeded = (event) => {
48
- const database = event.target.result;
49
- for (const name of storeNames) {
50
- const storeName = `i18n_resources_${name}`;
51
- if (!database.objectStoreNames.contains(storeName)) {
52
- const s = database.createObjectStore(storeName, { keyPath: "key" });
53
- s.createIndex("by_module", "moduleCode");
54
- s.createIndex("by_language", "langCode");
55
- }
56
- }
57
- if (!database.objectStoreNames.contains("i18n_meta")) {
58
- database.createObjectStore("i18n_meta", { keyPath: "key" });
59
- }
60
- };
61
- req.onsuccess = () => resolve(req.result);
62
- req.onerror = () => reject(req.error);
63
- });
64
- }
65
- function idbGet(database, storeName, key) {
66
- return new Promise((resolve, reject) => {
67
- const tx = database.transaction(storeName, "readonly");
68
- const req = tx.objectStore(storeName).get(key);
69
- req.onsuccess = () => resolve(req.result);
70
- req.onerror = () => reject(req.error);
71
- });
72
- }
73
- function idbPut(database, storeName, value) {
74
- return new Promise((resolve, reject) => {
75
- const tx = database.transaction(storeName, "readwrite");
76
- const req = tx.objectStore(storeName).put(value);
77
- req.onsuccess = () => resolve();
78
- req.onerror = () => reject(req.error);
79
- });
80
- }
81
7
  async function processTask(task, payload) {
82
- const { baseURL, headers, pullPath, pullMethod, stores } = payload;
8
+ const { baseURL, headers, pullPath, pullMethod } = payload;
83
9
  const params = _nullishCoalesce(task.params, () => ( {}));
84
10
  if (!task.params) {
85
11
  if (task.storeName) params["storeName"] = task.storeName;
@@ -100,62 +26,12 @@ async function processTask(task, payload) {
100
26
  res = await fetch(qs ? `${url}?${qs}` : url, { headers });
101
27
  }
102
28
  if (!res.ok) throw new Error(`[i18n worker] fetch failed: ${res.status}`);
103
- const blocks = await res.json();
104
- for (const block of blocks) {
105
- for (const mod of _nullishCoalesce(block.modules, () => ( []))) {
106
- const store = stores.find((s) => s.name === task.storeName);
107
- if (!store) continue;
108
- const storeIndex = stores.indexOf(store);
109
- const idbStoreName = `i18n_resources_${store.name}`;
110
- const key = buildKey(mod.moduleCode, block.langCode, store);
111
- const parsed = parseI18nValues(_nullishCoalesce(mod.i18nValues, () => ( [])));
112
- let resources;
113
- if (storeIndex === 0) {
114
- const existing = await idbGet(
115
- db,
116
- idbStoreName,
117
- key
118
- );
119
- resources = deepMerge(
120
- _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _ => _.resources]), () => ( {})),
121
- flatToNested(parsed)
122
- );
123
- } else {
124
- const existing = await idbGet(
125
- db,
126
- idbStoreName,
127
- key
128
- );
129
- resources = { ..._nullishCoalesce(_optionalChain([existing, 'optionalAccess', _2 => _2.resources]), () => ( {})), ...parsed };
130
- }
131
- const record = {
132
- key,
133
- moduleCode: mod.moduleCode,
134
- langCode: block.langCode,
135
- version: mod.version,
136
- resources
137
- };
138
- await idbPut(db, idbStoreName, record);
139
- self.postMessage({
140
- type: "moduleLoaded",
141
- storeName: task.storeName,
142
- langCode: block.langCode,
143
- moduleCode: mod.moduleCode,
144
- version: mod.version
145
- });
146
- }
147
- }
29
+ const raw = await res.json();
30
+ self.postMessage({ type: "rawData", task, raw });
148
31
  }
149
32
  self.onmessage = async (event) => {
150
33
  if (event.data.type !== "start") return;
151
34
  const { payload } = event.data;
152
- const storeNames = payload.stores.map((s) => s.name);
153
- try {
154
- db = await openDB(payload.dbName, storeNames);
155
- } catch (err) {
156
- self.postMessage({ type: "error", message: String(err) });
157
- return;
158
- }
159
35
  for (const task of payload.tasks) {
160
36
  try {
161
37
  await processTask(task, payload);