| 15 | return { |
| 16 | name: "add-bulk-and-track", |
| 17 | transform(code, id) { |
| 18 | // Only process JavaScript/TypeScript files |
| 19 | if (!id.match(/(\.[cm]?[jt]sx?$|@qwik)/)) { |
| 20 | return null; |
| 21 | } |
| 22 | |
| 23 | // Generate deterministic bulk based on filename |
| 24 | const hash = crypto.createHash("sha256").update(id).digest(); |
| 25 | |
| 26 | // Create bulk with an exponential-like distribution between 0kb and 50kb |
| 27 | // Most files will be closer to 0kb, with a few reaching 50kb |
| 28 | const maxSize = 500; |
| 29 | const x = hash[0] / 255; // Normalize first byte to 0-1 |
| 30 | const exp = Math.pow(x, 6); // Skew distribution |
| 31 | const bulkSize = Math.floor(maxSize * exp); |
| 32 | |
| 33 | // Create repeatable random bulk using the hash as seed |
| 34 | const prng = crypto.createHash("sha512").update(id).digest(); |
| 35 | const bulk = Array.from({ length: Math.ceil(bulkSize / 64) }, (_, i) => { |
| 36 | // Use the hash as a seed to generate new random blocks |
| 37 | const block = crypto |
| 38 | .createHash("sha512") |
| 39 | .update(prng) |
| 40 | .update(Buffer.from([i])) |
| 41 | .digest("base64"); |
| 42 | return block; |
| 43 | }).join(""); |
| 44 | |
| 45 | // Add tracking code and bulk assignment at the start of each module |
| 46 | const trackingCode = ` |
| 47 | console.log(">>> running", ${JSON.stringify(id)}); |
| 48 | ;(globalThis._loaded||=[]).push(${JSON.stringify(id)}); |
| 49 | `; |
| 50 | const bulkCode = ` |
| 51 | globalThis._fakeBulk?.(${JSON.stringify(bulk)}); |
| 52 | `; |
| 53 | |
| 54 | return { |
| 55 | /** Note that this code is injected before the import statements which is technically incorrect but Vite handles it */ |
| 56 | code: `${trackingCode}\n${code}\n${bulkCode}`, |
| 57 | map: null, |
| 58 | }; |
| 59 | }, |
| 60 | }; |
| 61 | } |
| 62 | |