| 199 | } |
| 200 | |
| 201 | export function handleSheetsFormat(input: unknown): { |
| 202 | csv?: string |
| 203 | rowCount: number |
| 204 | columnCount: number |
| 205 | } { |
| 206 | let workingValue: unknown = input |
| 207 | |
| 208 | if (typeof workingValue === 'string') { |
| 209 | try { |
| 210 | workingValue = JSON.parse(workingValue) |
| 211 | } catch (_error) { |
| 212 | const csvString = workingValue as string |
| 213 | return { csv: csvString, rowCount: 0, columnCount: 0 } |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | if (!Array.isArray(workingValue)) { |
| 218 | return { rowCount: 0, columnCount: 0 } |
| 219 | } |
| 220 | |
| 221 | let table: unknown[] = workingValue |
| 222 | |
| 223 | if ( |
| 224 | table.length > 0 && |
| 225 | typeof (table as any)[0] === 'object' && |
| 226 | (table as any)[0] !== null && |
| 227 | !Array.isArray((table as any)[0]) |
| 228 | ) { |
| 229 | const allKeys = new Set<string>() |
| 230 | ;(table as any[]).forEach((obj) => { |
| 231 | if (obj && typeof obj === 'object') { |
| 232 | Object.keys(obj).forEach((key) => allKeys.add(key)) |
| 233 | } |
| 234 | }) |
| 235 | const headers = Array.from(allKeys) |
| 236 | const rows = (table as any[]).map((obj) => { |
| 237 | if (!obj || typeof obj !== 'object') { |
| 238 | return Array(headers.length).fill('') |
| 239 | } |
| 240 | return headers.map((key) => { |
| 241 | const value = (obj as Record<string, unknown>)[key] |
| 242 | if (value !== null && typeof value === 'object') { |
| 243 | return JSON.stringify(value) |
| 244 | } |
| 245 | return value === undefined ? '' : (value as any) |
| 246 | }) |
| 247 | }) |
| 248 | table = [headers, ...rows] |
| 249 | } |
| 250 | |
| 251 | const escapeCell = (cell: unknown): string => { |
| 252 | if (cell === null || cell === undefined) return '' |
| 253 | const stringValue = String(cell) |
| 254 | const mustQuote = /[",\n\r]/.test(stringValue) |
| 255 | const doubledQuotes = stringValue.replace(/"/g, '""') |
| 256 | return mustQuote ? `"${doubledQuotes}"` : doubledQuotes |
| 257 | } |
| 258 | |