/*!
Provides completions for ripgrep's CLI for PowerShell.
*/

use crate::flags::defs::FLAGS;

const TEMPLATE: &'static str = "
using namespace System.Management.Automation
using namespace System.Management.Automation.Language

Register-ArgumentCompleter -Native -CommandName 'rg' -ScriptBlock {
  param($wordToComplete, $commandAst, $cursorPosition)
  $commandElements = $commandAst.CommandElements
  $command = @(
    'rg'
    for ($i = 1; $i -lt $commandElements.Count; $i++) {
        $element = $commandElements[$i]
        if ($element -isnot [StringConstantExpressionAst] -or
            $element.StringConstantType -ne [StringConstantType]::BareWord -or
            $element.Value.StartsWith('-')) {
            break
    }
    $element.Value
  }) -join ';'

  $completions = @(switch ($command) {
    'rg' {
!FLAGS!
    }
  })

  $completions.Where{ $_.CompletionText -like \"$wordToComplete*\" } |
    Sort-Object -Property ListItemText
}
";

const TEMPLATE_FLAG: &'static str = "[CompletionResult]::new('!DASH_NAME!', '!NAME!', [CompletionResultType]::ParameterName, '!DOC!')";

/// Generate completions for PowerShell.
///
/// Note that these completions are based on what was produced for ripgrep <=13
/// using Clap 2.x. Improvements on this are welcome.
pub(crate) fn generate() -> String {
    let mut flags = String::new();
    for (i, flag) in FLAGS.iter().enumerate() {
        let doc = flag.doc_short().replace("'", "''");

        let dash_name = format!("--{}", flag.name_long());
        let name = flag.name_long();
        if i > 0 {
            flags.push('\n');
        }
        flags.push_str("      ");
        flags.push_str(
            &TEMPLATE_FLAG
                .replace("!DASH_NAME!", &dash_name)
                .replace("!NAME!", &name)
                .replace("!DOC!", &doc),
        );

        if let Some(byte) = flag.name_short() {
            let dash_name = format!("-{}", char::from(byte));
            let name = char::from(byte).to_string();
            flags.push_str("\n      ");
            flags.push_str(
                &TEMPLATE_FLAG
                    .replace("!DASH_NAME!", &dash_name)
                    .replace("!NAME!", &name)
                    .replace("!DOC!", &doc),
            );
        }

        if let Some(negated) = flag.name_negated() {
            let dash_name = format!("--{negated}");
            flags.push_str("\n      ");
            flags.push_str(
                &TEMPLATE_FLAG
                    .replace("!DASH_NAME!", &dash_name)
                    .replace("!NAME!", &negated)
                    .replace("!DOC!", &doc),
            );
        }
    }
    TEMPLATE.trim_start().replace("!FLAGS!", &flags)
}


import { expect, test } from 'vitest'
import { getAdditionalAllowedHosts } from '../hostCheck'

test('getAdditionalAllowedHosts', async () => {
  const actual = getAdditionalAllowedHosts(
    {
      host: 'vite.host.example.com',
      ws: {
        host: 'vite.hmr-host.example.com',
      },
      origin: 'http://vite.origin.example.com:5173',
    },
    {
      host: 'vite.preview-host.example.com',
    },
  ).sort()
  expect(actual).toStrictEqual(
    [
      'vite.host.example.com',
      'vite.hmr-host.example.com',
      'vite.origin.example.com',
      'vite.preview-host.example.com',
    ].sort(),
  )
})


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

#include <iomanip>
#include <locale>
#include <vector>

#include "fmt/chrono.h"
#include "gmock/gmock.h"
#include "util.h"  // get_locale

using testing::Contains;

TEST(unicode_test, use_utf8) { EXPECT_TRUE(fmt::detail::use_utf8); }

TEST(unicode_test, legacy_locale) {
  auto loc = get_locale("be_BY.CP1251", "Belarusian_Belarus.1251");
  if (loc == std::locale::classic()) return;

  auto s = std::string();
  try {
    s = fmt::format(loc, "Дзень тыдня: {:L}", fmt::weekday(1));
  } catch (const fmt::format_error& e) {
    // Formatting can fail due to an unsupported encoding.
    fmt::print("Format error: {}\n", e.what());
    return;
  }

#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 500
  auto&& os = std::ostringstream();
  os.imbue(loc);
  auto tm = std::tm();
  tm.tm_wday = 1;
  os << std::put_time(&tm, "%a");
  auto wd = os.str();
  if (wd == "??") {
    EXPECT_EQ(s, "Дзень тыдня: ??");
    fmt::print("std::locale gives ?? as a weekday.\n");
    return;
  }
#endif
  EXPECT_THAT((std::vector<std::string>{"Дзень тыдня: пн", "Дзень тыдня: Пан"}),
              Contains(s));
}


import path from 'node:path'
import legacy from '@vitejs/plugin-legacy'
import { defineConfig } from 'vite'

export default defineConfig(({ isPreview }) => ({
  input: {
    index: path.resolve(import.meta.dirname, 'no-polyfills-no-systemjs.html'),
  },
  base: !isPreview ? './' : '/no-polyfills-no-systemjs/',
  plugins: [
    legacy({
      renderModernChunks: false,
      polyfills: false,
      externalSystemJS: true,
    }),
    {
      name: 'remove crossorigin attribute',
      transformIndexHtml: (html) => html.replaceAll('crossorigin', ''),
      enforce: 'post',
    },
  ],
  build: {
    outDir: 'dist/no-polyfills-no-systemjs',
  },
}))


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

#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
#define INCLUDE_NLOHMANN_JSON_FWD_HPP_

#include <cstdint> // int64_t, uint64_t
#include <map> // map
#include <memory> // allocator
#include <string> // string
#include <vector> // vector

#include <nlohmann/detail/abi_macros.hpp>

/*!
@brief namespace for Niels Lohmann
@see https://github.com/nlohmann
@since version 1.0.0
*/
NLOHMANN_JSON_NAMESPACE_BEGIN

/*!
@brief default JSONSerializer template argument

This serializer ignores the template arguments and uses ADL
([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
for serialization.
*/
template<typename T = void, typename SFINAE = void>
struct adl_serializer;

/// a class to store JSON values
/// @sa https://json.nlohmann.me/api/basic_json/
template<template<typename U, typename V, typename... Args> class ObjectType =
         std::map,
         template<typename U, typename... Args> class ArrayType = std::vector,
         class StringType = std::string, class BooleanType = bool,
         class NumberIntegerType = std::int64_t,
         class NumberUnsignedType = std::uint64_t,
         class NumberFloatType = double,
         template<typename U> class AllocatorType = std::allocator,
         template<typename T, typename SFINAE = void> class JSONSerializer =
         adl_serializer,
         class BinaryType = std::vector<std::uint8_t>, // cppcheck-suppress syntaxError
         class CustomBaseClass = void>
class basic_json;

/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document
/// @sa https://json.nlohmann.me/api/json_pointer/
template<typename RefStringType>
class json_pointer;

/*!
@brief default specialization
@sa https://json.nlohmann.me/api/json/
*/
using json = basic_json<>;

/// @brief a minimal map-like container that preserves insertion order
/// @sa https://json.nlohmann.me/api/ordered_map/
template<class Key, class T, class IgnoredLess, class Allocator>
struct ordered_map;

/// @brief specialization that maintains the insertion order of object keys
/// @sa https://json.nlohmann.me/api/ordered_json/
using ordered_json = basic_json<nlohmann::ordered_map>;

NLOHMANN_JSON_NAMESPACE_END

#endif  // INCLUDE_NLOHMANN_JSON_FWD_HPP_


//     __ _____ _____ _____
//  __|  |   __|     |   | |  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

/*
This file implements a parser test suitable for fuzz testing. Given a byte
array data, it performs the following steps:

- j1 = from_msgpack(data)
- vec = to_msgpack(j1)
- j2 = from_msgpack(vec)
- assert(j1 == j2)

The provided function `LLVMFuzzerTestOneInput` can be used in different fuzzer
drivers.
*/

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

using json = nlohmann::json;

// see http://llvm.org/docs/LibFuzzer.html
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
    try
    {
        // step 1: parse input
        std::vector<uint8_t> const vec1(data, data + size);
        json const j1 = json::from_msgpack(vec1);

        try
        {
            // step 2: round trip
            std::vector<uint8_t> const vec2 = json::to_msgpack(j1);

            // parse serialization
            json const j2 = json::from_msgpack(vec2);

            // serializations must match
            assert(json::to_msgpack(j2) == vec2);
        }
        catch (const json::parse_error&)
        {
            // parsing a MessagePack serialization must not fail
            assert(false);
        }
    }
    catch (const json::parse_error&)
    {
        // parse errors are ok, because input may be random bytes
    }
    catch (const json::type_error&)
    {
        // type errors can occur during parsing, too
    }
    catch (const json::out_of_range&)
    {
        // out of range errors may happen if provided sizes are excessive
    }

    // return 0 - non-zero return values are reserved for future use
    return 0;
}


# Server-Side Rendering (SSR)

:::tip Note
SSR specifically refers to front-end frameworks (for example React, Preact, Vue, and Svelte) that support running the same application in Node.js, pre-rendering it to HTML, and finally hydrating it on the client. If you are looking for integration with traditional server-side frameworks, check out the [Backend Integration guide](./backend-integration) instead.

The following guide also assumes prior experience working with SSR in your framework of choice, and will only focus on Vite-specific integration details.
:::

