archive-upload.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import { createReadStream } from 'node:fs';
  2. import { lstat, readdir, realpath } from 'node:fs/promises';
  3. import { isAbsolute, join, relative, sep } from 'node:path';
  4. import JSZip from 'jszip';
  5. import type { LocalWebsiteDeployStage } from '@mavis/agent-tools/desktop';
  6. import { deployFailure, ensureNotAborted, runDeployStage } from './deploy-failure.js';
  7. const GET_UPLOAD_URL_PATH = '/mavis/api/v1/mcp/get_upload_url';
  8. const ARCHIVE_MIME = 'application/zip';
  9. /** Default exclusions keep dev output and credentials out of public archives. */
  10. export const DEFAULT_IGNORE_PATTERNS: readonly RegExp[] = [
  11. /^\.git$/u,
  12. /^node_modules$/u,
  13. /^\.DS_Store$/u,
  14. /^\.env(\..+)?$/u,
  15. ];
  16. /** Gateway capabilities needed to obtain a presigned URL and upload an archive. */
  17. export interface WebsiteDeployGateway {
  18. postGatewayJson(
  19. pathname: string,
  20. body: Record<string, unknown>,
  21. signal?: AbortSignal,
  22. timeoutMs?: number,
  23. ): Promise<Record<string, unknown>>;
  24. putBytes(
  25. url: string,
  26. body: RequestInit['body'],
  27. headers: Record<string, string>,
  28. signal?: AbortSignal,
  29. timeoutMs?: number,
  30. ): Promise<void>;
  31. }
  32. export interface DeployableFile {
  33. absPath: string;
  34. relPath: string;
  35. bytes: number;
  36. }
  37. export interface UploadedArchive {
  38. ossKey: string;
  39. }
  40. interface UploadArchiveInput {
  41. files: DeployableFile[];
  42. archiveName: string;
  43. gateway: WebsiteDeployGateway;
  44. signal?: AbortSignal;
  45. timeoutMs: number;
  46. source: boolean;
  47. differentFromOssKey?: string;
  48. }
  49. /**
  50. * Recursively walks a deploy root while omitting ignored entries and symlinks.
  51. * Relative paths always use POSIX separators for the backend archive contract.
  52. */
  53. export async function walkDeployableFiles(
  54. rootDir: string,
  55. ignorePatterns: readonly RegExp[] = DEFAULT_IGNORE_PATTERNS,
  56. excludedDir?: string,
  57. ): Promise<DeployableFile[]> {
  58. const rootReal = await realpath(rootDir);
  59. const excludedReal = excludedDir ? await realpath(excludedDir) : undefined;
  60. if (excludedReal && (rootReal === excludedReal || isPathInside(excludedReal, rootReal))) {
  61. return [];
  62. }
  63. const out: DeployableFile[] = [];
  64. const stack: string[] = [rootReal];
  65. while (stack.length > 0) {
  66. const dir = stack.pop();
  67. if (dir === undefined) break;
  68. const entries = await readdir(dir, { withFileTypes: true });
  69. for (const ent of entries) {
  70. if (ignorePatterns.some((re) => re.test(ent.name))) continue;
  71. const abs = join(dir, ent.name);
  72. if (ent.isSymbolicLink()) continue;
  73. if (ent.isDirectory()) {
  74. const realDir = await realpath(abs);
  75. if (excludedReal && realDir === excludedReal) continue;
  76. stack.push(realDir);
  77. continue;
  78. }
  79. if (!ent.isFile()) continue;
  80. const st = await lstat(abs);
  81. if (!st.isFile()) continue;
  82. const relPath = relative(rootReal, abs).split(sep).join('/');
  83. out.push({ absPath: abs, relPath, bytes: st.size });
  84. }
  85. }
  86. return out;
  87. }
  88. export async function uploadArchive(input: UploadArchiveInput): Promise<UploadedArchive> {
  89. const packagingStage: LocalWebsiteDeployStage = input.source ? 'upload_source' : 'upload_site';
  90. ensureNotAborted(
  91. input.signal,
  92. `before ${input.source ? 'source' : 'site'} upload`,
  93. packagingStage,
  94. );
  95. const archive = await runDeployStage(packagingStage, input.signal, () =>
  96. packZip(input.files, input.signal, packagingStage),
  97. );
  98. const uploadUrlStage: LocalWebsiteDeployStage = input.source
  99. ? 'get_upload_url_source'
  100. : 'get_upload_url';
  101. const presigned = (await runDeployStage(uploadUrlStage, input.signal, () =>
  102. input.gateway.postGatewayJson(
  103. GET_UPLOAD_URL_PATH,
  104. {
  105. filename: input.archiveName,
  106. mime_type: ARCHIVE_MIME,
  107. size_bytes: archive.byteLength,
  108. category: 'website',
  109. },
  110. input.signal,
  111. input.timeoutMs,
  112. ),
  113. )) as {
  114. code?: number;
  115. put_url?: string;
  116. oss_key?: string;
  117. error?: string;
  118. message?: string;
  119. };
  120. if ((presigned.code ?? 0) !== 0 || !presigned.put_url || !presigned.oss_key) {
  121. const detail = presigned.error || presigned.message || 'no put_url/oss_key returned';
  122. throw deployFailure(
  123. `website_deploy ${uploadUrlStage} failed: code=${presigned.code ?? 'unknown'} ${detail}`,
  124. 'upload_url_rejected',
  125. uploadUrlStage,
  126. );
  127. }
  128. const putUrl = presigned.put_url;
  129. const ossKey = presigned.oss_key;
  130. if (input.differentFromOssKey === ossKey) {
  131. throw deployFailure(
  132. 'website_deploy get_upload_url_source returned the public site archive key.',
  133. 'upload_url_rejected',
  134. uploadUrlStage,
  135. );
  136. }
  137. const uploadStage: LocalWebsiteDeployStage = input.source
  138. ? 'upload_source_archive'
  139. : 'upload_archive';
  140. await runDeployStage(uploadStage, input.signal, () =>
  141. input.gateway.putBytes(
  142. putUrl,
  143. archive,
  144. { 'Content-Type': ARCHIVE_MIME },
  145. input.signal,
  146. input.timeoutMs,
  147. ),
  148. );
  149. return { ossKey };
  150. }
  151. function isPathInside(parent: string, candidate: string): boolean {
  152. const rel = relative(parent, candidate);
  153. return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
  154. }
  155. async function packZip(
  156. files: DeployableFile[],
  157. signal: AbortSignal | undefined,
  158. stage: LocalWebsiteDeployStage,
  159. ): Promise<Buffer> {
  160. const zip = new JSZip();
  161. for (const file of files) {
  162. ensureNotAborted(signal, 'during packaging', stage);
  163. zip.file(file.relPath, createReadStream(file.absPath));
  164. }
  165. const archive = await zip.generateAsync({
  166. type: 'nodebuffer',
  167. compression: 'DEFLATE',
  168. compressionOptions: { level: 6 },
  169. });
  170. ensureNotAborted(signal, 'after packaging', stage);
  171. return archive;
  172. }
  173. export function totalBytes(files: readonly DeployableFile[]): number {
  174. return files.reduce((sum, file) => sum + file.bytes, 0);
  175. }
  176. export function sanitizeStem(name: string): string {
  177. return name.replace(/[^A-Za-z0-9_-]/gu, '_').replace(/^_+|_+$/gu, '');
  178. }