Fix the locale resolver in a Cloudflare Worker
Your task
Your Cloudflare Worker renders a greeting in each visitor's language. The first version stored the detected locale on a shared module object and then awaited a load. Other requests overwrote it in between, so some pages rendered in the wrong language. The fix resolves each request's locale from that request's own Accept-Language header.
An assistant wrote render_locales(accept_language_headers, supported), which resolves a batch of requests. It is in the editor. It has a bug. Find it and fix it.
Input and output:
accept_language_headers: oneAccept-Languageheader per request, in order. A header can be empty or junk.supported: the locales the site supports, in lowercase.- Return one locale per request, in the same order.
Rules the tests check:
- A request's locale depends only on its own header, never on the requests before it.
- Take the header up to its first
,, the visitor's top choice. Drop everything from the first;, which is the weight, like;q=0.9. Trim whitespace from both ends and lowercase what is left. That is the tag. - The primary part is the tag up to its first
-, or the whole tag when it has no-. - If the tag is not empty and is in
supported, use the tag. - Otherwise, if the primary part is not empty and is in
supported, use the primary part. - Otherwise use
"en", even when"en"is not insupported.
Examples
render_locales(accept_language_headers: list[str], supported: list[str]) -> list[str]Example 1
Input
render_locales(["fr-CA,fr;q=0.9,en;q=0.8", "en-US,en;q=0.9", ""], ["en", "fr", "de"])Output
["fr", "en", "en"]Example 2
Input
render_locales([" FR ; q=0.7 , en"], ["en", "fr"])Output
["fr"]