Yolk SDK
Integrations

Extract file text

Turn PDF, DOCX, XLSX, PPTX, and text files into bounded, sanitized text, and feed it to knowledge ingestion.

@yolk-sdk/extractors turns file bytes your app already has into sanitized text with metadata. It gives you one Effect service, FileExtractor, a Node implementation that parses PDF, DOCX, XLSX, and PPTX in worker threads with size and time limits, and an adapter that plugs it into knowledge ingestion. Uploads, auth, storage, and what you do with the text stay in your app.

Install

pnpm add @yolk-sdk/extractors@canary effect@4.2.0

With knowledge ingestion:

pnpm add @yolk-sdk/extractors@canary @yolk-sdk/knowledge@canary effect@4.2.0

Only if you extract .xlsx files, add SheetJS from its CDN (not the npm xlsx package):

pnpm add https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz

Requires Node.js 22 or later. @yolk-sdk/extractors/node is server-only.

SheetJS (xlsx >=0.20.3) is an optional peer, loaded only when an XLSX file is extracted. The npm xlsx package stops at 0.18.5, which has CVE-2023-30533 and CVE-2024-22363; fixed releases are published only on cdn.sheetjs.com. Because the peer is optional, it never arrives transitively: each host adds it directly. pnpm records the tarball URL and integrity hash in the lockfile. Other formats never load SheetJS.

Subpaths

SubpathRuntimeUse for
@yolk-sdk/extractorsruntime-portablethe FileExtractor service tag and FileExtractorApi type; types FileInput, ExtractedFile, ExtractedFileMetadata, ExtractedFileFormat, OfficeFileFormat, FileExtractorError; fileFormatFor, extractedFileFormats, isOfficeFileFormat; defaultFileExtractorLimits and the FileExtractorLimits schema; sanitizeExtractedText; errors and FileExtractionFailureReason; minimumSheetJsVersion, sheetJsInstallCommand
@yolk-sdk/extractors/nodeNode, serverFileExtractorLayer, makeFileExtractorLayer(options), defaultWorkerIsolation, normalizeOfficeArchive; types FileExtractorOptions, FileExtractorIsolation, WorkerIsolationOptions, OfficeArchiveLimits, SheetJsLoader; also re-exports FileExtractor and FileExtractorApi
@yolk-sdk/extractors/knowledgeruntime-portableFileKnowledgeExtractorLayer and makeFileKnowledgeExtractor: a @yolk-sdk/knowledge/extraction KnowledgeExtractor backed by the FileExtractor in context
@yolk-sdk/extractors/node/extraction-workerNode workerthe worker entry the Node layer starts; do not import it directly (see Next.js)

The root and ./knowledge import no parsers and no Node built-ins, so code that only needs the contract (for example a service that receives a FileExtractor from context) can run anywhere.

Extract a file

Create extract.mts (the .mts extension makes it an ES module, so top-level await works in any project):

extract.mts
import { readFile } from 'node:fs/promises'
import { basename } from 'node:path'
import { Effect } from 'effect'
import { FileExtractor } from '@yolk-sdk/extractors'
import { FileExtractorLayer } from '@yolk-sdk/extractors/node'

const path = process.argv[2] ?? 'notes.txt'

const program = Effect.gen(function* () {
  const extractor = yield* FileExtractor
  const bytes = new Uint8Array(yield* Effect.promise(() => readFile(path)))

  return yield* extractor.extract({ filename: basename(path), mediaType: '', bytes })
}).pipe(Effect.provide(FileExtractorLayer))

const extracted = await Effect.runPromise(program)

console.log(extracted.metadata)
console.log(extracted.content)

Create a text file and run the script:

printf 'Quarterly   notes\r\n\r\n\r\n\r\nRevenue grew.\r\n' > notes.txt
pnpm dlx tsx extract.mts notes.txt

You should see the metadata and the sanitized text (line endings normalized, repeated spaces and blank lines collapsed):

{ format: 'text', title: 'notes.txt' }
Quarterly notes

Revenue grew.

Pass a .pdf, .docx, .pptx, or .xlsx path to parse it in a worker thread. A workbook with one sheet named Q1 prints { format: 'xlsx', title: 'report.xlsx', sheetNames: [ 'Q1' ] } followed by a # Q1 section of CSV rows.

In a server, bytes comes from your upload or storage layer. mediaType can be the upload's media type or ''. The extractor copies the input before a parser reads it, so your buffer is never detached.

Formats and output

