file-upload.client.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import { Context } from '@deepseek-ai/cordis'
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { apply } from '../src/client/index.ts'
  4. import { fileUploadWorker, FileUploadRuntime } from '../src/client/runtime.ts'
  5. import type { ClientFileUploadHooks, FileUploadBody } from '../src/client/contract.ts'
  6. interface UploadGlobal {
  7. __DSH_FILE_UPLOAD__?: ClientFileUploadHooks
  8. }
  9. afterEach(() => {
  10. delete (globalThis as UploadGlobal).__DSH_FILE_UPLOAD__
  11. vi.restoreAllMocks()
  12. vi.unstubAllGlobals()
  13. })
  14. describe('file upload worker body', () => {
  15. it('sends a Blob with credentials and reports progress, completion, and failure', () => {
  16. const posted: unknown[] = []
  17. const scope: {
  18. onmessage: ((event: MessageEvent<{
  19. url: string
  20. body: FileUploadBody
  21. headers: Readonly<Record<string, string>>
  22. }>) => void) | null
  23. postMessage(message: unknown): void
  24. } = { onmessage: null, postMessage: (message: unknown) => { posted.push(message) } }
  25. const xhr = {
  26. upload: { onprogress: null as ((event: ProgressEvent) => void) | null },
  27. status: 201,
  28. responseText: '{"ok":true}',
  29. withCredentials: false,
  30. onload: null as ((event: ProgressEvent) => void) | null,
  31. onerror: null as ((event: ProgressEvent) => void) | null,
  32. open: vi.fn(),
  33. setRequestHeader: vi.fn(),
  34. send: vi.fn(),
  35. }
  36. fileUploadWorker(scope, () => xhr)
  37. const body = new Blob(['large'])
  38. scope.onmessage?.({
  39. data: { url: 'https://harness.test/upload', body, headers: { 'content-type': 'application/octet-stream' } },
  40. } as never)
  41. expect(xhr.open).toHaveBeenCalledWith('POST', 'https://harness.test/upload')
  42. expect(xhr.withCredentials).toBe(true)
  43. expect(xhr.setRequestHeader).toHaveBeenCalledWith('content-type', 'application/octet-stream')
  44. expect(xhr.send).toHaveBeenCalledWith(body)
  45. xhr.upload.onprogress?.({ loaded: 2, total: 4, lengthComputable: true } as ProgressEvent)
  46. xhr.upload.onprogress?.({ loaded: 3, total: 0, lengthComputable: false } as ProgressEvent)
  47. xhr.onload?.({} as ProgressEvent)
  48. xhr.onerror?.({} as ProgressEvent)
  49. expect(posted).toEqual([
  50. { kind: 'progress', loaded: 2, total: 4 },
  51. { kind: 'progress', loaded: 3 },
  52. { kind: 'complete', status: 201, body: '{"ok":true}' },
  53. { kind: 'error', message: 'background upload transport failed' },
  54. ])
  55. })
  56. it('streams Uint8Array chunks through fetch and reports consumed bytes', async () => {
  57. const posted: unknown[] = []
  58. const scope = {
  59. onmessage: null as ((event: MessageEvent) => void) | null,
  60. postMessage: (message: unknown) => { posted.push(message) },
  61. }
  62. const fetch = vi.fn(async (_url: string, init: RequestInit & { readonly duplex: 'half' }) => {
  63. const chunks: number[][] = []
  64. for await (const chunk of init.body as ReadableStream<Uint8Array>) chunks.push([...chunk])
  65. expect(chunks).toEqual([[1, 2], [3]])
  66. expect(init).toMatchObject({
  67. method: 'POST',
  68. headers: { 'x-test': 'yes' },
  69. credentials: 'include',
  70. duplex: 'half',
  71. })
  72. return new Response('stored', { status: 202 })
  73. })
  74. const body = new ReadableStream<Uint8Array>({
  75. start(controller) {
  76. controller.enqueue(Uint8Array.of(1, 2))
  77. controller.enqueue(Uint8Array.of(3))
  78. controller.close()
  79. },
  80. })
  81. fileUploadWorker(scope, () => { throw new Error('XHR must not handle streams') }, fetch)
  82. scope.onmessage?.({ data: { url: 'https://harness.test/upload', body, headers: { 'x-test': 'yes' } } } as never)
  83. await vi.waitFor(() => {
  84. expect(posted).toEqual([
  85. { kind: 'progress', loaded: 2 },
  86. { kind: 'progress', loaded: 3 },
  87. { kind: 'complete', status: 202, body: 'stored' },
  88. ])
  89. })
  90. })
  91. it('propagates cancellation from the fetch body to the source stream', async () => {
  92. const posted: unknown[] = []
  93. const scope = {
  94. onmessage: null as ((event: MessageEvent) => void) | null,
  95. postMessage: (message: unknown) => { posted.push(message) },
  96. }
  97. const cancel = vi.fn()
  98. const source = new ReadableStream<Uint8Array>({ cancel })
  99. fileUploadWorker(
  100. scope,
  101. () => { throw new Error('unused') },
  102. async (_url, init) => {
  103. await (init.body as ReadableStream<Uint8Array>).cancel('fetch stopped')
  104. return new Response('cancelled')
  105. },
  106. )
  107. scope.onmessage?.({ data: { url: '/upload', body: source, headers: {} } } as never)
  108. await vi.waitFor(() => {
  109. expect(cancel).toHaveBeenCalledWith('fetch stopped')
  110. expect(posted.at(-1)).toEqual({ kind: 'complete', status: 200, body: 'cancelled' })
  111. })
  112. })
  113. it('reports invalid bodies, stream chunks, and fetch failures', async () => {
  114. const posted: unknown[] = []
  115. const scope = {
  116. onmessage: null as ((event: MessageEvent) => void) | null,
  117. postMessage: (message: unknown) => { posted.push(message) },
  118. }
  119. fileUploadWorker(scope, () => { throw new Error('unused') })
  120. scope.onmessage?.({ data: { url: '/upload', body: 'bad', headers: {} } } as never)
  121. expect(posted).toEqual([{ kind: 'error', message: 'background upload worker received an invalid body' }])
  122. const badChunk = new ReadableStream({ start(controller) { controller.enqueue('bad'); controller.close() } })
  123. fileUploadWorker(
  124. scope,
  125. () => { throw new Error('unused') },
  126. async (_url, init) => {
  127. await new Response(init.body).arrayBuffer()
  128. return new Response()
  129. },
  130. )
  131. scope.onmessage?.({ data: { url: '/upload', body: badChunk, headers: {} } } as never)
  132. await vi.waitFor(() => {
  133. expect(posted.at(-1)).toEqual({
  134. kind: 'error', message: 'background upload stream produced a non-Uint8Array chunk',
  135. })
  136. })
  137. const body = new ReadableStream<Uint8Array>({ start(controller) { controller.close() } })
  138. fileUploadWorker(
  139. scope,
  140. () => { throw new Error('unused') },
  141. () => Promise.reject(new Error('offline')),
  142. )
  143. scope.onmessage?.({ data: { url: '/upload', body, headers: {} } } as never)
  144. await vi.waitFor(() => {
  145. expect(posted.at(-1)).toEqual({ kind: 'error', message: 'offline' })
  146. })
  147. const failedSource = new ReadableStream<Uint8Array>({
  148. start(controller) { controller.error('source failed') },
  149. })
  150. fileUploadWorker(
  151. scope,
  152. () => { throw new Error('unused') },
  153. async (_url, init) => {
  154. await (init.body as ReadableStream<Uint8Array>).getReader().read()
  155. return new Response()
  156. },
  157. )
  158. scope.onmessage?.({ data: { url: '/upload', body: failedSource, headers: {} } } as never)
  159. await vi.waitFor(() => {
  160. expect(posted.at(-1)).toEqual({ kind: 'error', message: 'source failed' })
  161. })
  162. })
  163. it('uses Worker globals when the emitted body supplies no test seams', async () => {
  164. const posted: unknown[] = []
  165. const scope = {
  166. onmessage: null as ((event: MessageEvent) => void) | null,
  167. postMessage: (message: unknown) => { posted.push(message) },
  168. }
  169. const xhr = {
  170. upload: { onprogress: null },
  171. status: 204,
  172. responseText: '',
  173. withCredentials: false,
  174. onload: null,
  175. onerror: null,
  176. open: vi.fn(),
  177. setRequestHeader: vi.fn(),
  178. send: vi.fn(),
  179. }
  180. vi.stubGlobal('self', scope)
  181. vi.stubGlobal('XMLHttpRequest', vi.fn(function () { return xhr }))
  182. fileUploadWorker()
  183. scope.onmessage?.({ data: { url: '/upload', body: new Blob(), headers: {} } } as MessageEvent)
  184. expect(xhr.send).toHaveBeenCalledOnce()
  185. const fetch = vi.fn(async (_url: string, init: RequestInit) => {
  186. await new Response(init.body).arrayBuffer()
  187. return new Response(null, { status: 204 })
  188. })
  189. vi.stubGlobal('fetch', fetch)
  190. fileUploadWorker()
  191. const stream = new ReadableStream<Uint8Array>({ start(controller) { controller.close() } })
  192. scope.onmessage?.({ data: { url: '/stream', body: stream, headers: {} } } as MessageEvent)
  193. await vi.waitFor(() => {
  194. expect(fetch).toHaveBeenCalledOnce()
  195. expect(posted.at(-1)).toEqual({ kind: 'complete', status: 204, body: '' })
  196. })
  197. })
  198. })
  199. describe('file upload service', () => {
  200. it('uses a page-owned Host fetch for Blob and ReadableStream bodies', async () => {
  201. vi.stubGlobal('location', { origin: 'https://preview.test' })
  202. const fetch = vi.fn((_url: URL, _init?: RequestInit) =>
  203. Promise.resolve(new Response('accepted', { status: 202 })))
  204. ;(globalThis as UploadGlobal).__DSH_FILE_UPLOAD__ = { fetch }
  205. const ctx = new Context()
  206. const fiber = ctx.plugin(FileUploadRuntime)
  207. await fiber
  208. const blob = new Blob(['opaque'])
  209. const signal = new AbortController().signal
  210. await expect((ctx.fileUpload as FileUploadRuntime).post({
  211. path: '/api/upload', body: blob, headers: { 'x-test': 'yes' }, signal,
  212. })).resolves.toEqual({ status: 202, body: 'accepted' })
  213. expect(fetch).toHaveBeenLastCalledWith(new URL('https://preview.test/api/upload'), {
  214. method: 'POST', headers: { 'x-test': 'yes' }, body: blob, signal,
  215. })
  216. const stream = new ReadableStream<Uint8Array>({ start(controller) { controller.close() } })
  217. await (ctx.fileUpload as FileUploadRuntime).post({ path: '/stream', body: stream })
  218. expect(fetch).toHaveBeenLastCalledWith(new URL('https://preview.test/stream'), {
  219. method: 'POST', body: stream, duplex: 'half',
  220. })
  221. await fiber.dispose()
  222. })
  223. it('mounts through the plugin entry and resolves non-browser URLs', async () => {
  224. vi.stubGlobal('location', { origin: 'null' })
  225. const fetch = vi.fn(() => Promise.resolve(new Response(null, { status: 204 })))
  226. ;(globalThis as UploadGlobal).__DSH_FILE_UPLOAD__ = { fetch }
  227. const ctx = new Context()
  228. const fiber = ctx.plugin({ apply })
  229. await fiber
  230. const body = new Blob()
  231. await (ctx.fileUpload as FileUploadRuntime).post({ path: '/fallback', body })
  232. expect(fetch).toHaveBeenCalledWith(new URL('http://dsh.internal/fallback'), {
  233. method: 'POST', body,
  234. })
  235. await fiber.dispose()
  236. })
  237. it('leaves the fixture on its generated Remote fallback', async () => {
  238. vi.stubGlobal('location', { origin: 'https://fixture.test', search: '?fixture' })
  239. const ctx = new Context()
  240. const fiber = ctx.plugin(FileUploadRuntime)
  241. await fiber
  242. expect(ctx.fileUpload.available).toBe(false)
  243. await expect((ctx.fileUpload as FileUploadRuntime).post({ path: '/upload', body: new Blob() }))
  244. .rejects.toThrow('background upload is unavailable in fixture mode')
  245. await fiber.dispose()
  246. })
  247. it('fails loud when a served browser has no Worker implementation', async () => {
  248. vi.stubGlobal('Worker', undefined)
  249. const ctx = new Context()
  250. const fiber = ctx.plugin(FileUploadRuntime)
  251. await fiber
  252. await expect((ctx.fileUpload as FileUploadRuntime).post({ path: '/upload', body: new Blob() }))
  253. .rejects.toThrow('background upload requires Web Worker support')
  254. await fiber.dispose()
  255. })
  256. it('forwards progress and completion from a dedicated Worker and then terminates it', async () => {
  257. const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:worker')
  258. const revoked = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
  259. class FakeWorker {
  260. static last: FakeWorker | undefined
  261. onmessage: ((event: MessageEvent) => void) | null = null
  262. onerror: ((event: ErrorEvent) => void) | null = null
  263. readonly postMessage = vi.fn()
  264. readonly terminate = vi.fn()
  265. constructor(readonly url: string, readonly options: WorkerOptions) { FakeWorker.last = this }
  266. }
  267. vi.stubGlobal('Worker', FakeWorker)
  268. vi.stubGlobal('location', { origin: 'https://harness.test' })
  269. const ctx = new Context()
  270. const fiber = ctx.plugin(FileUploadRuntime)
  271. await fiber
  272. const progress = vi.fn()
  273. const blob = new Blob(['bytes'])
  274. const pending = (ctx.fileUpload as FileUploadRuntime).post({ path: '/api/upload', body: blob, onProgress: progress })
  275. const worker = FakeWorker.last
  276. if (worker === undefined) throw new Error('worker missing')
  277. expect(created).toHaveBeenCalledOnce()
  278. expect(revoked).toHaveBeenCalledWith('blob:worker')
  279. expect(worker.postMessage).toHaveBeenCalledWith({
  280. url: 'https://harness.test/api/upload', body: blob, headers: {},
  281. })
  282. worker.onmessage?.({ data: { kind: 'progress', loaded: 4, total: 5 } } as MessageEvent)
  283. worker.onmessage?.({ data: { kind: 'progress', loaded: 6 } } as MessageEvent)
  284. worker.onmessage?.({ data: { kind: 'complete', status: 200, body: 'done' } } as MessageEvent)
  285. worker.onmessage?.({ data: { kind: 'complete', status: 500, body: 'late' } } as MessageEvent)
  286. await expect(pending).resolves.toEqual({ status: 200, body: 'done' })
  287. expect(progress.mock.calls).toEqual([
  288. [{ loaded: 4, total: 5 }],
  289. [{ loaded: 6 }],
  290. ])
  291. expect(worker.terminate).toHaveBeenCalledOnce()
  292. await fiber.dispose()
  293. })
  294. it('transfers stream ownership to the dedicated Worker', async () => {
  295. vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:worker')
  296. vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
  297. class FakeWorker {
  298. static last: FakeWorker | undefined
  299. onmessage: ((event: MessageEvent) => void) | null = null
  300. onerror: ((event: ErrorEvent) => void) | null = null
  301. readonly postMessage = vi.fn()
  302. readonly terminate = vi.fn()
  303. constructor() { FakeWorker.last = this }
  304. }
  305. vi.stubGlobal('Worker', FakeWorker)
  306. const ctx = new Context()
  307. const fiber = ctx.plugin(FileUploadRuntime)
  308. await fiber
  309. const stream = new ReadableStream<Uint8Array>({ start(controller) { controller.close() } })
  310. const pending = (ctx.fileUpload as FileUploadRuntime).post({ path: '/stream', body: stream })
  311. const worker = FakeWorker.last
  312. if (worker === undefined) throw new Error('worker missing')
  313. expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ body: stream }), [stream])
  314. worker.onmessage?.({ data: { kind: 'complete', status: 200, body: 'done' } } as MessageEvent)
  315. await expect(pending).resolves.toEqual({ status: 200, body: 'done' })
  316. await fiber.dispose()
  317. })
  318. it('rejects worker messages, worker errors, and caller cancellation', async () => {
  319. vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:worker')
  320. vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
  321. class FakeWorker {
  322. static all: FakeWorker[] = []
  323. onmessage: ((event: MessageEvent) => void) | null = null
  324. onerror: ((event: ErrorEvent) => void) | null = null
  325. readonly postMessage = vi.fn()
  326. readonly terminate = vi.fn()
  327. constructor() { FakeWorker.all.push(this) }
  328. }
  329. vi.stubGlobal('Worker', FakeWorker)
  330. const ctx = new Context()
  331. const fiber = ctx.plugin(FileUploadRuntime)
  332. await fiber
  333. const reported = (ctx.fileUpload as FileUploadRuntime).post({ path: '/upload', body: new Blob() })
  334. FakeWorker.all[0]?.onmessage?.({ data: { kind: 'error', message: 'network failed' } } as MessageEvent)
  335. await expect(reported).rejects.toThrow('network failed')
  336. const errored = (ctx.fileUpload as FileUploadRuntime).post({ path: '/upload', body: new Blob() })
  337. FakeWorker.all[1]?.onerror?.({ message: 'worker crashed' } as ErrorEvent)
  338. await expect(errored).rejects.toThrow('worker crashed')
  339. const unnamed = (ctx.fileUpload as FileUploadRuntime).post({ path: '/upload', body: new Blob() })
  340. FakeWorker.all[2]?.onerror?.({ message: '' } as ErrorEvent)
  341. await expect(unnamed).rejects.toThrow('background upload worker failed')
  342. const controller = new AbortController()
  343. const aborted = (ctx.fileUpload as FileUploadRuntime).post({ path: '/upload', body: new Blob(), signal: controller.signal })
  344. controller.abort()
  345. await expect(aborted).rejects.toMatchObject({ name: 'AbortError' })
  346. expect(FakeWorker.all[3]?.terminate).toHaveBeenCalledOnce()
  347. const already = new AbortController()
  348. already.abort()
  349. await expect((ctx.fileUpload as FileUploadRuntime).post({ path: '/upload', body: new Blob(), signal: already.signal }))
  350. .rejects.toMatchObject({ name: 'AbortError' })
  351. expect(FakeWorker.all[4]?.postMessage).not.toHaveBeenCalled()
  352. await fiber.dispose()
  353. })
  354. })
  355. describe('Agent-scoped file upload', () => {
  356. async function scopedService(options: {
  357. readonly sessionId?: string
  358. readonly remote?: ReturnType<typeof vi.fn>
  359. } = {}) {
  360. const ctx = new Context()
  361. ctx.provide('sessions', {
  362. scopeOf: (candidate: Context) => Reflect.get(candidate, 'fixtureSessionId') as string | undefined,
  363. } as never)
  364. ctx.provide('typert', {
  365. contexts: {
  366. getClient: (kind: string) => kind === 'agent'
  367. ? { identity: (candidate: Context) => Reflect.get(candidate, 'fixtureSessionId') }
  368. : undefined,
  369. },
  370. } as never)
  371. const remote = options.remote ?? vi.fn(() => Promise.resolve({
  372. ok: true,
  373. value: {
  374. receiptId: 'remote-receipt',
  375. file: { attachmentId: 'remote-file', name: 'file', bytes: 3 },
  376. },
  377. }))
  378. ctx.provide('remote', { fileUploads: { upload: remote } } as never)
  379. const fiber = ctx.plugin(FileUploadRuntime)
  380. await fiber
  381. const owner = options.sessionId === undefined
  382. ? ctx
  383. : ctx.extend({ fixtureSessionId: options.sessionId })
  384. return { ctx, fiber, owner, remote, service: ctx.fileUpload }
  385. }
  386. it('assembles the scoped streaming request and parses progress and receipt fields', async () => {
  387. vi.stubGlobal('location', { origin: 'https://preview.test' })
  388. const progress = vi.fn()
  389. const fetch = vi.fn((_url: URL, init: RequestInit) => {
  390. expect(init.body).toBeInstanceOf(Blob)
  391. progress({ loaded: 2, total: 4 })
  392. return Promise.resolve(new Response(JSON.stringify({
  393. ok: true,
  394. value: {
  395. receiptId: 'receipt-1',
  396. file: { attachmentId: 'file-1', name: 'notes & refs.pdf', bytes: 4 },
  397. },
  398. }), { status: 200 }))
  399. })
  400. ;(globalThis as UploadGlobal).__DSH_FILE_UPLOAD__ = { fetch }
  401. const { fiber, owner, service } = await scopedService({ sessionId: 's1' })
  402. const signal = new AbortController().signal
  403. const file = new Blob(['data'])
  404. await expect(service.upload(owner, file, 'notes & refs.pdf', signal, progress)).resolves.toEqual({
  405. ok: true,
  406. value: {
  407. receiptId: 'receipt-1',
  408. file: { attachmentId: 'file-1', name: 'notes & refs.pdf', bytes: 4 },
  409. },
  410. })
  411. expect(fetch).toHaveBeenCalledWith(
  412. new URL('https://preview.test/api/session/uploadFileBinary?sessionId=s1&name=notes+%26+refs.pdf'),
  413. expect.objectContaining({
  414. method: 'POST',
  415. headers: { 'content-type': 'application/octet-stream' },
  416. body: file,
  417. signal,
  418. }),
  419. )
  420. await fiber.dispose()
  421. })
  422. it('uses the scoped Remote fallback for exact bytes and fixture Blob bodies', async () => {
  423. vi.stubGlobal('location', { origin: 'https://fixture.test', search: '?fixture' })
  424. const remote = vi.fn(() => Promise.resolve({
  425. ok: true,
  426. value: {
  427. receiptId: 'remote-receipt',
  428. file: { attachmentId: 'remote-file', name: 'bytes.bin', bytes: 3 },
  429. },
  430. }))
  431. const { fiber, owner, service } = await scopedService({ sessionId: 's1', remote })
  432. await expect(service.upload(owner, Uint8Array.of(0, 0, 0), 'bytes.bin'))
  433. .resolves.toMatchObject({ ok: true })
  434. await expect(service.upload(owner, new Blob([Uint8Array.of(1)])))
  435. .resolves.toMatchObject({ ok: true })
  436. expect(remote.mock.calls).toEqual([
  437. [{ data: 'AAAA', name: 'bytes.bin' }, undefined],
  438. [{ data: 'AQ==' }, undefined],
  439. ])
  440. await fiber.dispose()
  441. })
  442. it('rejects an unscoped call, an unavailable stream, and malformed background results', async () => {
  443. vi.stubGlobal('location', { origin: 'https://fixture.test', search: '?fixture' })
  444. const unscoped = await scopedService()
  445. await expect(unscoped.service.upload(unscoped.owner, Uint8Array.of(1)))
  446. .rejects.toThrow('fileUpload.upload requires an Agent-scoped context')
  447. await unscoped.fiber.dispose()
  448. const fixture = await scopedService({ sessionId: 's1' })
  449. const stream = new ReadableStream<Uint8Array>({ start(controller) { controller.close() } })
  450. await expect(fixture.service.upload(fixture.owner, stream))
  451. .rejects.toThrow('stream file upload requires a background carrier')
  452. await fixture.fiber.dispose()
  453. vi.stubGlobal('location', { origin: 'https://preview.test' })
  454. const bodies: unknown[] = [
  455. null,
  456. { ok: 'yes' },
  457. { ok: false, error: null },
  458. { ok: true, value: { receiptId: 'r', file: { attachmentId: 'a', name: 'x', bytes: -1 } } },
  459. ]
  460. for (const body of bodies) {
  461. ;(globalThis as UploadGlobal).__DSH_FILE_UPLOAD__ = {
  462. fetch: () => Promise.resolve(new Response(JSON.stringify(body), { status: 200 })),
  463. }
  464. const malformed = await scopedService({ sessionId: 's1' })
  465. await expect(malformed.service.upload(malformed.owner, new Blob()))
  466. .rejects.toThrow(/file upload transport returned an invalid/)
  467. await malformed.fiber.dispose()
  468. }
  469. })
  470. })