Skip to content

Commit 5c6ba1a

Browse files
committed
feat: sorter
1 parent 1d15667 commit 5c6ba1a

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/build.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { getInterfaceElementMergeData } from "./build/webref/elements.js";
1313
import { getInterfaceToEventMap } from "./build/webref/events.js";
1414
import { getWebidls } from "./build/webref/idl.js";
1515
import jsonc from "jsonc-parser";
16+
import { sortFiles } from "./build/sorter.js";
1617

1718
function mergeNamesakes(filtered: Browser.WebIdl) {
1819
const targets = [
@@ -396,3 +397,4 @@ async function emitDom() {
396397
}
397398

398399
await emitDom();
400+
sortFiles();

src/build/sorter.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import * as fs from "fs";
2+
import commentJson from "comment-json";
3+
4+
// A helper function to recursively sort object keys alphabetically.
5+
function sortObjectKeys<T>(obj: T): T {
6+
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
7+
const sorted = {} as any;
8+
Object.keys(obj)
9+
.sort()
10+
.forEach((key) => {
11+
// Recursively sort keys if the value is an object
12+
sorted[key] = sortObjectKeys((obj as any)[key]);
13+
});
14+
return sorted;
15+
}
16+
return obj;
17+
}
18+
19+
export function sortFiles() {
20+
const filePath = new URL(
21+
"../../inputfiles/overridingTypes.jsonc",
22+
import.meta.url,
23+
); // Replace with your JSONC file path
24+
25+
// Read the JSONC file content
26+
const fileContent = fs.readFileSync(filePath, "utf-8");
27+
28+
// Parse the JSONC file while preserving comments
29+
const parsed = commentJson.parse(fileContent, undefined, true);
30+
31+
// Sort the object keys alphabetically (recursively)
32+
const sortedObject = sortObjectKeys(parsed);
33+
34+
// Stringify the sorted object back to JSONC format (preserving comments)
35+
const sortedJsonC = commentJson.stringify(sortedObject, null, 2);
36+
37+
// Write the sorted content back to the file
38+
fs.writeFileSync(filePath, sortedJsonC, "utf-8");
39+
40+
console.log("JSONC file keys sorted successfully.");
41+
}

0 commit comments

Comments
 (0)