Skip to content

Commit

Permalink
Run detection prior to TransformStream initialization (`start(control…
Browse files Browse the repository at this point in the history
…ler)`).
  • Loading branch information
Borewit committed Aug 2, 2024
1 parent 72e1d95 commit 53ec046
Showing 1 changed file with 24 additions and 29 deletions.
53 changes: 24 additions & 29 deletions core.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,42 +111,37 @@ export class FileTypeParser {
async toDetectionStream(stream, options) {
const {sampleSize = reasonableDetectionSizeInBytes} = options;
let detectedFileType;
let firstChunk = null;
let firstChunk;

// Create a new ReadableStream to manage locking issues
const transformStream = new TransformStream({
async start(controller) {
const reader = stream.getReader({mode: 'byob'});
const reader = stream.getReader({mode: 'byob'});
try {
// Read the first chunk from the stream
const {value: chunk, done} = await reader.read(new Uint8Array(sampleSize));
firstChunk = chunk;
if (!done && chunk) {
try {
// Read the first chunk from the stream
const {value: chunk, done} = await reader.read(new Uint8Array(sampleSize));
firstChunk = chunk;
if (!done && chunk) {
try {
// Attempt to detect the file type from the chunk
detectedFileType = await this.fromBuffer(chunk.slice(0, sampleSize));
} catch (error) {
if (!(error instanceof strtok3.EndOfStreamError)) {
throw error; // Re-throw non-EndOfStreamError
}

detectedFileType = undefined;
}
// Attempt to detect the file type from the chunk
detectedFileType = await this.fromBuffer(chunk.slice(0, sampleSize));
} catch (error) {
if (!(error instanceof strtok3.EndOfStreamError)) {
throw error; // Re-throw non-EndOfStreamError
}

firstChunk = chunk;
} catch (error) {
controller.error(error); // Handle errors during start
} finally {
reader.releaseLock(); // Ensure the reader is released
detectedFileType = undefined;
}
}

firstChunk = chunk;
} finally {
reader.releaseLock(); // Ensure the reader is released
}

// Create a new ReadableStream to manage locking issues
const transformStream = new TransformStream({
async start(controller) {
controller.enqueue(firstChunk); // Enqueue the initial chunk
},
transform(chunk, controller) {
if (firstChunk) {
firstChunk = null;
controller.enqueue(firstChunk); // Enqueue the initial chunk
}

// Pass through the chunks without modification
controller.enqueue(chunk);
},
Expand Down

0 comments on commit 53ec046

Please sign in to comment.