@thirty-coder/electron-base-kit 0.2.1 → 0.3.0

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/README.md CHANGED
@@ -84,6 +84,7 @@ createWindow({ id: 'settings', preload, renderer, width: 640, height: 480, remem
84
84
  "url": "https://dl.example.com/myapp"
85
85
  },
86
86
  "license": { "publicKey": "" },
87
+ "log": { "level": "info", "maxDays": 7, "console": true },
87
88
  "window": { "width": 1200, "height": 800, "minWidth": 900, "minHeight": 600, "remember": true, "ensureVisible": true }
88
89
  }
89
90
  ```
@@ -110,6 +111,35 @@ settings.filePath
110
111
 
111
112
  `bootstrap` 之后才能用,提前访问会抛错。
112
113
 
114
+ ## 日志
115
+
116
+ ```ts
117
+ import { logger } from '@thirty-coder/electron-base-kit'
118
+
119
+ logger.info('窗口已创建', { id: 'main' })
120
+ logger.warn('配置项缺失,使用默认值')
121
+ logger.error('写盘失败', err)
122
+
123
+ const log = logger.child('window')
124
+ log.debug('bounds 已保存', bounds)
125
+
126
+ logger.dir // <userData>/logs
127
+ logger.file // 当天文件绝对路径
128
+ await logger.exportTo('/tmp/logs.txt') // 所有日志拼成一个文件
129
+ ```
130
+
131
+ 写 `<userData>/logs/2026-12-04.log`,一行一条:
132
+
133
+ ```
134
+ 2026-12-04 11:57:10.123 INFO [window] 窗口已创建 {"id":"main"}
135
+ 2026-12-04 11:57:11.045 ERROR [settings] 写入失败 Error: EACCES: permission denied
136
+ at writeNow (...)
137
+ ```
138
+
139
+ 同步追加,崩溃前最后几条一定在文件里。按天换文件,启动时删掉超过 `maxDays` 天的。`Error` 会展开成 `name: message` 加堆栈,循环引用、BigInt 之类序列化失败降级成 `String`,不抛错。
140
+
141
+ `level` 默认打包后 `info`、开发时 `debug`;`console` 默认打包后关、开发时开。`warn` / `error` 无论配置都打终端。
142
+
113
143
  ## 升级
114
144
 
115
145
  ```bash
@@ -122,7 +152,7 @@ pnpm dev
122
152
  ```bash
123
153
  pnpm build # 产出 dist
124
154
  pnpm typecheck # 只做类型检查
125
- cd playground && pnpm start # 在最小环境里验证
155
+ pnpm test # 构建并跑测试
126
156
  ```
127
157
 
128
158
  本包怎么改见 [MAINTAINING.md](./MAINTAINING.md)。
package/dist/index.d.ts CHANGED
@@ -26,6 +26,15 @@ interface LicenseConfig {
26
26
  /** 验签公钥,签发私钥不在此处 */
27
27
  publicKey: string;
28
28
  }
29
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
30
+ interface LogConfig {
31
+ /** 默认打包后 info,开发时 debug */
32
+ level?: LogLevel;
33
+ /** 保留天数,启动时删掉更早的。默认 7 */
34
+ maxDays?: number;
35
+ /** 是否同时打到终端。默认开发时 true,打包后 false */
36
+ console?: boolean;
37
+ }
29
38
  interface WindowConfig {
30
39
  width?: number;
31
40
  height?: number;
@@ -45,9 +54,25 @@ interface AppConfig {
45
54
  features?: FeatureFlags;
46
55
  update?: UpdateConfig;
47
56
  license?: LicenseConfig;
57
+ log?: LogConfig;
48
58
  window?: WindowConfig;
49
59
  }
50
60
 
61
+ interface LoggerApi {
62
+ debug(message: string, ...args: unknown[]): void;
63
+ info(message: string, ...args: unknown[]): void;
64
+ warn(message: string, ...args: unknown[]): void;
65
+ error(message: string, ...args: unknown[]): void;
66
+ /** 加一个来源标签,文件、级别、配置共用同一份 */
67
+ child(tag: string): LoggerApi;
68
+ /** 把所有日志按时间顺序拼成一个文本文件 */
69
+ exportTo(target: string): Promise<void>;
70
+ readonly dir: string;
71
+ readonly file: string;
72
+ readonly level: LogLevel;
73
+ }
74
+ declare const logger: LoggerApi;
75
+
51
76
  type Listener = (value: unknown) => void;
52
77
  interface SettingsApi {
53
78
  get<T>(key: string, fallback: T): T;
@@ -89,5 +114,5 @@ declare function createWindow(options: CreateWindowOptions): BrowserWindow;
89
114
  */
90
115
  declare function bootstrap(config: AppConfig): void;
91
116
 
92
- export { bootstrap, createWindow, settings };
93
- export type { AppConfig, CreateWindowOptions, FeatureFlags, LicenseConfig, SettingsApi, UpdateConfig, UpdateProvider, WindowConfig };
117
+ export { bootstrap, createWindow, logger, settings };
118
+ export type { AppConfig, CreateWindowOptions, FeatureFlags, LicenseConfig, LogConfig, LogLevel, LoggerApi, SettingsApi, UpdateConfig, UpdateProvider, WindowConfig };
package/dist/index.js CHANGED
@@ -22,15 +22,153 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  bootstrap: () => bootstrap,
24
24
  createWindow: () => createWindow,
25
+ logger: () => logger,
25
26
  settings: () => settings
26
27
  });
