// Formatting library for C++ - optional wchar_t and exotic character support
//
// Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors
// All rights reserved.
//
// For the license information refer to format.h.

#ifndef FMT_XCHAR_H_
#define FMT_XCHAR_H_

#include "color.h"
#include "format.h"
#include "ostream.h"
#include "ranges.h"

#ifndef FMT_MODULE
#  include <cwchar>
#  if FMT_USE_LOCALE
#    include <locale>
#  endif
#endif

FMT_BEGIN_NAMESPACE
namespace detail {

template <typename T>
using is_exotic_char = bool_constant<!std::is_same<T, char>::value>;

template <typename S, typename = void> struct format_string_char {};

template <typename S>
struct format_string_char<
    S, void_t<decltype(sizeof(detail::to_string_view(std::declval<S>())))>> {
  using type = char_t<S>;
};

template <typename S>
struct format_string_char<
    S, enable_if_t<std::is_base_of<detail::compile_string, S>::value>> {
  using type = typename S::char_type;
};

template <typename S>
using format_string_char_t = typename format_string_char<S>::type;

inline auto write_loc(basic_appender<wchar_t> out, loc_value value,
                      const format_specs& specs, locale_ref loc) -> bool {
#if FMT_USE_LOCALE
  auto loc_copy = loc.get<std::locale>();
  auto& numpunct = std::use_facet<std::numpunct<wchar_t>>(loc_copy);
  auto separator = std::wstring();
  auto grouping = numpunct.grouping();
  if (!grouping.empty()) separator = std::wstring(1, numpunct.thousands_sep());
  return value.visit(loc_writer<wchar_t>{out, specs, separator, grouping, {}});
#endif
  return false;
}

template <typename Char>
void vformat_to(buffer<Char>& buf, basic_string_view<Char> fmt,
                basic_format_args<buffered_context<Char>> args,
                locale_ref loc = {}) {
  static_assert(!std::is_same<Char, char>::value, "");
  auto out = basic_appender<Char>(buf);
  parse_format_string(
      fmt, format_handler<Char>{parse_context<Char>(fmt), {out, args, loc}});
}
}  // namespace detail

FMT_BEGIN_EXPORT

using wstring_view = basic_string_view<wchar_t>;
using wformat_parse_context = parse_context<wchar_t>;
using wformat_context = buffered_context<wchar_t>;
using wformat_args = basic_format_args<wformat_context>;
using wmemory_buffer = basic_memory_buffer<wchar_t>;

template <typename Char, typename... T> struct basic_fstring {
 private:
  basic_string_view<Char> str_;

  static constexpr int num_static_named_args =
      detail::count_static_named_args<T...>();

  using checker = detail::format_string_checker<
      Char, static_cast<int>(sizeof...(T)), num_static_named_args,
      num_static_named_args != detail::count_named_args<T...>()>;

  using arg_pack = detail::arg_pack<T...>;

 public:
  using t = basic_fstring;

  template <typename S,
            FMT_ENABLE_IF(
                std::is_convertible<const S&, basic_string_view<Char>>::value)>
  FMT_CONSTEVAL FMT_ALWAYS_INLINE basic_fstring(const S& s) : str_(s) {
    if (FMT_USE_CONSTEVAL)
      detail::parse_format_string<Char>(s, checker(s, arg_pack()));
  }
  template <typename S,
            FMT_ENABLE_IF(std::is_base_of<detail::compile_string, S>::value&&
                              std::is_same<typename S::char_type, Char>::value)>
  FMT_ALWAYS_INLINE basic_fstring(const S&) : str_(S()) {
    FMT_CONSTEXPR auto sv = basic_string_view<Char>(S());
    FMT_CONSTEXPR int ignore =
        (parse_format_string(sv, checker(sv, arg_pack())), 0);
    detail::ignore_unused(ignore);
  }
  basic_fstring(runtime_format_string<Char> fmt) : str_(fmt.str) {}

  FMT_DEPRECATED operator basic_string_view<Char>() const { return str_; }
  auto get() const -> basic_string_view<Char> { return str_; }
};

template <typename Char, typename... T>
using basic_format_string = basic_fstring<Char, T...>;

template <typename... T>
using wformat_string = typename basic_format_string<wchar_t, T...>::t;
inline auto runtime(wstring_view s) -> runtime_format_string<wchar_t> {
  return {{s}};
}

template <typename... T>
constexpr auto make_wformat_args(T&... args)
    -> decltype(fmt::make_format_args<wformat_context>(args...)) {
  return fmt::make_format_args<wformat_context>(args...);
}

#if !FMT_USE_NONTYPE_TEMPLATE_ARGS
inline namespace literals {
inline auto operator""_a(const wchar_t* s, size_t) -> detail::udl_arg<wchar_t> {
  return {s};
}
}  // namespace literals
#endif

template <typename T>
auto arg(const wchar_t* name, const T& arg) -> named_arg<T, wchar_t> {
  return {name, arg};
}

template <typename It, typename Sentinel, typename S,
          typename Char = typename decltype(detail::to_string_view(
              std::declval<S>()))::value_type,
          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>
auto join(It begin, Sentinel end, S&& sep) -> join_view<It, Sentinel, Char> {
  return {begin, end, detail::to_string_view(sep)};
}

template <typename Range, typename S,
          typename Char = typename decltype(detail::to_string_view(
              std::declval<S>()))::value_type,
          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value &&
                        !is_tuple_like<Range>::value)>
auto join(Range&& range, S&& sep)
    -> join_view<decltype(std::begin(range)), decltype(std::end(range)), Char> {
  return {std::begin(range), std::end(range), detail::to_string_view(sep)};
}

template <typename T>
FMT_DEPRECATED auto join(std::initializer_list<T> list, wstring_view sep)
    -> join_view<const T*, const T*, wchar_t> {
  return join(std::begin(list), std::end(list), sep);
}

template <typename Tuple, typename S,
          typename Char = typename decltype(detail::to_string_view(
              std::declval<S>()))::value_type,
          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value&&
                            is_tuple_like<Tuple>::value)>
auto join(const Tuple& tuple, S&& sep) -> tuple_join_view<Tuple, Char> {
  return {tuple, detail::to_string_view(sep)};
}

template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
auto vformat(basic_string_view<Char> fmt,
             basic_format_args<buffered_context<Char>> args)
    -> std::basic_string<Char> {
  auto buf = basic_memory_buffer<Char>();
  detail::vformat_to(buf, fmt, args);
  return {buf.data(), buf.size()};
}

template <typename... T>
auto format(wformat_string<T...> fmt, T&&... args) -> std::wstring {
  return vformat(fmt.get(), fmt::make_wformat_args(args...));
}

template <typename OutputIt, typename... T>
auto format_to(OutputIt out, wformat_string<T...> fmt, T&&... args)
    -> OutputIt {
  return vformat_to(out, fmt.get(), fmt::make_wformat_args(args...));
}

// Pass char_t as a default template parameter instead of using
// std::basic_string<char_t<S>> to reduce the symbol size.
template <typename S, typename... T,
          typename Char = detail::format_string_char_t<S>,
          FMT_ENABLE_IF(!std::is_same<Char, char>::value &&
                        !std::is_same<Char, wchar_t>::value)>
auto format(const S& fmt, T&&... args) -> std::basic_string<Char> {
  return vformat(detail::to_string_view(fmt),
                 fmt::make_format_args<buffered_context<Char>>(args...));
}

template <typename S, typename Char = detail::format_string_char_t<S>,
          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>
inline auto vformat(locale_ref loc, const S& fmt,
                    basic_format_args<buffered_context<Char>> args)
    -> std::basic_string<Char> {
  auto buf = basic_memory_buffer<Char>();
  detail::vformat_to(buf, detail::to_string_view(fmt), args, loc);
  return {buf.data(), buf.size()};
}

