index.cjs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. 'use strict';
  2. function genString(input, options = {}) {
  3. const str = JSON.stringify(input);
  4. if (!options.singleQuotes) {
  5. return str;
  6. }
  7. return `'${escapeString(str).slice(1, -1)}'`;
  8. }
  9. const NEEDS_ESCAPE_RE = /[\n\r'\\\u2028\u2029]/;
  10. const QUOTE_NEWLINE_RE = /([\n\r'\u2028\u2029])/g;
  11. const BACKSLASH_RE = /\\/g;
  12. function escapeString(id) {
  13. if (!NEEDS_ESCAPE_RE.test(id)) {
  14. return id;
  15. }
  16. return id.replace(BACKSLASH_RE, "\\\\").replace(QUOTE_NEWLINE_RE, "\\$1");
  17. }
  18. function genSafeVariableName(name) {
  19. if (reservedNames.has(name)) {
  20. return `_${name}`;
  21. }
  22. return name.replace(/^\d/, (r) => `_${r}`).replace(/\W/g, (r) => "_" + r.charCodeAt(0));
  23. }
  24. const reservedNames = /* @__PURE__ */ new Set([
  25. "Infinity",
  26. "NaN",
  27. "arguments",
  28. "await",
  29. "break",
  30. "case",
  31. "catch",
  32. "class",
  33. "const",
  34. "continue",
  35. "debugger",
  36. "default",
  37. "delete",
  38. "do",
  39. "else",
  40. "enum",
  41. "eval",
  42. "export",
  43. "extends",
  44. "false",
  45. "finally",
  46. "for",
  47. "function",
  48. "if",
  49. "implements",
  50. "import",
  51. "in",
  52. "instanceof",
  53. "interface",
  54. "let",
  55. "new",
  56. "null",
  57. "package",
  58. "private",
  59. "protected",
  60. "public",
  61. "return",
  62. "static",
  63. "super",
  64. "switch",
  65. "this",
  66. "throw",
  67. "true",
  68. "try",
  69. "typeof",
  70. "undefined",
  71. "var",
  72. "void",
  73. "while",
  74. "with",
  75. "yield"
  76. ]);
  77. function _genStatement(type, specifier, names, options = {}) {
  78. const specifierString = genString(specifier, options);
  79. if (!names) {
  80. return `${type} ${specifierString};`;
  81. }
  82. const nameArray = Array.isArray(names);
  83. const _names = (nameArray ? names : [names]).map((index) => {
  84. if (typeof index === "string") {
  85. return { name: index };
  86. }
  87. if (index.name === index.as) {
  88. index = { name: index.name };
  89. }
  90. return index;
  91. });
  92. const namesString = _names.map((index) => index.as ? `${index.name} as ${index.as}` : index.name).join(", ");
  93. if (nameArray) {
  94. return `${type} { ${namesString} } from ${genString(
  95. specifier,
  96. options
  97. )}${_genImportAttributes(type, options)};`;
  98. }
  99. return `${type} ${namesString} from ${genString(
  100. specifier,
  101. options
  102. )}${_genImportAttributes(type, options)};`;
  103. }
  104. function _genImportAttributes(type, options) {
  105. if (type === "import type" || type === "export type") {
  106. return "";
  107. }
  108. if (typeof options.attributes?.type === "string") {
  109. return ` with { type: ${genString(options.attributes.type)} }`;
  110. }
  111. if (typeof options.assert?.type === "string") {
  112. return ` assert { type: ${genString(options.assert.type)} }`;
  113. }
  114. return "";
  115. }
  116. function genImport(specifier, imports, options = {}) {
  117. return _genStatement("import", specifier, imports, options);
  118. }
  119. function genTypeImport(specifier, imports, options = {}) {
  120. return _genStatement("import type", specifier, imports, options);
  121. }
  122. function genExport(specifier, exports, options = {}) {
  123. return _genStatement("export", specifier, exports, options);
  124. }
  125. function genDynamicImport(specifier, options = {}) {
  126. const commentString = options.comment ? ` /* ${options.comment} */` : "";
  127. const wrapperString = options.wrapper === false ? "" : "() => ";
  128. const ineropString = options.interopDefault ? ".then(m => m.default || m)" : "";
  129. const optionsString = _genDynamicImportAttributes(options);
  130. return `${wrapperString}import(${genString(
  131. specifier,
  132. options
  133. )}${commentString}${optionsString})${ineropString}`;
  134. }
  135. function _genDynamicImportAttributes(options = {}) {
  136. if (typeof options.assert?.type === "string") {
  137. return `, { assert: { type: ${genString(options.assert.type)} } }`;
  138. }
  139. if (typeof options.attributes?.type === "string") {
  140. return `, { with: { type: ${genString(options.attributes.type)} } }`;
  141. }
  142. return "";
  143. }
  144. function wrapInDelimiters(lines, indent = "", delimiters = "{}", withComma = true) {
  145. if (lines.length === 0) {
  146. return delimiters;
  147. }
  148. const [start, end] = delimiters;
  149. return `${start}
  150. ` + lines.join(withComma ? ",\n" : "\n") + `
  151. ${indent}${end}`;
  152. }
  153. const VALID_IDENTIFIER_RE = /^[$_]?([A-Z_a-z]\w*|\d)$/;
  154. function genObjectKey(key) {
  155. return VALID_IDENTIFIER_RE.test(key) ? key : genString(key);
  156. }
  157. function genObjectFromRaw(object, indent = "", options = {}) {
  158. return genObjectFromRawEntries(Object.entries(object), indent, options);
  159. }
  160. function genObjectFromValues(obj, indent = "", options = {}) {
  161. return genObjectFromRaw(obj, indent, { preserveTypes: true, ...options });
  162. }
  163. function genArrayFromRaw(array, indent = "", options = {}) {
  164. const newIdent = indent + " ";
  165. return wrapInDelimiters(
  166. array.map((index) => `${newIdent}${genRawValue(index, newIdent, options)}`),
  167. indent,
  168. "[]"
  169. );
  170. }
  171. function genObjectFromRawEntries(array, indent = "", options = {}) {
  172. const newIdent = indent + " ";
  173. return wrapInDelimiters(
  174. array.map(
  175. ([key, value]) => `${newIdent}${genObjectKey(key)}: ${genRawValue(value, newIdent, options)}`
  176. ),
  177. indent,
  178. "{}"
  179. );
  180. }
  181. function genRawValue(value, indent = "", options = {}) {
  182. if (value === void 0) {
  183. return "undefined";
  184. }
  185. if (value === null) {
  186. return "null";
  187. }
  188. if (Array.isArray(value)) {
  189. return genArrayFromRaw(value, indent, options);
  190. }
  191. if (value && typeof value === "object") {
  192. return genObjectFromRaw(value, indent, options);
  193. }
  194. if (options.preserveTypes && typeof value !== "function") {
  195. return JSON.stringify(value);
  196. }
  197. return value.toString();
  198. }
  199. function genTypeExport(specifier, imports, options = {}) {
  200. return _genStatement("export type", specifier, imports, options);
  201. }
  202. function genInlineTypeImport(specifier, name = "default", options = {}) {
  203. return `typeof ${genDynamicImport(specifier, {
  204. ...options,
  205. wrapper: false
  206. })}.${name}`;
  207. }
  208. function genTypeObject(object, indent = "") {
  209. const newIndent = indent + " ";
  210. return wrapInDelimiters(
  211. Object.entries(object).map(([key, value]) => {
  212. const [, k = key, optional = ""] = key.match(/^(.*[^?])(\?)?$/) || [];
  213. if (typeof value === "string") {
  214. return `${newIndent}${genObjectKey(k)}${optional}: ${value}`;
  215. }
  216. return `${newIndent}${genObjectKey(k)}${optional}: ${genTypeObject(
  217. value,
  218. newIndent
  219. )}`;
  220. }),
  221. indent,
  222. "{}",
  223. false
  224. );
  225. }
  226. function genInterface(name, contents, options = {}, indent = "") {
  227. const result = [
  228. options.export && "export",
  229. `interface ${name}`,
  230. options.extends && `extends ${Array.isArray(options.extends) ? options.extends.join(", ") : options.extends}`,
  231. contents ? genTypeObject(contents, indent) : "{}"
  232. ].filter(Boolean).join(" ");
  233. return result;
  234. }
  235. function genAugmentation(specifier, interfaces) {
  236. return `declare module ${genString(specifier)} ${wrapInDelimiters(
  237. Object.entries(interfaces || {}).map(
  238. ([key, entry]) => " " + (Array.isArray(entry) ? genInterface(key, ...entry) : genInterface(key, entry, {}, " "))
  239. )
  240. )}`;
  241. }
  242. exports.escapeString = escapeString;
  243. exports.genArrayFromRaw = genArrayFromRaw;
  244. exports.genAugmentation = genAugmentation;
  245. exports.genDynamicImport = genDynamicImport;
  246. exports.genExport = genExport;
  247. exports.genImport = genImport;
  248. exports.genInlineTypeImport = genInlineTypeImport;
  249. exports.genInterface = genInterface;
  250. exports.genObjectFromRaw = genObjectFromRaw;
  251. exports.genObjectFromRawEntries = genObjectFromRawEntries;
  252. exports.genObjectFromValues = genObjectFromValues;
  253. exports.genObjectKey = genObjectKey;
  254. exports.genSafeVariableName = genSafeVariableName;
  255. exports.genString = genString;
  256. exports.genTypeExport = genTypeExport;
  257. exports.genTypeImport = genTypeImport;
  258. exports.genTypeObject = genTypeObject;
  259. exports.wrapInDelimiters = wrapInDelimiters;