27
28
  module.exports = __toCommonJS(index_exports);
28
29
 
29
- // src/settings.ts
30
+ // src/logger.ts
30
31
  var import_electron = require("electron");
31
32
  var import_node_fs = require("fs");
33
+ var import_promises = require("fs/promises");
32
34
  var import_node_path = require("path");
35
+ var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
36
+ var FILE_PATTERN = /^\d{4}-\d{2}-\d{2}\.log$/;
37
+ var DAY = 24 * 60 * 60 * 1e3;
38
+ var dir = "";
39
+ var level = "info";
40
+ var consoleOn = true;
41
+ var initialized = false;
42
+ function pad(value, width = 2) {
43
+ return String(value).padStart(width, "0");
44
+ }
45
+ function dateStamp(date) {
46
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
47
+ }
48
+ function timeStamp(date) {
49
+ const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
50
+ return `${dateStamp(date)} ${time}.${pad(date.getMilliseconds(), 3)}`;
51
+ }
52
+ function currentFile() {
53
+ return dir ? (0, import_node_path.join)(dir, `${dateStamp(/* @__PURE__ */ new Date())}.log`) : "";
54
+ }
55
+ function formatExtra(args) {
56
+ if (args.length === 0) return "";
57
+ const parts = args.map((arg) => {
58
+ if (arg instanceof Error) {
59
+ const head = `${arg.name}: ${arg.message}`;
60
+ const lines = (arg.stack ?? "").split("\n").slice(1).filter((line) => line.trim() !== "").map((line) => ` ${line.trim()}`);
61
+ return lines.length > 0 ? [head, ...lines].join("\n") : head;
62
+ }
63
+ if (typeof arg === "string") return arg;
64
+ try {
65
+ return JSON.stringify(arg) ?? String(arg);
66
+ } catch {
67
+ return String(arg);
68
+ }
69
+ });
70
+ return ` ${parts.join(" ")}`;
71
+ }
72
+ function formatLine(at, tag, message, args) {
73
+ const tagPart = tag ? ` [${tag}]` : "";
74
+ return `${timeStamp(/* @__PURE__ */ new Date())} ${at.toUpperCase().padEnd(5)}${tagPart} ${message}${formatExtra(args)}
75
+ `;
76
+ }
77
+ function cleanOldFiles(maxDays) {
78
+ let names;
79
+ try {
80
+ names = (0, import_node_fs.readdirSync)(dir);
81
+ } catch {
82
+ return;
83
+ }
84
+ const cutoff = Date.now() - maxDays * DAY;
85
+ for (const name of names) {
86
+ if (!FILE_PATTERN.test(name)) continue;
87
+ const full = (0, import_node_path.join)(dir, name);
88
+ try {
89
+ if ((0, import_node_fs.statSync)(full).mtimeMs < cutoff) (0, import_node_fs.unlinkSync)(full);
90
+ } catch {
91
+ }
92
+ }
93
+ }
94
+ function emit(at, tag, message, args) {
95
+ if (LEVELS[at] < LEVELS[level]) return;
96
+ const line = formatLine(at, tag, message, args);
97
+ if (!initialized) {
98
+ console[at](`[logger not initialized] ${line.trimEnd()}`);
99
+ return;
100
+ }
101
+ try {
102
+ (0, import_node_fs.appendFileSync)(currentFile(), line);
103
+ } catch (err) {
104
+ console.error("[electron-base-kit] \u5199\u65E5\u5FD7\u5931\u8D25\uFF1A", err);
105
+ }
106
+ if (at === "warn" || at === "error" || consoleOn) {
107
+ console[at](line.trimEnd());
108
+ }
109
+ }
110
+ function initLogger(config) {
111
+ if (initialized) return;
112
+ const packaged = import_electron.app.isPackaged === true;
113
+ level = config?.level ?? (packaged ? "info" : "debug");
114
+ consoleOn = config?.console ?? !packaged;
115
+ dir = (0, import_node_path.join)(import_electron.app.getPath("userData"), "logs");
116
+ initialized = true;
117
+ try {
118
+ (0, import_node_fs.mkdirSync)(dir, { recursive: true });
119
+ } catch (err) {
120
+ console.error("[electron-base-kit] \u521B\u5EFA\u65E5\u5FD7\u76EE\u5F55\u5931\u8D25\uFF1A", err);
121
+ return;
122
+ }
123
+ cleanOldFiles(config?.maxDays ?? 7);
124
+ }
125
+ function createLogger(tag) {
126
+ return {
127
+ debug: (message, ...args) => emit("debug", tag, message, args),
128
+ info: (message, ...args) => emit("info", tag, message, args),
129
+ warn: (message, ...args) => emit("warn", tag, message, args),
130
+ error: (message, ...args) => emit("error", tag, message, args),
131
+ child(next) {
132
+ return createLogger(tag ? `${tag}:${next}` : next);
133
+ },
134
+ async exportTo(target) {
135
+ if (!initialized) {
136
+ throw new Error("logger \u672A\u521D\u59CB\u5316\uFF1A\u8BF7\u5148\u5728 app.whenReady() \u4E2D\u8C03\u7528 bootstrap(config)");
137
+ }
138
+ let names = [];
139
+ try {
140
+ names = (0, import_node_fs.readdirSync)(dir).filter((name) => FILE_PATTERN.test(name)).sort();
141
+ } catch {
142
+ names = [];
143
+ }
144
+ const chunks = [];
145
+ for (const name of names) {
146
+ try {
147
+ chunks.push((0, import_node_fs.readFileSync)((0, import_node_path.join)(dir, name), "utf8"));
148
+ } catch {
149
+ }
150
+ }
151
+ await (0, import_promises.writeFile)(target, chunks.join(""), "utf8");
152
+ },
153
+ get dir() {
154
+ return dir;
155
+ },
156
+ get file() {
157
+ return currentFile();
158
+ },
159
+ get level() {
160
+ return level;
161
+ }
162
+ };
163
+ }
164
+ var logger = createLogger("");
165
+
166
+ // src/settings.ts
167
+ var import_electron2 = require("electron");
168
+ var import_node_fs2 = require("fs");
169
+ var import_node_path2 = require("path");
33
170
  var WRITE_DELAY = 100;
