-
Notifications
You must be signed in to change notification settings - Fork 3.6k
feat(files): export markdown as zip with embedded images #4413
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
6eb3f04
feat(files): export markdown as zip with embedded images in assets/ f…
waleedlatif1 879a869
fix(files): sanitize zip filenames, fix storage context cast, cap emb…
waleedlatif1 5ff59a0
fix(files): fix race condition in asset filename deduplication
waleedlatif1 39b5082
chore(files): remove extraneous comments from export route
waleedlatif1 7999084
fix(files): sanitize markdown zip entry name, full uuid fallback for …
waleedlatif1 e238466
fix(files): extract userId const to satisfy TypeScript narrowing in a…
waleedlatif1 e197831
fix(files): use replacer function to prevent $ special-char corruptio…
waleedlatif1 577a989
fix(files): wrap zip buffer in Uint8Array for NextResponse BodyInit c…
waleedlatif1 8d16465
lock behavior
waleedlatif1 0d5ac8e
fix(workflow): track resolved isAdmin in prevIsAdminRef to prevent st…
waleedlatif1 0610a59
refactor(uploads): rename server fn to fetchWorkspaceFileBuffer, move…
waleedlatif1 9b1dbd6
more lock updates
waleedlatif1 76a07aa
fix(tests): update mocks for fetchWorkspaceFileBuffer rename
waleedlatif1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| import path from 'node:path' | ||
| import { createLogger } from '@sim/logger' | ||
| import { toError } from '@sim/utils/errors' | ||
| import JSZip from 'jszip' | ||
| import type { NextRequest } from 'next/server' | ||
| import { NextResponse } from 'next/server' | ||
| import { fileExportContract } from '@/lib/api/contracts/storage-transfer' | ||
| import { parseRequest } from '@/lib/api/server' | ||
| import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import type { StorageContext } from '@/lib/uploads/config' | ||
| import { USE_BLOB_STORAGE } from '@/lib/uploads/config' | ||
| import { downloadFile } from '@/lib/uploads/core/storage-service' | ||
| import { getFileMetadataById } from '@/lib/uploads/server/metadata' | ||
| import { verifyFileAccess } from '@/app/api/files/authorization' | ||
|
|
||
| const logger = createLogger('FilesExportAPI') | ||
|
|
||
| const MARKDOWN_MIME_TYPES = new Set(['text/markdown', 'text/x-markdown']) | ||
| const MARKDOWN_EXTENSIONS = new Set(['md', 'markdown']) | ||
| const VIEW_URL_RE = | ||
| /\/api\/files\/view\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi | ||
| const MAX_EMBEDDED_IMAGES = 50 | ||
|
|
||
| function isMarkdown(originalName: string, contentType: string): boolean { | ||
| if (MARKDOWN_MIME_TYPES.has(contentType)) return true | ||
| const ext = originalName.split('.').pop()?.toLowerCase() ?? '' | ||
| return MARKDOWN_EXTENSIONS.has(ext) | ||
| } | ||
|
|
||
| function safeFilename(name: string): string { | ||
| return path | ||
| .basename(name) | ||
| .replace(/["\\]/g, '_') | ||
| .replace(/[\r\n\t]/g, '') | ||
| } | ||
|
|
||
| function deduplicatedFilename(preferred: string, existing: Set<string>, imageId: string): string { | ||
| if (!existing.has(preferred)) return preferred | ||
| const ext = path.extname(preferred) | ||
| const base = path.basename(preferred, ext) | ||
| const short = `${base}_${imageId.slice(0, 8)}${ext}` | ||
| if (!existing.has(short)) return short | ||
| return `${base}_${imageId}${ext}` | ||
| } | ||
|
|
||
| export const GET = withRouteHandler( | ||
| async (request: NextRequest, context: { params: Promise<{ id: string }> }) => { | ||
| const parsed = await parseRequest(fileExportContract, request, context) | ||
| if (!parsed.success) return parsed.response | ||
|
|
||
| const { id } = parsed.data.params | ||
|
|
||
| const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) | ||
| if (!authResult.success || !authResult.userId) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
| } | ||
| const userId = authResult.userId | ||
|
|
||
| const record = await getFileMetadataById(id) | ||
| if (!record) { | ||
| logger.warn('File not found by ID', { id }) | ||
| return NextResponse.json({ error: 'Not found' }, { status: 404 }) | ||
| } | ||
|
|
||
| const hasAccess = await verifyFileAccess(record.key, userId) | ||
| if (!hasAccess) { | ||
| logger.warn('Unauthorized file export attempt', { id, userId }) | ||
| return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) | ||
| } | ||
|
|
||
| if (!isMarkdown(record.originalName, record.contentType)) { | ||
| const storagePrefix = USE_BLOB_STORAGE ? 'blob' : 's3' | ||
| const servePath = `/api/files/serve/${storagePrefix}/${encodeURIComponent(record.key)}` | ||
| return NextResponse.redirect(new URL(servePath, request.url), { status: 302 }) | ||
|
waleedlatif1 marked this conversation as resolved.
|
||
| } | ||
|
|
||
| const mdBuffer = await downloadFile({ | ||
| key: record.key, | ||
| context: record.context as StorageContext, | ||
| }) | ||
| let mdContent = mdBuffer.toString('utf-8') | ||
|
|
||
| const imageIds = [...new Set([...mdContent.matchAll(VIEW_URL_RE)].map((m) => m[1]))].slice( | ||
| 0, | ||
| MAX_EMBEDDED_IMAGES | ||
| ) | ||
|
|
||
| logger.info('Exporting markdown with embedded images', { id, imageCount: imageIds.length }) | ||
|
|
||
| const fetchResults = await Promise.allSettled( | ||
| imageIds.map(async (imageId) => { | ||
| const imgRecord = await getFileMetadataById(imageId) | ||
| if (!imgRecord) return null | ||
| const imgHasAccess = await verifyFileAccess(imgRecord.key, userId) | ||
| if (!imgHasAccess) return null | ||
| const imgBuffer = await downloadFile({ | ||
| key: imgRecord.key, | ||
| context: imgRecord.context as StorageContext, | ||
| }) | ||
| return { imageId, originalName: imgRecord.originalName, buffer: imgBuffer } | ||
| }) | ||
| ) | ||
|
|
||
| const assetMap = new Map<string, { filename: string; buffer: Buffer }>() | ||
| const usedFilenames = new Set<string>() | ||
|
|
||
| for (let i = 0; i < fetchResults.length; i++) { | ||
| const result = fetchResults[i] | ||
| if (result.status === 'rejected') { | ||
| logger.warn('Failed to fetch asset for export', { | ||
| imageId: imageIds[i], | ||
| error: toError(result.reason).message, | ||
| }) | ||
| continue | ||
| } | ||
| if (!result.value) continue | ||
| const { imageId, originalName, buffer } = result.value | ||
| const preferred = safeFilename(originalName) | ||
| const filename = deduplicatedFilename(preferred, usedFilenames, imageId) | ||
| usedFilenames.add(filename) | ||
| assetMap.set(imageId, { filename, buffer }) | ||
| } | ||
|
|
||
| for (const [imageId, asset] of assetMap) { | ||
| const escapedId = imageId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') | ||
| const replacement = `./assets/${asset.filename}` | ||
| mdContent = mdContent.replace( | ||
| new RegExp(`/api/files/view/${escapedId}`, 'g'), | ||
| () => replacement | ||
| ) | ||
| } | ||
|
waleedlatif1 marked this conversation as resolved.
|
||
|
|
||
| const zip = new JSZip() | ||
| zip.file(safeFilename(record.originalName), mdContent) | ||
| const assetsFolder = zip.folder('assets')! | ||
| for (const { filename, buffer } of assetMap.values()) { | ||
|
waleedlatif1 marked this conversation as resolved.
|
||
| assetsFolder.file(filename, buffer) | ||
| } | ||
|
|
||
| const zipBuffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }) | ||
| const zipName = safeFilename(`${record.originalName.replace(/\.[^.]+$/, '')}.zip`) | ||
|
|
||
| return new NextResponse(new Uint8Array(zipBuffer), { | ||
| status: 200, | ||
| headers: { | ||
| 'Content-Type': 'application/zip', | ||
| 'Content-Disposition': `attachment; filename="${zipName}"`, | ||
| 'Content-Length': String(zipBuffer.length), | ||
| }, | ||
| }) | ||
| } | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.