Skip to content

Commit a8a6782

Browse files
Added logic to attempt to check file type as test or csv
1 parent 34a308b commit a8a6782

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

frontend/src/app/modules/policy-engine/policy-viewer/code/ipfs-transformation-ui-addon.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,11 +151,50 @@ export class IpfsTransformationUIAddonCode {
151151

152152
if (fileType) {
153153
mimeType = fileType.mime;
154+
} else if (this.isTextBuffer(buffer)) {
155+
mimeType = this.isCsvBuffer(buffer) ? 'text/csv' : 'text/plain';
154156
}
155157

156158
return `data:${mimeType};base64,${base64}`;
157159
}
158160

161+
private isTextBuffer(buffer: ArrayBuffer): boolean {
162+
const checkSize = Math.min(1024, buffer.byteLength);
163+
const chunk = new Uint8Array(buffer, 0, checkSize);
164+
for (let i = 0; i < chunk.length; i++) {
165+
const byte = chunk[i];
166+
if (byte === 0 || (byte < 9 || (byte > 13 && byte < 32)) && byte > 127) {
167+
return false;
168+
}
169+
}
170+
return true;
171+
}
172+
173+
private isCsvBuffer(buffer: ArrayBuffer): boolean {
174+
try {
175+
const text = new TextDecoder().decode(new Uint8Array(buffer, 0, buffer.byteLength));
176+
const lines = text.split('\n').filter(line => line.trim().length > 0);
177+
178+
const delimiters = [',', ';', '\r', '\t'];
179+
const firstLine = lines[0];
180+
181+
for (const delimiter of delimiters) {
182+
const count = (firstLine.match(new RegExp(`\\${delimiter}`, 'g')) || []).length;
183+
if (count > 0) {
184+
const consistent = lines.slice(0, 3).every(line =>
185+
(line.match(new RegExp(`\\${delimiter}`, 'g')) || []).length === count
186+
);
187+
if (consistent) {
188+
return true;
189+
}
190+
}
191+
}
192+
return false;
193+
} catch {
194+
return false;
195+
}
196+
}
197+
159198
private arrayBufferToBase64(buffer: ArrayBuffer): string {
160199
const CHUNK_SIZE_IN_KB = 32 * 1024;
161200
const chunks: string[] = [];

0 commit comments

Comments
 (0)