Skip to main content

sort_package_json/
lib.rs

1use serde_json::{Map, Value};
2
3/// Options for controlling JSON formatting when sorting
4#[derive(Debug, Clone)]
5pub struct SortOptions {
6    /// Whether to pretty-print the output JSON
7    pub pretty: bool,
8    /// Whether to sort the scripts field alphabetically
9    pub sort_scripts: bool,
10}
11
12impl Default for SortOptions {
13    fn default() -> Self {
14        Self { pretty: true, sort_scripts: false }
15    }
16}
17
18/// Sorts a package.json string with custom options
19pub fn sort_package_json_with_options(
20    input: &str,
21    options: &SortOptions,
22) -> Result<String, serde_json::Error> {
23    // Check for UTF-8 BOM and strip it for parsing
24    const BOM: char = '\u{FEFF}';
25    let input_without_bom = input.strip_prefix(BOM).unwrap_or(input);
26    let has_bom = input_without_bom.len() != input.len();
27
28    let value: Value = serde_json::from_str(input_without_bom)?;
29
30    let sorted_value = if let Value::Object(obj) = value {
31        Value::Object(sort_object_keys(obj, options))
32    } else {
33        value
34    };
35
36    let result = if options.pretty {
37        let mut s = serde_json::to_string_pretty(&sorted_value)?;
38        s.push('\n');
39        s
40    } else {
41        serde_json::to_string(&sorted_value)?
42    };
43
44    // Preserve BOM if it was present in the input
45    if has_bom {
46        let mut output = String::with_capacity(BOM.len_utf8() + result.len());
47        output.push(BOM);
48        output.push_str(&result);
49        Ok(output)
50    } else {
51        Ok(result)
52    }
53}
54
55/// Sorts a package.json string with default options (pretty-printed)
56pub fn sort_package_json(input: &str) -> Result<String, serde_json::Error> {
57    sort_package_json_with_options(input, &SortOptions::default())
58}
59
60/// Declares package.json field ordering with transformations.
61///
62/// This macro generates a match statement that handles known package.json fields
63/// in a specific order using explicit indices. It supports optional transformation
64/// expressions for fields that need special processing.
65///
66/// # Usage
67///
68/// ```ignore
69/// declare_field_order!(key, value, known, non_private, private; [
70///     0 => "$schema",
71///     1 => "name",
72///     7 => "categories" => transform_array(&value, sort_array_unique),
73/// ]);
74/// ```
75///
76/// # Parameters
77///
78/// - `key`: The field name identifier
79/// - `value`: The field value identifier
80/// - `known`: The vector to push known fields to
81/// - `non_private`: The vector to push non-private unknown fields to
82/// - `private`: The vector to push private (underscore-prefixed) fields to
83/// - Followed by an array of field declarations in the format:
84///   - `index => "field_name"` for fields without transformation
85///   - `index => "field_name" => transformation_expr` for fields with transformation
86macro_rules! declare_field_order {
87    (
88        $key:ident, $value:ident, $known:ident, $non_private:ident, $private:ident;
89        [
90            $( $idx:literal => $field_name:literal $( => $transform:expr )? ),* $(,)?
91        ]
92    ) => {
93        {
94            // Compile-time validation: ensure indices are literals
95            $( let _ = $idx; )*
96
97            // Generate the match statement
98            match $key.as_str() {
99                $(
100                    $field_name => {
101                        $known.push((
102                            $idx,
103                            $key,
104                            declare_field_order!(@value $value $(, $transform)?)
105                        ));
106                    },
107                )*
108                _ => {
109                    // Unknown field - check if private
110                    if $key.starts_with('_') {
111                        $private.push(($key, $value));
112                    } else {
113                        $non_private.push(($key, $value));
114                    }
115                }
116            }
117        }
118    };
119
120    // Helper: extract value without transformation
121    (@value $value:ident) => { $value };
122
123    // Helper: extract value with transformation
124    (@value $value:ident, $transform:expr) => { $transform };
125}
126
127fn transform_value<F>(value: Value, transform: F) -> Value
128where
129    F: FnOnce(Map<String, Value>) -> Map<String, Value>,
130{
131    match value {
132        Value::Object(o) => Value::Object(transform(o)),
133        _ => value,
134    }
135}
136
137fn transform_array<F>(value: Value, transform: F) -> Value
138where
139    F: FnOnce(Vec<Value>) -> Vec<Value>,
140{
141    match value {
142        Value::Array(arr) => Value::Array(transform(arr)),
143        _ => value,
144    }
145}
146
147fn transform_with_key_order(value: Value, key_order: &[&str]) -> Value {
148    transform_value(value, |o| sort_object_by_key_order(o, key_order))
149}
150
151fn sort_object_alphabetically(mut obj: Map<String, Value>) -> Map<String, Value> {
152    obj.sort_keys();
153    obj
154}
155
156fn sort_object_recursive(obj: Map<String, Value>) -> Map<String, Value> {
157    let mut obj = obj;
158    sort_object_recursive_in_place(&mut obj);
159    obj
160}
161
162fn sort_object_recursive_in_place(obj: &mut Map<String, Value>) {
163    for value in obj.values_mut() {
164        if let Value::Object(nested) = value {
165            sort_object_recursive_in_place(nested);
166        }
167    }
168    obj.sort_keys();
169}
170
171fn sort_array_unique(mut arr: Vec<Value>) -> Vec<Value> {
172    // Filter non-strings in-place (same behavior as filter_map)
173    arr.retain(|v| v.is_string());
174
175    // Sort in-place by comparing string values (zero allocations)
176    arr.sort_unstable_by(|a, b| a.as_str().unwrap().cmp(b.as_str().unwrap()));
177
178    // Remove consecutive duplicates in-place
179    arr.dedup_by(|a, b| a.as_str() == b.as_str());
180
181    arr
182}
183
184/// Deduplicate array while preserving order (no sorting).
185/// Used for fields where order matters (e.g., `files` with `!` negation patterns).
186fn dedupe_array(mut arr: Vec<Value>) -> Vec<Value> {
187    let mut write = 0;
188    for read in 0..arr.len() {
189        let keep = match arr[read].as_str() {
190            Some(s) => !arr[..write].iter().any(|seen| seen.as_str() == Some(s)),
191            None => false,
192        };
193        if keep {
194            if write != read {
195                arr.swap(write, read);
196            }
197            write += 1;
198        }
199    }
200    arr.truncate(write);
201    arr
202}
203
204fn sort_object_by_key_order(mut obj: Map<String, Value>, key_order: &[&str]) -> Map<String, Value> {
205    obj.sort_keys();
206
207    // Pre-allocate capacity to avoid reallocations
208    let mut result = Map::with_capacity(obj.len());
209
210    // Add keys in specified order
211    for &key in key_order {
212        if let Some(value) = obj.shift_remove(key) {
213            result.insert(key.into(), value);
214        }
215    }
216
217    // Remaining keys are already sorted alphabetically.
218    for (key, value) in obj {
219        result.insert(key, value);
220    }
221
222    result
223}
224
225fn sort_people_object(obj: Map<String, Value>) -> Map<String, Value> {
226    sort_object_by_key_order(obj, &["name", "email", "url"])
227}
228
229fn sort_object_keys(obj: Map<String, Value>, options: &SortOptions) -> Map<String, Value> {
230    // Storage for categorized keys with their values and ordering information
231    let mut known: Vec<(usize, String, Value)> = Vec::new(); // (order_index, key, value)
232    let mut non_private: Vec<(String, Value)> = Vec::new();
233    let mut private: Vec<(String, Value)> = Vec::new();
234
235    // Single pass through all keys using into_iter()
236    for (key, value) in obj {
237        declare_field_order!(key, value, known, non_private, private; [
238            // Core Package Metadata
239            0 => "$schema",
240            1 => "name",
241            2 => "displayName",
242            3 => "version",
243            4 => "stableVersion",
244            5 => "gitHead",
245            6 => "private",
246            7 => "description",
247            8 => "categories" => transform_array(value, sort_array_unique),
248            9 => "keywords" => transform_array(value, sort_array_unique),
249            10 => "homepage",
250            11 => "bugs" => transform_with_key_order(value, &["url", "email"]),
251            // License & People
252            12 => "license",
253            13 => "author" => transform_value(value, sort_people_object),
254            14 => "maintainers",
255            15 => "contributors",
256            // Repository & Funding
257            16 => "repository" => transform_with_key_order(value, &["type", "url"]),
258            17 => "funding" => transform_with_key_order(value, &["type", "url"]),
259            18 => "donate" => transform_with_key_order(value, &["type", "url"]),
260            19 => "sponsor" => transform_with_key_order(value, &["type", "url"]),
261            20 => "qna",
262            21 => "publisher",
263            // Package Content & Distribution
264            22 => "man",
265            23 => "style",
266            24 => "example",
267            25 => "examplestyle",
268            26 => "assets",
269            27 => "bin" => transform_value(value, sort_object_alphabetically),
270            28 => "source",
271            29 => "directories" => transform_with_key_order(value, &["lib", "bin", "man", "doc", "example", "test"]),
272            30 => "workspaces",
273            31 => "binary" => transform_with_key_order(value, &["module_name", "module_path", "remote_path", "package_name", "host"]),
274            32 => "files" => transform_array(value, dedupe_array),
275            33 => "os",
276            34 => "cpu",
277            35 => "libc" => transform_array(value, sort_array_unique),
278            // Package Entry Points
279            36 => "type",
280            37 => "sideEffects",
281            38 => "main",
282            39 => "module",
283            40 => "browser",
284            41 => "types",
285            42 => "typings",
286            43 => "typesVersions",
287            44 => "typeScriptVersion",
288            45 => "typesPublisherContentHash",
289            46 => "react-native",
290            47 => "svelte",
291            48 => "unpkg",
292            49 => "jsdelivr",
293            50 => "jsnext:main",
294            51 => "umd",
295            52 => "umd:main",
296            53 => "es5",
297            54 => "esm5",
298            55 => "fesm5",
299            56 => "es2015",
300            57 => "esm2015",
301            58 => "fesm2015",
302            59 => "es2020",
303            60 => "esm2020",
304            61 => "fesm2020",
305            62 => "esnext",
306            63 => "imports",
307            64 => "exports",
308            65 => "publishConfig" => transform_value(value, sort_object_alphabetically),
309            // Scripts
310            66 => "scripts" => if options.sort_scripts { transform_value(value, sort_object_alphabetically) } else { value },
311            67 => "betterScripts" => if options.sort_scripts { transform_value(value, sort_object_alphabetically) } else { value },
312            // Dependencies
313            68 => "dependencies" => transform_value(value, sort_object_alphabetically),
314            69 => "devDependencies" => transform_value(value, sort_object_alphabetically),
315            70 => "dependenciesMeta",
316            71 => "peerDependencies" => transform_value(value, sort_object_alphabetically),
317            72 => "peerDependenciesMeta",
318            73 => "optionalDependencies" => transform_value(value, sort_object_alphabetically),
319            74 => "bundledDependencies" => transform_array(value, sort_array_unique),
320            75 => "bundleDependencies" => transform_array(value, sort_array_unique),
321            76 => "resolutions" => transform_value(value, sort_object_alphabetically),
322            77 => "overrides" => transform_value(value, sort_object_alphabetically),
323            // Git Hooks & Commit Tools
324            78 => "husky" => transform_value(value, sort_object_recursive),
325            79 => "simple-git-hooks",
326            80 => "vite-staged",
327            81 => "lint-staged",
328            82 => "nano-staged",
329            83 => "pre-commit",
330            84 => "commitlint" => transform_value(value, sort_object_recursive),
331            // VSCode Extension Specific
332            85 => "l10n",
333            86 => "contributes",
334            87 => "activationEvents" => transform_array(value, sort_array_unique),
335            88 => "extensionPack" => transform_array(value, sort_array_unique),
336            89 => "extensionDependencies" => transform_array(value, sort_array_unique),
337            90 => "extensionKind" => transform_array(value, sort_array_unique),
338            91 => "icon",
339            92 => "badges",
340            93 => "galleryBanner",
341            94 => "preview",
342            95 => "markdown",
343            // Build & Tool Configuration
344            96 => "napi" => transform_value(value, sort_object_alphabetically),
345            97 => "flat",
346            98 => "config" => transform_value(value, sort_object_alphabetically),
347            99 => "nodemonConfig" => transform_value(value, sort_object_recursive),
348            100 => "browserify" => transform_value(value, sort_object_recursive),
349            101 => "babel" => transform_value(value, sort_object_recursive),
350            102 => "browserslist",
351            103 => "xo" => transform_value(value, sort_object_recursive),
352            104 => "prettier" => transform_value(value, sort_object_recursive),
353            105 => "eslintConfig" => transform_value(value, sort_object_recursive),
354            106 => "eslintIgnore",
355            107 => "standard" => transform_value(value, sort_object_recursive),
356            108 => "npmpkgjsonlint",
357            109 => "npmPackageJsonLintConfig",
358            110 => "npmpackagejsonlint",
359            111 => "release",
360            112 => "auto-changelog" => transform_value(value, sort_object_recursive),
361            113 => "remarkConfig" => transform_value(value, sort_object_recursive),
362            114 => "stylelint" => transform_value(value, sort_object_recursive),
363            115 => "typescript" => transform_value(value, sort_object_recursive),
364            116 => "typedoc" => transform_value(value, sort_object_recursive),
365            117 => "tshy" => transform_value(value, sort_object_recursive),
366            118 => "tsdown" => transform_value(value, sort_object_recursive),
367            119 => "size-limit",
368            // Testing
369            120 => "ava" => transform_value(value, sort_object_recursive),
370            121 => "jest" => transform_value(value, sort_object_recursive),
371            122 => "jest-junit",
372            123 => "jest-stare",
373            124 => "mocha" => transform_value(value, sort_object_recursive),
374            125 => "nyc" => transform_value(value, sort_object_recursive),
375            126 => "c8" => transform_value(value, sort_object_recursive),
376            127 => "tap",
377            128 => "tsd" => transform_value(value, sort_object_recursive),
378            129 => "typeCoverage" => transform_value(value, sort_object_recursive),
379            130 => "oclif" => transform_value(value, sort_object_recursive),
380            // Runtime & Package Manager
381            131 => "languageName",
382            132 => "preferGlobal",
383            133 => "devEngines" => transform_value(value, sort_object_alphabetically),
384            134 => "engines" => transform_value(value, sort_object_alphabetically),
385            135 => "engineStrict",
386            136 => "volta" => transform_value(value, sort_object_recursive),
387            137 => "packageManager",
388            138 => "pnpm",
389        ]);
390    }
391
392    // Sort each category (using unstable sort for better performance)
393    known.sort_unstable_by_key(|(index, _, _)| *index);
394    non_private.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
395    private.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
396
397    // Build result map
398    let mut result = Map::with_capacity(known.len() + non_private.len() + private.len());
399
400    // Insert known fields (already transformed)
401    for (_index, key, value) in known {
402        result.insert(key, value);
403    }
404
405    // Insert non-private unknown fields
406    for (key, value) in non_private {
407        result.insert(key, value);
408    }
409
410    // Insert private fields
411    for (key, value) in private {
412        result.insert(key, value);
413    }
414
415    result
416}