template <typename S, typename... T,
          typename Char = detail::format_string_char_t<S>,
          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>
inline auto format(locale_ref loc, const S& fmt, T&&... args)
    -> std::basic_string<Char> {
  return vformat(loc, detail::to_string_view(fmt),
                 fmt::make_format_args<buffered_context<Char>>(args...));
}

template <typename OutputIt, typename S,
          typename Char = detail::format_string_char_t<S>,
          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
                            detail::is_exotic_char<Char>::value)>
auto vformat_to(OutputIt out, const S& fmt,
                basic_format_args<buffered_context<Char>> args) -> OutputIt {
  auto&& buf = detail::get_buffer<Char>(out);
  detail::vformat_to(buf, detail::to_string_view(fmt), args);
  return detail::get_iterator(buf, out);
}

template <typename OutputIt, typename S, typename... T,
          typename Char = detail::format_string_char_t<S>,
          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value &&
                        !std::is_same<Char, char>::value &&
                        !std::is_same<Char, wchar_t>::value)>
inline auto format_to(OutputIt out, const S& fmt, T&&... args) -> OutputIt {
  return vformat_to(out, detail::to_string_view(fmt),
                    fmt::make_format_args<buffered_context<Char>>(args...));
}

template <typename S, typename OutputIt, typename... Args,
          typename Char = detail::format_string_char_t<S>,
          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
                            detail::is_exotic_char<Char>::value)>
inline auto vformat_to(OutputIt out, locale_ref loc, const S& fmt,
                       basic_format_args<buffered_context<Char>> args)
    -> OutputIt {
  auto&& buf = detail::get_buffer<Char>(out);
  vformat_to(buf, detail::to_string_view(fmt), args, loc);
  return detail::get_iterator(buf, out);
}

template <typename OutputIt, typename S, typename... T,
          typename Char = detail::format_string_char_t<S>,
          bool enable = detail::is_output_iterator<OutputIt, Char>::value &&
                        detail::is_exotic_char<Char>::value>
inline auto format_to(OutputIt out, locale_ref loc, const S& fmt, T&&... args)
    -> typename std::enable_if<enable, OutputIt>::type {
  return vformat_to(out, loc, detail::to_string_view(fmt),
                    fmt::make_format_args<buffered_context<Char>>(args...));
}

template <typename OutputIt, typename Char, typename... Args,
          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
                            detail::is_exotic_char<Char>::value)>
inline auto vformat_to_n(OutputIt out, size_t n, basic_string_view<Char> fmt,
                         basic_format_args<buffered_context<Char>> args)
    -> format_to_n_result<OutputIt> {
  using traits = detail::fixed_buffer_traits;
  auto buf = detail::iterator_buffer<OutputIt, Char, traits>(out, n);
  detail::vformat_to(buf, fmt, args);
  return {buf.out(), buf.count()};
}

template <typename OutputIt, typename... T,
          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, wchar_t>::value)>
FMT_INLINE auto format_to_n(OutputIt out, size_t n, wformat_string<T...> fmt,
                            T&&... args) -> format_to_n_result<OutputIt> {
  return vformat_to_n(out, n, fmt.get(), fmt::make_wformat_args(args...));
}

template <typename OutputIt, typename S, typename... T,
          typename Char = detail::format_string_char_t<S>,
          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value &&
                        !std::is_same<Char, char>::value &&
                        !std::is_same<Char, wchar_t>::value)>
inline auto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args)
    -> format_to_n_result<OutputIt> {
  return vformat_to_n(out, n, fmt::basic_string_view<Char>(fmt),
                      fmt::make_format_args<buffered_context<Char>>(args...));
}

template <typename S, typename... T,
          typename Char = detail::format_string_char_t<S>,
          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>
inline auto formatted_size(const S& fmt, T&&... args) -> size_t {
  auto buf = detail::counting_buffer<Char>();
  detail::vformat_to(buf, detail::to_string_view(fmt),
                     fmt::make_format_args<buffered_context<Char>>(args...));
  return buf.count();
}

inline void vprint(std::FILE* f, wstring_view fmt, wformat_args args) {
  auto buf = wmemory_buffer();
  detail::vformat_to(buf, fmt, args);
  buf.push_back(L'\0');
  if (std::fputws(buf.data(), f) == -1)
    FMT_THROW(system_error(errno, FMT_STRING("cannot write to file")));
}

inline void vprint(wstring_view fmt, wformat_args args) {
  vprint(stdout, fmt, args);
}

template <typename... T>
void print(std::FILE* f, wformat_string<T...> fmt, T&&... args) {
  return vprint(f, fmt.get(), fmt::make_wformat_args(args...));
}

template <typename... T> void print(wformat_string<T...> fmt, T&&... args) {
  return vprint(fmt.get(), fmt::make_wformat_args(args...));
}

template <typename... T>
void println(std::FILE* f, wformat_string<T...> fmt, T&&... args) {
  return print(f, L"{}\n", fmt::format(fmt, std::forward<T>(args)...));
}

template <typename... T> void println(wformat_string<T...> fmt, T&&... args) {
  return print(L"{}\n", fmt::format(fmt, std::forward<T>(args)...));
}

inline auto vformat(text_style ts, wstring_view fmt, wformat_args args)
    -> std::wstring {
  auto buf = wmemory_buffer();
  detail::vformat_to(buf, ts, fmt, args);
  return {buf.data(), buf.size()};
}

template <typename... T>
inline auto format(text_style ts, wformat_string<T...> fmt, T&&... args)
    -> std::wstring {
  return fmt::vformat(ts, fmt.get(), fmt::make_wformat_args(args...));
}

inline void vprint(std::wostream& os, wstring_view fmt, wformat_args args) {
  auto buffer = basic_memory_buffer<wchar_t>();
  detail::vformat_to(buffer, fmt, args);
  detail::write_buffer(os, buffer);
}

template <typename... T>
void print(std::wostream& os, wformat_string<T...> fmt, T&&... args) {
  vprint(os, fmt.get(),
         fmt::make_format_args<buffered_context<wchar_t>>(args...));
}

template <typename... T>
void println(std::wostream& os, wformat_string<T...> fmt, T&&... args) {
  print(os, L"{}\n", fmt::format(fmt, std::forward<T>(args)...));
}

/// Converts `value` to `std::wstring` using the default format for type `T`.
template <typename T> inline auto to_wstring(const T& value) -> std::wstring {
  return format(FMT_STRING(L"{}"), value);
}
FMT_END_EXPORT
FMT_END_NAMESPACE

#endif  // FMT_XCHAR_H_


import { describe, expect, test } from 'vitest'
import { clearServeError, serveError } from './serve'
import {
  browserLogs,
  editFile,
  isBuild,
  isBundledDev,
  isServe,
  page,
  readFile,
} from '~utils'

const tsconfigLoadErrorRE =
  /(\[TSCONFIG_ERROR\] )*Failed to load tsconfig|JSONError/

describe.runIf(isBuild)('build', () => {
  test('should throw an error on build', () => {
    expect(serveError).toBeTruthy()
    expect(serveError.message).toMatch(tsconfigLoadErrorRE)
    clearServeError() // got expected error, null it here so testsuite does not fail from rethrow in afterAll
  })

  test('should not output files to dist', () => {
    let err
    try {
      readFile('dist/index.html')
    } catch (e) {
      err = e
    }
    expect(err).toBeTruthy()
    expect(err.code).toBe('ENOENT')
  })
})

