CSS

Imported css string:

This should be blue

This should be black


#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // create an array value
    json array = {1, 2, 3, 4, 5};

    // get an iterator to the reverse-end
    json::const_reverse_iterator it = array.crend();

    // increment the iterator to point to the first element
    --it;

    // serialize the element that the iterator points to
    std::cout << *it << '\n';
}


import * as mrmime from 'mrmime'
import type { Connect } from '#dep-types/connect'
import { cleanUrl } from '../../../shared/utils'
import type { ViteDevServer } from '..'

export function memoryFilesMiddleware(
  server: ViteDevServer,
): Connect.NextHandleFunction {
  const bundledDev = server.environments.client.bundledDev
  const memoryFiles = bundledDev?.memoryFiles
  if (!bundledDev || !memoryFiles) {
    throw new Error('memoryFilesMiddleware can only be used for fullBundleMode')
  }
  const headers = server.config.server.headers

  return function viteMemoryFilesMiddleware(req, res, next) {
    const cleanedUrl = cleanUrl(req.url!)
    if (cleanedUrl.endsWith('.html')) {
      return next()
    }

    let pathname
    try {
      pathname = decodeURIComponent(cleanedUrl)
    } catch {
      // ignore malformed URI
      return next()
    }
    const filePath = pathname.slice(1) // remove first /

    const file = memoryFiles.get(filePath)
    if (file) {
      if (file.etag) {
        if (req.headers['if-none-match'] === file.etag) {
          res.statusCode = 304
          res.end()
          return
        }
        res.setHeader('Etag', file.etag)
      }

      const mime = mrmime.lookup(filePath)
      if (mime) {
        res.setHeader('Content-Type', mime)
      }

      for (const name in headers) {
        res.setHeader(name, headers[name]!)
      }

      res.on('finish', () => bundledDev.markPayloadDelivered(filePath))
      return res.end(file.source)
    }
    next()
  }
}


//===- FuzzerExtFunctionsDlsym.cpp - Interface to external functions ------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Implementation for operating systems that support dlsym(). We only use it on
// Apple platforms for now. We don't use this approach on Linux because it
// requires that clients of LibFuzzer pass ``--export-dynamic`` to the linker.
// That is a complication we don't wish to expose to clients right now.
//===----------------------------------------------------------------------===//
#include "FuzzerDefs.h"
#if LIBFUZZER_APPLE

#include "FuzzerExtFunctions.h"
#include "FuzzerIO.h"
#include <dlfcn.h>

using namespace fuzzer;

template <typename T>
static T GetFnPtr(const char *FnName, bool WarnIfMissing) {
  dlerror(); // Clear any previous errors.
  void *Fn = dlsym(RTLD_DEFAULT, FnName);
  if (Fn == nullptr) {
    if (WarnIfMissing) {
      const char *ErrorMsg = dlerror();
      Printf("WARNING: Failed to find function \"%s\".", FnName);
      if (ErrorMsg)
        Printf(" Reason %s.", ErrorMsg);
      Printf("\n");
    }
  }
  return reinterpret_cast<T>(Fn);
}

