import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { execFileSync } from 'node:child_process' import path from 'node:path' import type { APIRequestContext, Page, TestInfo } from '@playwright/test' type CleanupTask = () => Promise export interface SeededNamespace { id: number slug: string displayName: string } export interface SeededSkill { skillId: number namespace: string slug: string version: string status: string } export interface SeededReviewData { namespace: SeededNamespace skill: SeededSkill } interface ApiEnvelope { code: number msg: string data: T } interface ApiFailure extends Error { status?: number code?: number } function asApiErrorBody(value: unknown): string { if (!value || typeof value !== 'object') { return '' } const maybe = value as { msg?: unknown } return typeof maybe.msg === 'string' ? maybe.msg : '' } function uniqueSuffix(testInfo?: TestInfo): string { const worker = testInfo?.parallelIndex ?? 0 return `${worker}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}` } function buildSkillPackageZipBuffer(suffix: string): Buffer { const tempRoot = mkdtempSync(path.join(tmpdir(), 'skillhub-e2e-')) try { const packageDir = path.join(tempRoot, `pkg-${suffix}`) const zipPath = path.join(tempRoot, `pkg-${suffix}.zip`) const skillName = `e2e-skill-${suffix}`.slice(0, 48) const skillMd = `--- name: ${skillName} description: E2E generated skill for real-request tests version: 1.0.0 --- # ${skillName} Generated by Playwright E2E. ` execFileSync('mkdir', ['-p', packageDir]) writeFileSync(path.join(packageDir, 'SKILL.md'), skillMd, 'utf8') writeFileSync(path.join(packageDir, 'README.md'), `# ${skillName}\n`, 'utf8') execFileSync('zip', ['-q', '-r', zipPath, 'SKILL.md', 'README.md'], { cwd: packageDir }) return readFileSync(zipPath) } finally { rmSync(tempRoot, { recursive: true, force: true }) } } function createSkillPackageZipFile(suffix: string): { filePath: string; cleanup: () => void } { const tempRoot = mkdtempSync(path.join(tmpdir(), 'skillhub-e2e-file-')) const packageDir = path.join(tempRoot, `pkg-${suffix}`) const zipPath = path.join(tempRoot, `pkg-${suffix}.zip`) const skillName = `e2e-skill-${suffix}`.slice(0, 48) const skillMd = `--- name: ${skillName} description: E2E generated skill for real-request tests version: 1.0.0 --- # ${skillName} Generated by Playwright E2E. ` execFileSync('mkdir', ['-p', packageDir]) writeFileSync(path.join(packageDir, 'SKILL.md'), skillMd, 'utf8') writeFileSync(path.join(packageDir, 'README.md'), `# ${skillName}\n`, 'utf8') execFileSync('zip', ['-q', '-r', zipPath, 'SKILL.md', 'README.md'], { cwd: packageDir }) return { filePath: zipPath, cleanup: () => { rmSync(tempRoot, { recursive: true, force: true }) }, } } async function parseEnvelope(response: Awaited>): Promise { const text = await response.text() let parsed: ApiEnvelope | null = null try { parsed = JSON.parse(text) as ApiEnvelope } catch { throw new Error(`Non-JSON response: status=${response.status()} body=${text.slice(0, 200)}`) } if (!response.ok() || parsed.code !== 0) { const error = new Error( `API failed: status=${response.status()} code=${parsed.code} msg=${asApiErrorBody(parsed) || parsed.msg}`, ) as ApiFailure error.status = response.status() error.code = parsed.code throw error } return parsed.data } export class E2eTestDataBuilder { private readonly request: APIRequestContext private readonly suffix: string private readonly cleanupTasks: CleanupTask[] = [] private ensuredNamespace?: SeededNamespace constructor( private readonly page: Page, testInfo?: TestInfo, ) { this.request = page.context().request this.suffix = uniqueSuffix(testInfo) } async init(): Promise { // Prime CSRF/session cookie path used by write endpoints. await this.request.get('/api/v1/auth/providers') } async cleanup(): Promise { for (let i = this.cleanupTasks.length - 1; i >= 0; i -= 1) { try { await this.cleanupTasks[i]() } catch { // Best-effort cleanup for E2E environments. } } } async createNamespace(base = 'e2e-team'): Promise { const slug = `${base}-${this.suffix}`.slice(0, 64) const displayName = `E2E ${slug}` const created = await parseEnvelope( await this.request.post('/api/v1/namespaces', { data: { slug, displayName, description: `E2E namespace ${slug}`, }, }), ) this.cleanupTasks.push(async () => { await this.request.post(`/api/web/namespaces/${encodeURIComponent(created.slug)}/archive`, { data: { reason: 'e2e cleanup' }, }) }) return created } async listMyNamespaces(): Promise { return parseEnvelope( await this.request.get('/api/web/me/namespaces'), ) } async ensureWritableNamespace(): Promise { if (this.ensuredNamespace) { return this.ensuredNamespace } try { const created = await this.createNamespace('e2e-team') this.ensuredNamespace = created return created } catch (error) { const failure = error as ApiFailure if (failure.status !== 403) { throw error } } const namespaces = await this.listMyNamespaces() const writable = namespaces.find((item) => item.slug !== 'global') ?? namespaces[0] if (!writable) { throw new Error('No namespace available for e2e data seeding') } this.ensuredNamespace = writable return writable } private async getMySkillInNamespace(namespaceSlug: string): Promise { const page = await parseEnvelope<{ items: Array<{ id: number namespace: string slug: string headlineVersion?: { version: string; status: string } }> }>( await this.request.get('/api/web/me/skills?page=0&size=50'), ) const hit = page.items.find((item) => item.namespace === namespaceSlug) if (!hit || !hit.headlineVersion) { return null } return { skillId: hit.id, namespace: hit.namespace, slug: hit.slug, version: hit.headlineVersion.version, status: hit.headlineVersion.status, } } async publishSkill(namespaceSlug: string): Promise { const unique = `${this.suffix}_${Math.random().toString(36).slice(2, 6)}` const zipBuffer = buildSkillPackageZipBuffer(unique) let result: SeededSkill try { result = await parseEnvelope( await this.request.post(`/api/web/skills/${encodeURIComponent(namespaceSlug)}/publish`, { multipart: { file: { name: 'sample-skill.zip', mimeType: 'application/zip', buffer: zipBuffer, }, visibility: 'PUBLIC', }, }), ) } catch (error) { const fallback = await this.getMySkillInNamespace(namespaceSlug) if (!fallback) { throw error } return fallback } this.cleanupTasks.push(async () => { await this.request.delete(`/api/web/skills/${encodeURIComponent(result.namespace)}/${encodeURIComponent(result.slug)}`) }) return result } createSkillPackageFile(): string { const unique = `${this.suffix}_${Math.random().toString(36).slice(2, 6)}` const { filePath, cleanup } = createSkillPackageZipFile(unique) this.cleanupTasks.push(async () => { cleanup() }) return filePath } async createReviewData(): Promise { const namespace = await this.ensureWritableNamespace() const skill = await this.publishSkill(namespace.slug) return { namespace, skill } } }