|
| 1 | +import { spawn } from 'child_process'; |
| 2 | +import { randomUUID } from 'crypto'; |
| 3 | +import { unlink } from 'fs/promises'; |
| 4 | +import { tmpdir } from 'os'; |
| 5 | +import { join } from 'path'; |
| 6 | +import { TippecanoeOptions, TippecanoeResult } from './TippecanoeTypes'; |
| 7 | + |
| 8 | +// Map of option names to their CLI argument names |
| 9 | +const OPTION_MAP: Record<string, string> = { |
| 10 | + minZoom: '--minimum-zoom', |
| 11 | + maxZoom: '--maximum-zoom', |
| 12 | + baseZoom: '--base-zoom', |
| 13 | + dropRate: '--drop-rate', |
| 14 | + buffer: '--buffer', |
| 15 | + tolerance: '--tolerance', |
| 16 | + layer: '--layer', |
| 17 | + dropDensestAsNeeded: '--drop-densest-as-needed', |
| 18 | + extendZoomsIfStillDropping: '--extend-zooms-if-still-dropping', |
| 19 | +}; |
| 20 | + |
| 21 | +/** |
| 22 | + * Process a GeoJSON stream into a PMTiles file using tippecanoe CLI |
| 23 | + * |
| 24 | + * Usage examples: |
| 25 | + * |
| 26 | + * 1. Basic usage with automatic cleanup (recommended): |
| 27 | + * ```typescript |
| 28 | + * await using result = await tippecanoe(geojsonStream); |
| 29 | + * // Use result.outputPath to access the PMTiles file |
| 30 | + * // File is automatically cleaned up when result goes out of scope |
| 31 | + * ``` |
| 32 | + * |
| 33 | + * 2. Process with options: |
| 34 | + * ```typescript |
| 35 | + * await using result = await tippecanoe(geojsonStream, { |
| 36 | + * minZoom: 0, |
| 37 | + * maxZoom: 16 |
| 38 | + * }); |
| 39 | + * ``` |
| 40 | + * |
| 41 | + * 3. Process newline-delimited GeoJSON: |
| 42 | + * ```typescript |
| 43 | + * await using result = await tippecanoe(geojsonStream, { |
| 44 | + * newlineDelimited: true, |
| 45 | + * minZoom: 5, |
| 46 | + * maxZoom: 14 |
| 47 | + * }); |
| 48 | + * ``` |
| 49 | + * |
| 50 | + * 4. Error handling with automatic cleanup: |
| 51 | + * ```typescript |
| 52 | + * try { |
| 53 | + * await using result = await tippecanoe(geojsonStream); |
| 54 | + * console.log('PMTiles generation completed successfully'); |
| 55 | + * // Cleanup happens automatically, even if an error is thrown |
| 56 | + * } catch (error) { |
| 57 | + * console.error('Tippecanoe process error:', error); |
| 58 | + * } |
| 59 | + * ``` |
| 60 | + * |
| 61 | + * @param inputStream - NodeJS.ReadableStream containing GeoJSON data |
| 62 | + * @param options - Tippecanoe configuration options |
| 63 | + * @returns Promise that resolves to result object with output path and automatic cleanup |
| 64 | + */ |
| 65 | +export default async function tippecanoe( |
| 66 | + inputStream: NodeJS.ReadableStream, |
| 67 | + options: TippecanoeOptions = {} |
| 68 | +): Promise<TippecanoeResult> { |
| 69 | + const { newlineDelimited, additionalArgs = {} } = options; |
| 70 | + |
| 71 | + // Create temporary output file |
| 72 | + const outputPath = join(tmpdir(), `tippecanoe-${randomUUID()}.pmtiles`); |
| 73 | + |
| 74 | + // Build tippecanoe command arguments - only add if explicitly provided |
| 75 | + const args: string[] = ['--output', outputPath]; |
| 76 | + |
| 77 | + // Add numeric options |
| 78 | + Object.entries(OPTION_MAP).forEach(([optionName, cliArg]) => { |
| 79 | + const value = options[optionName as keyof TippecanoeOptions]; |
| 80 | + if (value !== undefined) { |
| 81 | + if (typeof value === 'boolean') { |
| 82 | + if (value) { |
| 83 | + args.push(cliArg); |
| 84 | + } |
| 85 | + } else { |
| 86 | + args.push(cliArg, value.toString()); |
| 87 | + } |
| 88 | + } |
| 89 | + }); |
| 90 | + |
| 91 | + if (newlineDelimited) { |
| 92 | + args.push('--newline-delimited'); |
| 93 | + } |
| 94 | + |
| 95 | + // Add additional arguments with validation |
| 96 | + for (const [key, value] of Object.entries(additionalArgs)) { |
| 97 | + if (value === undefined || value === null) { |
| 98 | + continue; // Skip undefined/null values |
| 99 | + } |
| 100 | + |
| 101 | + if (typeof value === 'boolean') { |
| 102 | + if (value) { |
| 103 | + args.push(`--${key}`); |
| 104 | + } |
| 105 | + } else if (typeof value === 'string' || typeof value === 'number') { |
| 106 | + args.push(`--${key}`, value.toString()); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + // Spawn tippecanoe process |
| 111 | + const tippecanoeProcess = spawn('tippecanoe', args, { |
| 112 | + stdio: ['pipe', 'pipe', 'pipe'], |
| 113 | + }); |
| 114 | + |
| 115 | + // Set up progress monitoring (stderr is where tippecanoe writes progress) |
| 116 | + tippecanoeProcess.stderr?.on('data', (data: Buffer) => { |
| 117 | + // Forward tippecanoe's stderr to the parent process stderr |
| 118 | + process.stderr.write(data); |
| 119 | + }); |
| 120 | + |
| 121 | + // Pipe input stream to tippecanoe stdin |
| 122 | + inputStream.pipe(tippecanoeProcess.stdin); |
| 123 | + |
| 124 | + // Handle process completion |
| 125 | + const processPromise = new Promise<void>((resolve, reject) => { |
| 126 | + tippecanoeProcess.on('error', (error) => { |
| 127 | + reject(new Error(`Tippecanoe process error: ${error.message}`)); |
| 128 | + }); |
| 129 | + |
| 130 | + tippecanoeProcess.on('exit', (code) => { |
| 131 | + if (code === 0) { |
| 132 | + resolve(); |
| 133 | + } else { |
| 134 | + reject(new Error(`Tippecanoe exited with code ${code ?? 'unknown'}`)); |
| 135 | + } |
| 136 | + }); |
| 137 | + }); |
| 138 | + |
| 139 | + // Wait for process to complete |
| 140 | + await processPromise; |
| 141 | + |
| 142 | + return { |
| 143 | + outputPath, |
| 144 | + [Symbol.dispose]() { |
| 145 | + // Automatic cleanup when using 'await using' |
| 146 | + unlink(outputPath).catch((error) => { |
| 147 | + console.warn(`Failed to cleanup temporary file ${outputPath}:`, error); |
| 148 | + }); |
| 149 | + }, |
| 150 | + }; |
| 151 | +} |
0 commit comments