namespace fuzzer {

ExternalFunctions::ExternalFunctions() {
#define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN)                            \
  this->NAME = GetFnPtr<decltype(ExternalFunctions::NAME)>(#NAME, WARN)

#include "FuzzerExtFunctions.def"

#undef EXT_FUNC
}

} // namespace fuzzer

#endif // LIBFUZZER_APPLE


#![allow(unused_macro_rules)]

use serde_test::Token;
use std::iter;

macro_rules! btreeset {
    () => {
        BTreeSet::new()
    };
    ($($value:expr),+) => {{
        let mut set = BTreeSet::new();
        $(set.insert($value);)+
        set
    }};
}

macro_rules! btreemap {
    () => {
        BTreeMap::new()
    };
    ($($key:expr => $value:expr),+) => {{
        let mut map = BTreeMap::new();
        $(map.insert($key, $value);)+
        map
    }};
}

macro_rules! hashset {
    () => {
        HashSet::new()
    };
    ($($value:expr),+) => {{
        let mut set = HashSet::new();
        $(set.insert($value);)+
        set
    }};
    ($hasher:ty; $($value:expr),+) => {{
        let mut set = HashSet::<_, $hasher>::default();
        $(set.insert($value);)+
        set
    }};
}

macro_rules! hashmap {
    () => {
        HashMap::new()
    };
    ($($key:expr => $value:expr),+) => {{
        let mut map = HashMap::new();
        $(map.insert($key, $value);)+
        map
    }};
    ($hasher:ty; $($key:expr => $value:expr),+) => {{
        let mut map = HashMap::<_, _, $hasher>::default();
        $(map.insert($key, $value);)+
        map
    }};
}

pub trait SingleTokenIntoIterator {
    fn into_iter(self) -> iter::Once<Token>;
}

impl SingleTokenIntoIterator for Token {
    fn into_iter(self) -> iter::Once<Token> {
        iter::once(self)
    }
}

macro_rules! seq {
    ($($elem:expr),* $(,)?) => {{
        use crate::macros::SingleTokenIntoIterator;
        let mut vec = Vec::new();
        $(<Vec<Token> as Extend<Token>>::extend(&mut vec, $elem.into_iter());)*
        vec
    }};
}


import path from 'node:path'
import url from 'node:url'
import { defineConfig } from 'vitest/config'

const _dirname = path.dirname(url.fileURLToPath(import.meta.url))

export default defineConfig({
  test: {
    include: ['**/__tests__/**/*.spec.[tj]s'],
    exclude: [
      '**/node_modules/**',
      '**/dist/**',
      './playground/**/*.*',
      './playground-temp/**/*.*',
    ],
    deps: {
      // we specify 'packages' so Vitest doesn't inline the files
      moduleDirectories: ['node_modules', 'packages'],
    },
    testTimeout: 20000,
    isolate: false,
  },
  oxc: {
    target: 'node20',
  },
  publicDir: false,
  resolve: {
    alias: {
      'vite/module-runner': path.resolve(
        _dirname,
        './packages/vite/src/module-runner/index.ts',
      ),
    },
  },
})


//===- FuzzerMutate.h - Internal header for the Fuzzer ----------*- C++ -* ===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// fuzzer::MutationDispatcher
//===----------------------------------------------------------------------===//

#ifndef LLVM_FUZZER_MUTATE_H
#define LLVM_FUZZER_MUTATE_H

#include "FuzzerDefs.h"
#include "FuzzerDictionary.h"
#include "FuzzerRandom.h"

namespace fuzzer {

class MutationDispatcher {
public:
  MutationDispatcher(Random &Rand, const FuzzingOptions &Options);
  ~MutationDispatcher() {}
  /// Indicate that we are about to start a new sequence of mutations.
  void StartMutationSequence();
  /// Print the current sequence of mutations.
  void PrintMutationSequence();
  /// Indicate that the current sequence of mutations was successfull.
  void RecordSuccessfulMutationSequence();
  /// Mutates data by invoking user-provided mutator.
  size_t Mutate_Custom(uint8_t *Data, size_t Size, size_t MaxSize);
  /// Mutates data by invoking user-provided crossover.
  size_t Mutate_CustomCrossOver(uint8_t *Data, size_t Size, size_t MaxSize);
  /// Mutates data by shuffling bytes.
  size_t Mutate_ShuffleBytes(uint8_t *Data, size_t Size, size_t MaxSize);
  /// Mutates data by erasing bytes.
  size_t Mutate_EraseBytes(uint8_t *Data, size_t Size, size_t MaxSize);
  /// Mutates data by inserting a byte.
  size_t Mutate_InsertByte(uint8_t *Data, size_t Size, size_t MaxSize);
  /// Mutates data by inserting several repeated bytes.
  size_t Mutate_InsertRepeatedBytes(uint8_t *Data, size_t Size, size_t MaxSize);
  /// Mutates data by chanding one byte.
  size_t Mutate_ChangeByte(uint8_t *Data, size_t Size, size_t MaxSize);
  /// Mutates data by chanding one bit.
  size_t Mutate_ChangeBit(uint8_t *Data, size_t Size, size_t MaxSize);
  /// Mutates data by copying/inserting a part of data into a different place.
  size_t Mutate_CopyPart(uint8_t *Data, size_t Size, size_t MaxSize);

  /// Mutates data by adding a word from the manual dictionary.
  size_t Mutate_AddWordFromManualDictionary(uint8_t *Data, size_t Size,
                                            size_t MaxSize);

  /// Mutates data by adding a word from the temporary automatic dictionary.
  size_t Mutate_AddWordFromTemporaryAutoDictionary(uint8_t *Data, size_t Size,
                                                   size_t MaxSize);

  /// Mutates data by adding a word from the TORC.
  size_t Mutate_AddWordFromTORC(uint8_t *Data, size_t Size, size_t MaxSize);

  /// Mutates data by adding a word from the persistent automatic dictionary.
  size_t Mutate_AddWordFromPersistentAutoDictionary(uint8_t *Data, size_t Size,
                                                    size_t MaxSize);

  /// Tries to find an ASCII integer in Data, changes it to another ASCII int.
  size_t Mutate_ChangeASCIIInteger(uint8_t *Data, size_t Size, size_t MaxSize);
  /// Change a 1-, 2-, 4-, or 8-byte integer in interesting ways.
  size_t Mutate_ChangeBinaryInteger(uint8_t *Data, size_t Size, size_t MaxSize);

  /// CrossOver Data with some other element of the corpus.
  size_t Mutate_CrossOver(uint8_t *Data, size_t Size, size_t MaxSize);

  /// Applies one of the configured mutations.
  /// Returns the new size of data which could be up to MaxSize.
  size_t Mutate(uint8_t *Data, size_t Size, size_t MaxSize);
  /// Applies one of the default mutations. Provided as a service
  /// to mutation authors.
  size_t DefaultMutate(uint8_t *Data, size_t Size, size_t MaxSize);