171
+ var log = logger.child("settings");
34
172
  var store = null;
35
173
  var filePath = "";
36
174
  var dirty = false;
@@ -43,12 +181,12 @@ function assertInit() {
43
181
  return store;
44
182
  }
45
183
  function load() {
46
- if (!(0, import_node_fs.existsSync)(filePath)) return {};
184
+ if (!(0, import_node_fs2.existsSync)(filePath)) return {};
47
185
  let raw;
48
186
  try {
49
- raw = (0, import_node_fs.readFileSync)(filePath, "utf8");
187
+ raw = (0, import_node_fs2.readFileSync)(filePath, "utf8");
50
188
  } catch (err) {
51
- console.error("[electron-base-kit] \u8BFB\u53D6 settings \u5931\u8D25\uFF1A", err);
189
+ log.error("\u8BFB\u53D6 settings \u5931\u8D25", err);
52
190
  return {};
53
191
  }
54
192
  try {
@@ -58,11 +196,11 @@ function load() {
58
196
  }
59
197
  return parsed;
60
198
  } catch (err) {
61
- console.error("[electron-base-kit] settings \u5185\u5BB9\u65E0\u6548\uFF0C\u5DF2\u6539\u540D\u7559\u6863\uFF1A", err);
199
+ log.error("settings \u5185\u5BB9\u65E0\u6548\uFF0C\u5DF2\u6539\u540D\u7559\u6863", err);
62
200
  try {
63
- (0, import_node_fs.renameSync)(filePath, (0, import_node_path.join)((0, import_node_path.dirname)(filePath), "settings.bad.json"));
201
+ (0, import_node_fs2.renameSync)(filePath, (0, import_node_path2.join)((0, import_node_path2.dirname)(filePath), "settings.bad.json"));
64
202
  } catch (renameErr) {
65
- console.error("[electron-base-kit] \u7559\u6863\u5931\u8D25\uFF1A", renameErr);
203
+ log.error("\u7559\u6863\u5931\u8D25", renameErr);
66
204
  }
67
205
  return {};
68
206
  }
@@ -71,12 +209,12 @@ function writeNow() {
71
209
  if (!dirty || store === null) return;
72
210
  try {
73
211
  const tmp = `${filePath}.tmp`;
74
- (0, import_node_fs.writeFileSync)(tmp, `${JSON.stringify(store, null, 2)}
212
+ (0, import_node_fs2.writeFileSync)(tmp, `${JSON.stringify(store, null, 2)}
75
213
  `);
76
- (0, import_node_fs.renameSync)(tmp, filePath);
214
+ (0, import_node_fs2.renameSync)(tmp, filePath);
77
215
  dirty = false;
78
216
  } catch (err) {
79
- console.error("[electron-base-kit] \u5199\u5165 settings \u5931\u8D25\uFF1A", err);
217
+ log.error("\u5199\u5165 settings \u5931\u8D25", err);
80
218
  }
81
219
  }
82
220
  function schedule() {
@@ -88,29 +226,31 @@ function schedule() {
88
226
  }, WRITE_DELAY);
89
227
  timer.unref?.();
90
228
  }
91
- function emit(key, value) {
229
+ function emit2(key, value) {
92
230
  const set = listeners.get(key);
93
231
  if (!set) return;
94
232
  for (const fn of [...set]) {
95
233
  try {
96
234
  fn(value);
97
235
  } catch (err) {
98
- console.error(`[electron-base-kit] settings.onChange(${key}) \u56DE\u8C03\u629B\u9519\uFF1A`, err);
236
+ log.error(`onChange(${key}) \u56DE\u8C03\u629B\u9519`, err);
99
237
  }
100
238
  }
101
239
  }
102
240
  function initSettings() {
103
241
  if (store !== null) return;
104
- filePath = (0, import_node_path.join)(import_electron.app.getPath("userData"), "settings.json");
105
- (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(filePath), { recursive: true });
242
+ filePath = (0, import_node_path2.join)(import_electron2.app.getPath("userData"), "settings.json");
243
+ (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(filePath), { recursive: true });
106
244
  store = load();
107
- import_electron.app.on("before-quit", () => {
245
+ const flushNow = () => {
108
246
  if (timer) {
109
247
  clearTimeout(timer);
110
248
  timer = null;
111
249
  }
112
250
  writeNow();
113
- });
251
+ };
252
+ import_electron2.app.on("before-quit", flushNow);
253
+ import_electron2.app.on("will-quit", flushNow);
114
254
  }
115
255
  var settings = {
116
256
  get(key, fallback) {
@@ -132,7 +272,7 @@ var settings = {
132
272
  if (previous === serialized) return;
133
273
  data[key] = value;
134
274
  schedule();
135
- emit(key, value);
275
+ emit2(key, value);
136
276
  },
137
277
  has(key) {
138
278
  const data = assertInit();
@@ -143,7 +283,7 @@ var settings = {
143
283
  if (!(key in data)) return;
144
284
  delete data[key];
145
285
  schedule();
146
- emit(key, void 0);
286
+ emit2(key, void 0);
147
287
  },
148
288
  all() {
149
289
  return { ...assertInit() };
@@ -178,7 +318,7 @@ var settings = {
178
318
  };
179
319
 
180
320
  // src/window.ts
181
- var import_electron2 = require("electron");
321
+ var import_electron3 = require("electron");
182
322
  var FALLBACK = { width: 1200, height: 800, minWidth: 900, minHeight: 600 };
183
323
  var VISIBLE_RATIO = 0.3;
184
324
  var SAVE_DELAY = 300;
@@ -203,9 +343,9 @@ function isBounds(value) {
203
343
  return bounds.width > 0 && bounds.height > 0;
204
344
  }
205
345
  function bestWorkArea(rect) {
206
- let best = import_electron2.screen.getPrimaryDisplay().workArea;
346
+ let best = import_electron3.screen.getPrimaryDisplay().workArea;
207
347
  let bestArea = 0;
208
- for (const display of import_electron2.screen.getAllDisplays()) {
348
+ for (const display of import_electron3.screen.getAllDisplays()) {
209
349
  const area = intersectArea(rect, display.workArea);
210
350
  if (area > bestArea) {
211
351
  bestArea = area;
@@ -215,7 +355,7 @@ function bestWorkArea(rect) {
215
355
  return best;
216
356
  }
217
357
  function centerOnPrimary(size) {
218
- const primary = import_electron2.screen.getPrimaryDisplay().workArea;
358
+ const primary = import_electron3.screen.getPrimaryDisplay().workArea;
219
359
  const width = Math.min(size.width, primary.width);
220
360
  const height = Math.min(size.height, primary.height);
221
361
  return {
@@ -274,6 +414,7 @@ function attachPersistence(win, key) {
274
414
  timer2 = null;
275
415
  }
276
416
  save();
417
+ void settings.flush();
277
418
  });
278
419
  }
279
420
  var guarded = /* @__PURE__ */ new Set();
@@ -295,8 +436,8 @@ function attachDisplayGuard(win) {
295
436
  guarded.add(win);
296
437
  if (!screenHooked) {
297
438
  screenHooked = true;
298
- import_electron2.screen.on("display-removed", guardAll);
299
- import_electron2.screen.on("display-metrics-changed", guardAll);
439
+ import_electron3.screen.on("display-removed", guardAll);
440
+ import_electron3.screen.on("display-metrics-changed", guardAll);
300
441
  }
301
442
  win.once("closed", () => {
302
443
  guarded.delete(win);
@@ -320,7 +461,7 @@ function createWindow(options) {
320
461
  settings.remove(`${key}.maximized`);
321
462
  }
322
463
  const { bounds, center } = resolveBounds(isBounds(saved) ? saved : void 0, size, ensureVisible);
323
- const win = new import_electron2.BrowserWindow({
464
+ const win = new import_electron3.BrowserWindow({
324
465
  ...bounds,
325
466
  minWidth,
326
467
  minHeight,
@@ -335,7 +476,12 @@ function createWindow(options) {
335
476
  }
336
477
  });
337
478
  if (maximized) win.maximize();
338
- win.once("ready-to-show", () => win.show());
479
+ win.once("ready-to-show", () => {
480
+ win.show();
481
+ if (!remember) return;
482
+ if (win.isMaximized() || win.isMinimized() || win.isFullScreen()) return;
483
+ settings.set(`${key}.bounds`, win.getBounds());
484
+ });
339
485
  if (process.env.ELECTRON_RENDERER_URL) {
340
486
  win.loadURL(process.env.ELECTRON_RENDERER_URL);
341
487
  } else {
@@ -360,6 +506,7 @@ function assertConfig(config) {
360
506
  }
361
507
  function bootstrap(config) {
362
508
  assertConfig(config);
509
+ initLogger(config.log);
363
510
  initSettings();
364
511
  setWindowDefaults(config.window);
365
512
  if (config.features?.updater) {
@@ -385,5 +532,6 @@ function bootstrap(config) {
385
532
  0 && (module.exports = {
386
533
  bootstrap,
387
534
  createWindow,
535
+ logger,
388
536
  settings
389
537
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thirty-coder/electron-base-kit",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Electron 桌面应用基础能力",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -22,6 +22,7 @@
22
22
  "scripts": {
23
23
  "build": "tsup",
24
24
  "dev": "tsup --watch",
25
+ "test": "tsup && node --test test/*.test.cjs",
25
26
  "typecheck": "tsc --noEmit",
26
27
  "release": "node scripts/release.mjs"
27
28
  },