Skip to content

Migrate to rescript webapi #1063

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jul 3, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@headlessui/react": "^2.2.4",
"@mdx-js/loader": "^3.1.0",
"@rescript/react": "^0.14.0-rc.1",
"@rescript/webapi": "^0.1.0-experimental-03eae8b",
"codemirror": "^5.54.0",
"docson": "^2.1.0",
"escodegen": "^2.1.0",
Expand Down
6 changes: 5 additions & 1 deletion rescript.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
"version": 4
},
"bs-dependencies": [
"@rescript/react"
"@rescript/react",
"@rescript/webapi"
],
"bsc-flags": [
"-open WebAPI.Global"
],
"sources": [
{
Expand Down
2 changes: 1 addition & 1 deletion src/ApiDocs.res
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ module SidebarTree = {
let version = url->Url.getVersionString

let moduleRoute =
Webapi.URL.make("file://" ++ router.asPath).pathname
WebAPI.URL.make(~url="file://" ++ router.asPath).pathname
->String.replace(`/docs/manual/${version}/api/`, "")
->String.split("/")

Expand Down
4 changes: 2 additions & 2 deletions src/ConsolePanel.res
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ let make = (~logs, ~appendLog) => {
| _ => ()
}
}
Webapi.Window.addEventListener("message", cb)
Some(() => Webapi.Window.removeEventListener("message", cb))
WebAPI.Window.addEventListener(window, Custom("message"), cb)
Some(() => WebAPI.Window.removeEventListener(window, Custom("message"), cb))
}, [appendLog])

<div className="px-2 py-6 relative flex flex-col flex-1 overflow-y-hidden">
Expand Down
157 changes: 91 additions & 66 deletions src/Packages.res
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ module Resource = {
})
}

let uniqueKeywords: array<string> => array<string> = %raw(`(keywords) => [...new Set(keywords)]`)
let uniqueKeywords = arr => arr->Set.fromArray->Set.toArray

