UNPKG

1.68 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const parseJson = require("json-parse-better-errors");
9const Parser = require("../Parser");
10const JsonExportsDependency = require("../dependencies/JsonExportsDependency");
11
12/** @typedef {import("../../declarations/plugins/JsonModulesPluginParser").JsonModulesPluginParserOptions} JsonModulesPluginParserOptions */
13/** @typedef {import("../Parser").ParserState} ParserState */
14/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
15
16class JsonParser extends Parser {
17 /**
18 * @param {JsonModulesPluginParserOptions} options parser options
19 */
20 constructor(options) {
21 super();
22 this.options = options || {};
23 }
24
25 /**
26 * @param {string | Buffer | PreparsedAst} source the source to parse
27 * @param {ParserState} state the parser state
28 * @returns {ParserState} the parser state
29 */
30 parse(source, state) {
31 if (Buffer.isBuffer(source)) {
32 source = source.toString("utf-8");
33 }
34
35 /** @type {JsonModulesPluginParserOptions["parse"]} */
36 const parseFn =
37 typeof this.options.parse === "function" ? this.options.parse : parseJson;
38
39 const data =
40 typeof source === "object"
41 ? source
42 : parseFn(source[0] === "\ufeff" ? source.slice(1) : source);
43
44 state.module.buildInfo.jsonData = data;
45 state.module.buildInfo.strict = true;
46 state.module.buildMeta.exportsType = "default";
47 state.module.buildMeta.defaultObject =
48 typeof data === "object" ? "redirect-warn" : false;
49 state.module.addDependency(
50 new JsonExportsDependency(JsonExportsDependency.getExportsFromData(data))
51 );
52 return state;
53 }
54}
55
56module.exports = JsonParser;