  /// Creates a cross-over of two pieces of Data, returns its size.
  size_t CrossOver(const uint8_t *Data1, size_t Size1, const uint8_t *Data2,
                   size_t Size2, uint8_t *Out, size_t MaxOutSize);

  void AddWordToManualDictionary(const Word &W);

  void AddWordToAutoDictionary(DictionaryEntry DE);
  void ClearAutoDictionary();
  void PrintRecommendedDictionary();

  void SetCorpus(const InputCorpus *Corpus) { this->Corpus = Corpus; }

  Random &GetRand() { return Rand; }

private:

  struct Mutator {
    size_t (MutationDispatcher::*Fn)(uint8_t *Data, size_t Size, size_t Max);
    const char *Name;
  };

  size_t AddWordFromDictionary(Dictionary &D, uint8_t *Data, size_t Size,
                               size_t MaxSize);
  size_t MutateImpl(uint8_t *Data, size_t Size, size_t MaxSize,
                    const std::vector<Mutator> &Mutators);

  size_t InsertPartOf(const uint8_t *From, size_t FromSize, uint8_t *To,
                      size_t ToSize, size_t MaxToSize);
  size_t CopyPartOf(const uint8_t *From, size_t FromSize, uint8_t *To,
                    size_t ToSize);
  size_t ApplyDictionaryEntry(uint8_t *Data, size_t Size, size_t MaxSize,
                              DictionaryEntry &DE);

  template <class T>
  DictionaryEntry MakeDictionaryEntryFromCMP(T Arg1, T Arg2,
                                             const uint8_t *Data, size_t Size);

  Random &Rand;
  const FuzzingOptions &Options;

  // Dictionary provided by the user via -dict=DICT_FILE.
  Dictionary ManualDictionary;
  // Temporary dictionary modified by the fuzzer itself,
  // recreated periodically.
  Dictionary TempAutoDictionary;
  // Persistent dictionary modified by the fuzzer, consists of
  // entries that led to successfull discoveries in the past mutations.
  Dictionary PersistentAutoDictionary;

  std::vector<Mutator> CurrentMutatorSequence;
  std::vector<DictionaryEntry *> CurrentDictionaryEntrySequence;

  static const size_t kCmpDictionaryEntriesDequeSize = 16;
  DictionaryEntry CmpDictionaryEntriesDeque[kCmpDictionaryEntriesDequeSize];
  size_t CmpDictionaryEntriesDequeIdx = 0;

  const InputCorpus *Corpus = nullptr;
  std::vector<uint8_t> MutateInPlaceHere;

  std::vector<Mutator> Mutators;
  std::vector<Mutator> DefaultMutators;
};

}  // namespace fuzzer

#endif  // LLVM_FUZZER_MUTATE_H


#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // create JSON values
    json j_boolean = true;
    json j_number_integer = 17;
    json j_number_float = 23.42;
    json j_object = {{"one", 1}, {"two", 2}};
    json j_array = {1, 2, 4, 8, 16};
    json j_string = "Hello, world";

    // call erase()
    j_boolean.erase(j_boolean.begin(), j_boolean.end());
    j_number_integer.erase(j_number_integer.begin(), j_number_integer.end());
    j_number_float.erase(j_number_float.begin(), j_number_float.end());
    j_object.erase(j_object.find("two"), j_object.end());
    j_array.erase(j_array.begin() + 1, j_array.begin() + 3);
    j_string.erase(j_string.begin(), j_string.end());

    // print values
    std::cout << j_boolean << '\n';
    std::cout << j_number_integer << '\n';
    std::cout << j_number_float << '\n';
    std::cout << j_object << '\n';
    std::cout << j_array << '\n';
    std::cout << j_string << '\n';
}


//     __ _____ _____ _____
//  __|  |   __|     |   | |  JSON for Modern C++ (supporting code)
// |  |  |__   |  |  | | | |  version 3.12.0
// |_____|_____|_____|_|___|  https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

#include <set>
#include <sstream>
#include <string>

#include "doctest_compatibility.h"

#include <nlohmann/json.hpp>

// Test extending nlohmann::json by using a custom base class.
// Add some metadata to each node and test the behaviour of copy / move
template<class MetaDataType>
class json_metadata
{
  public:
    using metadata_t = MetaDataType;
    metadata_t& metadata()
    {
        return m_metadata;
    }
    const metadata_t& metadata() const
    {
        return m_metadata;
    }
  private:
    metadata_t m_metadata = {};
};

template<class T>
using json_with_metadata =
    nlohmann::basic_json <
    std::map,
    std::vector,
    std::string,
    bool,
    std::int64_t,
    std::uint64_t,
    double,
    std::allocator,
    nlohmann::adl_serializer,
    std::vector<std::uint8_t>,
    json_metadata<T>
    >;

