| 59 | // declares a one-chunk bundle's units in one function: V8 inlines a call |
| 60 | // through its constant, not through a module variable a bundler writes as a var |
| 61 | export const flattenBundle = ( |
| 62 | sites: Record<string, string>, |
| 63 | modules: Record<string, string>, |
| 64 | program: FlatProgram, |
| 65 | whereSmaller = true |
| 66 | ): FlatBundle | undefined => { |
| 67 | const parsed = new Map<string, SourceModule>() |
| 68 | for (const specifier in modules) { |
| 69 | parsed.set( |
| 70 | specifier, |
| 71 | new SourceModule(`${specifier}.js`, modules[specifier], specifier) |
| 72 | ) |
| 73 | } |
| 74 | for (const id in sites) parsed.set(id, new SourceModule(id, sites[id], id)) |
| 75 | if ([...parsed.values()].some(module => module.parseErrors.length)) return |
| 76 | // a site as written, the rest as the scan read them |
| 77 | const bundled = new Map(parsed) |
| 78 | for (const module of program.modules) |
| 79 | if (!bundled.has(module.id)) bundled.set(module.id, module) |
| 80 | const keptIn = ( |
| 81 | modules: ReadonlyMap<string, SourceModule>, |
| 82 | skipped?: ReadonlyMap<SourceModule, Creation[]> |
| 83 | ) => keptCodeOf(modules, program, skipped) |
| 84 | const kept = keptIn(bundled) |
| 85 | const units = unitsOf(modules, parsed, kept) |
| 86 | if (!units) return |
| 87 | const creationsBySite = creationsIn(sites, parsed, units, kept) |
| 88 | const creations = [...creationsBySite.values()].flat() |
| 89 | const flat = writeFlat(units, creations) |
| 90 | if (!flat) return |
| 91 | const specifier = `~arktype/${hashOf(flat.code)}` |
| 92 | const flattened = new Set(units.map(unit => unit.specifier)) |
| 93 | // a flattened unit is read from the function's module |
| 94 | const read = new Set(creations.map(creation => creation.name)) |
| 95 | const created = new Map( |
| 96 | [...creationsBySite].map(([id, creations]) => [parsed.get(id)!, creations]) |
| 97 | ) |
| 98 | const readKept = creations.length ? keptIn(bundled, created) : kept |
| 99 | const repointed = new Map<string, Repointed[]>() |
| 100 | for (const [key, module] of parsed) { |
| 101 | if (flattened.has(key)) continue |
| 102 | const edits = repointedIn( |
| 103 | module, |
| 104 | flattened, |
| 105 | flat.exported, |
| 106 | specifier, |
| 107 | read, |
| 108 | binding => readKept.reads(binding) |
| 109 | ) |
| 110 | if (!edits) return |
| 111 | if (edits.length) repointed.set(key, edits) |
| 112 | } |
| 113 | if (!read.size) return |
| 114 | // as a minifier writes them, flat only where it's smaller |
| 115 | const unflattened = [ |
| 116 | ...units.flatMap(unit => |
| 117 | unit.declarations.map(d => unit.module.source.slice(d.start, d.end)) |
| 118 | ), |