| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- /*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
- */
- "use strict";
- const Parser = require("../Parser");
- const JsonExportsDependency = require("../dependencies/JsonExportsDependency");
- const parseJson = require("../util/parseJson");
- const JsonData = require("./JsonData");
- /** @import { JsonParserOptions } from "../../declarations/WebpackOptions" */
- /** @import { JsonModuleBuildInfo } from "./JsonModule" */
- /** @import { BuildMeta } from "../Module" */
- /** @import { ParserState, PreparsedAst } from "../Parser" */
- /** @import { JsonValue } from "../util/fs" */
- /** @typedef {(input: string) => Buffer | JsonValue} ParseFn */
- /**
- * Defines the function returning type used by this module.
- * @template T
- * @typedef {import("../util/memoize").FunctionReturning<T>} FunctionReturning
- */
- class JsonParser extends Parser {
- /**
- * Creates an instance of JsonParser.
- * @param {JsonParserOptions} options parser options
- */
- constructor(options = {}) {
- super();
- /** @type {JsonParserOptions} */
- this.options = options;
- }
- /**
- * Parses the provided source and updates the parser state.
- * @param {string | Buffer | PreparsedAst} source the source to parse
- * @param {ParserState} state the parser state
- * @returns {ParserState} the parser state
- */
- parse(source, state) {
- if (Buffer.isBuffer(source)) {
- source = source.toString("utf8");
- }
- const parseFn =
- typeof this.options.parse === "function" ? this.options.parse : parseJson;
- /** @type {Buffer | JsonValue | undefined} */
- const data =
- typeof source === "object"
- ? source
- : parseFn(source[0] === "\uFEFF" ? source.slice(1) : source);
- const jsonData = new JsonData(/** @type {Buffer | JsonValue} */ (data));
- const buildInfo = /** @type {JsonModuleBuildInfo} */ (
- state.module.buildInfo
- );
- buildInfo.jsonData = jsonData;
- buildInfo.strict = true;
- const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta);
- buildMeta.exportsType = "default";
- buildMeta.defaultObject =
- typeof data === "object"
- ? this.options.namedExports === false
- ? false
- : this.options.namedExports === true
- ? "redirect"
- : "redirect-warn"
- : false;
- state.module.addDependency(
- new JsonExportsDependency(
- jsonData,
- /** @type {number} */
- (this.options.exportsDepth)
- )
- );
- return state;
- }
- }
- module.exports = JsonParser;
|