describe.runIf(isServe)('server', () => {
  test.runIf(!isBundledDev)(
    'should log 500 error in browser for malformed tsconfig',
    () => {
      // don't test for actual complete message as this might be locale dependent. chrome does log 500 consistently though
      expect(browserLogs.find((x) => x.includes('500'))).toBeTruthy()
      expect(browserLogs).not.toContain('tsconfig error fixed, file loaded')
    },
  )

  test.runIf(isBundledDev)(
    'should keep the fallback page for malformed tsconfig',
    async () => {
      // bundled dev does not request modules one by one, so nothing can
      // answer with 500. The first build failed, so the server keeps serving
      // the fallback page with status 200. The error shows up in the overlay
      // instead, which the next test checks.
      expect(
        await page.evaluate(
          () => (globalThis as any).__vite_is_fallback_page__,
        ),
      ).toBe(true)
      expect(browserLogs).not.toContain('tsconfig error fixed, file loaded')
    },
  )

  test('should show error overlay for tsconfig error', async () => {
    const errorOverlay = await page.waitForSelector('vite-error-overlay')
    expect(errorOverlay).toBeTruthy()
    const message = await errorOverlay.$$eval('.message-body', (m) => {
      return m[0].innerHTML
    })
    // use regex with variable filename and position values because they are different on win
    expect(message).toMatch(tsconfigLoadErrorRE)
  })

  // bundled dev: no rebuild after initial-build failure yet (vitejs/vite#23028, rolldown#9598)
  test.skipIf(isBundledDev)(
    'should reload when tsconfig is changed',
    async () => {
      editFile('has-error/tsconfig.json', (content) => {
        return content.replace('"compilerOptions":', '"compilerOptions":{}')
      })
      await expect
        .poll(() => browserLogs)
        .toContain('tsconfig error fixed, file loaded')
    },
  )
})


// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Test strstr and strcasestr hooks.
#include <string>
#include <string.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>

// Windows does not have strcasestr and memmem, so we are not testing them.
#ifdef _WIN32
#define strcasestr strstr
#define memmem(a, b, c, d) true
#endif

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Size < 4) return 0;
  std::string s(reinterpret_cast<const char*>(Data), Size);
  if (strstr(s.c_str(), "FUZZ") &&
      strcasestr(s.c_str(), "aBcD") &&
      memmem(s.data(), s.size(), "kuku", 4)
      ) {
    fprintf(stderr, "BINGO\n");
    exit(1);
  }
  return 0;
}


# <small>nlohmann::basic_json::</small>is_structured

```cpp
constexpr bool is_structured() const noexcept;
```

This function returns `#!cpp true` if and only if the JSON type is structured (array or object).

## Return value

`#!cpp true` if type is structured (array or object), `#!cpp false` otherwise.

## Exception safety

No-throw guarantee: this member function never throws exceptions.

## Complexity

Constant.

## Possible implementation

```cpp
constexpr bool is_structured() const noexcept
{
    return is_array() || is_object();
}
```

## Notes

The term *structured* stems from [RFC 8259](https://tools.ietf.org/html/rfc8259):

> JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and
> arrays).

Note that though strings are containers in C++, they are treated as primitive values in JSON.

## Examples

??? example

    The following code exemplifies `is_structured()` for all JSON types.

    ```cpp
    --8<-- "examples/is_structured.cpp"
    ```

    Output:

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

## See also

- [is_primitive()](is_primitive.md) returns whether JSON value is primitive
- [is_array()](is_array.md) returns whether the value is an array
- [is_object()](is_object.md) returns whether the value is an object

## Version history

- Added in version 1.0.0.


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

using json = nlohmann::json;

int main()
{
    // create a binary vector
    std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE};

    // create a binary JSON value with subtype 42
    json j = json::binary(vec, 42);

    // output type and subtype
    std::cout << "type: " << j.type_name() << ", subtype: " << j.get_binary().subtype() << std::endl;
}


import { displayCount } from './re-export.js'

const button = document.querySelector('.intermediate-file-delete-increment')

const render = () => {
  document.querySelector('.intermediate-file-delete-display').textContent =
    displayCount(Number(button.textContent))
}

render()

button.addEventListener('click', () => {
  button.textContent = `${Number(button.textContent) + 1}`
  render()
})

if (import.meta.hot) import.meta.hot.accept()


// no node: protocol intentionally
// eslint-disable-next-line n/prefer-node-protocol
const fs = require('fs')
// eslint-disable-next-line n/prefer-node-protocol
const path = require('path')

// NOTE: require destructure would error immediately because of how esbuild
// compiles it. There's no way around it as it's direct property access, which
// triggers the Proxy get trap.

// access from default import
try {
  path.join()
} catch (e) {
  console.log('dep-with-builtin-module-cjs', e)
}

// access from function
module.exports.read = () => {
  return fs.readFileSync('test')
}


import { resolve } from 'node:path'
import { describe, expect, test } from 'vitest'
import { loadConfigFromFile } from 'vite'
import { runnerImport } from '../ssr/runnerImport'
import { slash } from '../../shared/utils'

// eslint-disable-next-line n/no-unsupported-features/node-builtins
const isTypeStrippingSupported = !!process.features.typescript

describe('importing files using inlined environment', () => {
  const fixture = (name: string) =>
    resolve(import.meta.dirname, './fixtures/runner-import', name)

  test('importing a basic file works', async () => {
    const { module } = await runnerImport<
      typeof import('./fixtures/runner-import/basic')
    >(fixture('basic'))
    expect(module.test).toEqual({
      field: true,
    })
  })

  test("cannot import cjs, 'runnerImport' doesn't support CJS syntax at all", async () => {
    await expect(() =>
      runnerImport<typeof import('./fixtures/runner-import/basic')>(
        fixture('cjs.js'),
      ),
    ).rejects.toThrow('module is not defined')
  })

  test('can import vite config', async () => {
    const { module, dependencies } = await runnerImport<
      typeof import('./fixtures/runner-import/vite.config')
    >(fixture('vite.config'))
    expect(module.default).toEqual({
      root: './test',
      plugins: [
        {
          name: 'test',
        },
      ],
    })
    expect(dependencies).toEqual([slash(fixture('plugin.ts'))])
  })

  test('can import vite config that imports a TS external module', async () => {
    const { module, dependencies } = await runnerImport<
      typeof import('./fixtures/runner-import/vite.config.outside-pkg-import.mjs')
    >(fixture('vite.config.outside-pkg-import.mts'))

    expect(module.default.__injected).toBe(true)
    expect(dependencies).toEqual([
      slash(resolve(import.meta.dirname, './packages/parent/index.ts')),
    ])

    // confirm that it fails with a bundle approach
    if (!isTypeStrippingSupported) {
      await expect(async () => {
        const root = resolve(import.meta.dirname, './fixtures/runner-import')
        await loadConfigFromFile(
          { mode: 'production', command: 'serve' },
          resolve(root, './vite.config.outside-pkg-import.mts'),
          root,
          'silent',
        )
      }).rejects.toThrow('Unknown file extension ".ts"')
    }
  })

  test('dynamic import', async () => {
    const { module } = await runnerImport<any>(fixture('dynamic-import.ts'))
    await expect(() => module.default()).rejects.toMatchInlineSnapshot(
      `[Error: Vite module runner has been closed.]`,
    )
    // const dep = await module.default();
    // expect(dep.default).toMatchInlineSnapshot(`"ok"`)
  })
})


import path from 'node:path'
import { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping'
import type { EnvironmentModuleGraph } from '..'

let offset: number

function calculateOffsetOnce() {
  if (offset !== undefined) {
    return
  }

  try {
    // `"use strict";` mirrors the directive prepended on its own line by
    // `ESModulesEvaluator`
    new Function('"use strict";\nthrow new Error(1)')()
  } catch (e) {
    // in Node 12, stack traces account for the function wrapper.
    // in Node 13 and later, the function wrapper adds two lines,
    // which must be subtracted to generate a valid mapping
    const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1])
    offset = match ? +match[1] - 1 : 0
  }
}

