| 321 | * @throws {Error} If the file does not exist or is not a valid ZIP archive |
| 322 | */ |
| 323 | export async function assertValidZip(filePath: string): Promise<boolean> { |
| 324 | if (!(await fs.exists(filePath))) { |
| 325 | throw new Error(`The file at '${filePath}' does not exist`); |
| 326 | } |
| 327 | |
| 328 | const {size} = await fs.stat(filePath); |
| 329 | if (size < 4) { |
| 330 | throw new Error(`The file at '${filePath}' is too small to be a ZIP archive`); |
| 331 | } |
| 332 | const fd = await fs.open(filePath, 'r'); |
| 333 | try { |
| 334 | const buffer = Buffer.alloc(ZIP_MAGIC.length); |
| 335 | await fs.read(fd, buffer, 0, ZIP_MAGIC.length, 0); |
| 336 | const signature = buffer.toString('ascii'); |
| 337 | if (signature !== ZIP_MAGIC) { |
| 338 | throw new Error( |
| 339 | `The file signature '${signature}' of '${filePath}' ` + |
| 340 | `is not equal to the expected ZIP archive signature '${ZIP_MAGIC}'`, |
| 341 | ); |
| 342 | } |
| 343 | return true; |
| 344 | } finally { |
| 345 | await fs.close(fd); |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | /** |
| 350 | * Creates an archive based on the given glob pattern |