TEST_CASE("JSON Node Metadata")
{
    SECTION("type int")
    {
        using json = json_with_metadata<int>;
        json null;
        auto obj   = json::object();
        auto array = json::array();

        null.metadata()  = 1;
        obj.metadata()   = 2;
        array.metadata() = 3;
        auto copy = array;

        CHECK(null.metadata()  == 1);
        CHECK(obj.metadata()   == 2);
        CHECK(array.metadata() == 3);
        CHECK(copy.metadata()  == 3);
    }
    SECTION("type vector<int>")
    {
        using json = json_with_metadata<std::vector<int>>;
        json value;
        value.metadata().emplace_back(1);
        auto copy = value;
        value.metadata().emplace_back(2);

        CHECK(copy.metadata().size()  == 1);
        CHECK(copy.metadata().at(0)   == 1);
        CHECK(value.metadata().size() == 2);
        CHECK(value.metadata().at(0)  == 1);
        CHECK(value.metadata().at(1)  == 2);
    }
    SECTION("copy ctor")
    {
        using json = json_with_metadata<std::vector<int>>;
        json value;
        value.metadata().emplace_back(1);
        value.metadata().emplace_back(2);

        json copy = value;

        CHECK(copy.metadata().size()  == 2);
        CHECK(copy.metadata().at(0)   == 1);
        CHECK(copy.metadata().at(1)   == 2);
        CHECK(value.metadata().size() == 2);
        CHECK(value.metadata().at(0)  == 1);
        CHECK(value.metadata().at(1)  == 2);

        value.metadata().clear();
        CHECK(copy.metadata().size()  == 2);
        CHECK(value.metadata().size() == 0);
    }
    SECTION("move ctor")
    {
        using json = json_with_metadata<std::vector<int>>;
        json value;
        value.metadata().emplace_back(1);
        value.metadata().emplace_back(2);

        const json moved = std::move(value);

        CHECK(moved.metadata().size()  == 2);
        CHECK(moved.metadata().at(0)   == 1);
        CHECK(moved.metadata().at(1)   == 2);
    }
    SECTION("move assign")
    {
        using json = json_with_metadata<std::vector<int>>;
        json value;
        value.metadata().emplace_back(1);
        value.metadata().emplace_back(2);

        json moved;
        moved = std::move(value);

        CHECK(moved.metadata().size()  == 2);
        CHECK(moved.metadata().at(0)   == 1);
        CHECK(moved.metadata().at(1)   == 2);
    }
    SECTION("copy assign")
    {
        using json = json_with_metadata<std::vector<int>>;
        json value;
        value.metadata().emplace_back(1);
        value.metadata().emplace_back(2);

        json copy;
        copy = value;

        CHECK(copy.metadata().size()  == 2);
        CHECK(copy.metadata().at(0)   == 1);
        CHECK(copy.metadata().at(1)   == 2);
        CHECK(value.metadata().size() == 2);
        CHECK(value.metadata().at(0)  == 1);
        CHECK(value.metadata().at(1)  == 2);

        value.metadata().clear();
        CHECK(copy.metadata().size()  == 2);
        CHECK(value.metadata().size() == 0);
    }
    SECTION("type unique_ptr<int>")
    {
        using json = json_with_metadata<std::unique_ptr<int>>;
        json value;
        value.metadata().reset(new int(42)); // NOLINT(cppcoreguidelines-owning-memory)
        auto moved = std::move(value);

        CHECK(moved.metadata() != nullptr);
        CHECK(*moved.metadata() == 42);
    }
    SECTION("type vector<int> in json array")
    {
        using json = json_with_metadata<std::vector<int>>;
        json value;
        value.metadata().emplace_back(1);
        value.metadata().emplace_back(2);

        json const array(10, value);

        CHECK(value.metadata().size() == 2);
        CHECK(value.metadata().at(0)  == 1);
        CHECK(value.metadata().at(1)  == 2);

        for (const auto& val : array)
        {
            CHECK(val.metadata().size() == 2);
            CHECK(val.metadata().at(0)  == 1);
            CHECK(val.metadata().at(1)  == 2);
        }
    }
}

// Test extending nlohmann::json by using a custom base class.
// Add a custom member function template iterating over the whole json tree.
class visitor_adaptor
{
  public:
    template <class Fnc>
    void visit(const Fnc& fnc) const;
  private:
    template <class Ptr, class Fnc>
    void do_visit(const Ptr& ptr, const Fnc& fnc) const;
};

using json_with_visitor_t = nlohmann::basic_json <
                            std::map,
                            std::vector,
                            std::string,
                            bool,
                            std::int64_t,
                            std::uint64_t,
                            double,
                            std::allocator,
                            nlohmann::adl_serializer,
                            std::vector<std::uint8_t>,
                            visitor_adaptor
                            >;

template <class Fnc>
void visitor_adaptor::visit(const Fnc& fnc) const
{
    do_visit(json_with_visitor_t::json_pointer{}, fnc);
}