export function ssrRewriteStacktrace(
  stack: string,
  moduleGraph: EnvironmentModuleGraph,
): { result: string; alreadyRewritten: boolean } {
  calculateOffsetOnce()

  let alreadyRewritten = false
  const rewritten = stack
    .split('\n')
    .map((line) => {
      return line.replace(
        /^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/,
        (input, varName, id, originalLine, originalColumn) => {
          if (!id) return input

          const mod = moduleGraph.getModuleById(id)
          const rawSourceMap = mod?.transformResult?.map

          if (!rawSourceMap) {
            return input
          }

          const traced = new TraceMap(rawSourceMap as any)
          const line = Number(originalLine) - offset
          // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed
          const column = Number(originalColumn) - 1
          if (line <= 0 || column < 0) {
            alreadyRewritten = true
            return input
          }

          const pos = originalPositionFor(traced, { line, column })
          if (!pos.source) {
            return input
          }

          const trimmedVarName = varName?.trim()
          const sourceFile = path.resolve(path.dirname(id), pos.source)
          // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed
          const source = `${sourceFile}:${pos.line}:${pos.column + 1}`
          if (!trimmedVarName || trimmedVarName === 'eval') {
            return `    at ${source}`
          } else {
            return `    at ${trimmedVarName} (${source})`
          }
        },
      )
    })
    .join('\n')
  return { result: rewritten, alreadyRewritten }
}

export function rebindErrorStacktrace(e: Error, stacktrace: string): void {
  const { configurable, writable } = Object.getOwnPropertyDescriptor(
    e,
    'stack',
  )!
  if (configurable) {
    Object.defineProperty(e, 'stack', {
      value: stacktrace,
      enumerable: true,
      configurable: true,
      writable: true,
    })
  } else if (writable) {
    e.stack = stacktrace
  }
}

const rewroteStacktraces = new WeakSet()

export function ssrFixStacktrace(
  e: Error,
  moduleGraph: EnvironmentModuleGraph,
): void {
  if (!e.stack) return
  // stacktrace shouldn't be rewritten more than once
  if (rewroteStacktraces.has(e)) return

  const { result: stacktrace, alreadyRewritten } = ssrRewriteStacktrace(
    e.stack,
    moduleGraph,
  )
  rebindErrorStacktrace(e, stacktrace)
  if (alreadyRewritten) {
    e.message +=
      ' (The stacktrace appears to be already rewritten by something else, but was passed to vite.ssrFixStacktrace. This may cause incorrect stacktraces.)'
  }

  rewroteStacktraces.add(e)
}


/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-unused-vars */
import type { Equal, ExpectTrue } from '@type-challenges/utils'
import {
  type UserConfig,
  type UserConfigExport,
  type UserConfigFn,
  type UserConfigFnObject,
  type UserConfigFnPromise,
  defineConfig,
} from '../config'
import { mergeConfig } from '../utils'

const configObjectDefined = defineConfig({})
const configObjectPromiseDefined = defineConfig(Promise.resolve({}))
const configFnObjectDefined = defineConfig(() => ({}))
const configFnPromiseDefined = defineConfig(async () => ({}))
const configFnDefined = defineConfig(() =>
  // TypeScript requires both non-promise config and
  // promise config to have at least one property
  Math.random() > 0.5 ? { base: '' } : Promise.resolve({ base: '/' }),
)
const configExportDefined = defineConfig({} as UserConfigExport)

export type cases1 = [
  ExpectTrue<Equal<typeof configObjectDefined, UserConfig>>,
  ExpectTrue<Equal<typeof configObjectPromiseDefined, Promise<UserConfig>>>,
  ExpectTrue<Equal<typeof configFnObjectDefined, UserConfigFnObject>>,
  ExpectTrue<Equal<typeof configFnPromiseDefined, UserConfigFnPromise>>,
  ExpectTrue<Equal<typeof configFnDefined, UserConfigFn>>,
  ExpectTrue<Equal<typeof configExportDefined, UserConfigExport>>,
]

defineConfig({
  base: '',
  build: {
    minify: 'oxc', // `as const` is not needed
  },
  server: {
    proxy: {
      '/test': {
        bypass: () => false,
      },
    },
  },
  // @ts-expect-error --- invalid option should error
  unknownProperty: 1,
})

defineConfig(() => ({
  base: '',
  build: {
    minify: 'oxc' as const, // ideally we don't want to require `as const` here
  },
  server: {
    proxy: {
      '/test': {
        bypass: () => false as const, // ideally we don't want to require `as const` here
      },
    },
  },
  unknownProperty: 1, // we cannot catch invalid option for this case, ideally we should
}))

// @ts-expect-error --- nested invalid option `build.unknown` should error
defineConfig(() => ({
  base: '',
  build: {
    unknown: 1,
  },
}))

defineConfig(async () => ({
  base: '',
  build: {
    minify: 'oxc' as const, // ideally we don't want to require `as const` here
  },
  server: {
    proxy: {
      '/test': {
        bypass: () => false as const, // ideally we don't want to require `as const` here
      },
    },
  },
  unknownProperty: 1, // we cannot catch invalid option for this case, ideally we should
}))

// @ts-expect-error --- nested invalid option `build.unknown` should error
defineConfig(async () => ({
  base: '',
  build: {
    unknown: 1,
  },
}))

mergeConfig(defineConfig({}), defineConfig({}))
mergeConfig(
  // @ts-expect-error
  defineConfig(() => ({})),
  defineConfig({}),
)

export {}


//     __ _____ _____ _____
//  __|  |   __|     |   | |  JSON for Modern C++
// |  |  |__   |  |  | | | |  version 3.12.0
// |_____|_____|_____|_|___|  https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2008, 2009 Björn Hoehrmann <bjoern@hoehrmann.de>
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

#pragma once

#include <algorithm> // reverse, remove, fill, find, none_of
#include <array> // array
#include <clocale> // localeconv, lconv
#include <cmath> // labs, isfinite, isnan, signbit
#include <cstddef> // size_t, ptrdiff_t
#include <cstdint> // uint8_t
#include <cstdio> // snprintf
#include <limits> // numeric_limits
#include <string> // string, char_traits
#include <iomanip> // setfill, setw
#include <type_traits> // is_same
#include <utility> // move

#include <nlohmann/detail/conversions/to_chars.hpp>
#include <nlohmann/detail/exceptions.hpp>
#include <nlohmann/detail/macro_scope.hpp>
#include <nlohmann/detail/meta/cpp_future.hpp>
#include <nlohmann/detail/output/binary_writer.hpp>
#include <nlohmann/detail/output/output_adapters.hpp>
#include <nlohmann/detail/string_concat.hpp>
#include <nlohmann/detail/value_t.hpp>

NLOHMANN_JSON_NAMESPACE_BEGIN
namespace detail
{

///////////////////
// serialization //
///////////////////

/// how to treat decoding errors
enum class error_handler_t
{
    strict,  ///< throw a type_error exception in case of invalid UTF-8
    replace, ///< replace invalid UTF-8 sequences with U+FFFD
    ignore   ///< ignore invalid UTF-8 sequences
};

template<typename BasicJsonType>
class serializer
{
    using string_t = typename BasicJsonType::string_t;
    using number_float_t = typename BasicJsonType::number_float_t;
    using number_integer_t = typename BasicJsonType::number_integer_t;
    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
    using binary_char_t = typename BasicJsonType::binary_t::value_type;
    static constexpr std::uint8_t UTF8_ACCEPT = 0;
    static constexpr std::uint8_t UTF8_REJECT = 1;

