Skip to content
Source
Sign inSign up
TanStack/cli
Open History to see the last commit

als-shim.ts

125 lines3.3 KB

1const ALS_RESOLVER = `resolve: {
2 alias: {
3 'node:async_hooks': '\\0virtual:async_hooks',
4 async_hooks: '\\0virtual:async_hooks',
5 },
6},`
7​
8const ALS_SHIM = `export class AsyncLocalStorage {
9 constructor() {
10 // queue: array of { store, fn, resolve, reject }
11 this._queue = [];
12 this._running = false; // true while processing queue
13 this._currentStore = undefined; // store visible to getStore() while a run executes
14 }
15​
16 /**
17 * run(store, callback, ...args) -> Promise
18 * Queues the callback to run with store as the current store. If the callback
19 * returns a Promise, the queue waits for it to settle before starting the next run.
20 */
21 run(store, callback, ...args) {
22 return new Promise((resolve, reject) => {
23 this._queue.push({
24 store,
25 fn: () => callback(...args),
26 resolve,
27 reject,
28 });
29 // start processing (if not already)
30 this._processQueue().catch((err) => {
31 // _processQueue shouldn't throw; but guard anyway.
32 console.error('SerialAsyncLocalStorage internal error:', err);
33 });
34 });
35 }
36​
37 /**
38 * getStore() -> current store or undefined
39 * Returns the store of the currently executing run (or undefined if none).
40 */
41 getStore() {
42 return this._currentStore;
43 }
44​
45 /**
46 * enterWith(store)
47 * Set the current store for the currently running task synchronously.
48 * Throws if there is no active run (this polyfill requires you to be inside a run).
49 */
50 enterWith(store) {
51 if (!this._running) {
52 throw new Error('enterWith() may be used only while a run is active.');
53 }
54 this._currentStore = store;
55 }
56​
57 // internal: process queue serially
58 async _processQueue() {
59 if (this._running) return;
60 this._running = true;
61​
62 while (this._queue.length) {
63 const { store, fn, resolve, reject } = this._queue.shift();
64 const prevStore = this._currentStore;
65 this._currentStore = store;
66​
67 try {
68 const result = fn();
69 // await if callback returned a promise
70 const awaited = result instanceof Promise ? await result : result;
71 resolve(awaited);
72 } catch (err) {
73 reject(err);
74 } finally {
75 // restore previous store (if any)
76 this._currentStore = prevStore;
77 }
78 // loop continues to next queued task
79 }
80​
81 this._running = false;
82 }
84export default AsyncLocalStorage
86​
87const ALS_SHIM_LOADER = `
88function alsShim(): PluginOption {
89 return {
90 enforce: 'pre',
91 name: 'virtual-async-hooks',
92 config() {
93 return {
94 resolve: {
95 alias: {
96 // catch both forms
97 'node:async_hooks': '\\0virtual:async_hooks',
98 async_hooks: '\\0virtual:async_hooks',
99 },
100 },
101 };
102 },
103 resolveId(id) {
104 if (id === '\\0virtual:async_hooks') return id;
105 },
106 load(id) {
107 if (id !== '\\0virtual:async_hooks') return null;
108​
109 return \`${ALS_SHIM}\`;
110 },
111 };
114​
115export default function shimALS(fileName: string, content: string) {
116 let adjustedContent = content
117 if (fileName === 'vite.config.ts') {
118 adjustedContent += ALS_SHIM_LOADER
119 adjustedContent = adjustedContent.replace(
120 'plugins: [',
121 `${ALS_RESOLVER}plugins: [alsShim(),`,
122 )
123 }
124 return adjustedContent