template <class Ptr, class Fnc>
void visitor_adaptor::do_visit(const Ptr& ptr, const Fnc& fnc) const
{
    using value_t = nlohmann::detail::value_t;
    const json_with_visitor_t& json = *static_cast<const json_with_visitor_t*>(this); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast)
    switch (json.type())
    {
        case value_t::object:
            for (const auto& entry : json.items())
            {
                entry.value().do_visit(ptr / entry.key(), fnc);
            }
            break;
        case value_t::array:
            for (std::size_t i = 0; i < json.size(); ++i)
            {
                json.at(i).do_visit(ptr / std::to_string(i), fnc);
            }
            break;
        case value_t::discarded:
            break;
        case value_t::null:
        case value_t::string:
        case value_t::boolean:
        case value_t::number_integer:
        case value_t::number_unsigned:
        case value_t::number_float:
        case value_t::binary:
        default:
            fnc(ptr, json);
    }
}

TEST_CASE("JSON Visit Node")
{
    json_with_visitor_t json;
    json["null"];
    json["int"]  = -1;
    json["uint"] = 1U;
    json["float"] = 1.0;
    json["boolean"] = true;
    json["string"] = "string";
    json["array"].push_back(0);
    json["array"].push_back(1);
    json["array"].push_back(json);

    std::set<std::string> expected
    {
        "/null - null - null",
        "/int - number_integer - -1",
        "/uint - number_unsigned - 1",
        "/float - number_float - 1.0",
        "/boolean - boolean - true",
        "/string - string - \"string\"",
        "/array/0 - number_integer - 0",
        "/array/1 - number_integer - 1",

        "/array/2/null - null - null",
        "/array/2/int - number_integer - -1",
        "/array/2/uint - number_unsigned - 1",
        "/array/2/float - number_float - 1.0",
        "/array/2/boolean - boolean - true",
        "/array/2/string - string - \"string\"",
        "/array/2/array/0 - number_integer - 0",
        "/array/2/array/1 - number_integer - 1"
    };

    json.visit(
            [&](const json_with_visitor_t::json_pointer & p,
                const json_with_visitor_t& j)
    {
        std::stringstream str;
        str << p.to_string() << " - " ;
        using value_t = nlohmann::detail::value_t;
        switch (j.type())
        {
            case value_t::object:
                str << "object";
                break;
            case value_t::array:
                str << "array";
                break;
            case value_t::discarded:
                str << "discarded";
                break;
            case value_t::null:
                str << "null";
                break;
            case value_t::string:
                str << "string";
                break;
            case value_t::boolean:
                str << "boolean";
                break;
            case value_t::number_integer:
                str << "number_integer";
                break;
            case value_t::number_unsigned:
                str << "number_unsigned";
                break;
            case value_t::number_float:
                str << "number_float";
                break;
            case value_t::binary:
                str << "binary";
                break;
            default:
                str << "error";
                break;
        }
        str << " - "  << j.dump();
        CHECK(json.at(p) == j);
        INFO(str.str());
        CHECK(expected.count(str.str()) == 1);
        expected.erase(str.str());
    }
        );
    CHECK(expected.empty());
}


<!doctype html>

    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Vue + TS</title>


export interface FetchFunctionOptions {
  cached?: boolean
  startOffset?: number
}

export type FetchResult =
  | CachedFetchResult
  | ExternalFetchResult
  | ViteFetchResult

export interface CachedFetchResult {
  /**
   * If the module is cached in the runner, this confirms
   * it was not invalidated on the server side.
   */
  cache: true
}

export interface ExternalFetchResult {
  /**
   * The path to the externalized module starting with file://.
   * By default this will be imported via a dynamic "import"
   * instead of being transformed by Vite and loaded with the Vite runner.
   */
  externalize: string
  /**
   * Type of the module. Used to determine if the import statement is correct.
   * For example, if Vite needs to throw an error if a variable is not actually exported.
   */
  type: 'module' | 'commonjs' | 'builtin' | 'network'
}

export interface ViteFetchResult {
  /**
   * Code that will be evaluated by the Vite runner.
   * By default this will be wrapped in an async function.
   */
  code: string
  /**
   * File path of the module on disk.
   * This will be resolved as import.meta.url/filename.
   * Will be `null` for virtual modules.
   */
  file: string | null
  /**
   * Module ID in the server module graph.
   */
  id: string
  /**
   * Module URL used in the import.
   */
  url: string
  /**
   * Invalidate module on the client side.
   */
  invalidate: boolean
}

export type InvokeSendData<
  T extends keyof InvokeMethods = keyof InvokeMethods,
> = {
  name: T
  /** 'send' is for requests without an id */
  id: 'send' | `send:${string}`
  data: Parameters<InvokeMethods[T]>
}

export type InvokeResponseData<
  T extends keyof InvokeMethods = keyof InvokeMethods,