  public:
    /*!
    @param[in] s  output stream to serialize to
    @param[in] ichar  indentation character to use
    @param[in] error_handler_  how to react on decoding errors
    */
    serializer(output_adapter_t<char> s, const char ichar,
               error_handler_t error_handler_ = error_handler_t::strict)
        : o(std::move(s))
        , loc(std::localeconv())
        , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->thousands_sep)))
        , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->decimal_point)))
        , indent_char(ichar)
        , indent_string(512, indent_char)
        , error_handler(error_handler_)
    {}

    // deleted because of pointer members
    serializer(const serializer&) = delete;
    serializer& operator=(const serializer&) = delete;
    serializer(serializer&&) = delete;
    serializer& operator=(serializer&&) = delete;
    ~serializer() = default;

    /*!
    @brief internal implementation of the serialization function

    This function is called by the public member function dump and organizes
    the serialization internally. The indentation level is propagated as
    additional parameter. In case of arrays and objects, the function is
    called recursively.

    - strings and object keys are escaped using `escape_string()`
    - integer numbers are converted implicitly via `operator<<`
    - floating-point numbers are converted to a string using `"%g"` format
    - binary values are serialized as objects containing the subtype and the
      byte array

    @param[in] val               value to serialize
    @param[in] pretty_print      whether the output shall be pretty-printed
    @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
    in the output are escaped with `\uXXXX` sequences, and the result consists
    of ASCII characters only.
    @param[in] indent_step       the indent level
    @param[in] current_indent    the current indent level (only used internally)
    */
    void dump(const BasicJsonType& val,
              const bool pretty_print,
              const bool ensure_ascii,
              const unsigned int indent_step,
              const unsigned int current_indent = 0)
    {
        switch (val.m_data.m_type)
        {
            case value_t::object:
            {
                if (val.m_data.m_value.object->empty())
                {
                    o->write_characters("{}", 2);
                    return;
                }

                if (pretty_print)
                {
                    o->write_characters("{\n", 2);

                    // variable to hold indentation for recursive calls
                    const auto new_indent = current_indent + indent_step;
                    if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
                    {
                        indent_string.resize(indent_string.size() * 2, ' ');
                    }

                    // first n-1 elements
                    auto i = val.m_data.m_value.object->cbegin();
                    for (std::size_t cnt = 0; cnt < val.m_data.m_value.object->size() - 1; ++cnt, ++i)
                    {
                        o->write_characters(indent_string.c_str(), new_indent);
                        o->write_character('\"');
                        dump_escaped(i->first, ensure_ascii);
                        o->write_characters("\": ", 3);
                        dump(i->second, true, ensure_ascii, indent_step, new_indent);
                        o->write_characters(",\n", 2);
                    }

                    // last element
                    JSON_ASSERT(i != val.m_data.m_value.object->cend());
                    JSON_ASSERT(std::next(i) == val.m_data.m_value.object->cend());
                    o->write_characters(indent_string.c_str(), new_indent);
                    o->write_character('\"');
                    dump_escaped(i->first, ensure_ascii);
                    o->write_characters("\": ", 3);
                    dump(i->second, true, ensure_ascii, indent_step, new_indent);

                    o->write_character('\n');
                    o->write_characters(indent_string.c_str(), current_indent);
                    o->write_character('}');
                }
                else
                {
                    o->write_character('{');

                    // first n-1 elements
                    auto i = val.m_data.m_value.object->cbegin();
                    for (std::size_t cnt = 0; cnt < val.m_data.m_value.object->size() - 1; ++cnt, ++i)
                    {
                        o->write_character('\"');
                        dump_escaped(i->first, ensure_ascii);
                        o->write_characters("\":", 2);
                        dump(i->second, false, ensure_ascii, indent_step, current_indent);
                        o->write_character(',');
                    }

                    // last element
                    JSON_ASSERT(i != val.m_data.m_value.object->cend());
                    JSON_ASSERT(std::next(i) == val.m_data.m_value.object->cend());
                    o->write_character('\"');
                    dump_escaped(i->first, ensure_ascii);
                    o->write_characters("\":", 2);
                    dump(i->second, false, ensure_ascii, indent_step, current_indent);

                    o->write_character('}');
                }

                return;
            }

            case value_t::array:
            {
                if (val.m_data.m_value.array->empty())
                {
                    o->write_characters("[]", 2);
                    return;
                }

                if (pretty_print)
                {
                    o->write_characters("[\n", 2);

                    // variable to hold indentation for recursive calls
                    const auto new_indent = current_indent + indent_step;
                    if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
                    {
                        indent_string.resize(indent_string.size() * 2, ' ');
                    }

                    // first n-1 elements
                    for (auto i = val.m_data.m_value.array->cbegin();
                            i != val.m_data.m_value.array->cend() - 1; ++i)
                    {
                        o->write_characters(indent_string.c_str(), new_indent);
                        dump(*i, true, ensure_ascii, indent_step, new_indent);
                        o->write_characters(",\n", 2);
                    }

                    // last element
                    JSON_ASSERT(!val.m_data.m_value.array->empty());
                    o->write_characters(indent_string.c_str(), new_indent);
                    dump(val.m_data.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);

                    o->write_character('\n');
                    o->write_characters(indent_string.c_str(), current_indent);
                    o->write_character(']');
                }
                else
                {
                    o->write_character('[');

                    // first n-1 elements
                    for (auto i = val.m_data.m_value.array->cbegin();
                            i != val.m_data.m_value.array->cend() - 1; ++i)
                    {
                        dump(*i, false, ensure_ascii, indent_step, current_indent);
                        o->write_character(',');
                    }

                    // last element
                    JSON_ASSERT(!val.m_data.m_value.array->empty());
                    dump(val.m_data.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);

                    o->write_character(']');
                }

                return;
            }

            case value_t::string:
            {
                o->write_character('\"');
                dump_escaped(*val.m_data.m_value.string, ensure_ascii);
                o->write_character('\"');
                return;
            }

            case value_t::binary:
            {
                if (pretty_print)
                {
                    o->write_characters("{\n", 2);

                    // variable to hold indentation for recursive calls
                    const auto new_indent = current_indent + indent_step;
                    if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
                    {
                        indent_string.resize(indent_string.size() * 2, ' ');
                    }

                    o->write_characters(indent_string.c_str(), new_indent);

                    o->write_characters("\"bytes\": [", 10);

                    if (!val.m_data.m_value.binary->empty())
                    {
                        for (auto i = val.m_data.m_value.binary->cbegin();
                                i != val.m_data.m_value.binary->cend() - 1; ++i)
                        {
                            dump_integer(*i);
                            o->write_characters(", ", 2);
                        }
                        dump_integer(val.m_data.m_value.binary->back());
                    }

                    o->write_characters("],\n", 3);
                    o->write_characters(indent_string.c_str(), new_indent);

                    o->write_characters("\"subtype\": ", 11);
                    if (val.m_data.m_value.binary->has_subtype())
                    {
                        dump_integer(val.m_data.m_value.binary->subtype());
                    }
                    else
                    {
                        o->write_characters("null", 4);
                    }
                    o->write_character('\n');
                    o->write_characters(indent_string.c_str(), current_indent);
                    o->write_character('}');
                }
                else
                {
                    o->write_characters("{\"bytes\":[", 10);

                    if (!val.m_data.m_value.binary->empty())
                    {
                        for (auto i = val.m_data.m_value.binary->cbegin();
                                i != val.m_data.m_value.binary->cend() - 1; ++i)
                        {
                            dump_integer(*i);
                            o->write_character(',');
                        }
                        dump_integer(val.m_data.m_value.binary->back());
                    }

                    o->write_characters("],\"subtype\":", 12);
                    if (val.m_data.m_value.binary->has_subtype())
                    {
                        dump_integer(val.m_data.m_value.binary->subtype());
                        o->write_character('}');
                    }
                    else
                    {
                        o->write_characters("null}", 5);
                    }
                }
                return;
            }

            case value_t::boolean:
            {
                if (val.m_data.m_value.boolean)
                {
                    o->write_characters("true", 4);
                }
                else
                {
                    o->write_characters("false", 5);
                }
                return;
            }

            case value_t::number_integer:
            {
                dump_integer(val.m_data.m_value.number_integer);
                return;
            }

            case value_t::number_unsigned:
            {
                dump_integer(val.m_data.m_value.number_unsigned);
                return;
            }

            case value_t::number_float:
            {
                dump_float(val.m_data.m_value.number_float);
                return;
            }

            case value_t::discarded:
            {
                o->write_characters("<discarded>", 11);
                return;
            }

            case value_t::null:
            {
                o->write_characters("null", 4);
                return;
            }

            default:            // LCOV_EXCL_LINE
                JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
        }
    }

  JSON_PRIVATE_UNLESS_TESTED:
    /*!
    @brief dump escaped string

    Escape a string by replacing certain special characters by a sequence of an
    escape character (backslash) and another character and other control
    characters by a sequence of "\u" followed by a four-digit hex
    representation. The escaped string is written to output stream @a o.

    @param[in] s  the string to escape
    @param[in] ensure_ascii  whether to escape non-ASCII characters with
                             \uXXXX sequences

    @complexity Linear in the length of string @a s.
    */
    void dump_escaped(const string_t& s, const bool ensure_ascii)
    {
        std::uint32_t codepoint{};
        std::uint8_t state = UTF8_ACCEPT;
        std::size_t bytes = 0;  // number of bytes written to string_buffer

        // number of bytes written at the point of the last valid byte
        std::size_t bytes_after_last_accept = 0;
        std::size_t undumped_chars = 0;

        for (std::size_t i = 0; i < s.size(); ++i)
        {
            const auto byte = static_cast<std::uint8_t>(s[i]);

            switch (decode(state, codepoint, byte))
            {
                case UTF8_ACCEPT:  // decode found a new code point
                {
                    switch (codepoint)
                    {
                        case 0x08: // backspace
                        {
                            string_buffer[bytes++] = '\\';
                            string_buffer[bytes++] = 'b';
                            break;
                        }

                        case 0x09: // horizontal tab
                        {
                            string_buffer[bytes++] = '\\';
                            string_buffer[bytes++] = 't';
                            break;
                        }

                        case 0x0A: // newline
                        {
                            string_buffer[bytes++] = '\\';
                            string_buffer[bytes++] = 'n';
                            break;
                        }

                        case 0x0C: // formfeed
                        {
                            string_buffer[bytes++] = '\\';
                            string_buffer[bytes++] = 'f';
                            break;
                        }

                        case 0x0D: // carriage return
                        {
                            string_buffer[bytes++] = '\\';
                            string_buffer[bytes++] = 'r';
                            break;
                        }

                        case 0x22: // quotation mark
                        {
                            string_buffer[bytes++] = '\\';
                            string_buffer[bytes++] = '\"';
                            break;
                        }

                        case 0x5C: // reverse solidus
                        {
                            string_buffer[bytes++] = '\\';
                            string_buffer[bytes++] = '\\';
                            break;
                        }

                        default:
                        {
                            // escape control characters (0x00..0x1F) or, if
                            // ensure_ascii parameter is used, non-ASCII characters
                            if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F)))
                            {
                                if (codepoint <= 0xFFFF)
                                {
                                    write_u_escape(bytes, static_cast<std::uint16_t>(codepoint));
                                }
                                else
                                {
                                    write_u_escape(bytes, static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)));
                                    write_u_escape(bytes, static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
                                }
                            }
                            else
                            {
                                // copy byte to buffer (all previous bytes
                                // been copied have in default case above)
                                string_buffer[bytes++] = s[i];
                            }
                            break;
                        }
                    }

                    // write buffer and reset index; there must be 13 bytes
                    // left, as this is the maximal number of bytes to be
                    // written ("\uxxxx\uxxxx\0") for one code point
                    if (string_buffer.size() - bytes < 13)
                    {
                        o->write_characters(string_buffer.data(), bytes);
                        bytes = 0;
                    }

                    // remember the byte position of this accept
                    bytes_after_last_accept = bytes;
                    undumped_chars = 0;
                    break;
                }

                case UTF8_REJECT:  // decode found invalid UTF-8 byte
                {
                    switch (error_handler)
                    {
                        case error_handler_t::strict:
                        {
                            JSON_THROW(type_error::create(316, concat("invalid UTF-8 byte at index ", std::to_string(i), ": 0x", hex_bytes(byte | 0)), nullptr));
                        }

                        case error_handler_t::ignore:
                        case error_handler_t::replace:
                        {
                            // in case we saw this character the first time, we
                            // would like to read it again, because the byte
                            // may be OK for itself, but just not OK for the
                            // previous sequence
                            if (undumped_chars > 0)
                            {
                                --i;
                            }

                            // reset length buffer to the last accepted index;
                            // thus removing/ignoring the invalid characters
                            bytes = bytes_after_last_accept;

                            if (error_handler == error_handler_t::replace)
                            {
                                // add a replacement character
                                if (ensure_ascii)
                                {
                                    string_buffer[bytes++] = '\\';
                                    string_buffer[bytes++] = 'u';
                                    string_buffer[bytes++] = 'f';
                                    string_buffer[bytes++] = 'f';
                                    string_buffer[bytes++] = 'f';
                                    string_buffer[bytes++] = 'd';
                                }
                                else
                                {
                                    string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
                                    string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
                                    string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
                                }

                                // write buffer and reset index; there must be 13 bytes
                                // left, as this is the maximal number of bytes to be
                                // written ("\uxxxx\uxxxx\0") for one code point
                                if (string_buffer.size() - bytes < 13)
                                {
                                    o->write_characters(string_buffer.data(), bytes);
                                    bytes = 0;
                                }

                                bytes_after_last_accept = bytes;
                            }

                            undumped_chars = 0;

                            // continue processing the string
                            state = UTF8_ACCEPT;
                            break;
                        }

                        default:            // LCOV_EXCL_LINE
                            JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
                    }
                    break;
                }

                default:  // decode found yet incomplete multibyte code point
                {
                    if (!ensure_ascii)
                    {
                        // code point will not be escaped - copy byte to buffer
                        string_buffer[bytes++] = s[i];
                    }
                    ++undumped_chars;
                    break;
                }
            }
        }

        // we finished processing the string
        if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
        {
            // write buffer
            if (bytes > 0)
            {
                o->write_characters(string_buffer.data(), bytes);
            }
        }
        else
        {
            // we finish reading, but do not accept: string was incomplete
            switch (error_handler)
            {
                case error_handler_t::strict:
                {
                    JSON_THROW(type_error::create(316, concat("incomplete UTF-8 string; last byte: 0x", hex_bytes(static_cast<std::uint8_t>(s.back() | 0))), nullptr));
                }

                case error_handler_t::ignore:
                {
                    // write all accepted bytes
                    o->write_characters(string_buffer.data(), bytes_after_last_accept);
                    break;
                }

                case error_handler_t::replace:
                {
                    // write all accepted bytes
                    o->write_characters(string_buffer.data(), bytes_after_last_accept);
                    // add a replacement character
                    if (ensure_ascii)
                    {
                        o->write_characters("\\ufffd", 6);
                    }
                    else
                    {
                        o->write_characters("\xEF\xBF\xBD", 3);
                    }
                    break;
                }

                default:            // LCOV_EXCL_LINE
                    JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
            }
        }
    }

  private:
    /*!
    @brief count digits

    Count the number of decimal (base 10) digits for an input unsigned integer.

    @param[in] x  unsigned integer number to count its digits
    @return    number of decimal digits
    */
    unsigned int count_digits(number_unsigned_t x) noexcept
    {
        unsigned int n_digits = 1;
        for (;;)
        {
            if (x < 10)
            {
                return n_digits;
            }
            if (x < 100)
            {
                return n_digits + 1;
            }
            if (x < 1000)
            {
                return n_digits + 2;
            }
            if (x < 10000)
            {
                return n_digits + 3;
            }
            x = x / 10000u;
            n_digits += 4;
        }
    }

    /*!
     * @brief convert a byte to a uppercase hex representation
     * @param[in] byte byte to represent
     * @return representation ("00".."FF")
     */
    static std::string hex_bytes(std::uint8_t byte)
    {
        std::string result = "FF";
        constexpr const char* nibble_to_hex = "0123456789ABCDEF";
        result[0] = nibble_to_hex[byte / 16];
        result[1] = nibble_to_hex[byte % 16];
        return result;
    }

    /*!
     * @brief write a lowercase "\uXXXX" escape sequence into @a string_buffer
     *
     * Branch-free replacement for `snprintf(buf, 7, "\\u%04x", codeunit)` in the
     * string escaping hot path. It writes exactly six characters ('\\', 'u' and
     * four hex digits) at position @a pos of @a string_buffer via a nibble
     * lookup table, avoiding the format-string parsing and locale machinery of
     * `snprintf`. Advances @a pos by the number of bytes written (6).
     *
     * @param[in] pos       position in @a string_buffer to write at; there must
     *                      be at least 6 bytes of headroom
     * @param[in] codeunit  16-bit value to encode
     */
    void write_u_escape(std::size_t& pos, std::uint16_t codeunit) noexcept
    {
        JSON_ASSERT(string_buffer.size() - pos >= 6);
        constexpr const char* nibble_to_hex = "0123456789abcdef";
        string_buffer[pos + 0] = '\\';
        string_buffer[pos + 1] = 'u';
        string_buffer[pos + 2] = nibble_to_hex[(codeunit >> 12u) & 0x0Fu];
        string_buffer[pos + 3] = nibble_to_hex[(codeunit >> 8u) & 0x0Fu];
        string_buffer[pos + 4] = nibble_to_hex[(codeunit >> 4u) & 0x0Fu];
        string_buffer[pos + 5] = nibble_to_hex[codeunit & 0x0Fu];
        pos += 6;
    }

    // templates to avoid warnings about useless casts
    template <typename NumberType, enable_if_t<std::is_signed<NumberType>::value, int> = 0>
    bool is_negative_number(NumberType x)
    {
        return x < 0;
    }

    template < typename NumberType, enable_if_t <std::is_unsigned<NumberType>::value, int > = 0 >
    bool is_negative_number(NumberType /*unused*/)
    {
        return false;
    }

    /*!
    @brief dump an integer

    Dump a given integer to output stream @a o. Works internally with
    @a number_buffer.

    @param[in] x  integer number (signed or unsigned) to dump
    @tparam NumberType either @a number_integer_t or @a number_unsigned_t
    */
    template < typename NumberType, detail::enable_if_t <
                   std::is_integral<NumberType>::value ||
                   std::is_same<NumberType, number_unsigned_t>::value ||
                   std::is_same<NumberType, number_integer_t>::value ||
                   std::is_same<NumberType, binary_char_t>::value,
                   int > = 0 >
    void dump_integer(NumberType x)
    {
        static constexpr std::array<std::array<char, 2>, 100> digits_to_99
        {
            {
                {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
                {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
                {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
                {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
                {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
                {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
                {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
                {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
                {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
                {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
            }
        };

        // special case for "0"
        if (x == 0)
        {
            o->write_character('0');
            return;
        }

        // use a pointer to fill the buffer
        auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg)

        number_unsigned_t abs_value;

        unsigned int n_chars{};

        if (is_negative_number(x))
        {
            *buffer_ptr = '-';
            abs_value = remove_sign(static_cast<number_integer_t>(x));

            // account one more byte for the minus sign
            n_chars = 1 + count_digits(abs_value);
        }
        else
        {
            abs_value = static_cast<number_unsigned_t>(x);
            n_chars = count_digits(abs_value);
        }

        // spare 1 byte for '\0'
        JSON_ASSERT(n_chars < number_buffer.size() - 1);

        // jump to the end to generate the string from backward,
        // so we later avoid reversing the result
        buffer_ptr += static_cast<typename decltype(number_buffer)::difference_type>(n_chars);

        // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
        // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
        while (abs_value >= 100)
        {
            const auto digits_index = static_cast<unsigned>((abs_value % 100));
            abs_value /= 100;
            *(--buffer_ptr) = digits_to_99[digits_index][1];
            *(--buffer_ptr) = digits_to_99[digits_index][0];
        }

        if (abs_value >= 10)
        {
            const auto digits_index = static_cast<unsigned>(abs_value);
            *(--buffer_ptr) = digits_to_99[digits_index][1];
            *(--buffer_ptr) = digits_to_99[digits_index][0];
        }
        else
        {
            *(--buffer_ptr) = static_cast<char>('0' + abs_value);
        }

        o->write_characters(number_buffer.data(), n_chars);
    }

    /*!
    @brief dump a floating-point number

    Dump a given floating-point number to output stream @a o. Works internally
    with @a number_buffer.

    @param[in] x  floating-point number to dump
    */
    void dump_float(number_float_t x)
    {
        // NaN / inf
        if (!std::isfinite(x))
        {
            o->write_characters("null", 4);
            return;
        }

        // If number_float_t is an IEEE-754 single or double precision number,
        // use the Grisu2 algorithm to produce short numbers which are
        // guaranteed to round-trip, using strtof and strtod, resp.
        //
        // NB: The test below works if <long double> == <double>.
        static constexpr bool is_ieee_single_or_double
            = (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128) ||
              (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024);

        dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
    }

    void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
    {
        auto* begin = number_buffer.data();
        auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);

        o->write_characters(begin, static_cast<size_t>(end - begin));
    }

    JSON_HEDLEY_NON_NULL(1)
    static int snprintf_float(char* buf, std::size_t size, int d, double x)
    {
        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
        return (std::snprintf)(buf, size, "%.*g", d, x);
    }

    JSON_HEDLEY_NON_NULL(1)
    static int snprintf_float(char* buf, std::size_t size, int d, long double x)
    {
        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
        return (std::snprintf)(buf, size, "%.*Lg", d, x);
    }

    void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
    {
        // get the number of digits for a float -> text -> float round-trip
        static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;

        // the actual conversion
        std::ptrdiff_t len = snprintf_float(number_buffer.data(), number_buffer.size(), d, x);

        // negative value indicates an error
        JSON_ASSERT(len > 0);
        // check if the buffer was large enough
        JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size());

        // erase thousands separators
        if (thousands_sep != '\0')
        {
            // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081
            const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep);
            std::fill(end, number_buffer.end(), '\0');
            JSON_ASSERT((end - number_buffer.begin()) <= len);
            len = (end - number_buffer.begin());
        }

        // convert decimal point to '.'
        if (decimal_point != '\0' && decimal_point != '.')
        {
            // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081
            const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
            if (dec_pos != number_buffer.end())
            {
                *dec_pos = '.';
            }
        }

        o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));

        // determine if we need to append ".0"
        const bool value_is_int_like =
            std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
                         [](char c)
        {
            return c == '.' || c == 'e';
        });

        if (value_is_int_like)
        {
            o->write_characters(".0", 2);
        }
    }

    /*!
    @brief check whether a string is UTF-8 encoded

    The function checks each byte of a string whether it is UTF-8 encoded. The
    result of the check is stored in the @a state parameter. The function must
    be called initially with state 0 (accept). State 1 means the string must
    be rejected, because the current byte is not allowed. If the string is
    completely processed, but the state is non-zero, the string ended
    prematurely; that is, the last byte indicated more bytes should have
    followed.

    @param[in,out] state  the state of the decoding
    @param[in,out] codep  codepoint (valid only if resulting state is UTF8_ACCEPT)
    @param[in] byte       next byte to decode
    @return               new state

    @note The function has been edited: a std::array is used.

    @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
    @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
    */
    static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
    {
        static const std::array<std::uint8_t, 400> utf8d =
        {
            {
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F
                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F
                7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF
                8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF
                0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
                0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
                0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2
                1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4
                1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6
                1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8
            }
        };

        JSON_ASSERT(static_cast<std::size_t>(byte) < utf8d.size());
        const std::uint8_t type = utf8d[byte];

        codep = (state != UTF8_ACCEPT)
                ? (byte & 0x3fu) | (codep << 6u)
                : (0xFFu >> type) & (byte);

        const std::size_t index = 256u + (static_cast<size_t>(state) * 16u) + static_cast<size_t>(type);
        JSON_ASSERT(index < utf8d.size());
        state = utf8d[index];
        return state;
    }

    /*
     * Overload to make the compiler happy while it is instantiating
     * dump_integer for number_unsigned_t.
     * Must never be called.
     */
    number_unsigned_t remove_sign(number_unsigned_t x)
    {
        JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
        return x; // LCOV_EXCL_LINE
    }

    /*
     * Helper function for dump_integer
     *
     * This function takes a negative signed integer and returns its absolute
     * value as an unsigned integer. The plus/minus shuffling is necessary as we
     * cannot directly remove the sign of an arbitrary signed integer as the
     * absolute values of INT_MIN and INT_MAX are usually not the same. See
     * #1708 for details.
     */
    number_unsigned_t remove_sign(number_integer_t x) noexcept
    {
        JSON_ASSERT(x < 0 && x < (std::numeric_limits<number_integer_t>::max)()); // NOLINT(misc-redundant-expression)
        return static_cast<number_unsigned_t>(-(x + 1)) + 1;
    }

  private:
    /// the output of the serializer
    output_adapter_t<char> o = nullptr;

    /// a (hopefully) large enough character buffer
    std::array<char, 64> number_buffer{{}};

    /// the locale
    const std::lconv* loc = nullptr;
    /// the locale's thousand separator character
    const char thousands_sep = '\0';
    /// the locale's decimal point character
    const char decimal_point = '\0';

    /// string buffer
    std::array<char, 512> string_buffer{{}};

    /// the indentation character
    const char indent_char;
    /// the indentation string
    string_t indent_string;

    /// error_handler how to react on decoding errors
    const error_handler_t error_handler;
};

}  // namespace detail
NLOHMANN_JSON_NAMESPACE_END


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

using json = nlohmann::json;

int main()
{
    // create JSON values
    json j_object = {{"one", 1}, {"two", 2}};
    json j_array = {1, 2, 4, 8, 16};

    // serialize without indentation
    std::cout << j_object << "\n\n";
    std::cout << j_array << "\n\n";

    // serialize with indentation
    std::cout << std::setw(4) << j_object << "\n\n";
    std::cout << std::setw(2) << j_array << "\n\n";
    std::cout << std::setw(1) << std::setfill('\t') << j_object << "\n\n";
}


use proc_macro2::{Group, Span, TokenStream, TokenTree};

pub(crate) fn respan(stream: TokenStream, span: Span) -> TokenStream {
    stream
        .into_iter()
        .map(|token| respan_token(token, span))
        .collect()
}

fn respan_token(mut token: TokenTree, span: Span) -> TokenTree {
    if let TokenTree::Group(g) = &mut token {
        *g = Group::new(g.delimiter(), respan(g.stream(), span));
    }
    token.set_span(span);
    token
}


from werkzeug.routing import BaseConverter

from flask import request
from flask import session
from flask import url_for

def test_custom_converters(app, client):
    class ListConverter(BaseConverter):
        def to_python(self, value):
            return value.split(",")

        def to_url(self, value):
            base_to_url = super().to_url
            return ",".join(base_to_url(x) for x in value)

    app.url_map.converters["list"] = ListConverter

    @app.route("/<list:args>")
    def index(args):
        return "|".join(args)

    assert client.get("/1,2,3").data == b"1|2|3"

    with app.test_request_context():
        assert url_for("index", args=[4, 5, 6]) == "/4,5,6"

def test_context_available(app, client):
    class ContextConverter(BaseConverter):
        def to_python(self, value):
            assert request is not None
            assert session is not None
            return value

    app.url_map.converters["ctx"] = ContextConverter

    @app.get("/<ctx:name>")
    def index(name):
        return name

    assert client.get("/admin").data == b"admin"


// @ts-check
import path from 'node:path'
import pug from 'pug'
import express from 'express'

const isTest = process.env.VITEST

const DYNAMIC_SCRIPTS = `
  <script type="module">
    const p = document.createElement('p');
    p.innerHTML = '✅ Dynamically injected inline script';
    document.body.appendChild(p);
  </script>
  <script type="module" src="/src/app.js"></script>
`

export async function createServer(root = process.cwd(), hmrPort) {
  const resolve = (p) => path.resolve(import.meta.dirname, p)

  const app = express()

  /**
   * @type {import('vite').ViteDevServer}
   */
  const vite = await (
    await import('vite')
  ).createServer({
    root,
    logLevel: isTest ? 'error' : 'info',
    server: {
      middlewareMode: true,
      watch: {
        // During tests we edit the files too fast and sometimes chokidar
        // misses change events, so enforce polling for consistency
        usePolling: true,
        interval: 100,
      },
      hmr: {
        port: hmrPort,
      },
    },
    appType: 'custom',
  })
  // use vite's connect instance as middleware
  app.use(vite.middlewares)

  app.use('*all', async (req, res) => {
    try {
      let [url] = req.originalUrl.split('?')
      url = url.replace(/\.html$/, '.pug')
      if (url.endsWith('/')) url += 'index.pug'

      const htmlLoc = resolve(`.${url}`)
      let html = pug.renderFile(htmlLoc)
      html = html.replace('</body>', `${DYNAMIC_SCRIPTS}</body>`)
      html = await vite.transformIndexHtml(url, html)

      res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
    } catch (e) {
      vite && vite.ssrFixStacktrace(e)
      console.log(e.stack)
      res.status(500).end(e.stack)
    }
  })

  return { app, vite }
}

if (!isTest) {
  createServer().then(({ app }) =>
    app.listen(5173, () => {
      console.log('http://localhost:5173')
    }),
  )
}


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

using json = nlohmann::json;

int main()
{
    // create a JSON value
    json j = {{"one", 1}, {"two", 2}};

    // format_as() is found via argument-dependent lookup, the same way
    // fmt::format/fmt::print would find it
    auto j_str = format_as(j);

    std::cout << j_str << std::endl;
}


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

using json = nlohmann::json;

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

    // call is_primitive()
    std::cout << std::boolalpha;
    std::cout << j_null.is_primitive() << '\n';
    std::cout << j_boolean.is_primitive() << '\n';
    std::cout << j_number_integer.is_primitive() << '\n';
    std::cout << j_number_unsigned_integer.is_primitive() << '\n';
    std::cout << j_number_float.is_primitive() << '\n';
    std::cout << j_object.is_primitive() << '\n';
    std::cout << j_array.is_primitive() << '\n';
    std::cout << j_string.is_primitive() << '\n';
    std::cout << j_binary.is_primitive() << '\n';
}