let isOfficial = (res: t) => {
switch res {
Expand Down Expand Up @@ -340,24 +340,15 @@ module InfoSidebar = {
}

type props = {
"packages": array<npmPackage>,
"urlResources": array<urlResource>,
"unmaintained": array<npmPackage>,
packages: array<npmPackage>,
urlResources: array<urlResource>,
unmaintained: array<npmPackage>,
}

type state =
| All
| Filtered(string) // search term

let scrollToTop: unit => unit = %raw(`function() {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
}
`)

let default = (props: props) => {
open Markdown

Expand All @@ -373,9 +364,9 @@ let default = (props: props) => {
})

let allResources = {
let npms = props["packages"]->Array.map(pkg => Resource.Npm(pkg))
let urls = props["urlResources"]->Array.map(res => Resource.Url(res))
let outdated = props["unmaintained"]->Array.map(pkg => Resource.Outdated(pkg))
let npms = props.packages->Array.map(pkg => Resource.Npm(pkg))
let urls = props.urlResources->Array.map(res => Resource.Url(res))
let outdated = props.unmaintained->Array.map(pkg => Resource.Outdated(pkg))
Belt.Array.concatMany([npms, urls, outdated])
}

Expand Down Expand Up @@ -420,7 +411,7 @@ let default = (props: props) => {
})

let onKeywordSelect = keyword => {
scrollToTop()
WebAPI.Window.scrollTo(window, ~options={left: 0.0, top: 0.0, behavior: Smooth})
setState(_ => {
Filtered(keyword)
})
Expand Down Expand Up @@ -524,73 +515,107 @@ let default = (props: props) => {
</>
}

type npmData = {
"objects": array<{
"searchScore": float,
"score": {
"final": float,
"detail": {"quality": float, "popularity": float, "maintenance": float},
},
"package": {
"name": string,
"keywords": array<string>,
"description": option<string>,
"version": string,
"links": {"npm": string, "repository": option<string>},
},
}>,
}
let parsePkgs = data => {
open JSON

switch data {
| Object(dict{"objects": Array(arr)}) =>
arr->Array.filterMap(pkg => {
switch pkg {
| Object(dict{
"searchScore": Number(searchScore),
"score": Object(dict{"detail": Object(dict{"maintenance": Number(maintenanceScore)})}),
"package": Object(
dict{
"name": String(name),
"keywords": Array(keywords),
"version": String(version),
"links": Object(dict{"npm": String(npmHref)} as links),
Copy link
Collaborator Author

@aspeddro aspeddro Jul 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Testing new dict pattern matching. @zth I can match optional fields (ex: dict{"npm": String(npmHref), "repository": ?Some(String(repo))})?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct! It's an optional field underlying so you need to specify if you want to match on the optionality.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!!

} as package,
),
}) =>
let keywords =
keywords
->Array.filterMap(k => {
switch k {
| String(k) => Some(k)
| _ => None
}
})
->Resource.filterKeywords
->Resource.uniqueKeywords

module Response = {
type t
@send external json: t => promise<npmData> = "json"
}
let repositoryHref = switch links->Dict.get("repository") {
| Some(String(v)) => Null.Value(v)
| _ => Null
}

@val external fetchNpmPackages: string => promise<Response.t> = "fetch"

let parsePkgs = data =>
Array.map(data["objects"], item => {
let pkg = item["package"]
{
name: pkg["name"],
version: pkg["version"],
keywords: Resource.filterKeywords(pkg["keywords"])->Resource.uniqueKeywords,
description: Option.getOr(pkg["description"], ""),
repositoryHref: Null.fromOption(pkg["links"]["repository"]),
npmHref: pkg["links"]["npm"],
searchScore: item["searchScore"],
maintenanceScore: item["score"]["detail"]["maintenance"],
}
})
let description = switch package {
| dict{"description": String(description)} => description
| _ => ""
}

Some({
name,
version,
keywords,
description,
repositoryHref,
npmHref,
searchScore,
maintenanceScore,
})
| _ => None
}
})
| _ => []
}
}

let getStaticProps: Next.GetStaticProps.t<props, unit> = async _ctx => {
let baseUrl = "https://registry.npmjs.org/-/v1/search?text=keywords:rescript&size=250&maintenance=1.0&popularity=0.5&quality=0.9"

let (one, two, three) = await Promise.all3((
fetchNpmPackages(baseUrl),
fetchNpmPackages(baseUrl ++ "&from=250"),
fetchNpmPackages(baseUrl ++ "&from=500"),
fetch(baseUrl),
fetch(baseUrl ++ "&from=250"),
fetch(baseUrl ++ "&from=500"),
))

let responseToOption = async response => {
try {
let json = await response->WebAPI.Response.json
Some(json)
} catch {
| _ =>
Console.error2("Failed to parse response", response)
None
}
}

let (data1, data2, data3) = await Promise.all3((
one->Response.json,
two->Response.json,
three->Response.json,
one->responseToOption,
two->responseToOption,
three->responseToOption,
))

let unmaintained = []

let pkges =
parsePkgs(data1)
->Array.concat(parsePkgs(data2))
->Array.concat(parsePkgs(data3))
[data1, data2, data3]
->Array.filterMap(d =>
switch d {
| Some(d) => Some(parsePkgs(d))
| None => None
}
)
->Array.flat
->Array.filter(pkg => {
if packageAllowList->Array.includes(pkg.name) {
true
} else if pkg.name->String.includes("reason") {
false
} else if pkg.maintenanceScore < 0.3 {
let _ = unmaintained->Array.push(pkg)
unmaintained->Array.push(pkg)
false
} else {
true
Expand All @@ -606,9 +631,9 @@ let getStaticProps: Next.GetStaticProps.t<props, unit> = async _ctx => {

{
"props": {
"packages": pkges,
"unmaintained": unmaintained,
"urlResources": urlResources,
packages: pkges,
unmaintained,
urlResources,
},
}
}
6 changes: 3 additions & 3 deletions src/Packages.resi
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ type npmPackage = {
}

type props = {
"packages": array<npmPackage>,
"urlResources": array<urlResource>,
"unmaintained": array<npmPackage>,
packages: array<npmPackage>,
urlResources: array<urlResource>,
unmaintained: array<npmPackage>,
}

let default: props => React.element
Expand Down
Loading
Loading