Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/rstack/src/cachedImport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/** Share the pending import while allowing a failed import to be retried. */
export const cachedImport = <T>(
importer: () => Promise<T>,
): (() => Promise<T>) => {
let promise: Promise<T> | undefined;

return () =>
(promise ??= importer().catch((error: unknown) => {
promise = undefined;
throw error;
}));
};
5 changes: 4 additions & 1 deletion packages/rstack/src/fmt/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { hash } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import { cachedImport } from '../cachedImport.ts';
import type { FmtCacheEntry } from './cacheStore.ts';
import { hasDottedBasename } from './pathHelpers.ts';
import type { FmtFileCache, FmtFileRequest, FmtWorkerResult } from './types.ts';
Expand All @@ -12,6 +13,8 @@ interface FormatFileTask {
cache?: FmtFileCache;
}

const getFormatModule = cachedImport(() => import('./format.ts'));

const hashContent = (content: string | Uint8Array): string =>
hash('sha256', content, 'base64url').slice(0, 16);

Expand Down Expand Up @@ -65,7 +68,7 @@ const formatFile = async ({
}
}

const { formatFmtSource } = await import('./format.ts');
const { formatFmtSource } = await getFormatModule();
const result = await formatFmtSource(file, () => (source ??= readSource()));
if (result.status === 'unsupported') {
return cache
Expand Down
30 changes: 30 additions & 0 deletions packages/rstack/tests/cachedImport.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { expect, rs, test } from 'rstack/test';
import { cachedImport } from '../src/cachedImport.ts';

test('loads lazily and shares pending and fulfilled imports', async () => {
const module = { value: 1 };
const importer = rs.fn(() => Promise.resolve(module));
const load = cachedImport(importer);

expect(importer).not.toHaveBeenCalled();
const pending = load();
expect(load()).toBe(pending);
await expect(pending).resolves.toBe(module);
await expect(load()).resolves.toBe(module);
expect(importer).toHaveBeenCalledTimes(1);
});

test('allows retrying a failed import', async () => {
const error = new Error('Failed to load module');
const module = { value: 1 };
const importer = rs
.fn<() => Promise<typeof module>>()
.mockRejectedValueOnce(error)
.mockResolvedValue(module);
const load = cachedImport(importer);

await expect(load()).rejects.toBe(error);
await expect(load()).resolves.toBe(module);
await expect(load()).resolves.toBe(module);
expect(importer).toHaveBeenCalledTimes(2);
});
Loading