The format comes from the filename extension (txt, md, markdown, csv, json, pdf, docx, xlsx, pptx), then the media type, then any text/* media type as plain text. fileFormatFor exposes the same rule. Anything else fails with UnsupportedFileFormatError.

FormatWhere it is readTextMetadata
text, markdown, csv, jsoncalling threadUTF-8 decodedtitle = filename
pdfworker thread (unpdf)text of all pagesPDF Title if set, pageCount
docxworker threadraw text (mammoth)title = filename
xlsxworker threadone # <sheet> section per worksheet with CSV rows; external links text <url>workbook title or filename, sheetNames
pptxworker threadslide text by slide part number, then speaker notestitle = filename

With the default isolation, only PDF, DOCX, XLSX, and PPTX are parsed in worker threads. Text formats are only decoded and sanitized in the calling thread; no parser reads them. Chart sheets appear in sheetNames but get no text section.

All text goes through sanitizeExtractedText: line endings are normalized, control characters dropped, and runs of spaces, dots, and blank lines collapsed. An empty result fails with FileExtractionError. XLSX cells show their cached values; formulas are never evaluated, so a formula cell without a cached value is empty. See the package README for the full XLSX and Office archive rules.

Limits

makeFileExtractorLayer({ limits }) overrides any of defaultFileExtractorLimits (fragment): FileExtractorLayer uses the defaults. Invalid values are a defect when the layer is built, not a typed failure.

import { makeFileExtractorLayer } from '@yolk-sdk/extractors/node'

const FileExtractorLive = makeFileExtractorLayer({
  limits: { maxInputBytes: 10 * 1024 * 1024, maxXlsxCellVisits: 50_000 }
})
LimitDefaultBounds
maxInputBytes50 MiBinput size, every format
maxArchiveEntries10,000ZIP entries in DOCX, XLSX, PPTX
maxExpandedBytes50 MiBinflated bytes of an Office archive, counted while inflating
maxXlsxSheets100worksheets
maxXlsxCellVisits100,000cells inside every sheet's declared range, absent cells included
maxXlsxTextCharacters512 KiXLSX text, annotations and the omission marker included; at least 62
maxXlsxHyperlinks10,000hyperlinks read per workbook; extra links are dropped from the text output

Exceeding a limit fails the extraction with FileExtractionError. Hyperlinks that do not fit the text budget or the hyperlink cap are the exception: the cell is written plain and the text ends with one [Some hyperlinks omitted: …] marker.

Worker isolation

Each PDF, DOCX, XLSX, and PPTX extraction runs in a fresh Node worker_threads worker. Only the extracted text and metadata come back. Pass an isolation object to change the defaults (defaultWorkerIsolation) (fragment):

import { makeFileExtractorLayer } from '@yolk-sdk/extractors/node'

const FileExtractorLive = makeFileExtractorLayer({
  isolation: { maxOldGenerationSizeMb: 512, timeoutMs: 60_000, maxConcurrentWorkers: 2 }
})
isolation optionDefaultBounds
maxOldGenerationSizeMb256V8 old-generation heap of each worker
maxYoungGenerationSizeMb32V8 young-generation heap of each worker
stackSizeMb4stack of each worker
timeoutMs30,000wall-clock time per worker (a real timer, at most 2³¹−1 ms)
maxConcurrentWorkers4this layer's share of the pool of 4 workers per JavaScript realm
maxQueueWaitMsthe layer's timeoutMswait for a worker slot (at most 2³¹−1 ms), then fail with busy
workerUrlthe package's own workerthe worker entry, for hosts that bundle or relocate the package
  • One pool per realm. Every layer in a JavaScript realm (the main thread, or each worker thread that builds the layer) shares one pool of 4 workers, however often the layer is built. maxConcurrentWorkers (1 to 4) can only lower a layer's share. Slots are handed out first come, first served.
  • What the worker bounds. V8 heap, stack, and running time. A worker that runs out of heap, times out, cannot start, or exits without a result is terminated and the extraction fails with a reason. There is no fallback to parsing in-process.
  • What it does not bound. Process memory (RSS) and memory outside the V8 heap, such as Buffers, inflated archive parts, and PDF.js decoded data. Those are limited only by the input and expanded-size limits. Your platform's memory limit is the outer bound: four workers at the default heap add up to about 1 GB of V8 heap, so size the host for that plus your own load, or lower the limits.

isolation: 'none' parses in the calling thread, for runtimes without worker threads. It is unsafe for untrusted input: a crafted file can exhaust the process heap or block the event loop. It is also the only mode that accepts a loadSheetJs or loadMammoth function (for example mammoth's browser build); passing one with worker isolation is a defect when the layer is built.

Errors and failure reasons

extract fails with one of three tagged errors (the FileExtractorError union):

ErrorWhenFields
UnsupportedFileFormatErrorneither the extension nor the media type maps to a supported formatfilename, mediaType
FileExtractionErrorthe file is unreadable, invalid, over a limit, or empty, or the worker stoppedmessage (safe to show users), format, reason, cause
SheetJsUnavailableErroran XLSX file arrived but SheetJS is missing, not a SheetJS build, or older than 0.20.3reason (missing, invalid, outdated), installedVersion

SheetJsUnavailableError is host misconfiguration, not a bad upload. Its message includes sheetJsInstallCommand. Office archive failures (OfficeArchiveError) reach you as FileExtractionError with the archive error as cause; OfficeArchiveError itself is only returned by normalizeOfficeArchive.

FileExtractionError.reason (FileExtractionFailureReason) is set only when a worker was stopped or never admitted:

reasonMeaningTypical host response
resource-limitthe worker ran out of its V8 heapreject the file, or raise maxOldGenerationSizeMb if your memory allows
timeoutthe worker exceeded timeoutMs and was terminatedreject the file, or retry; it may time out again with the same limits
worker-unavailablethe worker could not start (missing or unloadable file)fix deployment: see Next.js and workerUrl
worker-failedthe worker crashed, exited, or sent a malformed messagelog and reject the file
busyno worker slot freed up within maxQueueWaitMsretry later; no worker was started

No reason means the extraction itself failed, usually because the file is unreadable, invalid, too large, or empty.

Fragment, mapping errors to host responses inside the program above:

import { Effect } from 'effect'

const handled = program.pipe(
  Effect.catchTags({
    UnsupportedFileFormatError: error => Effect.fail(`Unsupported file: ${error.filename}`),
    FileExtractionError: error =>
      Effect.fail(error.reason === 'busy' ? 'Try again shortly' : error.message),
    SheetJsUnavailableError: error => Effect.die(error) // host misconfiguration
  })
)

Feed knowledge ingestion

FileKnowledgeExtractorLayer provides KnowledgeExtractor from the FileExtractor in context. Give it the Node layer and include the result in the layers you provide to ingestKnowledgeDocument (fragment):

import { Layer } from 'effect'
import { FileKnowledgeExtractorLayer } from '@yolk-sdk/extractors/knowledge'
import { FileExtractorLayer } from '@yolk-sdk/extractors/node'

const KnowledgeExtractorLive = FileKnowledgeExtractorLayer.pipe(Layer.provide(FileExtractorLayer))
  • String content passes through unchanged; blank text fails.
  • Bytes are extracted with the format chosen from the source name (File name or ref, Url path, Text label) and media type (LoadedKnowledgeSource.mediaType, then the File source's, then text/plain for Text sources).
  • The extracted title becomes the document title. format, pageCount, and sheetNames merge under the source's own metadata, so your keys win.
  • Failures become KnowledgeExtractionError with the original error as cause.

Use makeFileKnowledgeExtractor(extractor) when you already hold a FileExtractorApi value. See Ingest knowledge for the rest of the pipeline.

Next.js

The Node layer starts its worker from the package's dist/node/extraction-worker.mjs, a self-contained file whose only other import is the optional xlsx peer. Keep both packages unbundled in server code:

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  serverExternalPackages: ['@yolk-sdk/extractors', 'xlsx']
}

export default nextConfig

With the package external, Next.js 16 (Turbopack) output file tracing includes the worker; this was checked with an output: 'standalone' build. If a bundler moves the Node module into a chunk of another name, there is no default worker: extraction fails closed with reason: 'worker-unavailable' and starts nothing. Then copy @yolk-sdk/extractors/node/extraction-worker somewhere with xlsx resolvable beside it and pass its URL as isolation.workerUrl. If your tracer misses dist/node/extraction-worker.mjs, add it (and xlsx) with outputFileTracingIncludes.

Host responsibilities

  • Upload size, auth, and per-user quota policy; storage of the original files.
  • Limits that fit your runtime's memory and the model context you feed the text to. The worker limits bound V8 heap and time, not the process.
  • Installing SheetJS from the CDN when XLSX extraction is needed.
  • Deciding what happens to the text: knowledge ingestion, attachments, or other use.
  • Deployment config that keeps the worker file on disk (see Next.js).

Boundaries

  • The package is domain-free: no upload, auth, storage, or product concepts.
  • @yolk-sdk/extractors/knowledge is the only bridge to @yolk-sdk/knowledge; the knowledge package never imports extractors.

Next

On this page