From 1a7c3e83b2a0d4df5884a4b3b0ca87046190ce5e Mon Sep 17 00:00:00 2001 From: Jaga Santagostino Date: Thu, 11 Dec 2025 03:43:42 +0100 Subject: [PATCH] remove trailing commas from jsonc to json --- src/lib/cf/utils.ts | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/src/lib/cf/utils.ts b/src/lib/cf/utils.ts index 7bdde8f..348a3df 100644 --- a/src/lib/cf/utils.ts +++ b/src/lib/cf/utils.ts @@ -9,30 +9,49 @@ interface WranglerConfig { kv_namespaces: Binding[]; } -export const checkForDir = async (path: string, dir: string): Promise => { +export const checkForDir = async ( + path: string, + dir: string, +): Promise => { // who tf designed an api that returns undefined on success - return await access(path + "/" + dir).then(() => true).catch(() => false); -} + return await access(path + "/" + dir) + .then(() => true) + .catch(() => false); +}; export const readDir = async (path: string, dir: string): Promise => { return await readdir(path + "/" + dir); -} +}; -export const getBindingsByType = async (path: string, bindingType: keyof WranglerConfig): Promise => { +const jsoncToJson = (jsonc: string): string => { + // Remove comments (both // and /* */) + let json = jsonc.replace( + /\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, + (m, g) => (g ? "" : m), + ); + // Remove trailing commas before } or ] + json = json.replace(/,(\s*[}\]])/g, "$1"); + return json; +}; + +export const getBindingsByType = async ( + path: string, + bindingType: keyof WranglerConfig, +): Promise => { const wranglerConfig = Bun.file(`${path}/wrangler.jsonc`); const text = await wranglerConfig.text(); - const jsonString = text.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m); + const jsonString = jsoncToJson(text); const json: WranglerConfig = JSON.parse(jsonString); return json[bindingType as keyof WranglerConfig]; -} +}; export const getWranglerConfig = async (path: string): Promise => { const wranglerConfig = Bun.file(`${path}/wrangler.jsonc`); - if (!await wranglerConfig.exists()) { + if (!(await wranglerConfig.exists())) { return null; } const text = await wranglerConfig.text(); - const jsonString = text.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m); + const jsonString = jsoncToJson(text); return JSON.parse(jsonString); -} \ No newline at end of file +};