:::warning Low-level API
This is a low-level API meant for library and framework authors. If your goal is to create an application, make sure to check out the higher-level SSR plugins and tools at [Awesome Vite SSR section](https://github.com/vitejs/awesome-vite#ssr) first. That said, many applications are successfully built directly on top of Vite's native low-level API.

Currently, Vite is working on an improved SSR API with the [Environment API](https://github.com/vitejs/vite/discussions/16358). Check out the link for more details.
:::

## Example Projects

Vite provides built-in support for server-side rendering (SSR). [`create-vite-extra`](https://github.com/bluwy/create-vite-extra) contains example SSR setups you can use as references for this guide:

- [Vanilla](https://github.com/bluwy/create-vite-extra/tree/master/template-ssr-vanilla)
- [Vue](https://github.com/bluwy/create-vite-extra/tree/master/template-ssr-vue)
- [React](https://github.com/bluwy/create-vite-extra/tree/master/template-ssr-react)
- [Preact](https://github.com/bluwy/create-vite-extra/tree/master/template-ssr-preact)
- [Svelte](https://github.com/bluwy/create-vite-extra/tree/master/template-ssr-svelte)
- [Solid](https://github.com/bluwy/create-vite-extra/tree/master/template-ssr-solid)

You can also scaffold these projects locally by [running `create-vite`](./index.md#scaffolding-your-first-vite-project) and choose `Others > create-vite-extra` under the framework option.

## Source Structure

A typical SSR application will have the following source file structure:

```
- index.html
- server.js # main application server
- src/
  - main.js          # exports env-agnostic (universal) app code
  - entry-client.js  # mounts the app to a DOM element
  - entry-server.js  # renders the app using the framework's SSR API
```

The `index.html` will need to reference `entry-client.js` and include a placeholder where the server-rendered markup should be injected:

```html [index.html]
<div id="app"><!--ssr-outlet--></div>
<script type="module" src="/src/entry-client.js"></script>
```

You can use any placeholder you prefer instead of `<!--ssr-outlet-->`, as long as it can be precisely replaced.

## Conditional Logic

If you need to perform conditional logic based on SSR vs. client, you can use

```js twoslash
import 'vite/client'
// ---cut---
if (import.meta.env.SSR) {
  // ... server only logic
}
```

This is statically replaced during build so it will allow tree-shaking of unused branches.

## Setting Up the Dev Server

When building an SSR app, you likely want to have full control over your main server and decouple Vite from the production environment. It is therefore recommended to use Vite in middleware mode. Here is an example with [express](https://expressjs.com/):

```js{15-18} twoslash [server.js]
import fs from 'node:fs'
import path from 'node:path'
import express from 'express'
import { createServer as createViteServer } from 'vite'

async function createServer() {
  const app = express()

  // Create Vite server in middleware mode and configure the app type as
  // 'custom', disabling Vite's own HTML serving logic so parent server
  // can take control
  const vite = await createViteServer({
    server: { middlewareMode: true },
    appType: 'custom'
  })

  // Use vite's connect instance as middleware. If you use your own
  // express router (express.Router()), you should use router.use
  // When the server restarts (for example after the user modifies
  // vite.config.js), `vite.middlewares` is still going to be the same
  // reference (with a new internal stack of Vite and plugin-injected
  // middlewares). The following is valid even after restarts.
  app.use(vite.middlewares)

  app.use('*all', async (req, res) => {
    // serve index.html - we will tackle this next
  })

  app.listen(5173)
}

createServer()
```

Here `vite` is an instance of [ViteDevServer](./api-javascript#vitedevserver). `vite.middlewares` is a [Connect](https://github.com/senchalabs/connect) instance which can be used as a middleware in any connect-compatible Node.js framework.

The next step is implementing the `*` handler to serve server-rendered HTML:

```js twoslash [server.js]
// @noErrors
import fs from 'node:fs'
import path from 'node:path'

/** @type {import('express').Express} */
var app
/** @type {import('vite').ViteDevServer}  */
var vite

// ---cut---
app.use('*all', async (req, res, next) => {
  const url = req.originalUrl

  try {
    // 1. Read index.html
    let template = fs.readFileSync(
      path.resolve(import.meta.dirname, 'index.html'),
      'utf-8',
    )

    // 2. Apply Vite HTML transforms. This injects the Vite HMR client,
    //    and also applies HTML transforms from Vite plugins, e.g. global
    //    preambles from @vitejs/plugin-react
    template = await vite.transformIndexHtml(url, template)

    // 3. Load the server entry. ssrLoadModule automatically transforms
    //    ESM source code to be usable in Node.js! There is no bundling
    //    required, and provides efficient invalidation similar to HMR.
    const { render } = await vite.ssrLoadModule('/src/entry-server.js')

    // 4. render the app HTML. This assumes entry-server.js's exported
    //     `render` function calls appropriate framework SSR APIs,
    //    e.g. ReactDOMServer.renderToString()
    const appHtml = await render(url)

    // 5. Inject the app-rendered HTML into the template.
    const html = template.replace(`<!--ssr-outlet-->`, () => appHtml)

    // 6. Send the rendered HTML back.
    res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
  } catch (e) {
    // If an error is caught, let Vite fix the stack trace so it maps back
    // to your actual source code.
    vite.ssrFixStacktrace(e)
    next(e)
  }
})
```

The `dev` script in `package.json` should also be changed to use the server script instead:

```diff [package.json]
  "scripts": {
-   "dev": "vite"
+   "dev": "node server"
  }
```

## Building for Production

To ship an SSR project for production, we need to:

1. Produce a client build as normal;
2. Produce an SSR build, which can be directly loaded via `import()` so that we don't have to go through Vite's `ssrLoadModule`;

Our scripts in `package.json` will look like this:

```json [package.json]
{
  "scripts": {
    "dev": "node server",
    "build:client": "vite build --outDir dist/client",
    "build:server": "vite build --outDir dist/server --ssr src/entry-server.js"
  }
}
```

Note the `--ssr` flag which indicates this is an SSR build. It should also specify the SSR entry.

Then, in `server.js` we need to add some production specific logic by checking `process.env.NODE_ENV`:

- Instead of reading the root `index.html`, use the `dist/client/index.html` as the template, since it contains the correct asset links to the client build.

- Instead of `await vite.ssrLoadModule('/src/entry-server.js')`, use `import('./dist/server/entry-server.js')` (this file is the result of the SSR build).

- Move the creation and all usage of the `vite` dev server behind dev-only conditional branches, then add static file serving middlewares to serve files from `dist/client`.

Refer to the [example projects](#example-projects) for a working setup.

## Generating Preload Directives

`vite build` supports the `--ssrManifest` flag which will generate `.vite/ssr-manifest.json` in build output directory:

```diff
- "build:client": "vite build --outDir dist/client",
+ "build:client": "vite build --outDir dist/client --ssrManifest",
```

The above script will now generate `dist/client/.vite/ssr-manifest.json` for the client build (Yes, the SSR manifest is generated from the client build because we want to map module IDs to client files). The manifest contains mappings of module IDs to their associated chunks and asset files.

To leverage the manifest, frameworks need to provide a way to collect the module IDs of the components that were used during a server render call.

`@vitejs/plugin-vue` supports this out of the box and automatically registers used component module IDs on to the associated Vue SSR context:

```js [src/entry-server.js]
const ctx = {}
const html = await vueServerRenderer.renderToString(app, ctx)
// ctx.modules is now a Set of module IDs that were used during the render
```

In the production branch of `server.js` we need to read and pass the manifest to the `render` function exported by `src/entry-server.js`. This would provide us with enough information to render preload directives for files used by async routes! See [demo source](https://github.com/vitejs/vite-plugin-vue/blob/main/playground/ssr-vue/src/entry-server.js) for a full example. You can also use this information for [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/103).

## Pre-Rendering / SSG

If the routes and the data needed for certain routes are known ahead of time, we can pre-render these routes into static HTML using the same logic as production SSR. This can also be considered a form of Static-Site Generation (SSG). See [demo pre-render script](https://github.com/vitejs/vite-plugin-vue/blob/main/playground/ssr-vue/prerender.js) for working example.

## SSR Externals

Dependencies are "externalized" from Vite's SSR transform module system by default when running SSR. This speeds up both dev and build.

If a dependency needs to be transformed by Vite's pipeline, for example, because Vite features are used untranspiled in them, they can be added to [`ssr.noExternal`](../config/ssr-options.md#ssr-noexternal).

For linked dependencies, they are not externalized by default to take advantage of Vite's HMR. If this isn't desired, for example, to test dependencies as if they aren't linked, you can add it to [`ssr.external`](../config/ssr-options.md#ssr-external).

:::warning Working with Aliases
If you have configured aliases that redirect one package to another, you may want to alias the actual `node_modules` packages instead to make it work for SSR externalized dependencies. Both [Yarn](https://classic.yarnpkg.com/en/docs/cli/add/#toc-yarn-add-alias) and [pnpm](https://pnpm.io/aliases/) support aliasing via the `npm:` prefix.
:::

## SSR-specific Plugin Logic

Some frameworks such as Vue or Svelte compile components into different formats based on client vs. SSR. To support conditional transforms, Vite passes an additional `ssr` property in the `options` object of the following plugin hooks:

- `resolveId`
- `load`
- `transform`

**Example:**

```js twoslash
/** @type {() => import('vite').Plugin} */
// ---cut---
export function mySSRPlugin() {
  return {
    name: 'my-ssr',
    transform(code, id, options) {
      if (options?.ssr) {
        // perform ssr-specific transform...
      }
    },
  }
}
```

The options object in `load` and `transform` is optional, Rollup is not currently using this object but may extend these hooks with additional metadata in the future.

:::tip Note
Before Vite 2.7, this was informed to plugin hooks with a positional `ssr` param instead of using the `options` object. All major frameworks and plugins are updated but you may find outdated posts using the previous API.
:::

## SSR Target

The default target for the SSR build is a node environment, but you can also run the server in a Web Worker. Packages entry resolution is different for each platform. You can configure the target to be Web Worker using the `ssr.target` set to `'webworker'`.

## SSR Bundle

In some cases like `webworker` runtimes, you might want to bundle your SSR build into a single JavaScript file. You can enable this behavior by setting `ssr.noExternal` to `true`. This will do two things:

- Treat all dependencies as `noExternal`
- Throw an error if any Node.js built-ins are imported

## SSR Resolve Conditions

By default package entry resolution will use the conditions set in [`resolve.conditions`](../config/shared-options.md#resolve-conditions) for the SSR build. You can use [`ssr.resolve.conditions`](../config/ssr-options.md#ssr-resolve-conditions) and [`ssr.resolve.externalConditions`](../config/ssr-options.md#ssr-resolve-externalconditions) to customize this behavior.

## Vite CLI

The CLI commands `$ vite dev` and `$ vite preview` can also be used for SSR apps. You can add your SSR middlewares to the development server with [`configureServer`](/guide/api-plugin#configureserver) and to the preview server with [`configurePreviewServer`](/guide/api-plugin#configurepreviewserver).

:::tip Note
Use a post hook so that your SSR middleware runs _after_ Vite's middlewares.
:::


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

#pragma once

#include <nlohmann/detail/abi_macros.hpp>

NLOHMANN_JSON_NAMESPACE_BEGIN
namespace detail
{

/*!
@brief replace all occurrences of a substring by another string

@param[in,out] s  the string to manipulate; changed so that all
               occurrences of @a f are replaced with @a t
@param[in]     f  the substring to replace with @a t
@param[in]     t  the string to replace @a f

@pre The search string @a f must not be empty. **This precondition is
enforced with an assertion.**

@since version 2.0.0
*/
template<typename StringType>
inline void replace_substring(StringType& s, const StringType& f,
                              const StringType& t)
{
    JSON_ASSERT(!f.empty());
    for (auto pos = s.find(f);                // find the first occurrence of f
            pos != StringType::npos;          // make sure f was found
            s.replace(pos, f.size(), t),      // replace with t, and
            pos = s.find(f, pos + t.size()))  // find the next occurrence of f
    {}
}

/*!
 * @brief string escaping as described in RFC 6901 (Sect. 4)
 * @param[in] s string to escape
 * @return    escaped string
 *
 * Note the order of escaping "~" to "~0" and "/" to "~1" is important.
 */
template<typename StringType>
inline StringType escape(StringType s)
{
    replace_substring(s, StringType{"~"}, StringType{"~0"});
    replace_substring(s, StringType{"/"}, StringType{"~1"});
    return s;
}

/*!
 * @brief string unescaping as described in RFC 6901 (Sect. 4)
 * @param[in] s string to unescape
 * @return    unescaped string
 *
 * Note the order of escaping "~1" to "/" and "~0" to "~" is important.
 */
template<typename StringType>
inline void unescape(StringType& s)
{
    replace_substring(s, StringType{"~1"}, StringType{"/"});
    replace_substring(s, StringType{"~0"}, StringType{"~"});
}

}  // namespace detail
NLOHMANN_JSON_NAMESPACE_END


# <small>nlohmann::</small>json

```cpp
using json = basic_json<>;
```

This type is the default specialization of the [basic_json](basic_json/index.md) class which uses the standard template
types.

## Examples

??? example

    The example below demonstrates how to use the type `nlohmann::json`.

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

    Output:

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

## Version history

Since version 1.0.0.


import fs from 'node:fs'
import path from 'node:path'
import { ignoreInput } from '@voidzero-dev/vite-task-client'
import colors from 'picocolors'
import type { Plugin } from '../plugin'
import { getResolvedOutDirs, resolveEmptyOutDir } from '../watch'
import type { Environment } from '../environment'
import { copyDir, emptyDir, normalizePath } from '../utils'
import { withTrailingSlash } from '../../shared/utils'

export function prepareOutDirPlugin(): Plugin {
  const rendered = new Set<Environment>()
  return {
    name: 'vite:prepare-out-dir',
    watchChange() {
      rendered.delete(this.environment)
    },
    renderStart: {
      order: 'pre',
      handler() {
        if (rendered.has(this.environment)) {
          return
        }

        const { config } = this.environment
        if (config.build.write) {
          rendered.add(this.environment)
          const { root, build: options } = config
          const resolvedOutDirs = getResolvedOutDirs(
            root,
            options.outDir,
            options.rolldownOptions.output,
          )
          const emptyOutDir = resolveEmptyOutDir(
            options.emptyOutDir,
            root,
            resolvedOutDirs,
            this.environment.logger,
          )
          prepareOutDir(resolvedOutDirs, emptyOutDir, this.environment)
        }
      },
    },
  }
}

function prepareOutDir(
  outDirs: Set<string>,
  emptyOutDir: boolean | null,
  environment: Environment,
) {
  const { publicDir } = environment.config
  const outDirsArray = [...outDirs]
  for (const outDir of outDirs) {
    // When run inside Vite Task, `emptyDir` below reads the entries of
    // `outDir`. Without this, those reads would be recorded as build inputs
    // and mix with the writes that follow, tripping Vite Task's read-write
    // overlap check.
    ignoreInput(outDir)
    if (emptyOutDir !== false && fs.existsSync(outDir)) {
      // skip those other outDirs which are nested in current outDir
      const skipDirs = outDirsArray
        .map((dir) => {
          const relative = path.relative(outDir, dir)
          if (
            relative &&
            !relative.startsWith('..') &&
            !path.isAbsolute(relative)
          ) {
            return relative
          }
          return ''
        })
        .filter(Boolean)
      emptyDir(outDir, [...skipDirs, '.git'])
    }
    if (
      environment.config.build.copyPublicDir &&
      publicDir &&
      fs.existsSync(publicDir)
    ) {
      if (!areSeparateFolders(outDir, publicDir)) {
        environment.logger.warn(
          colors.yellow(
            `\n${colors.bold(
              `(!)`,
            )} The public directory feature may not work correctly. outDir ${colors.white(
              colors.dim(outDir),
            )} and publicDir ${colors.white(
              colors.dim(publicDir),
            )} are not separate folders.\n`,
          ),
        )
      }
      copyDir(publicDir, outDir)
    }
  }
}

function areSeparateFolders(a: string, b: string) {
  const na = normalizePath(a)
  const nb = normalizePath(b)
  return (
    na !== nb &&
    !na.startsWith(withTrailingSlash(nb)) &&
    !nb.startsWith(withTrailingSlash(na))
  )
}


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

using json = nlohmann::json;

int main()
{
    // create a JSON pointer
    json::json_pointer ptr("/foo");

    // append a JSON Pointer
    std::cout << "\"" << ptr / json::json_pointer("/bar/baz") << "\"\n";

    // append a string
    std::cout << "\"" << ptr / "fob" << "\"\n";

    // append an array index
    std::cout << "\"" << ptr / 42 << "\"" << std::endl;
}


<img src="https://user-images.githubusercontent.com/576385/156254208-f5b743a9-88cf-439d-b0c0-923d53e8d551.png" alt="{fmt}" width="25%"/>

[![image](https://github.com/fmtlib/fmt/actions/workflows/linux.yml/badge.svg?branch=master)](
https://github.com/fmtlib/fmt/actions?query=workflow%3Alinux)
[![image](https://github.com/fmtlib/fmt/actions/workflows/macos.yml/badge.svg?branch=master)](
https://github.com/fmtlib/fmt/actions?query=workflow%3Amacos)
[![image](https://github.com/fmtlib/fmt/actions/workflows/windows.yml/badge.svg?branch=master)](
https://github.com/fmtlib/fmt/actions?query=workflow%3Awindows)
[![fmt is continuously fuzzed at oss-fuzz](https://oss-fuzz-build-logs.storage.googleapis.com/badges/fmt.svg)](
https://issues.oss-fuzz.com/issues?q=title:fmt%20cc:victor.zverovich@gmail.com)
[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/8880/badge)](
https://www.bestpractices.dev/projects/8880)
[![image](https://api.securityscorecards.dev/projects/github.com/fmtlib/fmt/badge)](
https://securityscorecards.dev/viewer/?uri=github.com/fmtlib/fmt)
[![Ask questions at StackOverflow with the tag fmt](
https://img.shields.io/badge/stackoverflow-fmt-blue.svg)](https://stackoverflow.com/questions/tagged/fmt)
[![Support Ukraine](
https://img.shields.io/badge/Support-Ukraine-005BBB?labelColor=FFD500)](https://novaukraine.org/)

**{fmt}** is an open-source formatting library providing a fast and safe
alternative to C stdio and C++ iostreams.

[Documentation](https://fmt.dev)

[Cheat Sheets](https://hackingcpp.com/cpp/libs/fmt.html)

Q&A: ask questions on [StackOverflow with the tag
fmt](https://stackoverflow.com/questions/tagged/fmt).

Try {fmt} in [Compiler Explorer](https://godbolt.org/z/8Mx1EW73v).

# Features

- Simple [format API](https://fmt.dev/latest/api/) with positional
  arguments for localization
- Implementation of [C++20
  std::format](https://en.cppreference.com/w/cpp/utility/format) and
  [C++23 std::print](https://en.cppreference.com/w/cpp/io/print)
- [Format string syntax](https://fmt.dev/latest/syntax/) similar
  to Python\'s
  [format](https://docs.python.org/3/library/stdtypes.html#str.format)
- Fast IEEE 754 floating-point formatter with correct rounding,
  shortness and round-trip guarantees using the
  [Dragonbox](https://github.com/jk-jeon/dragonbox) algorithm
- Portable Unicode support
- Safe [printf
  implementation](https://fmt.dev/latest/api/#printf-api)
  including the POSIX extension for positional arguments
- Extensibility: [support for user-defined
  types](https://fmt.dev/latest/api/#formatting-user-defined-types)
- High performance: faster than common standard library
  implementations of `(s)printf`, iostreams, `to_string` and
  `to_chars`, see [Speed tests](#speed-tests) and [Converting a
  hundred million integers to strings per
  second](https://vitaut.net/posts/2020/fast-int-to-string-revisited/)
- Small code size both in terms of source code with the minimum
  configuration consisting of just three files, `base.h`, `format.h`
  and `format-inl.h`, and compiled code; see [Compile time and code
  bloat](#compile-time-and-code-bloat)
- Reliability: the library has an extensive set of
  [tests](https://github.com/fmtlib/fmt/tree/master/test) and is
  [continuously fuzzed](https://bugs.chromium.org/p/oss-fuzz/issues/list?colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20Summary&q=proj%3Dfmt&can=1)
- Safety: the library is fully type-safe, errors in format strings can
  be reported at compile time, automatic memory management prevents
  buffer overflow errors
- Ease of use: small self-contained code base, no external
  dependencies, permissive MIT
  [license](https://github.com/fmtlib/fmt/blob/master/LICENSE)
- [Portability](https://fmt.dev/latest/#portability) with
  consistent output across platforms and support for older compilers
- Clean warning-free codebase even on high warning levels such as
  `-Wall -Wextra -pedantic`
- Locale independence by default
- Optional header-only configuration enabled with the
  `FMT_HEADER_ONLY` macro

See the [documentation](https://fmt.dev) for more details.

# Examples

**Print to stdout** ([run](https://godbolt.org/z/Tevcjh))

``` c++
#include <fmt/base.h>

int main() {
  fmt::print("Hello, world!\n");
}
```

**Format a string** ([run](https://godbolt.org/z/oK8h33))

``` c++
std::string s = fmt::format("The answer is {}.", 42);
// s == "The answer is 42."
```

**Format a string using positional arguments**
([run](https://godbolt.org/z/Yn7Txe))

``` c++
std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
// s == "I'd rather be happy than right."
```

**Print dates and times** ([run](https://godbolt.org/z/c31ExdY3W))

``` c++
#include <fmt/chrono.h>

int main() {
  auto now = std::chrono::system_clock::now();
  fmt::print("Date and time: {}\n", now);
  fmt::print("Time: {:%H:%M}\n", now);
}
```

Output:

    Date and time: 2023-12-26 19:10:31.557195597
    Time: 19:10

**Print a container** ([run](https://godbolt.org/z/MxM1YqjE7))

``` c++
#include <vector>
#include <fmt/ranges.h>

int main() {
  std::vector<int> v = {1, 2, 3};
  fmt::print("{}\n", v);
}
```

Output:

    [1, 2, 3]

**Check a format string at compile time**

``` c++
std::string s = fmt::format("{:d}", "I am not a number");
```

This gives a compile-time error in C++20 because `d` is an invalid
format specifier for a string.

**Write a file from a single thread**

``` c++
#include <fmt/os.h>

int main() {
  auto out = fmt::output_file("guide.txt");
  out.print("Don't {}", "Panic");
}
```

This can be [up to 9 times faster than `fprintf`](
https://vitaut.net/posts/2020/optimal-file-buffer-size/).

**Print with colors and text styles**

``` c++
#include <fmt/color.h>

int main() {
  fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold,
             "Hello, {}!\n", "world");
  fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) |
             fmt::emphasis::underline, "Olá, {}!\n", "Mundo");
  fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic,
             "你好{}！\n", "世界");
}
```

Output on a modern terminal with Unicode support:

![image](https://github.com/fmtlib/fmt/assets/576385/2a93c904-d6fa-4aa6-b453-2618e1c327d7)

# Benchmarks

## Speed tests

| Library           | Method        | Run Time, s |
|-------------------|---------------|-------------|
| libc              | printf        |   0.66      |
| libc++            | std::ostream  |   1.63      |
| {fmt} 12.1        | fmt::print    |   0.44      |
| Boost Format 1.88 | boost::format |   3.89      |
| Folly Format      | folly::format |   1.28      |

{fmt} is the fastest of the benchmarked methods, \~50% faster than
`printf`.

The above results were generated by building `tinyformat_test.cpp` on
macOS 15.6.1 with `clang++ -O3 -DNDEBUG -DSPEED_TEST -DHAVE_FORMAT`, and
taking the best of three runs. In the test, the format string
`"%0.10f:%04d:%+g:%s:%p:%c:%%\n"` or equivalent is filled 2,000,000
times with output sent to `/dev/null`; for further details refer to the
[source](https://github.com/fmtlib/format-benchmark/blob/master/src/tinyformat-test.cc).

{fmt} is up to 20-30x faster than `std::ostringstream` and `sprintf` on
IEEE754 `float` and `double` formatting
([dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark)) and faster
than [double-conversion](https://github.com/google/double-conversion)
and [ryu](https://github.com/ulfjack/ryu):

[![image](https://user-images.githubusercontent.com/576385/95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png)](https://fmt.dev/unknown_mac64_clang12.0.html)

## Compile time and code bloat

The script [bloat-test.py][test] from [format-benchmark][bench] tests compile
time and code bloat for nontrivial projects. It generates 100 translation units
and uses `printf()` or its alternative five times in each to simulate a
medium-sized project. The resulting executable size and compile time (Apple
clang version 15.0.0 (clang-1500.1.0.2.5), macOS Sonoma, best of three) is shown
in the following tables.

[test]: https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py
[bench]: https://github.com/fmtlib/format-benchmark

**Optimized build (-O3)**

| Method          | Compile Time, s | Executable size, KiB | Stripped size, KiB |
|-----------------|-----------------|----------------------|--------------------|
| printf          |             1.6 |                   54 |                 50 |
| IOStreams       |            28.4 |                   98 |                 84 |
| {fmt} `1122268` |             5.0 |                   54 |                 50 |
| tinyformat      |            32.6 |                  164 |                136 |
| Boost Format    |            55.0 |                  530 |                317 |

{fmt} is fast to compile and is comparable to `printf` in terms of per-call
binary size (within a rounding error on this system).

**Non-optimized build**

| Method          | Compile Time, s | Executable size, KiB | Stripped size, KiB |
|-----------------|-----------------|----------------------|--------------------|
| printf          |             1.4 |                   54 |                 50 |
| IOStreams       |            27.0 |                   88 |                 68 |
| {fmt} `1122268` |             4.7 |                   87 |                 84 |
| tinyformat      |            28.1 |                  185 |                145 |
| Boost Format    |            38.9 |                  678 |                381 |

`libc`, `lib(std)c++`, and `libfmt` are all linked as shared libraries
to compare formatting function overhead only. Boost Format is a
header-only library so it doesn\'t provide any linkage options.

## Running the tests

Please refer to [Building the
library](https://fmt.dev/latest/get-started/#building-from-source) for
instructions on how to build the library and run the unit tests.

Benchmarks reside in a separate repository,
[format-benchmarks](https://github.com/fmtlib/format-benchmark), so to
run the benchmarks you first need to clone this repository and generate
Makefiles with CMake:

    $ git clone --recursive https://github.com/fmtlib/format-benchmark.git
    $ cd format-benchmark
    $ cmake .

Then you can run the speed test:

    $ make speed-test

or the bloat test:

    $ make bloat-test

# Migrating code

[clang-tidy](https://clang.llvm.org/extra/clang-tidy/) v18 provides the
[modernize-use-std-print](https://clang.llvm.org/extra/clang-tidy/checks/modernize/use-std-print.html)
check that is capable of converting occurrences of `printf` and
`fprintf` to `fmt::print` if configured to do so. (By default it
converts to `std::print`.)

# Notable projects using this library

- [0 A.D.](https://play0ad.com/): a free, open-source, cross-platform
  real-time strategy game
- [AMPL/MP](https://github.com/ampl/mp): an open-source library for
  mathematical programming
- [Apple's FoundationDB](https://github.com/apple/foundationdb): an open-source,
  distributed, transactional key-value store
- [Aseprite](https://github.com/aseprite/aseprite): animated sprite
  editor & pixel art tool
- [AvioBook](https://www.aviobook.aero/en): a comprehensive aircraft
  operations suite
- [Blizzard Battle.net](https://battle.net/): an online gaming
  platform
- [Celestia](https://celestia.space/): real-time 3D visualization of
  space
- [Ceph](https://ceph.com/): a scalable distributed storage system
- [ccache](https://ccache.dev/): a compiler cache
- [ClickHouse](https://github.com/ClickHouse/ClickHouse): an
  analytical database management system
- [ContextVision](https://www.contextvision.com/): medical imaging software
- [Contour](https://github.com/contour-terminal/contour/): a modern
  terminal emulator
- [CUAUV](https://cuauv.org/): Cornell University\'s autonomous
  underwater vehicle
- [Drake](https://drake.mit.edu/): a planning, control, and analysis
  toolbox for nonlinear dynamical systems (MIT)
- [Envoy](https://github.com/envoyproxy/envoy): C++ L7 proxy and
  communication bus (Lyft)
- [FiveM](https://fivem.net/): a modification framework for GTA V
- [fmtlog](https://github.com/MengRao/fmtlog): a performant
  fmtlib-style logging library with latency in nanoseconds
- [Folly](https://github.com/facebook/folly): Facebook open-source
  library
- [GemRB](https://gemrb.org/): a portable open-source implementation
  of Bioware's Infinity Engine
- [Grand Mountain
  Adventure](https://store.steampowered.com/app/1247360/Grand_Mountain_Adventure/):
  a beautiful open-world ski & snowboarding game
- [HarpyWar/pvpgn](https://github.com/pvpgn/pvpgn-server): Player vs
  Player Gaming Network with tweaks
- [KBEngine](https://github.com/kbengine/kbengine): an open-source
  MMOG server engine
- [Keypirinha](https://keypirinha.com/): a semantic launcher for
  Windows
- [Kodi](https://kodi.tv/) (formerly xbmc): home theater software
- [Knuth](https://kth.cash/): high-performance Bitcoin full-node
- [libunicode](https://github.com/contour-terminal/libunicode/): a
  modern C++17 Unicode library
- [MariaDB](https://mariadb.org/): relational database management
  system
- [Microsoft Verona](https://github.com/microsoft/verona): research
  programming language for concurrent ownership
- [MongoDB](https://mongodb.com/): distributed document database
- [MongoDB Smasher](https://github.com/duckie/mongo_smasher): a small
  tool to generate randomized datasets
- [OpenSpace](https://openspaceproject.com/): an open-source
  astrovisualization framework
- [PenUltima Online (POL)](https://www.polserver.com/): an MMO server,
  compatible with most Ultima Online clients
- [PyTorch](https://github.com/pytorch/pytorch): an open-source
  machine learning library
- [quasardb](https://www.quasardb.net/): a distributed,
  high-performance, associative database
- [Quill](https://github.com/odygrd/quill): asynchronous low-latency
  logging library
- [QKW](https://github.com/ravijanjam/qkw): generalizing aliasing to
  simplify navigation, and execute complex multi-line terminal
  command sequences
- [redis-cerberus](https://github.com/HunanTV/redis-cerberus): a Redis
  cluster proxy
- [redpanda](https://vectorized.io/redpanda): a 10x faster Kafka®
  replacement for mission-critical systems written in C++
- [rpclib](https://github.com/rpclib/rpclib): a modern C++ msgpack-RPC server and
  client library
- [Salesforce Analytics
  Cloud](https://www.salesforce.com/analytics-cloud/overview/):
  business intelligence software
- [Scylla](https://www.scylladb.com/): a Cassandra-compatible NoSQL
  data store that can handle 1 million transactions per second on a
  single server
- [Seastar](https://seastar.io/): an advanced, open-source
  C++ framework for high-performance server applications on modern
  hardware
- [spdlog](https://github.com/gabime/spdlog): super fast C++ logging
  library
- [Stellar](https://www.stellar.org/): financial platform
- [Touch Surgery](https://www.touchsurgery.com/): surgery simulator
- [TrinityCore](https://github.com/TrinityCore/TrinityCore):
  open-source MMORPG framework
- [🐙 userver framework](https://userver.tech/): open-source
  asynchronous framework with a rich set of abstractions and database
  drivers
- [Windows Terminal](https://github.com/microsoft/terminal): the new
  Windows terminal

[More\...](https://github.com/search?q=fmtlib&type=Code)

If you are aware of other projects using this library, please let me
know by [email](mailto:victor.zverovich@gmail.com) or by submitting an
[issue](https://github.com/fmtlib/fmt/issues).

# Maintainers

The {fmt} library is maintained by Victor Zverovich
([vitaut](https://github.com/vitaut)) with contributions from many other
people. See
[Contributors](https://github.com/fmtlib/fmt/graphs/contributors) and
[Releases](https://github.com/fmtlib/fmt/releases) for some of the
names. Let us know if your contribution is not listed or mentioned
incorrectly and we\'ll make it right.


import assert from 'node:assert'
import { fileURLToPath } from 'node:url'
import { createServer, createServerModuleRunner } from 'vite'

async function runTest(userRunner) {
  const server = await createServer({
    configFile: false,
    root: fileURLToPath(new URL('.', import.meta.url)),
    server: {
      middlewareMode: true,
      ws: false,
    },
  })
  let mod
  if (userRunner) {
    const runner = await createServerModuleRunner(server.environments.ssr, {
      hmr: false,
    })
    mod = await runner.import('/src/network-imports.js')
  } else {
    mod = await server.ssrLoadModule('/src/network-imports.js')
  }
  assert.equal(mod.slash('foo\\bar'), 'foo/bar')
  await server.close()
}

runTest(process.argv.includes('--module-runner'))


# Qwik + Vite

## Qwik in CSR mode

This starter is using a pure CSR (Client-Side Rendering) mode. This means, that the application is fully bootstrapped in the browser. Most of Qwik innovations however take advantage of SSR (Server-Side Rendering) mode.

```ts
export default defineConfig({
  plugins: [
    qwikVite({
      csr: true,
    }),
  ],
})
```

Use `npm create qwik@latest` to create a full production ready Qwik application, using SSR and [QwikCity](https://qwik.dev/docs/qwikcity/), our server-side meta-framework.

## Usage

```bash
$ npm install # or pnpm install or yarn install
```

Learn more on the [Qwik Website](https://qwik.dev) and join our community on our [Discord](https://qwik.dev/chat)

## Available Scripts

In the project directory, you can run:

### `npm run dev`

Runs the app in the development mode.

Open [http://localhost:5173](http://localhost:5173) to view it in the browser.

### `npm run build`

Builds the app for production to the `dist` folder.


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

using json = nlohmann::json;

int main()
{
    // create JSON values
    json object = {{"one", 1}, {"two", 2}};
    json null;

    // print values
    std::cout << object << '\n';
    std::cout << null << '\n';

    // add values
    object.push_back(json::object_t::value_type("three", 3));
    object += json::object_t::value_type("four", 4);
    null += json::object_t::value_type("A", "a");
    null += json::object_t::value_type("B", "b");

    // print values
    std::cout << object << '\n';
    std::cout << null << '\n';
}


/*!
Defines a builder for haystacks.

A "haystack" represents something we want to search. It encapsulates the logic
for whether a haystack ought to be searched or not, separate from the standard
ignore rules and other filtering logic.

Effectively, a haystack wraps a directory entry and adds some light application
level logic around it.
*/

use std::path::Path;

/// A builder for constructing things to search over.
#[derive(Clone, Debug)]
pub(crate) struct HaystackBuilder {
    strip_dot_prefix: bool,
}

impl HaystackBuilder {
    /// Return a new haystack builder with a default configuration.
    pub(crate) fn new() -> HaystackBuilder {
        HaystackBuilder { strip_dot_prefix: false }
    }

    /// Create a new haystack from a possibly missing directory entry.
    ///
    /// If the directory entry isn't present, then the corresponding error is
    /// logged if messages have been configured. Otherwise, if the directory
    /// entry is deemed searchable, then it is returned as a haystack.
    pub(crate) fn build_from_result(
        &self,
        result: Result<ignore::DirEntry, ignore::Error>,
    ) -> Option<Haystack> {
        match result {
            Ok(dent) => self.build(dent),
            Err(err) => {
                err_message!("{err}");
                None
            }
        }
    }

    /// Create a new haystack using this builder's configuration.
    ///
    /// If a directory entry could not be created or should otherwise not be
    /// searched, then this returns `None` after emitting any relevant log
    /// messages.
    fn build(&self, dent: ignore::DirEntry) -> Option<Haystack> {
        let hay = Haystack { dent, strip_dot_prefix: self.strip_dot_prefix };
        if let Some(err) = hay.dent.error() {
            ignore_message!("{err}");
        }
        // If this entry was explicitly provided by an end user, then we always
        // want to search it.
        if hay.is_explicit() {
            return Some(hay);
        }
        // At this point, we only want to search something if it's explicitly a
        // file. This omits symlinks. (If ripgrep was configured to follow
        // symlinks, then they have already been followed by the directory
        // traversal.)
        if hay.is_file() {
            return Some(hay);
        }
        // We got nothing. Emit a debug message, but only if this isn't a
        // directory. Otherwise, emitting messages for directories is just
        // noisy.
        if !hay.is_dir() {
            log::debug!(
                "ignoring {}: failed to pass haystack filter: \
                 file type: {:?}, metadata: {:?}",
                hay.dent.path().display(),
                hay.dent.file_type(),
                hay.dent.metadata()
            );
        }
        None
    }

    /// When enabled, if the haystack's file path starts with `./` then it is
    /// stripped.
    ///
    /// This is useful when implicitly searching the current working directory.
    pub(crate) fn strip_dot_prefix(
        &mut self,
        yes: bool,
    ) -> &mut HaystackBuilder {
        self.strip_dot_prefix = yes;
        self
    }
}

/// A haystack is a thing we want to search.
///
/// Generally, a haystack is either a file or stdin.
#[derive(Clone, Debug)]
pub(crate) struct Haystack {
    dent: ignore::DirEntry,
    strip_dot_prefix: bool,
}

impl Haystack {
    /// Return the file path corresponding to this haystack.
    ///
    /// If this haystack corresponds to stdin, then a special `<stdin>` path
    /// is returned instead.
    pub(crate) fn path(&self) -> &Path {
        if self.strip_dot_prefix && self.dent.path().starts_with("./") {
            self.dent.path().strip_prefix("./").unwrap()
        } else {
            self.dent.path()
        }
    }

    /// Returns true if and only if this entry corresponds to stdin.
    pub(crate) fn is_stdin(&self) -> bool {
        self.dent.is_stdin()
    }

    /// Returns true if and only if this entry corresponds to a haystack to
    /// search that was explicitly supplied by an end user.
    ///
    /// Generally, this corresponds to either stdin or an explicit file path
    /// argument. e.g., in `rg foo some-file ./some-dir/`, `some-file` is
    /// an explicit haystack, but, e.g., `./some-dir/some-other-file` is not.
    ///
    /// However, note that ripgrep does not see through shell globbing. e.g.,
    /// in `rg foo ./some-dir/*`, `./some-dir/some-other-file` will be treated
    /// as an explicit haystack.
    pub(crate) fn is_explicit(&self) -> bool {
        // stdin is obvious. When an entry has a depth of 0, that means it
        // was explicitly provided to our directory iterator, which means it
        // was in turn explicitly provided by the end user. The !is_dir check
        // means that we want to search files even if their symlinks, again,
        // because they were explicitly provided. (And we never want to try
        // to search a directory.)
        self.is_stdin() || (self.dent.depth() == 0 && !self.is_dir())
    }

    /// Returns true if and only if this haystack points to a directory after
    /// following symbolic links.
    fn is_dir(&self) -> bool {
        let ft = match self.dent.file_type() {
            None => return false,
            Some(ft) => ft,
        };
        if ft.is_dir() {
            return true;
        }
        // If this is a symlink, then we want to follow it to determine
        // whether it's a directory or not.
        self.dent.path_is_symlink() && self.dent.path().is_dir()
    }

    /// Returns true if and only if this haystack points to a file.
    fn is_file(&self) -> bool {
        self.dent.file_type().map_or(false, |ft| ft.is_file())
    }
}


import type {
  IncomingMessage,
  OutgoingHttpHeaders,
  ServerResponse,
} from 'node:http'
import path from 'node:path'
import convertSourceMap from 'convert-source-map'
import getEtag from 'etag'
import type { SourceMap } from 'rolldown'
import MagicString from 'magic-string'
import { createDebugger, removeTimestampQuery } from '../utils'
import { getCodeWithSourcemap } from './sourcemap'

const debug = createDebugger('vite:send', {
  onlyWhenFocused: true,
})

const alias: Record<string, string | undefined> = {
  js: 'text/javascript',
  css: 'text/css',
  html: 'text/html',
  json: 'application/json',
}

export interface SendOptions {
  etag?: string
  cacheControl?: string
  headers?: OutgoingHttpHeaders
  map?: SourceMap | { mappings: '' } | null
}

export function send(
  req: IncomingMessage,
  res: ServerResponse,
  content: string | Buffer,
  type: string,
  options: SendOptions,
): void {
  const {
    etag = getEtag(content, { weak: true }),
    cacheControl = 'no-cache',
    headers,
    map,
  } = options

  if (res.writableEnded) {
    return
  }

  if (req.headers['if-none-match'] === etag) {
    res.statusCode = 304
    res.end()
    return
  }

  res.setHeader('Content-Type', alias[type] || type)
  res.setHeader('Cache-Control', cacheControl)
  res.setHeader('Etag', etag)

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

  // inject source map reference
  if (map && 'version' in map && map.mappings) {
    if (type === 'js' || type === 'css') {
      content = getCodeWithSourcemap(type, content.toString(), map)
    }
  }
  // inject fallback sourcemap for js for improved debugging
  // https://github.com/vitejs/vite/pull/13514#issuecomment-1592431496
  else if (type === 'js' && (!map || map.mappings !== '')) {
    const code = content.toString()
    // if the code has existing inline sourcemap, assume it's correct and skip
    if (convertSourceMap.mapFileCommentRegex.test(code)) {
      debug?.(`Skipped injecting fallback sourcemap for ${req.url}`)
    } else {
      const urlWithoutTimestamp = removeTimestampQuery(req.url!)
      const ms = new MagicString(code)
      content = getCodeWithSourcemap(
        type,
        code,
        ms.generateMap({
          source: path.basename(urlWithoutTimestamp),
          hires: 'boundary',
          includeContent: true,
        }) as SourceMap,
      )
    }
  }

  res.statusCode = 200
  if (req.method === 'HEAD') {
    res.end()
  } else {
    res.end(content)
  }
  return
}


import { fileURLToPath } from 'node:url'
import path from 'node:path'
import fs from 'node:fs'
import { stripVTControlCharacters } from 'node:util'
import { expect, onTestFinished, test, vi } from 'vitest'
import { createServer } from '../../server'
import { DevEnvironment } from '../../server/environment'
import { normalizePath } from '../../utils'

const root = fileURLToPath(new URL('./', import.meta.url))

async function createDevServer() {
  const server = await createServer({
    configFile: false,
    root,
    logLevel: 'silent',
    optimizeDeps: {
      noDiscovery: true,
    },
  })
  await server.environments.ssr.pluginContainer.buildStart({})
  return server
}

test('ssrLoad', async () => {
  expect.assertions(1)
  const server = await createDevServer()
  const moduleRelativePath = '/fixtures/modules/has-invalid-import.js'
  const moduleAbsolutePath = normalizePath(path.join(root, moduleRelativePath))
  try {
    await server.ssrLoadModule(moduleRelativePath)
  } catch (e) {
    expect(e.message).toBe(
      `Failed to load url ./non-existent.js (resolved id: ./non-existent.js) in ${moduleAbsolutePath}. Does the file exist?`,
    )
  }
})

test('error has same instance', async () => {
  expect.assertions(3)
  const s = Symbol()

  const server = await createDevServer()
  try {
    await server.ssrLoadModule('/fixtures/modules/has-error.js')
  } catch (e) {
    expect(e[s]).toBeUndefined()
    e[s] = true
    expect(e[s]).toBe(true)
  }

  try {
    await server.ssrLoadModule('/fixtures/modules/has-error.js')
  } catch (e) {
    expect(e[s]).toBe(true)
  }
})

test('import.meta.filename/dirname returns same value with Node', async () => {
  const server = await createDevServer()
  const moduleRelativePath = '/fixtures/modules/import-meta.js'
  const filename = path.resolve(root, '.' + moduleRelativePath)

  const viteValue = await server.ssrLoadModule(moduleRelativePath)
  expect(viteValue.dirname).toBe(path.dirname(filename))
  expect(viteValue.filename).toBe(filename)
})

test('virtual module invalidation simple', async () => {
  const server = await createServer({
    configFile: false,
    root,
    logLevel: 'silent',
    optimizeDeps: {
      noDiscovery: true,
    },
    plugins: [
      {
        name: 'virtual-test',
        resolveId(id) {
          if (id === 'virtual:test') {
            return '\0virtual:test'
          }
        },
        load(id) {
          if (id === '\0virtual:test') {
            return `
              globalThis.__virtual_test_state ??= 0;
              globalThis.__virtual_test_state++;
              export default globalThis.__virtual_test_state;
            `
          }
        },
      },
    ],
  })
  await server.environments.ssr.pluginContainer.buildStart({})

  const mod1 = await server.ssrLoadModule('virtual:test')
  expect(mod1.default).toEqual(1)
  const mod2 = await server.ssrLoadModule('virtual:test')
  expect(mod2.default).toEqual(1)

  const modNode = server.moduleGraph.getModuleById('\0virtual:test')
  server.moduleGraph.invalidateModule(modNode!)

  const mod3 = await server.ssrLoadModule('virtual:test')
  expect(mod3.default).toEqual(2)
})

test('virtual module invalidation nested', async () => {
  const server = await createServer({
    configFile: false,
    root,
    logLevel: 'silent',
    optimizeDeps: {
      noDiscovery: true,
    },
    plugins: [
      {
        name: 'test-virtual',
        resolveId(id) {
          if (id === 'virtual:test') {
            return '\0virtual:test'
          }
        },
        load(id) {
          if (id === '\0virtual:test') {
            return `
              import testDep from "virtual:test-dep";
              export default testDep;
            `
          }
        },
      },
      {
        name: 'test-virtual-dep',
        resolveId(id) {
          if (id === 'virtual:test-dep') {
            return '\0virtual:test-dep'
          }
        },
        load(id) {
          if (id === '\0virtual:test-dep') {
            return `
              globalThis.__virtual_test_state2 ??= 0;
              globalThis.__virtual_test_state2++;
              export default globalThis.__virtual_test_state2;
            `
          }
        },
      },
    ],
  })
  await server.environments.ssr.pluginContainer.buildStart({})

  const mod1 = await server.ssrLoadModule('virtual:test')
  expect(mod1.default).toEqual(1)
  const mod2 = await server.ssrLoadModule('virtual:test')
  expect(mod2.default).toEqual(1)

  server.moduleGraph.invalidateModule(
    server.moduleGraph.getModuleById('\0virtual:test')!,
  )
  server.moduleGraph.invalidateModule(
    server.moduleGraph.getModuleById('\0virtual:test-dep')!,
  )

  const mod3 = await server.ssrLoadModule('virtual:test')
  expect(mod3.default).toEqual(2)
})

test('can export global', async () => {
  const server = await createDevServer()
  const mod = await server.ssrLoadModule('/fixtures/global/export.js')
  expect(mod.global).toBe('ok')
})

test('can access nodejs global', async () => {
  const server = await createDevServer()
  const mod = await server.ssrLoadModule('/fixtures/global/test.js')
  expect(mod.default).toBe(globalThis)
})

// skip for now as rolldown returns different error message from esbuild
// related: https://github.com/oxc-project/oxc/issues/7261
// (rolldown does not set the properties passed from Oxc)
test.skip('parse error', async () => {
  const server = await createDevServer()

  function stripRoot(s?: string) {
    return (s || '').replace(server.config.root, '<root>')
  }

  for (const file of [
    '/fixtures/errors/syntax-error.ts',
    '/fixtures/errors/syntax-error.js',
    '/fixtures/errors/syntax-error-dep.ts',
    '/fixtures/errors/syntax-error-dep.js',
  ]) {
    try {
      await server.ssrLoadModule(file)
    } catch (e) {
      expect(e).toBeInstanceOf(Error)
      expect({
        message: stripRoot(e.message),
        frame: stripVTControlCharacters(e.frame || ''),
        id: stripRoot(e.id),
        loc: e.loc && {
          file: stripRoot(e.loc.file),
          column: e.loc.column,
          line: e.loc.line,
        },
      }).toMatchSnapshot()
      continue
    }
    expect.unreachable()
  }
})

test('json', async () => {
  const server = await createDevServer()
  const mod = await server.ssrLoadModule('/fixtures/json/test.json')
  expect(mod).toMatchInlineSnapshot(`
    {
      "default": {
        "hello": "this is json",
      },
      "hello": "this is json",
    }
  `)

  const source = fs.readFileSync(
    path.join(root, 'fixtures/json/test.json'),
    'utf-8',
  )
  const json = await server.ssrTransform(
    `export default ${source}`,
    null,
    '/test.json',
  )
  expect(json?.code.length).toMatchInlineSnapshot(`165`)
})

test('file url', async () => {
  const server = await createDevServer()

  const mod = await server.ssrLoadModule(
    new URL('./fixtures/file-url/test.js', import.meta.url).href,
  )
  expect(mod.msg).toBe('works')

  const modWithSpace = await server.ssrLoadModule(
    new URL('./fixtures/file-url/test space.js', import.meta.url).href,
  )
  expect(modWithSpace.msg).toBe('works')
})

test('plugin error', async () => {
  const server = await createServer({
    configFile: false,
    root,
    logLevel: 'error',
    plugins: [
      {
        name: 'test-plugin',
        resolveId(source) {
          if (source === 'virtual:test') {
            return '\0' + source
          }
        },
        load(id) {
          if (id === '\0virtual:test') {
            return this.error('test-error')
          }
        },
      },
    ],
  })
  onTestFinished(() => server.close())

  const spy = vi
    .spyOn(server.config.logger, 'error')
    .mockImplementation(() => {})
  try {
    await server.ssrLoadModule('virtual:test')
    expect.unreachable()
  } catch {}
  expect(
    stripVTControlCharacters(spy.mock.lastCall![0])
      .split('\n')
      .slice(0, 2)
      .join('\n'),
  ).toMatchInlineSnapshot(`
    "Error when evaluating SSR module virtual:test: test-error
      Plugin: test-plugin"
  `)
})

test('named exports overwrite export all', async () => {
  const server = await createDevServer()
  const mod = await server.ssrLoadModule(
    './fixtures/named-overwrite-all/main.js',
  )

  // ESM spec doesn't allow conflicting `export *` and such duplicate exports are removed (in this case "d"),
  // but this is likely not possible to support due to Vite dev SSR's lazy nature.
  // [Node]
  //   $ node -e 'import("./packages/vite/src/node/ssr/__tests__/fixtures/named-overwrite-all/main.js").then(console.log)'
  //   [Module: null prototype] { a: 'main-a', b: 'dep1-b', c: 'main-c' }
  // [Rollup]
  //   Conflicting namespaces: "main.js" re-exports "d" from one of the modules "dep1.js" and "dep2.js" (will be ignored).
  expect(mod).toMatchInlineSnapshot(`
    {
      "a": "main-a",
      "b": "dep1-b",
      "c": "main-c",
      "d": "dep1-d",
    }
  `)
})

test('throws when ssr environment is not runnable', async () => {
  const server = await createServer({
    configFile: false,
    root,
    logLevel: 'silent',
    optimizeDeps: {
      noDiscovery: true,
    },
    environments: {
      ssr: {
        dev: {
          createEnvironment: (name, config) =>
            new DevEnvironment(name, config, { hot: false }),
        },
      },
    },
  })
  onTestFinished(() => server.close())

  await expect(
    server.ssrLoadModule('/fixtures/modules/has-invalid-import.js'),
  ).rejects.toThrow(
    "ssrLoadModule requires the 'ssr' environment to be a runnable environment.",
  )
})

test('buildStart before transform', async () => {
  const fn = vi.fn()
  const server = await createServer({
    configFile: false,
    root,
    logLevel: 'error',
    plugins: [
      {
        name: 'test-plugin',
        async buildStart() {
          fn('buildStart:in')
          await new Promise((r) => setTimeout(r, 200))
          fn('buildStart:out')
        },
        resolveId(source) {
          if (source === 'virtual:test') {
            fn('resolveId')
            return '\0' + source
          }
        },
        load(id) {
          if (id === '\0virtual:test') {
            fn('load')
            return `export default 'ok'`
          }
        },
        transform(code, id) {
          if (id === '\0virtual:test') {
            fn('transform')
            return code
          }
        },
      },
    ],
  })
  onTestFinished(() => server.close())
  await server.pluginContainer.buildStart({})

  const mod = await server.ssrLoadModule('virtual:test')
  expect(mod.default).toBe('ok')
  expect(fn.mock.calls).toMatchInlineSnapshot(`
    [
      [
        "buildStart:in",
      ],
      [
        "buildStart:out",
      ],
      [
        "resolveId",
      ],
      [
        "load",
      ],
      [
        "transform",
      ],
    ]
  `)
})

test('server.fs check is not applied to ssrLoadModule', async () => {
  const server = await createServer({
    configFile: false,
    root,
    logLevel: 'silent',
    optimizeDeps: {
      noDiscovery: true,
    },
    server: {
      fs: {
        allow: [
          path.resolve(import.meta.dirname, './fixtures/named-overwrite-all'),
        ],
      },
    },
  })
  onTestFinished(() => server.close())
  await server.environments.ssr.pluginContainer.buildStart({})

  const mod = await server.ssrLoadModule('/fixtures/basic/file.js')
  expect(mod.default).toBe('ok')
})


// Formatting library for C++ - scanning API proof of concept
//
// Copyright (c) 2019 - present, Victor Zverovich and {fmt} contributors
// All rights reserved.
//
// For the license information refer to format.h.

#include <array>
#include <cassert>
#include <climits>
#include <tuple>

#include "fmt/format-inl.h"

FMT_BEGIN_NAMESPACE
namespace detail {

inline auto is_whitespace(char c) -> bool { return c == ' ' || c == '\n'; }

// If c is a hex digit returns its numeric value, otherwise -1.
inline auto to_hex_digit(char c) -> int {
  if (c >= '0' && c <= '9') return c - '0';
  if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  if (c >= 'A' && c <= 'F') return c - 'A' + 10;
  return -1;
}

struct maybe_contiguous_range {
  const char* begin;
  const char* end;

  explicit operator bool() const { return begin != nullptr; }
};

class scan_buffer {
 private:
  const char* ptr_;
  const char* end_;
  bool contiguous_;

 protected:
  scan_buffer(const char* ptr, const char* end, bool contiguous)
      : ptr_(ptr), end_(end), contiguous_(contiguous) {}
  ~scan_buffer() = default;

  void set(span<const char> buf) {
    ptr_ = buf.data;
    end_ = buf.data + buf.size;
  }

  auto ptr() const -> const char* { return ptr_; }

 public:
  scan_buffer(const scan_buffer&) = delete;
  void operator=(const scan_buffer&) = delete;

  // Fills the buffer with more input if available.
  virtual void consume() = 0;

  class sentinel {};

  class iterator {
   private:
    const char** ptr_;
    scan_buffer* buf_;  // This could be merged with ptr_.
    char value_;

    static auto get_sentinel() -> const char** {
      static const char* ptr = nullptr;
      return &ptr;
    }

    friend class scan_buffer;

    friend auto operator==(iterator lhs, sentinel) -> bool {
      return *lhs.ptr_ == nullptr;
    }
    friend auto operator!=(iterator lhs, sentinel) -> bool {
      return *lhs.ptr_ != nullptr;
    }

    iterator(scan_buffer* buf) : buf_(buf) {
      if (buf->ptr_ == buf->end_) {
        ptr_ = get_sentinel();
        return;
      }
      ptr_ = &buf->ptr_;
      value_ = *buf->ptr_;
    }

    friend scan_buffer& get_buffer(iterator it) { return *it.buf_; }

   public:
    iterator() : ptr_(get_sentinel()), buf_(nullptr) {}

    auto operator++() -> iterator& {
      if (!buf_->try_consume()) ptr_ = get_sentinel();
      value_ = *buf_->ptr_;
      return *this;
    }
    auto operator++(int) -> iterator {
      iterator copy = *this;
      ++*this;
      return copy;
    }
    auto operator*() const -> char { return value_; }

    auto base() const -> const char* { return buf_->ptr_; }

    friend auto to_contiguous(iterator it) -> maybe_contiguous_range;
    friend auto advance(iterator it, size_t n) -> iterator;
  };

  friend auto to_contiguous(iterator it) -> maybe_contiguous_range {
    if (it.buf_->is_contiguous()) return {it.buf_->ptr_, it.buf_->end_};
    return {nullptr, nullptr};
  }
  friend auto advance(iterator it, size_t n) -> iterator {
    FMT_ASSERT(it.buf_->is_contiguous(), "");
    const char*& ptr = it.buf_->ptr_;
    ptr += n;
    it.value_ = *ptr;
    if (ptr == it.buf_->end_) it.ptr_ = iterator::get_sentinel();
    return it;
  }

  auto begin() -> iterator { return this; }
  auto end() -> sentinel { return {}; }

  auto is_contiguous() const -> bool { return contiguous_; }

  // Tries consuming a single code unit. Returns true iff there is more input.
  auto try_consume() -> bool {
    FMT_ASSERT(ptr_ != end_, "");
    ++ptr_;
    if (ptr_ != end_) return true;
    consume();
    return ptr_ != end_;
  }
};

using scan_iterator = scan_buffer::iterator;
using scan_sentinel = scan_buffer::sentinel;

class string_scan_buffer final : public scan_buffer {
 private:
  void consume() override {}

 public:
  explicit string_scan_buffer(string_view s)
      : scan_buffer(s.begin(), s.end(), true) {}
};

class file_scan_buffer final : public scan_buffer {
 private:
  template <typename F, FMT_ENABLE_IF(sizeof(F::_IO_read_ptr) != 0 &&
                                      !FMT_USE_FALLBACK_FILE)>
  static auto get_file(F* f, int) -> glibc_file<F> {
    return f;
  }
  template <typename F,
            FMT_ENABLE_IF(sizeof(F::_p) != 0 && !FMT_USE_FALLBACK_FILE)>
  static auto get_file(F* f, int) -> apple_file<F> {
    return f;
  }
  static auto get_file(FILE* f, ...) -> fallback_file<FILE> { return f; }

  decltype(get_file(static_cast<FILE*>(nullptr), 0)) file_;

  // Fills the buffer if it is empty.
  void fill() {
    span<const char> buf = file_.get_read_buffer();
    if (buf.size == 0) {
      int c = file_.get();
      // Put the character back since we are only filling the buffer.
      if (c != EOF) file_.unget(static_cast<char>(c));
      buf = file_.get_read_buffer();
    }
    set(buf);
  }

  void consume() override {
    // Consume the current buffer content.
    size_t n = to_unsigned(ptr() - file_.get_read_buffer().data);
    for (size_t i = 0; i != n; ++i) file_.get();
    fill();
  }

 public:
  explicit file_scan_buffer(FILE* f)
      : scan_buffer(nullptr, nullptr, false), file_(f) {
    flockfile(f);
    fill();
  }
  ~file_scan_buffer() {
    FILE* f = file_;
    funlockfile(f);
  }
};
}  // namespace detail

template <typename T, typename Char = char> struct scanner {
  // A deleted default constructor indicates a disabled scanner.
  scanner() = delete;
};

class scan_parse_context {
 private:
  string_view format_;

 public:
  using iterator = string_view::iterator;

  FMT_CONSTEXPR explicit scan_parse_context(string_view format)
      : format_(format) {}

  FMT_CONSTEXPR auto begin() const -> iterator { return format_.begin(); }
  FMT_CONSTEXPR auto end() const -> iterator { return format_.end(); }

  void advance_to(iterator it) {
    format_.remove_prefix(detail::to_unsigned(it - begin()));
  }
};

namespace detail {
enum class scan_type {
  none_type,
  int_type,
  uint_type,
  long_long_type,
  ulong_long_type,
  double_type,
  float_type,
  string_type,
  string_view_type,
  custom_type
};

template <typename Context> struct custom_scan_arg {
  void* value;
  void (*scan)(void* arg, scan_parse_context& parse_ctx, Context& ctx);
};
}  // namespace detail

// A scan argument. Context is a template parameter for the compiled API where
// output can be unbuffered.
template <typename Context> class basic_scan_arg {
 private:
  using scan_type = detail::scan_type;
  scan_type type_;
  union {
    int* int_value_;
    unsigned* uint_value_;
    long long* long_long_value_;
    unsigned long long* ulong_long_value_;
    double* double_value_;
    float* float_value_;
    std::string* string_;
    string_view* string_view_;
    detail::custom_scan_arg<Context> custom_;
    // TODO: more types
  };

  template <typename T>
  static void scan_custom_arg(void* arg, scan_parse_context& parse_ctx,
                              Context& ctx) {
    auto s = scanner<T>();
    parse_ctx.advance_to(s.parse(parse_ctx));
    ctx.advance_to(s.scan(*static_cast<T*>(arg), ctx));
  }

 public:
  FMT_CONSTEXPR basic_scan_arg()
      : type_(scan_type::none_type), int_value_(nullptr) {}
  FMT_CONSTEXPR basic_scan_arg(int& value)
      : type_(scan_type::int_type), int_value_(&value) {}
  FMT_CONSTEXPR basic_scan_arg(unsigned& value)
      : type_(scan_type::uint_type), uint_value_(&value) {}
  FMT_CONSTEXPR basic_scan_arg(long long& value)
      : type_(scan_type::long_long_type), long_long_value_(&value) {}
  FMT_CONSTEXPR basic_scan_arg(unsigned long long& value)
      : type_(scan_type::ulong_long_type), ulong_long_value_(&value) {}
  FMT_CONSTEXPR basic_scan_arg(double& value)
      : type_(scan_type::double_type), double_value_(&value) {}
  FMT_CONSTEXPR basic_scan_arg(float& value)
      : type_(scan_type::float_type), float_value_(&value) {}
  FMT_CONSTEXPR basic_scan_arg(std::string& value)
      : type_(scan_type::string_type), string_(&value) {}
  FMT_CONSTEXPR basic_scan_arg(string_view& value)
      : type_(scan_type::string_view_type), string_view_(&value) {}
  template <typename T>
  FMT_CONSTEXPR basic_scan_arg(T& value) : type_(scan_type::custom_type) {
    custom_.value = &value;
    custom_.scan = scan_custom_arg<T>;
  }

  constexpr explicit operator bool() const noexcept {
    return type_ != scan_type::none_type;
  }

  auto type() const -> detail::scan_type { return type_; }

  template <typename Visitor>
  auto visit(Visitor&& vis) -> decltype(vis(monostate())) {
    switch (type_) {
    case scan_type::none_type:
      break;
    case scan_type::int_type:
      return vis(*int_value_);
    case scan_type::uint_type:
      return vis(*uint_value_);
    case scan_type::long_long_type:
      return vis(*long_long_value_);
    case scan_type::ulong_long_type:
      return vis(*ulong_long_value_);
    case scan_type::double_type:
      return vis(*double_value_);
    case scan_type::float_type:
      return vis(*float_value_);
    case scan_type::string_type:
      return vis(*string_);
    case scan_type::string_view_type:
      return vis(*string_view_);
    case scan_type::custom_type:
      break;
    }
    return vis(monostate());
  }

  auto scan_custom(const char* parse_begin, scan_parse_context& parse_ctx,
                   Context& ctx) const -> bool {
    if (type_ != scan_type::custom_type) return false;
    parse_ctx.advance_to(parse_begin);
    custom_.scan(custom_.value, parse_ctx, ctx);
    return true;
  }
};

class scan_context;
using scan_arg = basic_scan_arg<scan_context>;

struct scan_args {
  int size;
  const scan_arg* data;

  template <size_t N>
  FMT_CONSTEXPR scan_args(const std::array<scan_arg, N>& store)
      : size(N), data(store.data()) {
    static_assert(N < INT_MAX, "too many arguments");
  }
};

class scan_context {
 private:
  detail::scan_buffer& buf_;
  scan_args args_;

 public:
  using iterator = detail::scan_iterator;
  using sentinel = detail::scan_sentinel;

  FMT_CONSTEXPR explicit scan_context(detail::scan_buffer& buf, scan_args args)
      : buf_(buf), args_(args) {}

  FMT_CONSTEXPR auto arg(int id) const -> scan_arg {
    return id < args_.size ? args_.data[id] : scan_arg();
  }

  auto begin() const -> iterator { return buf_.begin(); }
  auto end() const -> sentinel { return {}; }

  void advance_to(iterator) { buf_.consume(); }
};

namespace detail {

const char* parse_scan_specs(const char* begin, const char* end,
                             format_specs& specs, scan_type) {
  while (begin != end) {
    switch (to_ascii(*begin)) {
    // TODO: parse more scan format specifiers
    case 'x':
      specs.set_type(presentation_type::hex);
      ++begin;
      break;
    case '}':
      return begin;
    }
  }
  return begin;
}

template <typename T, FMT_ENABLE_IF(std::is_unsigned<T>::value)>
auto read(scan_iterator it, T& value) -> scan_iterator {
  if (it == scan_sentinel()) return it;
  char c = *it;
  if (c < '0' || c > '9') report_error("invalid input");

  int num_digits = 0;
  T n = 0, prev = 0;
  char prev_digit = c;
  do {
    prev = n;
    n = n * 10 + static_cast<unsigned>(c - '0');
    prev_digit = c;
    c = *++it;
    ++num_digits;
    if (c < '0' || c > '9') break;
  } while (it != scan_sentinel());

  // Check overflow.
  if (num_digits <= std::numeric_limits<int>::digits10) {
    value = n;
    return it;
  }
  unsigned max = to_unsigned((std::numeric_limits<int>::max)());
  if (num_digits == std::numeric_limits<int>::digits10 + 1 &&
      prev * 10ull + unsigned(prev_digit - '0') <= max) {
    value = n;
  } else {
    report_error("number is too big");
  }
  return it;
}

template <typename T, FMT_ENABLE_IF(std::is_unsigned<T>::value)>
auto read_hex(scan_iterator it, T& value) -> scan_iterator {
  if (it == scan_sentinel()) return it;
  int digit = to_hex_digit(*it);
  if (digit < 0) report_error("invalid input");

  int num_digits = 0;
  T n = 0;
  do {
    n = (n << 4) + static_cast<unsigned>(digit);
    ++num_digits;
    digit = to_hex_digit(*++it);
    if (digit < 0) break;
  } while (it != scan_sentinel());

  // Check overflow.
  if (num_digits <= (std::numeric_limits<T>::digits >> 2))
    value = n;
  else
    report_error("number is too big");
  return it;
}

template <typename T, FMT_ENABLE_IF(std::is_unsigned<T>::value)>
auto read(scan_iterator it, T& value, const format_specs& specs)
    -> scan_iterator {
  if (specs.type() == presentation_type::hex) return read_hex(it, value);
  return read(it, value);
}

template <typename T, FMT_ENABLE_IF(std::is_signed<T>::value)>
auto read(scan_iterator it, T& value, const format_specs& specs = {})
    -> scan_iterator {
  bool negative = it != scan_sentinel() && *it == '-';
  if (negative) {
    ++it;
    if (it == scan_sentinel()) report_error("invalid input");
  }
  using unsigned_type = typename std::make_unsigned<T>::type;
  unsigned_type abs_value = 0;
  it = read(it, abs_value, specs);
  auto n = static_cast<T>(abs_value);
  value = negative ? -n : n;
  return it;
}

auto read(scan_iterator it, double& value, const format_specs& = {})
    -> scan_iterator {
  if (it == scan_sentinel()) return it;

  // Simple floating-point parsing
  bool negative = *it == '-';
  if (negative) {
    ++it;
    if (it == scan_sentinel()) report_error("invalid input");
  }

  double result = 0.0;
  // Parse integer part
  while (it != scan_sentinel() && *it >= '0' && *it <= '9') {
    result = result * 10.0 + (*it - '0');
    ++it;
  }

  // Parse decimal part if present
  if (it != scan_sentinel() && *it == '.') {
    ++it;
    double fraction = 0.1;
    while (it != scan_sentinel() && *it >= '0' && *it <= '9') {
      result += (*it - '0') * fraction;
      fraction *= 0.1;
      ++it;
    }
  }

  value = negative ? -result : result;
  return it;
}

auto read(scan_iterator it, float& value, const format_specs& specs = {})
    -> scan_iterator {
  double temp;
  it = read(it, temp, specs);
  value = static_cast<float>(temp);
  return it;
}

auto read(scan_iterator it, std::string& value, const format_specs& = {})
    -> scan_iterator {
  while (it != scan_sentinel() && *it != ' ') value.push_back(*it++);
  return it;
}

auto read(scan_iterator it, string_view& value, const format_specs& = {})
    -> scan_iterator {
  auto range = to_contiguous(it);
  // This could also be checked at compile time in scan.
  if (!range) report_error("string_view requires contiguous input");
  auto p = range.begin;
  while (p != range.end && *p != ' ') ++p;
  size_t size = to_unsigned(p - range.begin);
  value = {range.begin, size};
  return advance(it, size);
}

auto read(scan_iterator it, monostate, const format_specs& = {})
    -> scan_iterator {
  return it;
}

// An argument scanner that uses the default format, e.g. decimal for integers.
struct default_arg_scanner {
  scan_iterator it;

  template <typename T> FMT_INLINE auto operator()(T&& value) -> scan_iterator {
    return read(it, value);
  }
};

// An argument scanner with format specifiers.
struct arg_scanner {
  scan_iterator it;
  const format_specs& specs;

  template <typename T> auto operator()(T&& value) -> scan_iterator {
    return read(it, value, specs);
  }
};

struct scan_handler {
 private:
  scan_parse_context parse_ctx_;
  scan_context scan_ctx_;
  int next_arg_id_;

  using sentinel = scan_buffer::sentinel;

 public:
  FMT_CONSTEXPR scan_handler(string_view format, scan_buffer& buf,
                             scan_args args)
      : parse_ctx_(format), scan_ctx_(buf, args), next_arg_id_(0) {}

  auto pos() const -> scan_buffer::iterator { return scan_ctx_.begin(); }

  void on_text(const char* begin, const char* end) {
    if (begin == end) return;
    auto it = scan_ctx_.begin();
    for (; begin != end; ++begin, ++it) {
      if (it == sentinel() || *begin != *it) on_error("invalid input");
    }
    scan_ctx_.advance_to(it);
  }

  FMT_CONSTEXPR auto on_arg_id() -> int { return on_arg_id(next_arg_id_++); }
  FMT_CONSTEXPR auto on_arg_id(int id) -> int {
    if (!scan_ctx_.arg(id)) on_error("argument index out of range");
    return id;
  }
  FMT_CONSTEXPR auto on_arg_id(string_view id) -> int {
    if (id.data()) on_error("invalid format");
    return 0;
  }

  void on_replacement_field(int arg_id, const char* begin) {
    scan_arg arg = scan_ctx_.arg(arg_id);
    if (arg.scan_custom(begin, parse_ctx_, scan_ctx_)) return;
    auto it = scan_ctx_.begin();
    while (it != sentinel() && is_whitespace(*it)) ++it;
    scan_ctx_.advance_to(arg.visit(default_arg_scanner{it}));
  }

  auto on_format_specs(int arg_id, const char* begin, const char* end) -> const
      char* {
    scan_arg arg = scan_ctx_.arg(arg_id);
    if (arg.scan_custom(begin, parse_ctx_, scan_ctx_))
      return parse_ctx_.begin();
    auto specs = format_specs();
    begin = parse_scan_specs(begin, end, specs, arg.type());
    if (begin == end || *begin != '}') on_error("missing '}' in format string");
    scan_ctx_.advance_to(arg.visit(arg_scanner{scan_ctx_.begin(), specs}));
    return begin;
  }

  FMT_NORETURN void on_error(const char* message) { report_error(message); }
};

void vscan(detail::scan_buffer& buf, string_view fmt, scan_args args) {
  auto h = detail::scan_handler(fmt, buf, args);
  detail::parse_format_string(fmt, h);
}

template <size_t I, typename... T, FMT_ENABLE_IF(I == sizeof...(T))>
void make_args(std::array<scan_arg, sizeof...(T)>&, std::tuple<T...>&) {}

template <size_t I, typename... T, FMT_ENABLE_IF(I < sizeof...(T))>
void make_args(std::array<scan_arg, sizeof...(T)>& args,
               std::tuple<T...>& values) {
  using element_type = typename std::tuple_element<I, std::tuple<T...>>::type;
  static_assert(std::is_same<remove_cvref_t<element_type>, element_type>::value,
                "");
  args[I] = std::get<I>(values);
  make_args<I + 1>(args, values);
}
}  // namespace detail

template <typename Range, typename... T> class scan_data {
 private:
  std::tuple<T...> values_;
  Range range_;

 public:
  scan_data() = default;
  scan_data(T... values) : values_(std::move(values)...) {}

  auto value() const -> decltype(std::get<0>(values_)) {
    return std::get<0>(values_);
  }

  auto values() const -> const std::tuple<T...>& { return values_; }

  auto make_args() -> std::array<scan_arg, sizeof...(T)> {
    auto args = std::array<scan_arg, sizeof...(T)>();
    detail::make_args<0>(args, values_);
    return args;
  }

  auto range() const -> Range { return range_; }

  auto begin() const -> decltype(range_.begin()) { return range_.begin(); }
  auto end() const -> decltype(range_.end()) { return range_.end(); }
};

template <typename... T>
auto make_scan_args(T&... args) -> std::array<scan_arg, sizeof...(T)> {
  return {{args...}};
}

class scan_error {};

// A rudimentary version of std::expected for testing the API shape.
template <typename T, typename E> class expected {
 private:
  T value_;
  bool has_value_ = true;

 public:
  expected(T value) : value_(std::move(value)) {}

  explicit operator bool() const { return has_value_; }

  auto operator->() const -> const T* { return &value_; }

  auto error() -> E const { return E(); }
};

template <typename Range, typename... T>
using scan_result = expected<scan_data<Range, T...>, scan_error>;

auto vscan(string_view input, string_view fmt, scan_args args)
    -> string_view::iterator {
  auto&& buf = detail::string_scan_buffer(input);
  detail::vscan(buf, fmt, args);
  return input.begin() + (buf.begin().base() - input.data());
}

// Scans the input and stores the results (in)to args.
template <typename... T>
auto scan_to(string_view input, string_view fmt, T&... args)
    -> string_view::iterator {
  return vscan(input, fmt, make_scan_args(args...));
}

template <typename... T>
auto scan(string_view input, string_view fmt)
    -> scan_result<string_view, T...> {
  auto data = scan_data<string_view, T...>();
  vscan(input, fmt, data.make_args());
  return data;
}

template <typename Range, typename... T,
          FMT_ENABLE_IF(!std::is_convertible<Range, string_view>::value)>
auto scan_to(Range&& input, string_view fmt, T&... args)
    -> decltype(std::begin(input)) {
  auto it = std::begin(input);
  detail::vscan(get_buffer(it), fmt, make_scan_args(args...));
  return it;
}

template <typename... T>
auto scan_to(FILE* f, string_view fmt, T&... args) -> bool {
  auto&& buf = detail::file_scan_buffer(f);
  detail::vscan(buf, fmt, make_scan_args(args...));
  return buf.begin() != buf.end();
}

FMT_END_NAMESPACE


#!/usr/bin/env node
import { performance } from 'node:perf_hooks'
import module from 'node:module'

if (!import.meta.url.includes('node_modules')) {
  if (!process.env.DEBUG_DISABLE_SOURCE_MAP) {
    // eslint-disable-next-line n/no-unsupported-features/node-builtins -- only used in dev
    process.setSourceMapsEnabled(true)
  }

  process.on('unhandledRejection', (err) => {
    throw new Error('UNHANDLED PROMISE REJECTION', { cause: err })
  })
}

global.__vite_start_time = performance.now()

// check debug mode first before requiring the CLI.
const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg))
const filterIndex = process.argv.findIndex((arg) =>
  /^(?:-f|--filter)$/.test(arg),
)
const profileIndex = process.argv.indexOf('--profile')

if (debugIndex > 0) {
  let value = process.argv[debugIndex + 1]
  if (!value || value[0] === '-') {
    value = 'vite:*'
  } else {
    // support debugging multiple flags with comma-separated list
    value = value
      .split(',')
      .map((v) => `vite:${v}`)
      .join(',')
  }
  process.env.DEBUG = `${
    process.env.DEBUG ? process.env.DEBUG + ',' : ''
  }${value}`

  if (filterIndex > 0) {
    const filter = process.argv[filterIndex + 1]
    if (filter && filter[0] !== '-') {
      process.env.VITE_DEBUG_FILTER = filter
    }
  }
}

function start() {
  try {
    // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.8.0+ and only called if it exists
    module.enableCompileCache?.()
    // flush the cache after 10s because the cache is not flushed until process end
    // for dev server, the cache is never flushed unless manually flushed because the process.exit is called
    // also flushing the cache in SIGINT handler seems to cause the process to hang
    setTimeout(() => {
      try {
        // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.12.0+ and only called if it exists
        module.flushCompileCache?.()
      } catch {}
    }, 10 * 1000).unref()
  } catch {}
  return import('../dist/node/cli.js')
}

if (profileIndex > 0) {
  process.argv.splice(profileIndex, 1)
  const next = process.argv[profileIndex]
  if (next && next[0] !== '-') {
    process.argv.splice(profileIndex, 1)
  }
  const inspector = await import('node:inspector').then((r) => r.default)
  const session = (global.__vite_profile_session = new inspector.Session())
  session.connect()
  session.post('Profiler.enable', () => {
    session.post('Profiler.start', start)
  })
} else {
  start()
}


// eslint-disable-next-line n/prefer-node-protocol
import { URL } from 'url'
import { defineConfig } from 'vite'

// make sure bundling works even if `url` refers to the locally installed
// `url` package instead of the built-in `url` nodejs module
globalThis.__test_url = URL

export default defineConfig({
  server: {
    host: 'localhost',
  },
  build: {
    //speed up build
    minify: false,
    target: 'esnext',
  },
})


import { expect, test } from 'vitest'
import {
  editFile,
  isBuild,
  page,
  untilBrowserLogAfter,
  viteTestUrl,
} from '~utils'

test.runIf(!isBuild)('proxy-hmr', async () => {
  await untilBrowserLogAfter(
    () => page.goto(viteTestUrl),
    // wait for both main and sub app HMR connection
    [/connected/, /connected/],
  )

  const otherAppTextLocator = page.frameLocator('iframe').locator('.content')
  await expect
    .poll(() => otherAppTextLocator.textContent())
    .toMatch('other app')
  editFile('other-app/index.html', (code) =>
    code.replace('app', 'modified app'),
  )
  await expect
    .poll(() => otherAppTextLocator.textContent())
    .toMatch('other modified app')
})


import path from 'node:path'
import { defineConfig } from 'vite'

export default defineConfig({
  input: {
    entry1: path.join(
      import.meta.dirname,
      'sass-modern-compiler-build/entry1.scss',
    ),
    entry2: path.join(
      import.meta.dirname,
      'sass-modern-compiler-build/entry2.scss',
    ),
  },
  build: {
    outDir: 'dist/sass-modern-compiler-build',
  },
})


@import '~/styles/background.css';
@import '~/styles/tailwind.css';
@import '../../references.css';

html,
body {
  font-family: sans-serif;
  line-height: 2.4rem;
}

body {
  color: black;
  margin: 4vh auto;
  max-width: 800px;
  padding: 0 4vw;
}

ul {
  padding: 0 0.4em;
  margin: 0;
}

li {
  display: flex;
  align-items: center;
}

img {
  height: 32px;
  width: 32px;
}


import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, test } from 'vitest'
import { isBuild, testDir } from '~utils'

describe.runIf(isBuild)('build', () => {
  // assert correct files
  test('sourcemap generation for web workers', async () => {
    const assetsDir = path.resolve(testDir, 'dist/iife-sourcemap-inline/assets')
    const files = fs.readdirSync(assetsDir)
    // inline sourcemaps should not produce .map files
    expect(files.filter((f) => f.endsWith('.map'))).toStrictEqual([])
    const index = files.find((f) => f.includes('main-module'))
    const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
    const indexSourcemap = getSourceMapUrl(content)
    const worker = files.find((f) => /^my-worker-[-\w]+\.js$/.test(f))
    const workerContent = fs.readFileSync(
      path.resolve(assetsDir, worker),
      'utf-8',
    )
    const workerSourcemap = getSourceMapUrl(workerContent)
    const sharedWorker = files.find((f) =>
      /^my-shared-worker-[-\w]+\.js$/.test(f),
    )
    const sharedWorkerContent = fs.readFileSync(
      path.resolve(assetsDir, sharedWorker),
      'utf-8',
    )
    const sharedWorkerSourcemap = getSourceMapUrl(sharedWorkerContent)
    const possibleTsOutputWorker = files.find((f) =>
      /^possible-ts-output-worker-[-\w]+\.js$/.test(f),
    )
    const possibleTsOutputWorkerContent = fs.readFileSync(
      path.resolve(assetsDir, possibleTsOutputWorker),
      'utf-8',
    )
    const possibleTsOutputWorkerSourcemap = getSourceMapUrl(
      possibleTsOutputWorkerContent,
    )
    const workerNestedWorker = files.find((f) =>
      /^worker-nested-worker-[-\w]+\.js$/.test(f),
    )
    const workerNestedWorkerContent = fs.readFileSync(
      path.resolve(assetsDir, workerNestedWorker),
      'utf-8',
    )
    const workerNestedWorkerSourcemap = getSourceMapUrl(
      workerNestedWorkerContent,
    )
    const subWorker = files.find((f) => /^sub-worker-[-\w]+\.js$/.test(f))
    const subWorkerContent = fs.readFileSync(
      path.resolve(assetsDir, subWorker),
      'utf-8',
    )
    const subWorkerSourcemap = getSourceMapUrl(subWorkerContent)

    // sourcemap should exist and have a data URL
    expect(indexSourcemap).toMatch(/^data:/)
    expect(workerSourcemap).toMatch(/^data:/)
    expect(sharedWorkerSourcemap).toMatch(/^data:/)
    expect(possibleTsOutputWorkerSourcemap).toMatch(/^data:/)
    expect(workerNestedWorkerSourcemap).toMatch(/^data:/)
    expect(subWorkerSourcemap).toMatch(/^data:/)

    // worker should have all imports resolved and no exports
    expect(workerContent).not.toMatch(/import\s*["(]/)
    expect(workerContent).not.toMatch(/\bexport\b/)

    // shared worker should have all imports resolved and no exports
    expect(sharedWorkerContent).not.toMatch(/import\s*["(]/)
    expect(sharedWorkerContent).not.toMatch(/\bexport\b/)

    // chunk
    expect(content).toMatch(
      'new Worker(`/iife-sourcemap-inline/assets/my-worker',
    )
    expect(content).toMatch('new Worker(`data:text/javascript;charset=utf-8,')
    expect(content).toMatch(
      'new Worker(`/iife-sourcemap-inline/assets/possible-ts-output-worker',
    )
    expect(content).toMatch(
      'new Worker(`/iife-sourcemap-inline/assets/worker-nested-worker',
    )
    expect(content).toMatch(
      'new SharedWorker(`/iife-sourcemap-inline/assets/my-shared-worker',
    )

    // inlined
    expect(content).toMatch(`(self.URL||self.webkitURL).createObjectURL`)
    expect(content).toMatch(`self.Blob`)

    expect(workerNestedWorkerContent).toMatch(
      'new Worker(`/iife-sourcemap-inline/assets/sub-worker',
    )
  })
})

function getSourceMapUrl(code: string): string {
  const regex = /\/\/[#@]\ssource(?:Mapping)?URL=\s*(\S+)/
  const results = regex.exec(code)

  if (results && results.length >= 2) {
    return results[1]
  }
  return null
}


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

```cpp
#if JSON_DIAGNOSTIC_POSITIONS
constexpr std::size_t end_pos() const noexcept;
#endif
```

Returns the position immediately following the last character of the JSON string from which the value was parsed from.

| JSON type | return value                      |
|-----------|-----------------------------------|
| object    | position after the closing `}`    |
| array     | position after the closing `]`    |
| string    | position after the closing `"`    |
| number    | position after the last character |
| boolean   | position after `e`                |
| null      | position after `l`                |

## Return value

the position of the character _following_ the last character of the given value in the parsed JSON string, if the
value was created by the [`parse`](parse.md) function, or `std::string::npos` if the value was constructed otherwise

## Exception safety

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

## Complexity

Constant.

## Notes

!!! note "Note"

    The function is only available if macro [`JSON_DIAGNOSTIC_POSITIONS`](../macros/json_diagnostic_positions.md) has
    been defined to `#!cpp 1` before including the library header.

!!! warning "Invalidation"

    The returned positions are only valid as long as the JSON value is not changed. The positions are *not* updated
    when the JSON value is changed.

## Examples

??? example "Example"

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

    Output:

    ```
    --8<-- "examples/diagnostic_positions.output"
    ```

    The output shows the start/end positions of all the objects and fields in the JSON string.

## See also

- [start_pos](start_pos.md) to access the start position
- [JSON_DIAGNOSTIC_POSITIONS](../macros/json_diagnostic_positions.md) for an overview of the diagnostic positions

## Version history

- Added in version 3.12.0.


{% extends 'base.html' %}

{% block intro %}
  fetch
  is the modern plain JavaScript way to make requests. It's
  supported in all modern browsers.
{% endblock %}

{% block script %}

{% endblock %}


import { defineConfig } from 'vite'
import { composeVisitors } from 'lightningcss'
import baseConfig from './vite.config.js'
import {
  nestedLikePlugin,
  testDirDep,
  testInjectUrl,
  testSourceInput,
} from './lightningcss-plugins.js'

export default defineConfig({
  ...baseConfig,
  css: {
    ...baseConfig.css,
    transformer: 'lightningcss',
    lightningcss: {
      cssModules: {
        pattern: '[name]__[local]___[hash]',
      },
      visitor: composeVisitors([
        nestedLikePlugin(),
        testDirDep,
        testSourceInput(),
        testInjectUrl(),
      ]),
    },
  },
  cacheDir: 'node_modules/.vite-no-css-minify',
})


export async function render(url) {
  switch (url) {
    case '/':
      return `<ul>${[
        '/static-light',
        '/static-heavy',
        '/direct-add',
        '/direct-light',
      ]
        .map((name) => `<li><a href="${name}">${name}</a></li>`)
        .join('')}</ul>`
    case '/static-light':
      return (await import('./static-light')).render()
    case '/static-heavy':
      return (await import('./static-heavy')).render()
    case '/direct-add':
      return (await import('./direct-add')).render()
    case '/direct-light':
      return (await import('./direct-light')).render()
  }
}