> = {
  name: T
  /** 'response' is for responses without an id */
  id: 'response' | `response:${string}`
  data:
    | { result: Awaited<ReturnType<InvokeMethods[T]>>; error?: undefined }
    | { result?: undefined; error: any }
}

export type InvokeMethods = {
  fetchModule: (
    id: string,
    importer?: string,
    options?: FetchFunctionOptions,
  ) => Promise<FetchResult>

  getBuiltins: () => Promise<
    Array<
      | { type: 'string'; value: string }
      | { type: 'RegExp'; source: string; flags: string }
    >
  >
}


#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // different JSON Pointers
    json::json_pointer ptr1("");
    json::json_pointer ptr2("/foo");
    json::json_pointer ptr3("/foo/0");

    // call parent_pointer()
    std::cout << std::boolalpha
              << "parent of \"" << ptr1 << "\" is \"" << ptr1.parent_pointer() << "\"\n"
              << "parent of \"" << ptr2 << "\" is \"" << ptr2.parent_pointer() << "\"\n"
              << "parent of \"" << ptr3 << "\" is \"" << ptr3.parent_pointer() << "\"" << std::endl;
}


import { isWindows } from '../shared/utils'
import { createImportMetaResolver } from './importMetaResolver'
import type { ModuleRunnerImportMeta } from './types'
import { posixDirname, posixPathToFileHref, toWindowsPath } from './utils'

const envProxy = new Proxy({} as any, {
  get(_, p) {
    throw new Error(
      `[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`,
    )
  },
})

export function createDefaultImportMeta(
  modulePath: string,
): ModuleRunnerImportMeta {
  const href = posixPathToFileHref(modulePath)
  const filename = modulePath
  const dirname = posixDirname(modulePath)
  return {
    filename: isWindows ? toWindowsPath(filename) : filename,
    dirname: isWindows ? toWindowsPath(dirname) : dirname,
    url: href,
    env: envProxy,
    resolve(_id: string, _parent?: string) {
      throw new Error('[module runner] "import.meta.resolve" is not supported.')
    },
    // should be replaced during transformation
    glob() {
      throw new Error(
        `[module runner] "import.meta.glob" is statically replaced during ` +
          `file transformation. Make sure to reference it by the full name.`,
      )
    },
  }
}

/**
 * Create import.meta object for Node.js.
 */
export function createNodeImportMeta(
  modulePath: string,
): ModuleRunnerImportMeta {
  const defaultMeta = createDefaultImportMeta(modulePath)
  const href = defaultMeta.url

  const importMetaResolver = createImportMetaResolver()

  return {
    ...defaultMeta,
    main: false,
    resolve(id: string, parent?: string) {
      const resolver = importMetaResolver ?? defaultMeta.resolve
      return resolver(id, parent ?? href)
    },
  }
}


#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

namespace ns
{
// a simple struct to model a person
struct person
{
    std::string name;
    std::string address;
    int age;
};
} // namespace ns

namespace ns
{
void to_json(json& j, const person& p)
{
    j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} };
}
} // namespace ns

int main()
{
    ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};

    json j = p;

    std::cout << j << std::endl;
}


# JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON

```cpp
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */
```

This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are `1` to
enable or `0` to disable (default).

When enabled, comparisons involving at least one discarded JSON value yield results as follows:

| **Operator** | **Result**    |
|--------------|---------------|
| `==`         | `#!cpp false` |
| `!=`         | `#!cpp true`  |
| `<`          | `#!cpp false` |
| `<=`         | `#!cpp true`  |
| `>=`         | `#!cpp true`  |
| `>`          | `#!cpp false` |

Otherwise, comparisons involving at least one discarded JSON value always yield `#!cpp false`.

## Default definition

The default value is `0`.

```cpp
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0
```

When the macro is not defined, the library will define it to its default value.

## Notes

!!! warning "Inconsistent behavior in C++20 and beyond"

    When targeting C++20 or above, enabling the legacy comparison behavior is _strongly_
    discouraged.

      - The 3-way comparison operator (`<=>`) will always give the correct result
        (`#!cpp std::partial_ordering::unordered`) regardless of the value of
        `JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON`.
      - Overloads for the equality and relational operators emulate the legacy behavior.

    Code outside your control may use either 3-way comparison or the equality and relational operators, resulting in
    inconsistent and unpredictable behavior.

    See [`operator<=>`](../basic_json/operator_spaceship.md) for more information on 3-way comparison.

!!! warning "Deprecation"

    The legacy comparison behavior is deprecated and may be removed in a future major version release.

    New code should not depend on it and existing code should try to remove or rewrite expressions relying on it.

