From f7f01c447c37030406a41407b475514b80805f85 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sat, 21 Nov 2026 07:52:24 +0000 Subject: [PATCH 1/4] fix(graphile-i18n): resolve physical relation identities --- .../graphile-i18n/src/__tests__/i18n.test.ts | 39 ++++++++++++++++- .../graphile-i18n/src/__tests__/setup.sql | 27 ++++++++++++ graphile/graphile-i18n/src/plugin.ts | 43 ++++++------------- 3 files changed, 79 insertions(+), 30 deletions(-) diff --git a/graphile/graphile-i18n/src/__tests__/i18n.test.ts b/graphile/graphile-i18n/src/__tests__/i18n.test.ts index 4435813e32..ba864c959f 100644 --- a/graphile/graphile-i18n/src/__tests__/i18n.test.ts +++ b/graphile/graphile-i18n/src/__tests__/i18n.test.ts @@ -60,7 +60,7 @@ describe('graphile-i18n plugin', () => { const connections = await (getConnections as any)( { - schemas: ['i18n_test'], + schemas: ['i18n_test', 'i18n-quoted"schema'], preset: testPreset, useRoot: true, authRole: 'postgres', @@ -77,6 +77,43 @@ describe('graphile-i18n plugin', () => { await teardown(); }); + beforeEach(async () => { + await db.beforeEach(); + }); + + afterEach(async () => { + await db.afterEach(); + }); + + it('reads snake_case base and companion tables in a quoted schema', async () => { + const result = await query<{ allI18NQuotedSchemaSnakePosts: { nodes: PostNode[] } }>(` + { allI18NQuotedSchemaSnakePosts(orderBy: ROW_ID_ASC) { + nodes { rowId title body localeStrings { langCode title body } } + } } + `, {}, false, { langCodes: ['fr'] }); + + expect(result.errors).toBeUndefined(); + expect(result.data?.allI18NQuotedSchemaSnakePosts.nodes).toEqual([ + { + rowId: 1, title: 'Source title', body: 'Source body', + localeStrings: { langCode: 'fr', title: 'Titre traduit', body: 'Corps traduit' }, + }, + { + rowId: 2, title: 'Untranslated title', body: null, + localeStrings: { langCode: null, title: 'Untranslated title', body: null }, + }, + ]); + }); + + it('returns null for a missing row in a quoted schema', async () => { + const result = await query<{ i18NQuotedSchemaSnakePostByRowId: PostNode | null }>(` + { i18NQuotedSchemaSnakePostByRowId(rowId: 999) { localeStrings { langCode title body } } } + `); + + expect(result.errors).toBeUndefined(); + expect(result.data?.i18NQuotedSchemaSnakePostByRowId).toBeNull(); + }); + it('should add localeStrings field to posts with @i18n tag', async () => { const result = await query(` { diff --git a/graphile/graphile-i18n/src/__tests__/setup.sql b/graphile/graphile-i18n/src/__tests__/setup.sql index ed0815e3c2..293f9dd33a 100644 --- a/graphile/graphile-i18n/src/__tests__/setup.sql +++ b/graphile/graphile-i18n/src/__tests__/setup.sql @@ -39,3 +39,30 @@ SELECT setval('i18n_test.posts_id_seq', 10); -- Grant access so withPgClient pool can query GRANT ALL ON ALL TABLES IN SCHEMA i18n_test TO PUBLIC; GRANT ALL ON ALL SEQUENCES IN SCHEMA i18n_test TO PUBLIC; + +CREATE SCHEMA "i18n-quoted""schema"; +GRANT USAGE ON SCHEMA "i18n-quoted""schema" TO PUBLIC; + +CREATE TABLE "i18n-quoted""schema".snake_posts ( + id serial PRIMARY KEY, + title text NOT NULL, + body text +); +COMMENT ON TABLE "i18n-quoted""schema".snake_posts IS E'@i18n snake_posts_translations'; + +CREATE TABLE "i18n-quoted""schema".snake_posts_translations ( + id serial PRIMARY KEY, + snake_posts_id int NOT NULL REFERENCES "i18n-quoted""schema".snake_posts(id), + lang_code text NOT NULL, + title text NOT NULL, + body text, + UNIQUE (snake_posts_id, lang_code) +); + +INSERT INTO "i18n-quoted""schema".snake_posts (id, title, body) VALUES + (1, 'Source title', 'Source body'), + (2, 'Untranslated title', NULL); +INSERT INTO "i18n-quoted""schema".snake_posts_translations (snake_posts_id, lang_code, title, body) VALUES + (1, 'fr', 'Titre traduit', 'Corps traduit'); + +GRANT SELECT ON ALL TABLES IN SCHEMA "i18n-quoted""schema" TO PUBLIC; diff --git a/graphile/graphile-i18n/src/plugin.ts b/graphile/graphile-i18n/src/plugin.ts index ed3e525248..6f5b7ae12f 100644 --- a/graphile/graphile-i18n/src/plugin.ts +++ b/graphile/graphile-i18n/src/plugin.ts @@ -25,6 +25,7 @@ import { TYPES } from '@dataplan/pg'; import { context as grafastContext, lambda, object } from 'grafast'; import type { GraphileConfig } from 'graphile-config'; import { withRequestPgClient } from 'graphile-plugin-utils'; +import { sql } from 'pg-sql2'; import type { I18nPluginOptions, I18nTableInfo, TranslatableField } from './types'; @@ -95,16 +96,15 @@ export function createI18nPlugin(options: I18nPluginOptions = {}): GraphileConfi const translationTableName = hasI18nTag(c); if (!translationTableName) continue; - // Get schema name from the codec's pg extensions - let schemaName = (c.extensions as any)?.pg?.schemaName ?? 'public'; + const pg = (c.extensions as any)?.pg; + if (!pg?.schemaName || !pg?.name) continue; + const schemaName = pg.schemaName; + const baseTable = pg.name; let pkColumn: string | null = null; let pkType = 'text'; for (const [, resource] of Object.entries(build.input.pgRegistry.pgResources)) { const r = resource as any; if (r.codec === c) { - // Try multiple sources for schema name - const rSchema = r.extensions?.pg?.schemaName ?? r.schemaName; - if (rSchema) schemaName = rSchema; // Extract PK from the resource's uniques array const uniques = r.uniques as Array<{ attributes: string[]; isPrimary?: boolean }> | undefined; if (uniques) { @@ -122,38 +122,21 @@ export function createI18nPlugin(options: I18nPluginOptions = {}): GraphileConfi } if (!pkColumn) continue; - // Find the translation codec. The @i18n tag value is the SQL table name - // (e.g. 'posts_translations'), but PostGraphile inflects codec names - // to camelCase (e.g. 'postsTranslations'). Match via resource name. let translationCodec: PgCodecWithAttributes | null = null; for (const [, resource] of Object.entries(build.input.pgRegistry.pgResources)) { const r = resource as any; if (!r.codec?.attributes) continue; - // Match by the resource's SQL name (which preserves snake_case) - const sqlName = r.codec?.extensions?.pg?.name ?? r.name; - if (sqlName === translationTableName) { + const translationPg = r.codec.extensions?.pg; + if (translationPg?.schemaName === schemaName && translationPg?.name === translationTableName) { translationCodec = r.codec as PgCodecWithAttributes; break; } } - // Fallback: try matching the inflected codec name directly - if (!translationCodec) { - const inflectedName = build.inflection.camelCase(translationTableName); - for (const [, tCodec] of Object.entries(build.input.pgRegistry.pgCodecs)) { - const tc = tCodec as any; - if (!tc.attributes) continue; - if (tc.name === translationTableName || tc.name === inflectedName) { - translationCodec = tc; - break; - } - } - } - if (!translationCodec) continue; // Find FK column on translation table — convention first, then type match let fkColumn: string | null = null; - const conventionalFk = `${c.name}_id`; + const conventionalFk = `${baseTable}_id`; if (translationCodec.attributes[conventionalFk]) { fkColumn = conventionalFk; } @@ -191,8 +174,8 @@ export function createI18nPlugin(options: I18nPluginOptions = {}): GraphileConfi if (Object.keys(fields).length === 0) continue; i18nRegistry[c.name] = { - baseTable: c.name, - translationTable: translationTableName, + baseTable, + translationTable: (translationCodec.extensions as any).pg.name, schemaName, fkColumn, pkColumn, @@ -235,6 +218,8 @@ export function createI18nPlugin(options: I18nPluginOptions = {}): GraphileConfi const localeType = localeTypeCache[localeTypeName]; const { schemaName, baseTable, translationTable, fkColumn, pkColumn, pkType, fields: i18nFields } = info; + const baseTableSql = sql.compile(sql.identifier(schemaName, baseTable)).text; + const translationTableSql = sql.compile(sql.identifier(schemaName, translationTable)).text; const coalescedCols = Object.values(i18nFields) .map(f => `coalesce(v."${f.column}", b."${f.column}") as "${f.column}"`) @@ -242,8 +227,8 @@ export function createI18nPlugin(options: I18nPluginOptions = {}): GraphileConfi // Build the SQL query template const sqlQuery = `SELECT v."${langCodeColumn}" AS "lang_code", ${coalescedCols} - FROM "${schemaName}"."${baseTable}" b - LEFT JOIN "${schemaName}"."${translationTable}" v + FROM ${baseTableSql} b + LEFT JOIN ${translationTableSql} v ON v."${fkColumn}" = b."${pkColumn}" AND array_position($2::text[], v."${langCodeColumn}") IS NOT NULL WHERE b."${pkColumn}" = $1::${pkType} From 5f09ca1db8b9535837c18d616d36fdf291fc0c93 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sat, 21 Nov 2026 08:29:51 +0000 Subject: [PATCH 2/4] fix(graphql-server): propagate HTTP and websocket request languages --- .../__tests__/websocket.integration.test.ts | 64 ++++++++++++++++++- graphql/server/package.json | 2 + graphql/server/src/middleware/graphile.ts | 23 ++++++- graphql/server/src/middleware/websocket.ts | 7 ++ pnpm-lock.yaml | 6 ++ 5 files changed, 98 insertions(+), 4 deletions(-) diff --git a/graphql/server-test/__tests__/websocket.integration.test.ts b/graphql/server-test/__tests__/websocket.integration.test.ts index dd59e43324..7372f5da3a 100644 --- a/graphql/server-test/__tests__/websocket.integration.test.ts +++ b/graphql/server-test/__tests__/websocket.integration.test.ts @@ -18,9 +18,21 @@ const DATABASE = '80a2eaaf-f77e-4bfe-8506-df929ef1b8d9'; const shared = path.join(__dirname, '../../../__fixtures__/seed'); let releasePulse: () => void; const probe = makeExtendSchemaPlugin({ - typeDefs: 'extend type Subscription { identity: String! pulse: Int! }', + typeDefs: `extend type Query { requestLanguages: String! } + extend type Subscription { identity: String! pulse: Int! requestLanguages: String! }`, plans: { + Query: { + requestLanguages: () => lambda(context(), (ctx: { langCodes?: string[] }) => JSON.stringify(ctx.langCodes ?? null)) + }, Subscription: { + requestLanguages: { + subscribePlan() { + return lambda(context(), async function* (ctx: { langCodes?: string[] }) { + yield JSON.stringify(ctx.langCodes ?? null); + }); + }, + plan: ($event) => $event + }, pulse: { subscribePlan() { return lambda(context(), async function* () { @@ -127,6 +139,56 @@ describe('public tenant WebSocket subscriptions', () => { expect(JSON.parse(result.data.identity)['jwt.claims.user_id']).toBe(ACTOR); }); + it.each([ + [undefined, null], + ['', null], + [';;;', null], + ['*;q=1, fr;q=0', null], + ['en;q=0', []], + ['zh-hant, zh-Hant-TW;q=0.9', ['zh-Hant', 'zh-Hant-TW']], + ['fr;q=0.8, en;q=1, fr-CA;q=0.9', ['en', 'fr-CA', 'fr']], + ['FR-ca, fr;q=0.9, fr;q=0.8', ['fr-CA', 'fr']] + ])('parses HTTP request languages %p', async (header, expected) => { + const req = request.post('/graphql').set('Host', HOST).set('Authorization', `Bearer ${token}`); + if (header !== undefined) req.set('Accept-Language', header as string); + const result = await req.send({ query: '{ requestLanguages }' }); + expect(result.status).toBe(200); + expect(result.body.errors).toBeUndefined(); + expect(JSON.parse(result.body.data.requestLanguages)).toEqual(expected); + }); + + it('keeps HTTP request languages independent across cached handler executions', async () => { + for (const language of ['en', 'fr', 'en', 'fr']) { + const result = await request.post('/graphql').set('Host', HOST) + .set('Authorization', `Bearer ${token}`).set('Accept-Language', language) + .send({ query: '{ requestLanguages }' }); + expect(result.body.errors).toBeUndefined(); + expect(JSON.parse(result.body.data.requestLanguages)).toEqual([language]); + } + }); + + it.each([ + [{}, { 'Accept-Language': 'fr' }, ['fr']], + [{ 'Accept-Language': 'fr-CA, fr;q=0.8, en;q=0.5' }, {}, ['fr-CA', 'fr', 'en']], + [{ 'aCcEpT-LaNgUaGe': 'en' }, { 'Accept-Language': 'fr' }, ['en']], + [{}, {}, null] + ])('parses WebSocket request languages from parameters or upgrade headers %#', async (params, headers, expected) => { + const result = await subscribe({ Authorization: `Bearer ${token}`, ...params }, headers, + 'subscription { requestLanguages }'); + expect(result.errors).toBeUndefined(); + expect(JSON.parse(result.data.requestLanguages)).toEqual(expected); + }); + + it.each([ + { 'Accept-Language': ['fr'] }, + { 'Accept-Language': 'fr', 'accept-language': 'en' } + ])('rejects malformed WebSocket request languages %p', async (params) => { + await expect(subscribe({ Authorization: `Bearer ${token}`, ...params }, {}, + 'subscription { requestLanguages }')).rejects.toEqual(expect.arrayContaining([ + expect.objectContaining({ message: 'Invalid Accept-Language', extensions: expect.objectContaining({ code: 'BAD_USER_INPUT' }) }) + ])); + }); + it.each([ { query: `subscription { identity } #${'é'.repeat(600)}` }, { query: 'subscription { identity }', variables: { value: 'é'.repeat(600) } } diff --git a/graphql/server/package.json b/graphql/server/package.json index 85c779b804..a9186ff5d0 100644 --- a/graphql/server/package.json +++ b/graphql/server/package.json @@ -57,6 +57,7 @@ "@pgpmjs/types": "workspace:^", "@pgsql/quotes": "^18.2.4", "@simplewebauthn/server": "13.3.2", + "accept-language-parser": "^1.5.0", "cookie-parser": "^1.4.7", "cors": "^2.8.6", "deepmerge": "^4.3.1", @@ -85,6 +86,7 @@ "postgraphile": "5.1.4" }, "devDependencies": { + "@types/accept-language-parser": "^1.5.4", "@aws-sdk/client-s3": "^3.1052.0", "@types/cookie-parser": "^1.4.10", "@types/cors": "^2.8.17", diff --git a/graphql/server/src/middleware/graphile.ts b/graphql/server/src/middleware/graphile.ts index 7c8a2610ef..1fea244699 100644 --- a/graphql/server/src/middleware/graphile.ts +++ b/graphql/server/src/middleware/graphile.ts @@ -5,6 +5,7 @@ import type { ComputeConfig } from '@constructive-io/express-context'; import { DEFAULT_REQUEST_PROTECTION, protectionPgSettings } from '@constructive-io/express-context'; import type { ConstructiveOptions } from '@constructive-io/graphql-types'; import { Logger } from '@pgpmjs/logger'; +import { parse as parseAcceptLanguage } from 'accept-language-parser'; import type { NextFunction, Request, RequestHandler, Response } from 'express'; import { cacheGraphileInstance, @@ -78,6 +79,20 @@ export function clearInFlightMap(): void { const log = new Logger('graphile'); const reqLabel = (req: Request): string => (req.requestId ? `[${req.requestId}]` : '[req]'); +const requestLanguages = (header: string | string[] | undefined): string[] | undefined => { + const preferences = parseAcceptLanguage(Array.isArray(header) ? header.join(',') : header ?? ''); + const languages = preferences + .filter(({ code, quality }) => code !== '*' && quality > 0 && quality <= 1) + .map(({ code, script, region }) => [ + code.toLowerCase(), + script && script[0].toUpperCase() + script.slice(1).toLowerCase(), + region && (region.length === 4 ? region[0].toUpperCase() + region.slice(1).toLowerCase() : region.toUpperCase()) + ].filter(Boolean).join('-')); + if (languages.length) return [...new Set(languages)]; + return preferences.length && !preferences.some(({ code, quality }) => code === '*' && quality > 0) + ? [] : undefined; +}; + /** * Build a PostGraphile v5 preset for a tenant. * @@ -211,6 +226,7 @@ const buildPreset = ( ? await authenticatedWebSocketRequest(ws.request, ws.normalizedConnectionParams, serverOptions) : (requestContext as { expressv4?: { req?: Request } })?.expressv4?.req; if (ws && req) ws.request = req; + const langCodes = requestLanguages(req?.headers?.['accept-language']); const context: Record = {}; // Timeouts travel with the transaction as GUCs, so they bound the work @@ -286,7 +302,7 @@ const buildPreset = ( pgSettings['request.id'] = req.requestId; } - return { pgSettings }; + return { pgSettings, langCodes }; } // Private (in-cluster) surface: there is no token — identity @@ -322,7 +338,7 @@ const buildPreset = ( if (req.requestId) { pgSettings['request.id'] = req.requestId; } - return { pgSettings }; + return { pgSettings, langCodes }; } } @@ -345,7 +361,8 @@ const buildPreset = ( } return { - pgSettings: anonSettings + pgSettings: anonSettings, + langCodes }; } } diff --git a/graphql/server/src/middleware/websocket.ts b/graphql/server/src/middleware/websocket.ts index feac691186..60c97ee6a9 100644 --- a/graphql/server/src/middleware/websocket.ts +++ b/graphql/server/src/middleware/websocket.ts @@ -58,6 +58,13 @@ export async function authenticatedWebSocketRequest( } req.headers.authorization = authorizations[0][1]; } + const languages = Object.entries(params ?? {}).filter(([key]) => key.toLowerCase() === 'accept-language'); + if (languages.length) { + if (languages.length !== 1 || typeof languages[0][1] !== 'string') { + throw new SafeError('Invalid Accept-Language', { code: 'BAD_USER_INPUT' }); + } + req.headers['accept-language'] = languages[0][1]; + } if (!getBearerToken(req) && requiresAuth) { throw new SafeError('Authentication required', { code: 'UNAUTHENTICATED' }); } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 272a948739..34aa23e3cc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2189,6 +2189,9 @@ importers: '@simplewebauthn/server': specifier: 13.3.2 version: 13.3.2 + accept-language-parser: + specifier: ^1.5.0 + version: 1.5.0 cookie-parser: specifier: ^1.4.7 version: 1.4.7 @@ -2271,6 +2274,9 @@ importers: '@aws-sdk/client-s3': specifier: ^3.1052.0 version: 3.1052.0 + '@types/accept-language-parser': + specifier: ^1.5.4 + version: 1.5.8 '@types/cookie-parser': specifier: ^1.4.10 version: 1.4.10(@types/express@5.0.6) From 2719a46484c9f35f00e595fe5e7193a3d64db795 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sat, 21 Nov 2026 08:51:14 +0000 Subject: [PATCH 3/4] fix(graphql-server): normalize whitespace around language quality parameters --- graphql/server-test/__tests__/websocket.integration.test.ts | 3 +++ graphql/server/src/middleware/graphile.ts | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/graphql/server-test/__tests__/websocket.integration.test.ts b/graphql/server-test/__tests__/websocket.integration.test.ts index 7372f5da3a..c20a9a4cfd 100644 --- a/graphql/server-test/__tests__/websocket.integration.test.ts +++ b/graphql/server-test/__tests__/websocket.integration.test.ts @@ -145,6 +145,8 @@ describe('public tenant WebSocket subscriptions', () => { [';;;', null], ['*;q=1, fr;q=0', null], ['en;q=0', []], + ['fr; q=0, en;q=0.5', ['en']], + ['fr ; q = 0, en ; q = 0.5', ['en']], ['zh-hant, zh-Hant-TW;q=0.9', ['zh-Hant', 'zh-Hant-TW']], ['fr;q=0.8, en;q=1, fr-CA;q=0.9', ['en', 'fr-CA', 'fr']], ['FR-ca, fr;q=0.9, fr;q=0.8', ['fr-CA', 'fr']] @@ -169,6 +171,7 @@ describe('public tenant WebSocket subscriptions', () => { it.each([ [{}, { 'Accept-Language': 'fr' }, ['fr']], + [{ 'Accept-Language': 'fr; q=0, en;q=0.5' }, {}, ['en']], [{ 'Accept-Language': 'fr-CA, fr;q=0.8, en;q=0.5' }, {}, ['fr-CA', 'fr', 'en']], [{ 'aCcEpT-LaNgUaGe': 'en' }, { 'Accept-Language': 'fr' }, ['en']], [{}, {}, null] diff --git a/graphql/server/src/middleware/graphile.ts b/graphql/server/src/middleware/graphile.ts index 1fea244699..0fdf79d3ad 100644 --- a/graphql/server/src/middleware/graphile.ts +++ b/graphql/server/src/middleware/graphile.ts @@ -80,7 +80,9 @@ const log = new Logger('graphile'); const reqLabel = (req: Request): string => (req.requestId ? `[${req.requestId}]` : '[req]'); const requestLanguages = (header: string | string[] | undefined): string[] | undefined => { - const preferences = parseAcceptLanguage(Array.isArray(header) ? header.join(',') : header ?? ''); + const value = (Array.isArray(header) ? header.join(',') : header ?? '') + .replace(/\s*;\s*/g, ';').replace(/\s*=\s*/g, '='); + const preferences = parseAcceptLanguage(value); const languages = preferences .filter(({ code, quality }) => code !== '*' && quality > 0 && quality <= 1) .map(({ code, script, region }) => [ From b20fa71cc12318033241bdaec922ce36f159f5ca Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sat, 21 Nov 2026 08:52:05 +0000 Subject: [PATCH 4/4] fix(graphql-server): normalize language subtags by BCP47 shape --- .../__tests__/websocket.integration.test.ts | 3 +++ graphql/server/src/middleware/graphile.ts | 12 +++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/graphql/server-test/__tests__/websocket.integration.test.ts b/graphql/server-test/__tests__/websocket.integration.test.ts index c20a9a4cfd..d79aef033b 100644 --- a/graphql/server-test/__tests__/websocket.integration.test.ts +++ b/graphql/server-test/__tests__/websocket.integration.test.ts @@ -148,6 +148,8 @@ describe('public tenant WebSocket subscriptions', () => { ['fr; q=0, en;q=0.5', ['en']], ['fr ; q = 0, en ; q = 0.5', ['en']], ['zh-hant, zh-Hant-TW;q=0.9', ['zh-Hant', 'zh-Hant-TW']], + ['de-DE-1996', ['de-DE-1996']], + ['SL-ROZAJ, es-419;q=0.9, EN-latn-us;q=0.8', ['sl-rozaj', 'es-419', 'en-Latn-US']], ['fr;q=0.8, en;q=1, fr-CA;q=0.9', ['en', 'fr-CA', 'fr']], ['FR-ca, fr;q=0.9, fr;q=0.8', ['fr-CA', 'fr']] ])('parses HTTP request languages %p', async (header, expected) => { @@ -171,6 +173,7 @@ describe('public tenant WebSocket subscriptions', () => { it.each([ [{}, { 'Accept-Language': 'fr' }, ['fr']], + [{}, { 'Accept-Language': 'de-DE-1996' }, ['de-DE-1996']], [{ 'Accept-Language': 'fr; q=0, en;q=0.5' }, {}, ['en']], [{ 'Accept-Language': 'fr-CA, fr;q=0.8, en;q=0.5' }, {}, ['fr-CA', 'fr', 'en']], [{ 'aCcEpT-LaNgUaGe': 'en' }, { 'Accept-Language': 'fr' }, ['en']], diff --git a/graphql/server/src/middleware/graphile.ts b/graphql/server/src/middleware/graphile.ts index 0fdf79d3ad..d31e7eaf33 100644 --- a/graphql/server/src/middleware/graphile.ts +++ b/graphql/server/src/middleware/graphile.ts @@ -85,11 +85,13 @@ const requestLanguages = (header: string | string[] | undefined): string[] | und const preferences = parseAcceptLanguage(value); const languages = preferences .filter(({ code, quality }) => code !== '*' && quality > 0 && quality <= 1) - .map(({ code, script, region }) => [ - code.toLowerCase(), - script && script[0].toUpperCase() + script.slice(1).toLowerCase(), - region && (region.length === 4 ? region[0].toUpperCase() + region.slice(1).toLowerCase() : region.toUpperCase()) - ].filter(Boolean).join('-')); + .map(({ code, script, region }) => [code, script, region].filter(Boolean) + .map((subtag, index) => { + if (index === 0) return subtag.toLowerCase(); + if (/^[a-z]{4}$/i.test(subtag)) return subtag[0].toUpperCase() + subtag.slice(1).toLowerCase(); + if (/^(?:[a-z]{2}|[0-9]{3})$/i.test(subtag)) return subtag.toUpperCase(); + return subtag.toLowerCase(); + }).join('-')); if (languages.length) return [...new Set(languages)]; return preferences.length && !preferences.some(({ code, quality }) => code === '*' && quality > 0) ? [] : undefined;