Skip to content

Commit

Permalink
fix greedy 404
Browse files Browse the repository at this point in the history
  • Loading branch information
SirajChokshi committed Apr 11, 2023
1 parent 4df6e4d commit 2e9e0be
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 12 deletions.
3 changes: 3 additions & 0 deletions src/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import type { resourceType } from '../types/resources'

export enum errorType {
URL_ERROR = 'URL_ERROR',
NETWORK_ERROR = 'NETWORK_ERROR',
NOT_FOUND = 'NOT_FOUND',
NOT_HTML = 'NOT_HTML',
}

export class PreviewError extends Error {
Expand Down
26 changes: 18 additions & 8 deletions src/utils/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
export const proxyFetch = (url: string) =>
fetch(`https://api.codetabs.com/v1/proxy/?quest=${url}`, undefined).then(
(res) => {
if (!res.ok) throw new Error(`Could not load ${url}`)
// TODO - handle 404s/pageful errors
// if (res.status === 404) return null
return res.text()
},
import { PreviewError, errorType } from './errors'

export async function proxyFetch(url: string) {
const res = await fetch(
`https://api.codetabs.com/v1/proxy/?quest=${url}`,
undefined,
)

if (!res.ok)
throw new PreviewError(`Could not load ${url}`, errorType.NETWORK_ERROR)

const raw = await res.text()

if (res.status === 404 || raw.includes('<title>Not Found</title>'))
// Manually check for this title since Gitlab returns a 200 for non-existent files
throw new PreviewError(`Could not load ${url}`, errorType.NOT_FOUND)

return raw
}
16 changes: 12 additions & 4 deletions src/utils/preview.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { goto } from '$app/navigation'
import { PreviewError, errorType } from './errors'
import { proxyFetch } from './fetch'
import { processCSS } from './lang/css'
import { isHTML, processHTML, type HTMLPageData } from './lang/html'
Expand Down Expand Up @@ -44,8 +45,13 @@ export class Preview {
.then(async (data) => {
await this.loadHTML(data, htmlURL)
})
.catch((error) => {
console.error(error)
.catch(() => {
throw new PreviewError(
`Could not find any valid HTML files. Tried:\n${urls.join(
'\n - ',
)}`,
errorType.NOT_FOUND,
)
})
} else {
// otherwise we have to attempt to load 3 possible URLs
Expand All @@ -65,8 +71,10 @@ export class Preview {
)

if (errorTable.every((e) => e)) {
// TODO: only throw error if the user is attempting to load without a file path
// throw Error('Could not find index.html on <main> or <master> branch')
throw new PreviewError(
`Could not find any valid HTML files. Tried:\n${urls.join('\n - ')}`,
errorType.NOT_FOUND,
)
}
}
}
Expand Down

0 comments on commit 2e9e0be

Please sign in to comment.