!!! hint "CMake option"

    Legacy comparison can also be controlled with the CMake option
    [`JSON_LegacyDiscardedValueComparison`](../../integration/cmake.md#json_legacydiscardedvaluecomparison)
    (`OFF` by default) which defines `JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON` accordingly.

## Examples

??? example

    The code below switches on the legacy discarded value comparison behavior in the library.

    ```cpp
    #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1
    #include <nlohmann/json.hpp>

    ...
    ```

## See also

- [:simple-cmake: JSON_LegacyDiscardedValueComparison](../../integration/cmake.md#json_legacydiscardedvaluecomparison) - CMake option to control the macro

## Version history

- Added in version 3.11.0.


//     __ _____ _____ _____
//  __|  |   __|     |   | |  JSON for Modern C++ (supporting code)
// |  |  |__   |  |  | | | |  version 3.12.0
// |_____|_____|_____|_|___|  https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

#include "doctest_compatibility.h"

#include <nlohmann/json.hpp>
using nlohmann::json;
using nlohmann::ordered_json;

TEST_CASE("ordered_json")
{
    json j;
    ordered_json oj;

    j["element3"] = 3;
    j["element1"] = 1;
    j["element2"] = 2;

    oj["element3"] = 3;
    oj["element1"] = 1;
    oj["element2"] = 2;

    CHECK(j.dump() == "{\"element1\":1,\"element2\":2,\"element3\":3}");
    CHECK(oj.dump() == "{\"element3\":3,\"element1\":1,\"element2\":2}");

    CHECK(j == json(oj));
    CHECK(ordered_json(json(oj)) == ordered_json(j));

    j.erase("element1");
    oj.erase("element1");

    CHECK(j.dump() == "{\"element2\":2,\"element3\":3}");
    CHECK(oj.dump() == "{\"element3\":3,\"element2\":2}");

    // remove again and nothing changes
    j.erase("element1");
    oj.erase("element1");

    CHECK(j.dump() == "{\"element2\":2,\"element3\":3}");
    CHECK(oj.dump() == "{\"element3\":3,\"element2\":2}");

    // There are no dup keys cause constructor calls emplace...
    json const multi {{"z", 1}, {"m", 2}, {"m", 3}, {"y", 4}, {"m", 5}};
    CHECK(multi.size() == 3);
    CHECK(multi.dump() == "{\"m\":2,\"y\":4,\"z\":1}");

    ordered_json multi_ordered {{"z", 1}, {"m", 2}, {"m", 3}, {"y", 4}, {"m", 5}};
    CHECK(multi_ordered.size() == 3);
    CHECK(multi_ordered.dump() == "{\"z\":1,\"m\":2,\"y\":4}");
    CHECK(multi_ordered.erase("m") == 1);
    CHECK(multi_ordered.dump() == "{\"z\":1,\"y\":4}");

    // Ranged insert test.
    // It seems that values shouldn't be overwritten. Only new values are added
    json j1 {{"c", 1}, {"b", 2}, {"a", 3}};
    const json j2 {{"c", 77}, {"d", 42}, {"a", 4}};
    j1.insert( j2.cbegin(), j2.cend() );
    CHECK(j1.size() == 4);
    CHECK(j1.dump() == "{\"a\":3,\"b\":2,\"c\":1,\"d\":42}");

    ordered_json oj1 {{"c", 1}, {"b", 2}, {"a", 3}};
    const ordered_json oj2 {{"c", 77}, {"d", 42}, {"a", 4}};
    oj1.insert( oj2.cbegin(), oj2.cend() );
    CHECK(oj1.size() == 4);
    CHECK(oj1.dump() == "{\"c\":1,\"b\":2,\"a\":3,\"d\":42}");
}

TEST_CASE("regression test for issue #3732 - iteration_proxy_value<iter_impl<ordered_json>>")
{
    // Naming the proxy type in a function-parameter position forces eager
    // instantiation of basic_json<ordered_map>; previously this hit an
    // incomplete-type error in set_parents().
    auto fn = [](nlohmann::detail::iteration_proxy_value<nlohmann::detail::iter_impl<nlohmann::ordered_json>> const & val)
    {
        return val.value();
    };
    static_cast<void>(fn);
}


# NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE

```cpp
#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)              // (1)
#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)
#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...) // (3)
```

These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as
serialization and want to use the member variable names as object keys in that object. The macro is to be defined
**inside** the class/struct to create code for. Unlike
[`NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`](nlohmann_define_type_non_intrusive.md), it can access private members. The first
parameter is the name of the class/struct, and all remaining parameters name the members.

1. Will use [`at`](../basic_json/at.md) during deserialization and will throw
  [`out_of_range.403`](../../home/exceptions.md#jsonexceptionout_of_range403) if a key is missing in the JSON object.
2. Will use [`value`](../basic_json/value.md) during deserialization and fall back to the default value for the
   respective type of the member variable if a key in the JSON object is missing. The generated `from_json()` function
   default constructs an object and uses its values as the defaults when calling the `value` function.
3. Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization is required.

Summary:

| Need access to private members                                   | Need only serialization                                          | Allow missing values when de-serializing                         | macro                                                 |
|------------------------------------------------------------------|------------------------------------------------------------------|------------------------------------------------------------------|-------------------------------------------------------|
|
:octicons-check-circle-fill-24:
 |
:octicons-x-circle-fill-24:
       |
:octicons-x-circle-fill-24:
       | **NLOHMANN_DEFINE_TYPE_INTRUSIVE**                    |
|
:octicons-check-circle-fill-24:
 |
:octicons-x-circle-fill-24:
       |
:octicons-check-circle-fill-24:
 | **NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT**       |
|
:octicons-check-circle-fill-24:
 |
:octicons-check-circle-fill-24:
 |
:octicons-skip-fill-24:
          | **NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE**     |

## Parameters

`type` (in)
:   name of the type (class, struct) to serialize/deserialize

`member` (in)
:   name of the member variable to serialize/deserialize; up to 63 members can be given as a comma-separated list

## Default definition

The macros add two friend functions to the class which take care of the serialization and deserialization:

```cpp
template<typename BasicJsonType>
friend void to_json(BasicJsonType&, const type&);
template<typename BasicJsonType>
friend void from_json(const BasicJsonType&, type&); // except (3)
```

See the examples below for the concrete generated code.

## Notes

!!! info "Prerequisites"

    1. The type `type` must be default constructible (except (3)). See [How can I use `get()` for non-default
       constructible/non-copyable types?][GetNonDefNonCopy] for how to overcome this limitation.
    2. The macro must be used inside the type (class/struct).

[GetNonDefNonCopy]: ../../features/arbitrary_types.md#how-can-i-use-get-for-non-default-constructiblenon-copyable-types

!!! warning "Implementation limits"

    - The current implementation is limited to at most 63 member variables. If you want to serialize/deserialize types
      with more than 63 member variables, you need to define the `to_json`/`from_json` functions manually.
    - These macros always produce object-style (named-key) JSON, one key per member. There is no macro variant
      that serializes a struct's members positionally into a JSON array; for that, write `to_json`/`from_json` by
      hand, building/reading a `json::array()` of the members in order.

## Examples

??? example "Example (1): NLOHMANN_DEFINE_TYPE_INTRUSIVE"

    Consider the following complete example:

    ```cpp hl_lines="22"
    --8<-- "examples/nlohmann_define_type_intrusive_macro.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/nlohmann_define_type_intrusive_macro.output"
    ```

    Notes:

    - `ns::person` is default-constructible. This is a requirement for using the macro.
    - `ns::person` has private member variables. This makes `NLOHMANN_DEFINE_TYPE_INTRUSIVE` applicable, but not
      `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`.
    - The macro `NLOHMANN_DEFINE_TYPE_INTRUSIVE` is used _inside_ the class.
    - A missing key "age" in the deserialization yields an exception. To fall back to the default value,
      `NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT` can be used.

    The macro is equivalent to:

    ```cpp hl_lines="22 23 24 25 26 27 28 29 30 31 32 33 34 35 36"
    --8<-- "examples/nlohmann_define_type_intrusive_explicit.cpp"
    ```

??? example "Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT"

    Consider the following complete example:

    ```cpp hl_lines="22"
    --8<-- "examples/nlohmann_define_type_intrusive_with_default_macro.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/nlohmann_define_type_intrusive_with_default_macro.output"
    ```

    Notes:

    - `ns::person` is default-constructible. This is a requirement for using the macro.
    - `ns::person` has private member variables. This makes `NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT` applicable,
       but not `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT`.
    - The macro `NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT` is used _inside_ the class.
    - A missing key "age" in the deserialization does not yield an exception. Instead, the default value `-1` is used.

    The macro is equivalent to:

    ```cpp hl_lines="22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37"
    --8<-- "examples/nlohmann_define_type_intrusive_with_default_explicit.cpp"
    ```

    Note how a default-initialized `person` object is used in the `from_json` to fill missing values.

??? example "Example (3): NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE"
    Consider the following complete example:

    ```cpp hl_lines="22"
    --8<-- "examples/nlohmann_define_type_intrusive_only_serialize_macro.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/nlohmann_define_type_intrusive_only_serialize_macro.output"
    ```

    Notes:

    - `ns::person` is non-default-constructible. This allows this macro to be used instead of
      `NLOHMANN_DEFINE_TYPE_INTRUSIVE` and `NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT`.
    - `ns::person` has private member variables. This makes `NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE` applicable, but not
      `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE`.
    - The macro `NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE` is used _inside_ the class.

    The macro is equivalent to:

    ```cpp hl_lines="22 22 23 24 25 26 27 28"
    --8<-- "examples/nlohmann_define_type_intrusive_only_serialize_explicit.cpp"
    ```

## See also

- [NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT,
  NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE](nlohmann_define_type_non_intrusive.md)
  for a similar macro that can be defined _outside_ the type.
- [NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT,
  NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE,
  NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT,
  NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE](nlohmann_define_derived_type.md) for similar macros for
  derived types
- [Arbitrary Type Conversions](../../features/arbitrary_types.md) for an overview.

## Version history

1. Added in version 3.9.0.
2. Added in version 3.11.0.
3. Added in version 3.11.3.