import assert from "node:assert/strict"; import fs from "node:fs"; import path from "node:path"; import { chromium } from "playwright"; import { authenticationHeaders, booleanEnv, createAcceptanceAPIClient, loginIfConfigured, validateSessionCredentials, } from "./lib/acceptance-client.mjs"; import { apiBaseURLFromEnv } from "./lib/service-endpoints.mjs"; const MAX_EDITOR_PAYLOAD_BYTES = 4 * 1024 * 1024; const BASE_URL = apiBaseURLFromEnv({ env: process.env, cliIndex: null }); const API_TOKEN = (process.env.DROBOTICFLOW_API_TOKEN || "").trim(); const ACCEPTANCE_EMAIL = (process.env.DROBOTICFLOW_ACCEPTANCE_EMAIL || "").trim(); const ACCEPTANCE_PASSWORD = process.env.DROBOTICFLOW_ACCEPTANCE_PASSWORD || ""; const CONNECTION_ID = (process.env.OBJECT_STORAGE_CONNECTION_ID || "").trim(); const CONNECTION_NAME = (process.env.OBJECT_STORAGE_CONNECTION_NAME || "").trim(); const CONFIGURED_BUCKET = (process.env.OBJECT_STORAGE_BUCKET || "").trim(); const VIDEO_KEY = (process.env.OBJECT_STORAGE_VIDEO_KEY || "").trim(); const ACCEPTANCE_PAYLOAD_FILE = (process.env.OBJECT_STORAGE_ACCEPTANCE_PAYLOAD_FILE || "").trim(); const ACCEPTANCE_CONTENT_TYPE = (process.env.OBJECT_STORAGE_ACCEPTANCE_CONTENT_TYPE || "").trim(); const IGNORE_HTTPS_ERRORS = booleanEnv("PLAYWRIGHT_IGNORE_HTTPS_ERRORS", false); function requireAcceptancePayload(filePath) { if (!filePath) { throw new Error( "OBJECT_STORAGE_ACCEPTANCE_PAYLOAD_FILE is required. Point it at a real UTF-8 text or JSON file used for create/upload/preview checks.", ); } const resolvedPath = path.resolve(filePath); let stat; try { stat = fs.statSync(resolvedPath); } catch (error) { throw new Error( `OBJECT_STORAGE_ACCEPTANCE_PAYLOAD_FILE is not readable: ${resolvedPath} (${ error instanceof Error ? error.message : String(error) })`, ); } if (!stat.isFile()) { throw new Error(`OBJECT_STORAGE_ACCEPTANCE_PAYLOAD_FILE must be a file: ${resolvedPath}`); } if (stat.size === 0) { throw new Error(`OBJECT_STORAGE_ACCEPTANCE_PAYLOAD_FILE must not be empty: ${resolvedPath}`); } if (stat.size > MAX_EDITOR_PAYLOAD_BYTES) { throw new Error( `OBJECT_STORAGE_ACCEPTANCE_PAYLOAD_FILE is ${stat.size} bytes; keep it at or below ${MAX_EDITOR_PAYLOAD_BYTES} bytes so the browser editor preview remains bounded.`, ); } const content = fs.readFileSync(resolvedPath, "utf8"); const previewNeedle = content .split(/\r?\n/) .map((line) => line.trim()) .find(Boolean); if (!previewNeedle) { throw new Error(`OBJECT_STORAGE_ACCEPTANCE_PAYLOAD_FILE must contain visible text: ${resolvedPath}`); } return { path: resolvedPath, fileName: path.basename(resolvedPath), content, previewNeedle: previewNeedle.slice(0, 120), }; } function inferContentType(fileName, content) { if (ACCEPTANCE_CONTENT_TYPE) { return ACCEPTANCE_CONTENT_TYPE; } if (/\.json$/i.test(fileName)) { return "application/json"; } try { JSON.parse(content); return "application/json"; } catch { // Fall through to extension based text formats. } if (/\.csv$/i.test(fileName)) { return "text/csv"; } if (/\.tsv$/i.test(fileName)) { return "text/tab-separated-values"; } if (/\.xml$/i.test(fileName)) { return "application/xml"; } return "text/plain; charset=utf-8"; } function extensionForContentType(contentType) { const normalized = contentType.toLowerCase(); if (normalized.includes("json")) { return ".json"; } if (normalized.includes("csv")) { return ".csv"; } if (normalized.includes("tab-separated-values")) { return ".tsv"; } if (normalized.includes("xml")) { return ".xml"; } return ".txt"; } const acceptancePayload = requireAcceptancePayload(ACCEPTANCE_PAYLOAD_FILE); const acceptanceContentType = inferContentType(acceptancePayload.fileName, acceptancePayload.content); const objectExtension = extensionForContentType(acceptanceContentType); const testPrefix = `object-storage-acceptance-${Date.now()}`; const createdKey = `${testPrefix}/object-storage-test${objectExtension}`; const renamedKey = `${testPrefix}/object-storage-renamed${objectExtension}`; const uploadKey = `${testPrefix}/nested/${acceptancePayload.fileName || `object-upload${objectExtension}`}`; validateSessionCredentials(ACCEPTANCE_EMAIL, ACCEPTANCE_PASSWORD); async function resolveConnection(apiClient) { const payload = await apiClient.request("/api/storage/connections"); const items = payload?.items || []; let matched = null; if (CONNECTION_ID) { matched = items.find((item) => item.id === CONNECTION_ID); } else if (CONNECTION_NAME) { matched = items.find((item) => item.name === CONNECTION_NAME); } else if (CONFIGURED_BUCKET) { matched = items.find((item) => item.bucket === CONFIGURED_BUCKET); } else { throw new Error( "Set OBJECT_STORAGE_CONNECTION_ID, OBJECT_STORAGE_CONNECTION_NAME, or OBJECT_STORAGE_BUCKET before running object-storage acceptance", ); } if (!matched?.id) { const selectors = [ CONNECTION_ID && `id=${CONNECTION_ID}`, CONNECTION_NAME && `name=${CONNECTION_NAME}`, CONFIGURED_BUCKET && `bucket=${CONFIGURED_BUCKET}`, ] .filter(Boolean) .join(", "); throw new Error(`No storage connection matched ${selectors || "the configured selector"}`); } return matched; } function objectStoragePath(pathName, connectionId, bucket, params = {}) { const search = new URLSearchParams({ connectionId }); if (bucket) { search.set("bucket", bucket); } for (const [key, value] of Object.entries(params)) { if (value !== undefined && value !== "") { search.set(key, String(value)); } } return `${pathName}?${search.toString()}`; } async function cleanupArtifacts(apiClient, connectionId, bucket) { try { await apiClient.request( objectStoragePath("/api/object-storage/objects", connectionId, bucket, { key: testPrefix, recursive: "true", }), { method: "DELETE", expected: [200, 204, 404], }, ); } catch (error) { console.warn(`cleanup skipped: ${error instanceof Error ? error.message : String(error)}`); } } async function waitForObjectRow(page, key) { const locator = page.locator(`[data-object-key=${JSON.stringify(key)}]`); await locator.waitFor({ state: "visible" }); return locator; } async function openObjectKey(page, key) { const segments = key.split("/").filter(Boolean); assert.ok(segments.length > 0, "OBJECT_STORAGE_VIDEO_KEY must not be empty"); await page.click('button:has-text("根目录")'); let prefix = ""; for (const segment of segments.slice(0, -1)) { prefix = prefix ? `${prefix}/${segment}` : segment; await waitForObjectRow(page, prefix); await page.dblclick(`[data-object-key=${JSON.stringify(prefix)}]`); } await waitForObjectRow(page, key); await page.click(`[data-object-key=${JSON.stringify(key)}]`); } async function run() { const browser = await chromium.launch({ headless: true }); const context = await browser.newContext({ extraHTTPHeaders: authenticationHeaders(API_TOKEN), ignoreHTTPSErrors: IGNORE_HTTPS_ERRORS, }); const apiClient = createAcceptanceAPIClient({ baseURL: BASE_URL, apiToken: API_TOKEN, context, }); let connection = null; let bucketName = ""; try { await loginIfConfigured(apiClient, { email: ACCEPTANCE_EMAIL, password: ACCEPTANCE_PASSWORD, label: "object-storage acceptance user", }); connection = await resolveConnection(apiClient); bucketName = CONFIGURED_BUCKET || connection.bucket || ""; assert.ok( bucketName, "Selected storage connection has no bound bucket; set OBJECT_STORAGE_BUCKET for object-storage acceptance", ); const page = await context.newPage(); page.on("dialog", (dialog) => dialog.accept()); await page.goto(`${BASE_URL}/object-storage`, { waitUntil: "networkidle" }); await page.waitForSelector('[data-testid="object-storage-connection-select"]'); await page.waitForFunction( (id) => Array.from( document.querySelector('[data-testid="object-storage-connection-select"]')?.querySelectorAll("option") || [], ).some((option) => option.value === id), connection.id, ); await page.selectOption('[data-testid="object-storage-connection-select"]', connection.id); await page.waitForSelector('[data-testid="bound-bucket-name"]'); await page.waitForFunction( (expected) => document.querySelector('[data-testid="bound-bucket-name"]')?.textContent?.includes(expected), bucketName, ); await page.click('[data-testid="object-create-draft-button"]'); await page.fill('[data-testid="object-key-input"]', createdKey); await page.fill('[data-testid="object-content-type-input"]', acceptanceContentType); await page.fill('[data-testid="object-editor"]', acceptancePayload.content); await page.click('[data-testid="object-save-button"]'); await waitForObjectRow(page, testPrefix); await page.dblclick(`[data-object-key=${JSON.stringify(testPrefix)}]`); await waitForObjectRow(page, createdKey); await page.click(`[data-object-key=${JSON.stringify(createdKey)}]`); await page.waitForFunction((needle) => { const preview = document.querySelector("pre"); const normalize = (value) => String(value || "").replace(/\s+/g, " ").trim(); return preview && normalize(preview.textContent).includes(normalize(needle)); }, acceptancePayload.previewNeedle); await page.fill('[data-testid="rename-key-input"]', renamedKey); await page.click('[data-testid="object-rename-button"]'); await waitForObjectRow(page, renamedKey); await page.fill('[data-testid="upload-key-input"]', uploadKey); await page.setInputFiles('[data-testid="upload-file-input"]', acceptancePayload.path); await page.click('[data-testid="object-upload-button"]'); await waitForObjectRow(page, `${testPrefix}/nested`); await page.dblclick(`[data-object-key=${JSON.stringify(`${testPrefix}/nested`)}]`); await waitForObjectRow(page, uploadKey); await page.click(`[data-object-key=${JSON.stringify(uploadKey)}]`); await page.waitForFunction((needle) => { const preview = document.querySelector("pre"); const normalize = (value) => String(value || "").replace(/\s+/g, " ").trim(); return preview && normalize(preview.textContent).includes(normalize(needle)); }, acceptancePayload.previewNeedle); await page.click('button:has-text("返回上级")'); await waitForObjectRow(page, renamedKey); await page.click(`[data-object-key=${JSON.stringify(renamedKey)}]`); await page.click('[data-testid="object-delete-button"]'); await page.waitForFunction( (key) => !document.querySelector(`[data-object-key=${JSON.stringify(key)}]`), renamedKey, ); await page.click(`[data-object-key=${JSON.stringify(`${testPrefix}/nested`)}]`); await page.click('[data-testid="object-delete-button"]'); await page.waitForFunction( (key) => !document.querySelector(`[data-object-key=${JSON.stringify(key)}]`), `${testPrefix}/nested`, ); if (VIDEO_KEY) { await openObjectKey(page, VIDEO_KEY); await page.waitForSelector("video"); await page.waitForFunction(() => { const element = document.querySelector("video"); return element && element.readyState >= 2; }); } const overview = await apiClient.request(objectStoragePath("/api/object-storage", connection.id, bucketName)); assert.equal(overview?.bucket, bucketName, "expected bound bucket in overview"); console.log( JSON.stringify( { baseUrl: BASE_URL, connectionId: connection.id, bucket: bucketName, testPrefix, verifiedVideoKey: VIDEO_KEY || null, status: "ok", }, null, 2, ), ); } finally { if (connection?.id) { await cleanupArtifacts(apiClient, connection.id, bucketName); } await browser.close(); } } run().catch((error) => { console.error(error); process.exitCode = 1; });