From 1648fda68c5d50b6f7cf0ddd1a3666dbe58d29cb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 16:25:39 +0800 Subject: [PATCH] Build the raw data export in the browser so large files are not cut off The export-raw-responses Edge Function streamed the workbook after already answering 200. Large exports exceeded the function's 2 second CPU limit, the worker was stopped mid-stream, and the browser saved a truncated file that Excel reported as corrupted. The workbook is now built in the browser with the same sheets and columns. It is only saved once complete, and a failed or short read shows an error. Also guards against Excel's hyperlink and cell limits and split surrogate pairs. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_011zdoJUrqnkRrxhSVaRvd1X --- app/platform/[projectId]/dashboard/page.tsx | 33 ++--- app/platform/[projectId]/responses/page.tsx | 6 +- lib/excel-cell.ts | 11 ++ .../xlsx_stream.ts => lib/raw-export-xlsx.ts | 74 ++++++---- lib/raw-export.test.ts | 94 +++++++++++++ lib/raw-export.ts | 97 +++++++++++++ package-lock.json | 7 + package.json | 1 + supabase/config.toml | 3 - .../functions/export-raw-responses/index.ts | 128 ------------------ 10 files changed, 269 insertions(+), 185 deletions(-) create mode 100644 lib/excel-cell.ts rename supabase/functions/export-raw-responses/xlsx_stream.ts => lib/raw-export-xlsx.ts (83%) create mode 100644 lib/raw-export.test.ts create mode 100644 lib/raw-export.ts delete mode 100644 supabase/functions/export-raw-responses/index.ts diff --git a/app/platform/[projectId]/dashboard/page.tsx b/app/platform/[projectId]/dashboard/page.tsx index 1a4ceefc..1a9b8ebf 100644 --- a/app/platform/[projectId]/dashboard/page.tsx +++ b/app/platform/[projectId]/dashboard/page.tsx @@ -240,41 +240,24 @@ export default function DashboardPage() { const endDate = period === "Custom" ? customEnd : malaysiaDateString(); if (!startDate || !endDate || startDate > endDate) throw new Error("Select a valid date range before exporting."); const { data: { session } } = await supabase.auth.getSession(); - if (!session?.access_token) throw new Error("Your session has expired. Please sign in again."); - const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; - const publishableKey = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY; - if (!supabaseUrl || !publishableKey) throw new Error("Supabase export configuration is missing."); - - const response = await fetch(supabaseUrl.replace(/\/$/, "") + "/functions/v1/export-raw-responses", { - method: "POST", - headers: { - Authorization: "Bearer " + session.access_token, - apikey: publishableKey, - "Content-Type": "application/json", - }, - body: JSON.stringify({ project_id: projectId, start_date: startDate, end_date: endDate, tracking_location: trackingLocation }), + if (!session) throw new Error("Your session has expired. Please sign in again."); + // Loaded on demand so the compression library is not part of the initial dashboard bundle. + const { buildRawExport } = await import("@/lib/raw-export"); + const { blob, filename, total } = await buildRawExport(supabase, { + projectId, trackingLocation, startDate, endDate, + onProgress: (done, count) => setTrackingMessage("Preparing Excel: " + done.toLocaleString("en-US") + " / " + count.toLocaleString("en-US") + " responses"), }); - if (!response.ok) { - let message = "Unable to export raw AI responses."; - try { - const body = await response.json(); - message = body?.error || body?.message || message; - } catch { /* response may not be JSON */ } - throw new Error(message); - } - const blob = await response.blob(); const url = URL.createObjectURL(blob); const link = document.createElement("a"); - const disposition = response.headers.get("content-disposition"); - const filename = disposition?.match(/filename="?([^";]+)"?/i)?.[1] || ("lifewood-raw-responses-" + startDate + "-to-" + endDate + ".xlsx"); link.href = url; link.download = filename; document.body.appendChild(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000); - setTrackingMessage("Excel export prepared for " + startDate + " to " + endDate + "."); + setTrackingMessage("Excel export of " + total.toLocaleString("en-US") + " responses prepared for " + startDate + " to " + endDate + "."); } catch (e) { + setTrackingMessage(""); setError(e instanceof Error ? e.message : String(e)); } finally { setExporting(false); diff --git a/app/platform/[projectId]/responses/page.tsx b/app/platform/[projectId]/responses/page.tsx index e897cf9a..f66c4294 100644 --- a/app/platform/[projectId]/responses/page.tsx +++ b/app/platform/[projectId]/responses/page.tsx @@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import { useParams } from "next/navigation"; import { CalendarDays, ChevronDown, ChevronRight, Download, ExternalLink, FileText, Search } from "lucide-react"; import * as XLSX from "xlsx"; +import { fitCell } from "@/lib/excel-cell"; import { ProjectShell } from "@/components/project-shell"; import { supabase } from "@/lib/supabase"; import { MIN_TRACKING_DATE, malaysiaDateString, shiftDateString, malaysiaDayStart, malaysiaDayEndExclusive } from "@/lib/reporting-date"; @@ -197,8 +198,9 @@ export default function ResponsesPage() { Region: row.tracking_location ?? "", Status: row.response_status, Brand_Mentioned: row.response_status !== "completed" || !responseText(row).trim() ? "Unable to verify" : containsTrackedBrand(row) ? "Yes" : "No", - Response: responseText(row), - Raw_Response_JSON: row.raw_response == null ? "" : JSON.stringify(row.raw_response), + // Excel cells hold at most 32,767 characters; longer values are shortened here and complete in the dashboard export. + Response: fitCell(responseText(row)), + Raw_Response_JSON: fitCell(row.raw_response == null ? "" : JSON.stringify(row.raw_response)), Error: row.error_message ?? "", Run_ID: row.run_id ?? "", Response_ID: row.id, diff --git a/lib/excel-cell.ts b/lib/excel-cell.ts new file mode 100644 index 00000000..6ab22fc4 --- /dev/null +++ b/lib/excel-cell.ts @@ -0,0 +1,11 @@ +export const EXCEL_CELL_LIMIT = 32767; +const NOTE = "\n[Shortened to fit an Excel cell. Use Export Raw Data on the dashboard for the complete value.]"; + +/** Excel cannot store more than 32,767 characters in a cell. */ +export function fitCell(value: string) { + if (value.length <= EXCEL_CELL_LIMIT) return value; + let end = EXCEL_CELL_LIMIT - NOTE.length; + const previous = value.charCodeAt(end - 1); + if (previous >= 0xd800 && previous <= 0xdbff) end -= 1; + return value.slice(0, end) + NOTE; +} diff --git a/supabase/functions/export-raw-responses/xlsx_stream.ts b/lib/raw-export-xlsx.ts similarity index 83% rename from supabase/functions/export-raw-responses/xlsx_stream.ts rename to lib/raw-export-xlsx.ts index c48e9265..6debad9c 100644 --- a/supabase/functions/export-raw-responses/xlsx_stream.ts +++ b/lib/raw-export-xlsx.ts @@ -1,15 +1,13 @@ -// Streaming raw-response workbook writer. +// Streaming raw-response workbook writer, run in the browser by lib/raw-export.ts. // -// The export used to hold every response, its raw JSON, a second stringified copy, the chunk sheets and the finished -// XML in memory at once, which exceeded the Edge Function worker's limit once an export covered a few weeks of data. -// This writer fetches responses in small pages and writes each sheet straight into a streaming zip, so memory stays -// flat however many responses are exported. The workbook layout (sheets, columns, chunking) is unchanged. +// This used to run in a Supabase Edge Function. Large exports exceeded the function's CPU time limit after the +// download had already started, so the browser saved a cut-off file that Excel reported as corrupted. export type ZipLib = { // deno-lint-ignore no-explicit-any Zip: new () => any; // deno-lint-ignore no-explicit-any - ZipDeflate: new (name: string, opts?: { level?: number }) => any; + ZipDeflate: new (name: string, opts?: { level?: 1 }) => any; strToU8: (value: string) => Uint8Array; }; @@ -17,8 +15,8 @@ export type ResponseRow = Record; export type PromptRow = { prompt_number?: unknown; prompt?: unknown; category?: unknown; language?: unknown }; export type ExportSource = { - /** Pages of responses: "full" has every column, "raw" only id/prompt/captured_at/raw_response. */ - pages: (kind: "full" | "raw") => AsyncIterable; + /** Pages of responses, oldest first. */ + pages: () => AsyncIterable; prompts: Map; }; @@ -32,17 +30,33 @@ export type ExportMeta = { const MAX_CELL = 30000; const FLUSH_AT = 256 * 1024; +// Excel refuses to open a worksheet with more hyperlinks than this, or with a longer link target. +export const MAX_SHEET_LINKS = 65530; +const MAX_LINK_LENGTH = 2079; +// Half of a surrogate pair on its own cannot be written as valid UTF-8 XML. +const LONE_SURROGATES = /\p{Surrogate}/gu; const CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g; +/** Moves a cut back by one if it would split a surrogate pair (emoji, rarer Chinese characters). */ +function cutPoint(value: string, index: number) { + if (index >= value.length) return value.length; + const previous = value.charCodeAt(index - 1); + return previous >= 0xd800 && previous <= 0xdbff ? index - 1 : index; +} + export function splitText(value: string, maxLength = MAX_CELL) { if (!value) return [""]; const parts: string[] = []; - for (let i = 0; i < value.length; i += maxLength) parts.push(value.slice(i, i + maxLength)); + for (let start = 0; start < value.length;) { + const end = cutPoint(value, start + maxLength); + parts.push(value.slice(start, end)); + start = end; + } return parts; } export function safeSheetText(value: string) { - return value.length <= 32767 ? value : value.slice(0, MAX_CELL) + "\n[Truncated in this cell; see the corresponding chunks sheet for the complete value.]"; + return value.length <= 32767 ? value : value.slice(0, cutPoint(value, MAX_CELL)) + "\n[Truncated in this cell; see the corresponding chunks sheet for the complete value.]"; } export function extractCitationLinks(raw: unknown, responseText: string) { @@ -87,6 +101,7 @@ export function extractCitationLinks(raw: unknown, responseText: string) { function xmlEscape(value: unknown) { return String(value ?? "") .replace(CONTROL_CHARS, "") + .replace(LONE_SURROGATES, "") .replace(/&/g, "&").replace(//g, ">") .replace(/"/g, """).replace(/'/g, "'"); } @@ -104,6 +119,17 @@ function columnName(index: number) { type Link = { ref: string; id: string; target: string }; +/** The link target Excel will accept for a cell, or null to leave the cell as plain text. */ +export function linkTarget(text: string) { + if (!/^https?:\/\/\S+$/i.test(text)) return null; + try { + const href = new URL(text).href; + return href.length <= MAX_LINK_LENGTH ? href : null; + } catch { + return null; + } +} + function rowXml(rowNumber: number, values: unknown[], linkColumn: number, links: Link[]) { let cells = ""; for (let columnIndex = 0; columnIndex < values.length; columnIndex++) { @@ -114,8 +140,9 @@ function rowXml(rowNumber: number, values: unknown[], linkColumn: number, links: continue; } const text = String(value ?? ""); - if (columnIndex === linkColumn && rowNumber > 1 && /^https?:\/\/\S+$/i.test(text)) { - links.push({ ref, id: "rId" + (links.length + 1), target: text }); + if (columnIndex === linkColumn && rowNumber > 1 && links.length < MAX_SHEET_LINKS) { + const target = linkTarget(text); + if (target) links.push({ ref, id: "rId" + (links.length + 1), target }); } cells += '' + xmlEscape(text) + ""; } @@ -171,13 +198,14 @@ export function streamWorkbook(lib: ZipLib, source: ExportSource, meta: ExportMe ]; async function run() { - // Pass 1: Raw Responses, streamed. Citation rows and the (rare) oversized text chunks are small and kept for the later sheets. + // Raw Responses is streamed. Citation rows and the (rare) oversized values are kept for the later sheets. const citationRows: unknown[][] = []; const textChunkRows: unknown[][] = []; + const jsonChunkRows: unknown[][] = []; let total = 0, completed = 0, failed = 0; const distinctPrompts = new Set(); await addSheet(2, responseHeaders, -1, async (emit) => { - for await (const page of source.pages("full")) { + for await (const page of source.pages()) { for (const row of page) { total++; if (row.response_status === "completed") completed++; @@ -203,6 +231,10 @@ export function streamWorkbook(lib: ZipLib, source: ExportSource, meta: ExportMe const chunks = splitText(text); chunks.forEach((chunk, index) => textChunkRows.push([String(row.id ?? ""), prompt?.prompt_number ?? "", String(row.captured_at ?? ""), index + 1, chunks.length, chunk])); } + if (rawJson.length > MAX_CELL) { + const chunks = splitText(rawJson); + chunks.forEach((chunk, index) => jsonChunkRows.push([String(row.id ?? ""), prompt?.prompt_number ?? "", String(row.captured_at ?? ""), index + 1, chunks.length, chunk])); + } } } }); @@ -210,19 +242,7 @@ export function streamWorkbook(lib: ZipLib, source: ExportSource, meta: ExportMe await addSheet(3, citationHeaders, 11, (emit) => { for (const values of citationRows) emit(values); }); await addSheet(4, ["Response_ID", "Prompt_No", "Captured_At", "Chunk_No", "Total_Chunks", "Response_Text_Chunk"], -1, (emit) => { for (const values of textChunkRows) emit(values); }); - // Pass 2: complete raw JSON for responses whose JSON does not fit in one cell. Only these rows are written. - await addSheet(5, ["Response_ID", "Prompt_No", "Captured_At", "Chunk_No", "Total_Chunks", "Raw_JSON_Chunk"], -1, async (emit) => { - for await (const page of source.pages("raw")) { - for (const row of page) { - if (row.raw_response == null) continue; - const rawJson = JSON.stringify(row.raw_response); - if (rawJson.length <= MAX_CELL) continue; - const prompt = source.prompts.get(String(row.prompt_id ?? "")); - const chunks = splitText(rawJson); - chunks.forEach((chunk, index) => emit([String(row.id ?? ""), prompt?.prompt_number ?? "", String(row.captured_at ?? ""), index + 1, chunks.length, chunk])); - } - } - }); + await addSheet(5, ["Response_ID", "Prompt_No", "Captured_At", "Chunk_No", "Total_Chunks", "Raw_JSON_Chunk"], -1, (emit) => { for (const values of jsonChunkRows) emit(values); }); const summary: unknown[][] = [ ["Project", meta.brandName], ["Project ID", meta.projectId], ["Tracking Location", meta.trackingLocation], diff --git a/lib/raw-export.test.ts b/lib/raw-export.test.ts new file mode 100644 index 00000000..cb321d46 --- /dev/null +++ b/lib/raw-export.test.ts @@ -0,0 +1,94 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { unzipSync, strFromU8 } from "fflate"; +import type { SupabaseClient } from "@supabase/supabase-js"; +import { buildRawExport } from "./raw-export.ts"; +import { linkTarget, safeSheetText, splitText, MAX_SHEET_LINKS } from "./raw-export-xlsx.ts"; +import { fitCell, EXCEL_CELL_LIMIT } from "./excel-cell.ts"; + +type Row = Record; + +/** Just enough of the Supabase query builder: results are served in the order the rows are given. */ +function fakeClient(responses: Row[], options: { failAfter?: number; pageCap?: number; count?: number } = {}) { + let served = 0; + return { + from(table: string) { + let head = false, afterId = "", limit = Infinity; + const query = { + select(_: string, opts?: { head?: boolean }) { head = Boolean(opts?.head); return query; }, + eq: () => query, gte: () => query, lt: () => query, order: () => query, single: () => query, range: () => query, + or(filter: string) { afterId = /id\.gt\.([^)]+)\)/.exec(filter)![1]; return query; }, + limit(n: number) { limit = n; return query; }, + then(resolve: (value: unknown) => unknown) { + if (table === "projects") return resolve({ data: { brand_name: "Dr D Signature Clinic" }, error: null }); + if (table === "prompts") return resolve({ data: [{ id: "p1", prompt_number: 1, prompt: "Best clinic?", category: "Overall", language: "English" }], error: null }); + if (head) return resolve({ data: null, error: null, count: options.count ?? responses.length }); + if (options.failAfter !== undefined && served >= options.failAfter) return resolve({ data: null, error: { message: "boom" } }); + const start = afterId ? responses.findIndex((row) => row.id === afterId) + 1 : 0; + const rows = responses.slice(start, start + Math.min(limit, options.pageCap ?? Infinity)); + served += rows.length; + return resolve({ data: rows, error: null }); + }, + }; + return query; + }, + } as unknown as SupabaseClient; +} + +const makeResponses = (n: number): Row[] => Array.from({ length: n }, (_, i) => ({ + id: "r" + String(i).padStart(5, "0"), prompt_id: "p1", llm_provider: "openai", captured_at: "2026-11-01T00:00:00+00:00", + response_status: "completed", response_text: "See https://example.com/page-" + i, raw_response: { n: i }, tracking_location: "MY", +})); + +const request = { projectId: "x", trackingLocation: "MY", startDate: "2026-10-01", endDate: "2026-12-04" }; + +async function open(blob: Blob) { + const files = unzipSync(new Uint8Array(await blob.arrayBuffer())); + return (name: string) => strFromU8(files[name]); +} + +const rowCount = (xml: string) => xml.split(" { + const progress: number[] = []; + const result = await buildRawExport(fakeClient(makeResponses(4113)), { ...request, onProgress: (done) => progress.push(done) }); + const read = await open(result.blob); + assert.equal(result.total, 4113); + assert.equal(rowCount(read("xl/worksheets/sheet2.xml")), 4114); + assert.equal(rowCount(read("xl/worksheets/sheet3.xml")), 4114); + assert.match(read("xl/workbook.xml"), /Raw JSON Chunks/); + assert.equal(progress.at(-1), 4113); + assert.equal(result.filename, "dr-d-signature-clinic-raw-responses-2026-10-01-to-2026-12-04.xlsx"); +}); + +test("a server page cap smaller than the page size does not shorten the export", async () => { + const result = await buildRawExport(fakeClient(makeResponses(250), { pageCap: 90 }), request); + assert.equal(result.total, 250); +}); + +test("a failed or short read produces an error instead of a file", async () => { + await assert.rejects(buildRawExport(fakeClient(makeResponses(600), { failAfter: 200 }), request), /boom/); + await assert.rejects(buildRawExport(fakeClient(makeResponses(10), { count: 20 }), request), /only 10 of 20/); +}); + +test("oversized values are chunked without splitting characters and reassemble exactly", async () => { + const long = "a" + "😀中".repeat(30000); + assert.equal(splitText(long).join(""), long); + for (const part of [...splitText(long), safeSheetText(long)]) assert.doesNotMatch(part, /\p{Surrogate}/u); + assert.doesNotMatch(fitCell(long), /\p{Surrogate}/u); + assert.ok(fitCell(long).length <= EXCEL_CELL_LIMIT); + const [row] = makeResponses(1); + const read = await open((await buildRawExport(fakeClient([{ ...row, response_text: long, raw_response: { long } }]), request)).blob); + assert.ok(rowCount(read("xl/worksheets/sheet4.xml")) > 2); + assert.ok(rowCount(read("xl/worksheets/sheet5.xml")) > 2); +}); + +test("hyperlinks stay within what Excel accepts", async () => { + assert.equal(linkTarget("https://[broken"), null); + assert.equal(linkTarget("https://example.com/" + "a".repeat(3000)), null); + assert.equal(linkTarget("https://example.com/中"), "https://example.com/%E4%B8%AD"); + const urls = Array.from({ length: MAX_SHEET_LINKS + 5 }, (_, i) => "https://e.com/" + i).join(" "); + const [row] = makeResponses(1); + const read = await open((await buildRawExport(fakeClient([{ ...row, response_text: urls }]), request)).blob); + assert.equal(read("xl/worksheets/sheet3.xml").split(" void; +}; + +type QueryResult = { data: unknown; error: { message: string } | null; count?: number | null }; + +async function withRetry(what: string, run: () => PromiseLike) { + let message = ""; + for (let attempt = 1; attempt <= ATTEMPTS; attempt++) { + const result = await run(); + if (!result.error) return result; + message = result.error.message; + if (attempt < ATTEMPTS) await new Promise((resolve) => setTimeout(resolve, attempt * 500)); + } + throw new Error("Unable to export raw data (" + what + "): " + message); +} + +export function rawExportFilename(brandName: string, startDate: string, endDate: string) { + const brand = brandName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "project"; + return brand + "-raw-responses-" + startDate + "-to-" + endDate + ".xlsx"; +} + +export async function buildRawExport(client: SupabaseClient, request: RawExportRequest) { + const { projectId, trackingLocation, startDate, endDate, onProgress } = request; + const startIso = new Date(startDate + "T00:00:00+08:00").toISOString(); + const endExclusiveIso = new Date(new Date(endDate + "T00:00:00+08:00").getTime() + 86400000).toISOString(); + + const project = (await withRetry("project", () => client.from("projects").select("brand_name").eq("id", projectId).single())).data as { brand_name?: string }; + const total = (await withRetry("count", () => client.from("ai_responses") + .select("id", { count: "exact", head: true }) + .eq("project_id", projectId).eq("tracking_location", trackingLocation) + .gte("captured_at", startIso).lt("captured_at", endExclusiveIso))).count ?? 0; + if (total > MAX_EXPORT_RESPONSES) { + throw new Error("This export has more than " + MAX_EXPORT_RESPONSES.toLocaleString("en-US") + " responses. Choose a shorter date range."); + } + + const prompts = new Map(); + for (let offset = 0; ; offset += 500) { + const rows = (await withRetry("prompts", () => client.from("prompts") + .select("id,prompt_number,prompt,category,language").eq("project_id", projectId) + .order("prompt_number", { ascending: true }).order("id", { ascending: true }) + .range(offset, offset + 499))).data as Array; + for (const row of rows) prompts.set(row.id, row); + if (rows.length < 500) break; + } + + let done = 0; + async function* pages(): AsyncGenerator { + // Each page continues after the last row of the previous one, so later pages are as quick as the first. + let last: { captured_at: string; id: string } | null = null; + onProgress?.(0, total); + for (;;) { + const after = last; + const rows = (await withRetry("responses", () => { + let query = client.from("ai_responses").select(COLUMNS) + .eq("project_id", projectId).eq("tracking_location", trackingLocation) + .gte("captured_at", after ? after.captured_at : startIso).lt("captured_at", endExclusiveIso); + if (after) query = query.or(`captured_at.gt."${after.captured_at}",and(captured_at.eq."${after.captured_at}",id.gt.${after.id})`); + return query.order("captured_at", { ascending: true }).order("id", { ascending: true }).limit(PAGE_SIZE); + })).data as Array; + // An empty page ends the export; a short one may only mean the server caps the page size. + if (!rows.length) break; + yield rows; + done += rows.length; + onProgress?.(done, Math.max(total, done)); + last = rows[rows.length - 1]; + } + if (done < total) throw new Error("Unable to export raw data: only " + done + " of " + total + " responses could be read. Please try again."); + } + + const stream = streamWorkbook({ Zip, ZipDeflate, strToU8 }, { pages, prompts }, { + brandName: String(project.brand_name ?? "Project"), projectId, trackingLocation, startDate, endDate, + }); + // A failure anywhere rejects here, so an incomplete workbook is never saved. + const bytes = await new Response(stream).arrayBuffer(); + return { + blob: new Blob([bytes], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }), + filename: rawExportFilename(String(project.brand_name ?? "project"), startDate, endDate), + total: done, + }; +} diff --git a/package-lock.json b/package-lock.json index fa72a589..fc7a7905 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "@supabase/supabase-js": "^2.110.5", "exceljs": "^4.4.0", + "fflate": "^0.8.2", "jszip": "^3.10.2", "lucide-react": "^0.468.0", "next": "16.2.10", @@ -4098,6 +4099,12 @@ "reusify": "^1.0.4" } }, + "node_modules/fflate": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "license": "MIT" + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", diff --git a/package.json b/package.json index 900bc532..296d75f9 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "dependencies":{ "@supabase/supabase-js":"^2.110.5", "exceljs":"^4.4.0", + "fflate":"^0.8.2", "jszip":"^3.10.2", "lucide-react":"^0.468.0", "next":"16.2.10", diff --git a/supabase/config.toml b/supabase/config.toml index 18de4e20..5af3cb51 100644 --- a/supabase/config.toml +++ b/supabase/config.toml @@ -6,9 +6,6 @@ verify_jwt = true [functions.backfill-direct-competitors] verify_jwt = true -[functions.export-raw-responses] -verify_jwt = true - [functions.llm-key-management] verify_jwt = false diff --git a/supabase/functions/export-raw-responses/index.ts b/supabase/functions/export-raw-responses/index.ts deleted file mode 100644 index 6a91b21e..00000000 --- a/supabase/functions/export-raw-responses/index.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { createClient } from "npm:@supabase/supabase-js@2"; -import { Zip, ZipDeflate, strToU8 } from "npm:fflate@0.8.2"; -import { streamWorkbook, type PromptRow, type ResponseRow } from "./xlsx_stream.ts"; - -const corsHeaders = { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type", - "Access-Control-Allow-Methods": "POST, OPTIONS", - "Access-Control-Expose-Headers": "Content-Disposition", -}; - -// Responses are streamed into the workbook page by page, so memory no longer limits the export; wall-clock time does. -const MAX_RESPONSES = 8000; -const PAGE_SIZE = 150; - -function jsonError(error: string, status = 400) { - return new Response(JSON.stringify({ error }), { - status, - headers: { ...corsHeaders, "Content-Type": "application/json", "Cache-Control": "no-store" }, - }); -} - -function validDate(value: unknown): value is string { - return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && - !Number.isNaN(Date.parse(value + "T00:00:00Z")); -} - -Deno.serve(async (req: Request) => { - if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders }); - if (req.method !== "POST") return jsonError("METHOD_NOT_ALLOWED", 405); - - try { - const supabaseUrl = Deno.env.get("SUPABASE_URL"); - const serviceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? Deno.env.get("SUPABASE_SECRET_KEY"); - if (!supabaseUrl || !serviceKey) return jsonError("SUPABASE_SERVER_CONFIG_MISSING", 500); - - const token = (req.headers.get("Authorization") ?? "").replace(/^Bearer\s+/i, "").trim(); - if (!token) return jsonError("AUTHORIZATION_TOKEN_MISSING", 401); - const admin = createClient(supabaseUrl, serviceKey, { auth: { persistSession: false, autoRefreshToken: false } }); - const { data: authData, error: authError } = await admin.auth.getUser(token); - const user = authData?.user; - if (authError || !user) return jsonError("AUTH_VALIDATION_FAILED", 401); - - const body = await req.json(); - const projectId = String(body?.project_id ?? ""); - const startDate = body?.start_date; - const endDate = body?.end_date; - const requestedLocation = typeof body?.tracking_location === "string" ? body.tracking_location : null; - if (!projectId) return jsonError("PROJECT_ID_REQUIRED"); - if (!validDate(startDate) || !validDate(endDate) || startDate > endDate) return jsonError("INVALID_DATE_RANGE"); - - const [{ data: profile, error: profileError }, { data: member, error: memberError }, { data: project, error: projectError }] = await Promise.all([ - admin.from("profiles").select("role").eq("id", user.id).maybeSingle(), - admin.from("project_members").select("role").eq("project_id", projectId).eq("user_id", user.id).maybeSingle(), - admin.from("projects").select("id,brand_name,tracking_market").eq("id", projectId).maybeSingle(), - ]); - if (profileError || memberError || projectError) return jsonError("PROJECT_ACCESS_LOOKUP_FAILED", 500); - if (!project) return jsonError("PROJECT_NOT_FOUND", 404); - if (profile?.role !== "superadmin" && !member) return jsonError("PROJECT_ACCESS_DENIED", 403); - - const trackingLocation = requestedLocation ?? project.tracking_market ?? "MY"; - if (trackingLocation !== "LEGACY" && trackingLocation !== "GLOBAL" && !/^[A-Z]{2}$/.test(trackingLocation)) return jsonError("INVALID_TRACKING_LOCATION"); - const startIso = new Date(startDate + "T00:00:00+08:00").toISOString(); - const endExclusiveIso = new Date(new Date(endDate + "T00:00:00+08:00").getTime() + 86400000).toISOString(); - - const scoped = () => admin.from("ai_responses") - .select("id", { count: "exact", head: true }) - .eq("project_id", projectId).eq("tracking_location", trackingLocation) - .gte("captured_at", startIso).lt("captured_at", endExclusiveIso); - const { count, error: countError } = await scoped(); - if (countError) { - console.error("RAW_EXPORT_COUNT_FAILED", countError.message); - return jsonError("RAW_RESPONSE_EXPORT_QUERY_FAILED", 500); - } - if ((count ?? 0) > MAX_RESPONSES) return jsonError("EXPORT_TOO_LARGE_NARROW_THE_DATE_RANGE", 413); - - const promptRows: Array> = []; - for (let offset = 0; ; offset += 500) { - const { data, error } = await admin.from("prompts") - .select("id,prompt_number,prompt,category,language") - .eq("project_id", projectId) - .order("prompt_number", { ascending: true }) - .range(offset, offset + 499); - if (error) return jsonError("PROMPT_METADATA_QUERY_FAILED", 500); - promptRows.push(...(data ?? []) as Array>); - if (!data || data.length < 500) break; - } - const prompts = new Map(promptRows.map((prompt) => [String(prompt.id), prompt])); - - const columns = { - full: "id,project_id,prompt_id,llm_provider,captured_at,prompt_snapshot,raw_response,response_text,response_status,error_message,run_id,brand_name_snapshot,tracking_location", - raw: "id,prompt_id,captured_at,raw_response", - }; - async function* pages(kind: "full" | "raw"): AsyncGenerator { - for (let offset = 0; ; offset += PAGE_SIZE) { - // The id tiebreak keeps paging stable when many responses share a capture time (imported data does). - const { data, error } = await admin.from("ai_responses") - .select(columns[kind]) - .eq("project_id", projectId).eq("tracking_location", trackingLocation) - .gte("captured_at", startIso).lt("captured_at", endExclusiveIso) - .order("captured_at", { ascending: true }).order("id", { ascending: true }) - .range(offset, offset + PAGE_SIZE - 1); - if (error) throw new Error("RAW_RESPONSE_EXPORT_QUERY_FAILED: " + error.message); - const rows = (data ?? []) as unknown as ResponseRow[]; - if (rows.length) yield rows; - if (rows.length < PAGE_SIZE) break; - } - } - - const stream = streamWorkbook({ Zip, ZipDeflate, strToU8 }, { pages, prompts }, { - brandName: String(project.brand_name ?? "Project"), projectId, trackingLocation, startDate, endDate, - }); - const filenameBrand = String(project.brand_name ?? "project").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "project"; - const filename = filenameBrand + "-raw-responses-" + startDate + "-to-" + endDate + ".xlsx"; - return new Response(stream, { - status: 200, - headers: { - ...corsHeaders, - "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - "Content-Disposition": "attachment; filename=\"" + filename + "\"", - "Cache-Control": "no-store", - }, - }); - } catch (error) { - console.error("RAW_RESPONSE_EXPORT_FAILED", error instanceof Error ? error.message : String(error)); - return jsonError("RAW_RESPONSE_EXPORT_FAILED", 500); - } -});