@weapp-vite/hmr 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/dist/index.d.mts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/assets.d.ts
2
1
  export interface HmrAsset {
3
2
  fileName: string;
4
3
  source: string | Uint8Array;
@@ -21,8 +20,6 @@ export declare class HmrAssetStore<T extends HmrAsset = HmrAsset> {
21
20
  diff(assets: readonly T[], retainedFileNames?: Iterable<string>): HmrAssetChanges<T>;
22
21
  commit(assets: readonly T[], write: (changes: HmrAssetChanges<T>) => Promise<void>, retainedFileNames?: Iterable<string>): Promise<HmrAssetChanges<T>>;
23
22
  }
24
- //#endregion
25
- //#region src/types.d.ts
26
23
  export interface HmrCompilerOutputRequest {
27
24
  fileName: string;
28
25
  code: string;
@@ -61,8 +58,6 @@ export interface HmrCompilerPreparation {
61
58
  export interface HmrCompilerProvider {
62
59
  prepareHmr?: (request: HmrCompilerRequest) => HmrCompilerPreparation | Promise<HmrCompilerPreparation>;
63
60
  }
64
- //#endregion
65
- //#region src/batch.d.ts
66
61
  export interface HmrSourceMap {
67
62
  version: number;
68
63
  sources: string[];
@@ -113,8 +108,6 @@ export declare function transformHmrPatch(patch: {
113
108
  export declare function transformHmrBatch<B extends HmrBatch>(batch: B, preparations: readonly HmrCompilerPreparation[], options: {
114
109
  sourcemap: boolean;
115
110
  }): Promise<TransformedHmrBatch<B>>;
116
- //#endregion
117
- //#region src/compilerHost.d.ts
118
111
  interface Provider {
119
112
  prepare?: HmrCompilerProvider['prepareHmr'];
120
113
  }
@@ -149,8 +142,6 @@ export declare class HmrCompilerHost {
149
142
  freeze(changedFiles: readonly string[]): HmrCompilerRequest;
150
143
  prepare(request: HmrCompilerRequest): Promise<HmrCompilerPreparation[]>;
151
144
  }
152
- //#endregion
153
- //#region src/deliveryCoordinator.d.ts
154
145
  export interface HmrDeliveryPreparation {
155
146
  commit: () => Promise<void>;
156
147
  publish: () => Promise<void>;
@@ -174,6 +165,8 @@ export declare class HmrDeliveryCoordinator {
174
165
  private revision;
175
166
  private pendingBytes;
176
167
  private readonly disposals;
168
+ private readonly disposalFailures;
169
+ private closing?;
177
170
  constructor(onError: (error: unknown) => void, requestResynchronization?: (() => void) | undefined, maxPending?: number);
178
171
  enqueue(task: HmrDeliveryTask): void;
179
172
  retry(): void;
@@ -183,21 +176,23 @@ export declare class HmrDeliveryCoordinator {
183
176
  close(): Promise<void>;
184
177
  private prepare;
185
178
  private dispose;
179
+ private reportError;
180
+ private recordDisposalFailure;
181
+ private waitForDisposals;
182
+ private throwDisposalFailures;
186
183
  private drain;
187
184
  }
188
- //#endregion
189
- //#region src/errors.d.ts
190
185
  export declare class CompilerHmrResyncError extends Error {
191
186
  readonly files: readonly string[];
192
187
  constructor(files: readonly string[], message: string);
193
188
  }
194
- //#endregion
195
- //#region src/retention.d.ts
189
+ /** @internal */
190
+ export declare class HmrPreparationCleanupError extends AggregateError {
191
+ constructor(failure: unknown, cleanupErrors: readonly unknown[]);
192
+ }
196
193
  export declare const maxRetainedDeltaCount = 1000;
197
194
  export declare const maxRetainedDeltaBytes: number;
198
195
  export declare function shouldResetStatefulHmrRetention(count: number, bytes: number, nextBytes: number): boolean;
199
- //#endregion
200
- //#region src/transaction.d.ts
201
196
  export interface HmrBatchIdentity {
202
197
  generation: string;
203
198
  revision: number;
@@ -227,4 +222,4 @@ export declare class HmrTransaction<T> {
227
222
  private isDisposed;
228
223
  private deliver;
229
224
  }
230
- //#endregion
225
+ export {};
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Buffer } from "node:buffer";
2
2
  import remapping from "@jridgewell/remapping";
3
- //#region src/assets.ts
3
+ // src/assets.ts
4
4
  function copyAsset(asset) {
5
5
  return {
6
6
  ...asset,
@@ -63,8 +63,7 @@ var HmrAssetStore = class {
63
63
  return changes;
64
64
  }
65
65
  };
66
- //#endregion
67
- //#region src/batch.ts
66
+ // src/batch.ts
68
67
  /** 在回调入口保留完整元数据和原始顺序,不合并不同的源码代次。 */
69
68
  function captureHmrBatch(batch) {
70
69
  const snapshot = structuredClone(batch);
@@ -164,8 +163,7 @@ async function transformHmrBatch(batch, preparations, options) {
164
163
  updates
165
164
  };
166
165
  }
167
- //#endregion
168
- //#region src/errors.ts
166
+ // src/errors.ts
169
167
  var CompilerHmrResyncError = class extends Error {
170
168
  files;
171
169
  constructor(files, message) {
@@ -174,8 +172,20 @@ var CompilerHmrResyncError = class extends Error {
174
172
  this.name = "CompilerHmrResyncError";
175
173
  }
176
174
  };
177
- //#endregion
178
- //#region src/compilerHost.ts
175
+ /** @internal */
176
+ var HmrPreparationCleanupError = class extends AggregateError {
177
+ constructor(failure, cleanupErrors) {
178
+ super([failure, ...cleanupErrors], "HMR preparation failed and resource disposal failed", { cause: failure });
179
+ this.name = "HmrPreparationCleanupError";
180
+ }
181
+ };
182
+ // src/compilerHost.ts
183
+ /** 部分准备失败后仍尝试全部释放,保留最初的拒绝及每个清理错误。 */
184
+ async function rejectPreparations(results, failure) {
185
+ const failures = (await Promise.allSettled(results.map((result) => Promise.resolve().then(() => result.dispose?.())))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
186
+ if (failures.length) throw new HmrPreparationCleanupError(failure, failures);
187
+ throw failure;
188
+ }
179
189
  /** 只保存宿主实际提供的输入;模块身份和框架语义由适配器决定。 */
180
190
  var HmrCompilerHost = class {
181
191
  options;
@@ -271,31 +281,23 @@ var HmrCompilerHost = class {
271
281
  const settled = await Promise.allSettled(pending);
272
282
  const results = settled.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
273
283
  const failure = settled.find((result) => result.status === "rejected");
274
- if (failure?.status === "rejected") {
275
- await Promise.allSettled(results.map((result) => result.dispose?.()));
276
- throw failure.reason;
277
- }
284
+ if (failure?.status === "rejected") return rejectPreparations(results, failure.reason);
278
285
  const assets = /* @__PURE__ */ new Set();
279
286
  for (const result of results) for (const asset of result.assets ?? []) {
280
287
  const file = asset.fileName.replaceAll("\\", "/");
281
- if (assets.has(file)) {
282
- await Promise.allSettled(results.map((result) => result.dispose?.()));
283
- throw new CompilerHmrResyncError(request.changedFiles, `Compiler HMR asset has multiple providers: ${file}`);
284
- }
288
+ if (assets.has(file)) return rejectPreparations(results, new CompilerHmrResyncError(request.changedFiles, `Compiler HMR asset has multiple providers: ${file}`));
285
289
  assets.add(file);
286
290
  }
287
291
  return results;
288
292
  }
289
293
  };
290
- //#endregion
291
- //#region src/retention.ts
294
+ // src/retention.ts
292
295
  const maxRetainedDeltaCount = 1e3;
293
296
  const maxRetainedDeltaBytes = 16777216;
294
297
  function shouldResetStatefulHmrRetention(count, bytes, nextBytes) {
295
298
  return count >= 1e3 || bytes + nextBytes >= 16777216;
296
299
  }
297
- //#endregion
298
- //#region src/deliveryCoordinator.ts
300
+ // src/deliveryCoordinator.ts
299
301
  /** 编译结果可以提前准备,资产提交与客户端执行确认必须保持同一条交付链。 */
300
302
  var HmrDeliveryCoordinator = class {
301
303
  onError;
@@ -310,13 +312,15 @@ var HmrDeliveryCoordinator = class {
310
312
  revision = 0;
311
313
  pendingBytes = 0;
312
314
  disposals = /* @__PURE__ */ new Set();
315
+ disposalFailures = [];
316
+ closing;
313
317
  constructor(onError, requestResynchronization, maxPending = maxRetainedDeltaCount) {
314
318
  this.onError = onError;
315
319
  this.requestResynchronization = requestResynchronization;
316
320
  this.maxPending = maxPending;
317
321
  }
318
322
  enqueue(task) {
319
- if (this.closed) return;
323
+ if (this.closed || this.disposalFailures.length) return;
320
324
  if (this.failed && this.requestResynchronization) {
321
325
  this.requestResynchronization();
322
326
  return;
@@ -336,12 +340,13 @@ var HmrDeliveryCoordinator = class {
336
340
  this.retry();
337
341
  }
338
342
  retry() {
343
+ if (this.closed || this.disposalFailures.length) return;
339
344
  this.failed = false;
340
345
  this.failure = void 0;
341
346
  this.revision += 1;
342
347
  if (!this.running && !this.closed) this.running = this.drain().finally(() => {
343
348
  this.running = void 0;
344
- if (this.pending.length && !this.failed && !this.closed) this.retry();
349
+ if (this.pending.length && !this.failed && !this.closed && !this.disposalFailures.length) this.retry();
345
350
  });
346
351
  }
347
352
  reset() {
@@ -359,26 +364,34 @@ var HmrDeliveryCoordinator = class {
359
364
  const revision = this.revision;
360
365
  try {
361
366
  await this.running;
362
- await Promise.all(this.disposals);
367
+ await this.waitForDisposals();
363
368
  } catch (error) {
364
369
  throw this.failed ? this.failure : error;
365
370
  }
366
- if (this.closed) throw new Error("HMR delivery coordinator closed before settlement");
371
+ this.throwDisposalFailures();
367
372
  if (this.failed) throw this.failure;
373
+ if (this.closed) throw new Error("HMR delivery coordinator closed before settlement");
368
374
  if (revision === this.revision && !this.running && this.pending.length === 0 && this.disposals.size === 0) return;
369
375
  }
370
376
  }
371
- async close() {
372
- this.closed = true;
373
- this.reset();
374
- await this.running;
375
- await Promise.all(this.disposals);
377
+ close() {
378
+ if (!this.closing) {
379
+ this.closed = true;
380
+ this.reset();
381
+ this.closing = (async () => {
382
+ await this.running;
383
+ await this.waitForDisposals();
384
+ this.throwDisposalFailures();
385
+ })();
386
+ }
387
+ return this.closing;
376
388
  }
377
389
  prepare(item) {
378
390
  if (!item.preparation) {
379
391
  item.preparation = item.task.prepare();
380
- item.preparation.catch(() => {
392
+ item.preparation.catch((error) => {
381
393
  item.preparation = void 0;
394
+ if (error instanceof HmrPreparationCleanupError) this.recordDisposalFailure(error);
382
395
  });
383
396
  }
384
397
  return item.preparation;
@@ -386,25 +399,48 @@ var HmrDeliveryCoordinator = class {
386
399
  dispose(item) {
387
400
  if (item.disposal) return item.disposal;
388
401
  item.disposal = (async () => {
402
+ let preparation;
389
403
  try {
390
- await (await item.preparation)?.dispose?.();
391
- } catch {}
404
+ preparation = await item.preparation;
405
+ } catch {
406
+ return;
407
+ }
408
+ await preparation?.dispose?.();
392
409
  })();
393
410
  this.disposals.add(item.disposal);
394
- item.disposal.then(() => this.disposals.delete(item.disposal));
411
+ item.disposal.then(() => this.disposals.delete(item.disposal), (error) => {
412
+ this.disposals.delete(item.disposal);
413
+ this.recordDisposalFailure(error);
414
+ });
395
415
  return item.disposal;
396
416
  }
417
+ reportError(error) {
418
+ try {
419
+ this.onError(error);
420
+ } catch {}
421
+ }
422
+ recordDisposalFailure(error) {
423
+ this.disposalFailures.push(error);
424
+ this.reportError(error);
425
+ }
426
+ async waitForDisposals() {
427
+ while (this.disposals.size) await Promise.allSettled(this.disposals);
428
+ }
429
+ throwDisposalFailures() {
430
+ if (this.disposalFailures.length === 1) throw this.disposalFailures[0];
431
+ if (this.disposalFailures.length > 1) throw new AggregateError(this.disposalFailures, "HMR delivery disposal failed", { cause: this.disposalFailures[0] });
432
+ }
397
433
  async drain() {
398
- while (!this.closed && this.pending.length) {
434
+ while (!this.closed && !this.disposalFailures.length && this.pending.length) {
399
435
  const item = this.pending[0];
400
436
  try {
401
437
  const prepared = await this.prepare(item);
402
- if (item.generation !== this.generation) continue;
438
+ if (item.generation !== this.generation || this.disposalFailures.length) continue;
403
439
  if (!item.committed) {
404
440
  await prepared.commit();
405
441
  item.committed = true;
406
442
  }
407
- if (item.generation !== this.generation) continue;
443
+ if (item.generation !== this.generation || this.disposalFailures.length) continue;
408
444
  await prepared.publish();
409
445
  if (this.pending[0] === item) {
410
446
  this.pending.shift();
@@ -412,19 +448,23 @@ var HmrDeliveryCoordinator = class {
412
448
  }
413
449
  await this.dispose(item);
414
450
  } catch (error) {
451
+ if (this.disposalFailures.includes(error)) return;
415
452
  if (item.generation === this.generation && !this.closed) {
416
453
  this.failed = true;
417
454
  this.failure = error;
418
- this.onError(error);
419
- if (item.generation === this.generation && this.pending.length > 1) this.requestResynchronization?.();
455
+ this.reportError(error);
456
+ if (item.generation === this.generation && this.pending.length > 1) try {
457
+ this.requestResynchronization?.();
458
+ } catch (resyncError) {
459
+ this.reportError(resyncError);
460
+ }
420
461
  return;
421
462
  }
422
463
  }
423
464
  }
424
465
  }
425
466
  };
426
- //#endregion
427
- //#region src/transaction.ts
467
+ // src/transaction.ts
428
468
  /** 可由现有宿主队列调度的单批事务;确认入口不占用或等待该队列。 */
429
469
  var HmrTransaction = class {
430
470
  options;
@@ -495,5 +535,4 @@ var HmrTransaction = class {
495
535
  }
496
536
  }
497
537
  };
498
- //#endregion
499
- export { CompilerHmrResyncError, HmrAssetStore, HmrCompilerHost, HmrDeliveryCoordinator, HmrTransaction, captureHmrBatch, composeHmrSourceMaps, maxRetainedDeltaBytes, maxRetainedDeltaCount, normalizeHmrSourceMap, shouldResetStatefulHmrRetention, transformHmrBatch, transformHmrPatch };
538
+ export { CompilerHmrResyncError, HmrAssetStore, HmrCompilerHost, HmrDeliveryCoordinator, HmrPreparationCleanupError, HmrTransaction, captureHmrBatch, composeHmrSourceMaps, maxRetainedDeltaBytes, maxRetainedDeltaCount, normalizeHmrSourceMap, shouldResetStatefulHmrRetention, transformHmrBatch, transformHmrPatch };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@weapp-vite/hmr",
3
3
  "type": "module",
4
- "version": "0.2.1",
4
+ "version": "0.3.0",
5
5
  "description": "小程序宿主共享的编译批次、资产提交与交付协调内核",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/weapp-vite/weapp-vite#readme",
@@ -34,7 +34,7 @@
34
34
  "dist"
35
35
  ],
36
36
  "engines": {
37
- "node": "^20.19.0 || >=22.12.0"
37
+ "node": "^22.23.4 || ^24.22.1 || >=26.12.1"
38
38
  },
39
39
  "dependencies": {
40
40
  "@jridgewell/remapping": "^2.3.5"
@@ -47,6 +47,7 @@
47
47
  "build": "tsdown",
48
48
  "typecheck": "tsc --noEmit -p tsconfig.json",
49
49
  "test": "vitest run -c vitest.config.ts",
50
+ "test:pure": "vitest run -c vitest.config.ts --coverage.enabled=false --maxWorkers=1",
50
51
  "test:types": "pnpm run test:types:check",
51
52
  "test:types:check": "tsd --files \"test-d/**/*.test-d.ts\"",
52
53
  "lint": "eslint ."