stringifyNumber-dea1120c.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. 'use strict';
  2. var _rollupPluginBabelHelpers = require('./_rollupPluginBabelHelpers-eed30217.js');
  3. function addCommentBefore(str, indent, comment) {
  4. if (!comment) return str;
  5. const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`);
  6. return `#${cc}\n${indent}${str}`;
  7. }
  8. function addComment(str, indent, comment) {
  9. return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`);
  10. }
  11. class Node {}
  12. /**
  13. * Recursively convert any node or its contents to native JavaScript
  14. *
  15. * @param value - The input value
  16. * @param {string|null} arg - If `value` defines a `toJSON()` method, use this
  17. * as its first argument
  18. * @param ctx - Conversion context, originally set in Document#toJS(). If
  19. * `{ keep: true }` is not set, output should be suitable for JSON
  20. * stringification.
  21. */
  22. function toJS(value, arg, ctx) {
  23. if (Array.isArray(value)) return value.map((v, i) => toJS(v, String(i), ctx));
  24. if (value && typeof value.toJSON === 'function') {
  25. const anchor = ctx && ctx.anchors && ctx.anchors.get(value);
  26. if (anchor) ctx.onCreate = res => {
  27. anchor.res = res;
  28. delete ctx.onCreate;
  29. };
  30. const res = value.toJSON(arg, ctx);
  31. if (anchor && ctx.onCreate) ctx.onCreate(res);
  32. return res;
  33. }
  34. if (!(ctx && ctx.keep) && typeof value === 'bigint') return Number(value);
  35. return value;
  36. }
  37. const isScalarValue = value => !value || typeof value !== 'function' && typeof value !== 'object';
  38. class Scalar extends Node {
  39. constructor(value) {
  40. super();
  41. this.value = value;
  42. }
  43. toJSON(arg, ctx) {
  44. return ctx && ctx.keep ? this.value : toJS(this.value, arg, ctx);
  45. }
  46. toString() {
  47. return String(this.value);
  48. }
  49. }
  50. function findTagObject(value, tagName, tags) {
  51. if (tagName) {
  52. const match = tags.filter(t => t.tag === tagName);
  53. const tagObj = match.find(t => !t.format) || match[0];
  54. if (!tagObj) throw new Error(`Tag ${tagName} not found`);
  55. return tagObj;
  56. }
  57. return tags.find(t => t.identify && t.identify(value) && !t.format);
  58. }
  59. function createNode(value, tagName, ctx) {
  60. if (value instanceof Node) return value;
  61. const {
  62. onAlias,
  63. onTagObj,
  64. prevObjects,
  65. wrapScalars
  66. } = ctx;
  67. const {
  68. map,
  69. seq,
  70. tags
  71. } = ctx.schema;
  72. if (tagName && tagName.startsWith('!!')) tagName = _rollupPluginBabelHelpers.defaultTagPrefix + tagName.slice(2);
  73. let tagObj = findTagObject(value, tagName, tags);
  74. if (!tagObj) {
  75. if (typeof value.toJSON === 'function') value = value.toJSON();
  76. if (!value || typeof value !== 'object') return wrapScalars ? new Scalar(value) : value;
  77. tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map;
  78. }
  79. if (onTagObj) {
  80. onTagObj(tagObj);
  81. delete ctx.onTagObj;
  82. } // Detect duplicate references to the same object & use Alias nodes for all
  83. // after first. The `obj` wrapper allows for circular references to resolve.
  84. const obj = {
  85. value: undefined,
  86. node: undefined
  87. };
  88. if (value && typeof value === 'object') {
  89. const prev = prevObjects.get(value);
  90. if (prev) return onAlias(prev);
  91. obj.value = value;
  92. prevObjects.set(value, obj);
  93. }
  94. obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new Scalar(value) : value;
  95. if (tagName && obj.node instanceof Node) obj.node.tag = tagName;
  96. return obj.node;
  97. }
  98. function collectionFromPath(schema, path, value) {
  99. let v = value;
  100. for (let i = path.length - 1; i >= 0; --i) {
  101. const k = path[i];
  102. if (Number.isInteger(k) && k >= 0) {
  103. const a = [];
  104. a[k] = v;
  105. v = a;
  106. } else {
  107. const o = {};
  108. Object.defineProperty(o, k, {
  109. value: v,
  110. writable: true,
  111. enumerable: true,
  112. configurable: true
  113. });
  114. v = o;
  115. }
  116. }
  117. return createNode(v, null, {
  118. onAlias() {
  119. throw new Error('Repeated objects are not supported here');
  120. },
  121. prevObjects: new Map(),
  122. schema,
  123. wrapScalars: false
  124. });
  125. } // null, undefined, or an empty non-string iterable (e.g. [])
  126. const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done;
  127. class Collection extends Node {
  128. constructor(schema) {
  129. super();
  130. _rollupPluginBabelHelpers._defineProperty(this, "items", []);
  131. this.schema = schema;
  132. }
  133. addIn(path, value) {
  134. if (isEmptyPath(path)) this.add(value);else {
  135. const [key, ...rest] = path;
  136. const node = this.get(key, true);
  137. if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  138. }
  139. }
  140. deleteIn([key, ...rest]) {
  141. if (rest.length === 0) return this.delete(key);
  142. const node = this.get(key, true);
  143. if (node instanceof Collection) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  144. }
  145. getIn([key, ...rest], keepScalar) {
  146. const node = this.get(key, true);
  147. if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined;
  148. }
  149. hasAllNullValues() {
  150. return this.items.every(node => {
  151. if (!node || node.type !== 'PAIR') return false;
  152. const n = node.value;
  153. return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag;
  154. });
  155. }
  156. hasIn([key, ...rest]) {
  157. if (rest.length === 0) return this.has(key);
  158. const node = this.get(key, true);
  159. return node instanceof Collection ? node.hasIn(rest) : false;
  160. }
  161. setIn([key, ...rest], value) {
  162. if (rest.length === 0) {
  163. this.set(key, value);
  164. } else {
  165. const node = this.get(key, true);
  166. if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  167. }
  168. }
  169. /* istanbul ignore next: overridden in implementations */
  170. toJSON() {
  171. return null;
  172. }
  173. toString(ctx, {
  174. blockItem,
  175. flowChars,
  176. isMap,
  177. itemIndent
  178. }, onComment, onChompKeep) {
  179. const {
  180. indent,
  181. indentStep,
  182. stringify
  183. } = ctx;
  184. const inFlow = this.type === _rollupPluginBabelHelpers.Type.FLOW_MAP || this.type === _rollupPluginBabelHelpers.Type.FLOW_SEQ || ctx.inFlow;
  185. if (inFlow) itemIndent += indentStep;
  186. const allNullValues = isMap && this.hasAllNullValues();
  187. ctx = Object.assign({}, ctx, {
  188. allNullValues,
  189. indent: itemIndent,
  190. inFlow,
  191. type: null
  192. });
  193. let chompKeep = false;
  194. let hasItemWithNewLine = false;
  195. const nodes = this.items.reduce((nodes, item, i) => {
  196. let comment;
  197. if (item) {
  198. if (!chompKeep && item.spaceBefore) nodes.push({
  199. type: 'comment',
  200. str: ''
  201. });
  202. if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => {
  203. nodes.push({
  204. type: 'comment',
  205. str: `#${line}`
  206. });
  207. });
  208. if (item.comment) comment = item.comment;
  209. if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true;
  210. }
  211. chompKeep = false;
  212. let str = stringify(item, ctx, () => comment = null, () => chompKeep = true);
  213. if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true;
  214. if (inFlow && i < this.items.length - 1) str += ',';
  215. str = addComment(str, itemIndent, comment);
  216. if (chompKeep && (comment || inFlow)) chompKeep = false;
  217. nodes.push({
  218. type: 'item',
  219. str
  220. });
  221. return nodes;
  222. }, []);
  223. let str;
  224. if (nodes.length === 0) {
  225. str = flowChars.start + flowChars.end;
  226. } else if (inFlow) {
  227. const {
  228. start,
  229. end
  230. } = flowChars;
  231. const strings = nodes.map(n => n.str);
  232. if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection.maxFlowStringSingleLineLength) {
  233. str = start;
  234. for (const s of strings) {
  235. str += s ? `\n${indentStep}${indent}${s}` : '\n';
  236. }
  237. str += `\n${indent}${end}`;
  238. } else {
  239. str = `${start} ${strings.join(' ')} ${end}`;
  240. }
  241. } else {
  242. const strings = nodes.map(blockItem);
  243. str = strings.shift();
  244. for (const s of strings) str += s ? `\n${indent}${s}` : '\n';
  245. }
  246. if (this.comment) {
  247. str += '\n' + this.comment.replace(/^/gm, `${indent}#`);
  248. if (onComment) onComment();
  249. } else if (chompKeep && onChompKeep) onChompKeep();
  250. return str;
  251. }
  252. }
  253. _rollupPluginBabelHelpers._defineProperty(Collection, "maxFlowStringSingleLineLength", 60);
  254. function asItemIndex(key) {
  255. let idx = key instanceof Scalar ? key.value : key;
  256. if (idx && typeof idx === 'string') idx = Number(idx);
  257. return Number.isInteger(idx) && idx >= 0 ? idx : null;
  258. }
  259. class YAMLSeq extends Collection {
  260. add(value) {
  261. this.items.push(value);
  262. }
  263. delete(key) {
  264. const idx = asItemIndex(key);
  265. if (typeof idx !== 'number') return false;
  266. const del = this.items.splice(idx, 1);
  267. return del.length > 0;
  268. }
  269. get(key, keepScalar) {
  270. const idx = asItemIndex(key);
  271. if (typeof idx !== 'number') return undefined;
  272. const it = this.items[idx];
  273. return !keepScalar && it instanceof Scalar ? it.value : it;
  274. }
  275. has(key) {
  276. const idx = asItemIndex(key);
  277. return typeof idx === 'number' && idx < this.items.length;
  278. }
  279. set(key, value) {
  280. const idx = asItemIndex(key);
  281. if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`);
  282. const prev = this.items[idx];
  283. if (prev instanceof Scalar && isScalarValue(value)) prev.value = value;else this.items[idx] = value;
  284. }
  285. toJSON(_, ctx) {
  286. const seq = [];
  287. if (ctx && ctx.onCreate) ctx.onCreate(seq);
  288. let i = 0;
  289. for (const item of this.items) seq.push(toJS(item, String(i++), ctx));
  290. return seq;
  291. }
  292. toString(ctx, onComment, onChompKeep) {
  293. if (!ctx) return JSON.stringify(this);
  294. return super.toString(ctx, {
  295. blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`,
  296. flowChars: {
  297. start: '[',
  298. end: ']'
  299. },
  300. isMap: false,
  301. itemIndent: (ctx.indent || '') + ' '
  302. }, onComment, onChompKeep);
  303. }
  304. }
  305. const stringifyKey = (key, jsKey, ctx) => {
  306. if (jsKey === null) return '';
  307. if (typeof jsKey !== 'object') return String(jsKey);
  308. if (key instanceof Node && ctx && ctx.doc) return key.toString({
  309. anchors: Object.create(null),
  310. doc: ctx.doc,
  311. indent: '',
  312. indentStep: ctx.indentStep,
  313. inFlow: true,
  314. inStringifyKey: true,
  315. stringify: ctx.stringify
  316. });
  317. return JSON.stringify(jsKey);
  318. };
  319. function createPair(key, value, ctx) {
  320. const k = createNode(key, null, ctx);
  321. const v = createNode(value, null, ctx);
  322. return new Pair(k, v);
  323. }
  324. class Pair extends Node {
  325. constructor(key, value = null) {
  326. super();
  327. this.key = key;
  328. this.value = value;
  329. this.type = Pair.Type.PAIR;
  330. }
  331. get commentBefore() {
  332. return this.key instanceof Node ? this.key.commentBefore : undefined;
  333. }
  334. set commentBefore(cb) {
  335. if (this.key == null) this.key = new Scalar(null);
  336. if (this.key instanceof Node) this.key.commentBefore = cb;else {
  337. const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.';
  338. throw new Error(msg);
  339. }
  340. }
  341. addToJSMap(ctx, map) {
  342. const key = toJS(this.key, '', ctx);
  343. if (map instanceof Map) {
  344. const value = toJS(this.value, key, ctx);
  345. map.set(key, value);
  346. } else if (map instanceof Set) {
  347. map.add(key);
  348. } else {
  349. const stringKey = stringifyKey(this.key, key, ctx);
  350. const value = toJS(this.value, stringKey, ctx);
  351. if (stringKey in map) Object.defineProperty(map, stringKey, {
  352. value,
  353. writable: true,
  354. enumerable: true,
  355. configurable: true
  356. });else map[stringKey] = value;
  357. }
  358. return map;
  359. }
  360. toJSON(_, ctx) {
  361. const pair = ctx && ctx.mapAsMap ? new Map() : {};
  362. return this.addToJSMap(ctx, pair);
  363. }
  364. toString(ctx, onComment, onChompKeep) {
  365. if (!ctx || !ctx.doc) return JSON.stringify(this);
  366. const {
  367. indent: indentSize,
  368. indentSeq,
  369. simpleKeys
  370. } = ctx.doc.options;
  371. let {
  372. key,
  373. value
  374. } = this;
  375. let keyComment = key instanceof Node && key.comment;
  376. if (simpleKeys) {
  377. if (keyComment) {
  378. throw new Error('With simple keys, key nodes cannot have comments');
  379. }
  380. if (key instanceof Collection) {
  381. const msg = 'With simple keys, collection cannot be used as a key value';
  382. throw new Error(msg);
  383. }
  384. }
  385. let explicitKey = !simpleKeys && (!key || keyComment || key instanceof Collection || key.type === _rollupPluginBabelHelpers.Type.BLOCK_FOLDED || key.type === _rollupPluginBabelHelpers.Type.BLOCK_LITERAL);
  386. const {
  387. allNullValues,
  388. doc,
  389. indent,
  390. indentStep,
  391. stringify
  392. } = ctx;
  393. ctx = Object.assign({}, ctx, {
  394. implicitKey: !explicitKey && (simpleKeys || !allNullValues),
  395. indent: indent + indentStep
  396. });
  397. let chompKeep = false;
  398. let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true);
  399. str = addComment(str, ctx.indent, keyComment);
  400. if (allNullValues && !simpleKeys) {
  401. if (this.comment) {
  402. str = addComment(str, ctx.indent, this.comment);
  403. if (onComment) onComment();
  404. } else if (chompKeep && !keyComment && onChompKeep) onChompKeep();
  405. return ctx.inFlow ? str : `? ${str}`;
  406. }
  407. if (!explicitKey && str.length > 1024) {
  408. if (!simpleKeys) {
  409. explicitKey = true;
  410. } else {
  411. const msg = 'With simple keys, single line scalar must not span more than 1024 characters';
  412. throw new Error(msg);
  413. }
  414. }
  415. str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`;
  416. if (this.comment) {
  417. // expected (but not strictly required) to be a single-line comment
  418. str = addComment(str, ctx.indent, this.comment);
  419. if (onComment) onComment();
  420. }
  421. let vcb = '';
  422. let valueComment = null;
  423. if (value instanceof Node) {
  424. if (value.spaceBefore) vcb = '\n';
  425. if (value.commentBefore) {
  426. const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`);
  427. vcb += `\n${cs}`;
  428. }
  429. valueComment = value.comment;
  430. } else if (value && typeof value === 'object') {
  431. value = doc.createNode(value);
  432. }
  433. ctx.implicitKey = false;
  434. if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1;
  435. chompKeep = false;
  436. if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== _rollupPluginBabelHelpers.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) {
  437. // If indentSeq === false, consider '- ' as part of indentation where possible
  438. ctx.indent = ctx.indent.substr(2);
  439. }
  440. const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true);
  441. let ws = ' ';
  442. if (vcb || this.comment) {
  443. ws = `${vcb}\n${ctx.indent}`;
  444. } else if (!explicitKey && value instanceof Collection) {
  445. const flow = valueStr[0] === '[' || valueStr[0] === '{';
  446. if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`;
  447. } else if (valueStr[0] === '\n') ws = '';
  448. if (chompKeep && !valueComment && onChompKeep) onChompKeep();
  449. return addComment(str + ws + valueStr, ctx.indent, valueComment);
  450. }
  451. }
  452. _rollupPluginBabelHelpers._defineProperty(Pair, "Type", {
  453. PAIR: 'PAIR',
  454. MERGE_PAIR: 'MERGE_PAIR'
  455. });
  456. const getAliasCount = (node, anchors) => {
  457. if (node instanceof Alias) {
  458. const anchor = anchors.get(node.source);
  459. return anchor.count * anchor.aliasCount;
  460. } else if (node instanceof Collection) {
  461. let count = 0;
  462. for (const item of node.items) {
  463. const c = getAliasCount(item, anchors);
  464. if (c > count) count = c;
  465. }
  466. return count;
  467. } else if (node instanceof Pair) {
  468. const kc = getAliasCount(node.key, anchors);
  469. const vc = getAliasCount(node.value, anchors);
  470. return Math.max(kc, vc);
  471. }
  472. return 1;
  473. };
  474. class Alias extends Node {
  475. static stringify({
  476. range,
  477. source
  478. }, {
  479. anchors,
  480. doc,
  481. implicitKey,
  482. inStringifyKey
  483. }) {
  484. let anchor = Object.keys(anchors).find(a => anchors[a] === source);
  485. if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName();
  486. if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`;
  487. const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node';
  488. throw new Error(`${msg} [${range}]`);
  489. }
  490. constructor(source) {
  491. super();
  492. this.source = source;
  493. this.type = _rollupPluginBabelHelpers.Type.ALIAS;
  494. }
  495. set tag(t) {
  496. throw new Error('Alias nodes cannot have tags');
  497. }
  498. toJSON(arg, ctx) {
  499. if (!ctx) return toJS(this.source, arg, ctx);
  500. const {
  501. anchors,
  502. maxAliasCount
  503. } = ctx;
  504. const anchor = anchors.get(this.source);
  505. /* istanbul ignore if */
  506. if (!anchor || anchor.res === undefined) {
  507. const msg = 'This should not happen: Alias anchor was not resolved?';
  508. if (this.cstNode) throw new _rollupPluginBabelHelpers.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
  509. }
  510. if (maxAliasCount >= 0) {
  511. anchor.count += 1;
  512. if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors);
  513. if (anchor.count * anchor.aliasCount > maxAliasCount) {
  514. const msg = 'Excessive alias count indicates a resource exhaustion attack';
  515. if (this.cstNode) throw new _rollupPluginBabelHelpers.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
  516. }
  517. }
  518. return anchor.res;
  519. } // Only called when stringifying an alias mapping key while constructing
  520. // Object output.
  521. toString(ctx) {
  522. return Alias.stringify(this, ctx);
  523. }
  524. }
  525. _rollupPluginBabelHelpers._defineProperty(Alias, "default", true);
  526. function findPair(items, key) {
  527. const k = key instanceof Scalar ? key.value : key;
  528. for (const it of items) {
  529. if (it instanceof Pair) {
  530. if (it.key === key || it.key === k) return it;
  531. if (it.key && it.key.value === k) return it;
  532. }
  533. }
  534. return undefined;
  535. }
  536. class YAMLMap extends Collection {
  537. add(pair, overwrite) {
  538. if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value);
  539. const prev = findPair(this.items, pair.key);
  540. const sortEntries = this.schema && this.schema.sortMapEntries;
  541. if (prev) {
  542. if (!overwrite) throw new Error(`Key ${pair.key} already set`); // For scalars, keep the old node & its comments and anchors
  543. if (prev.value instanceof Scalar && isScalarValue(pair.value)) prev.value.value = pair.value;else prev.value = pair.value;
  544. } else if (sortEntries) {
  545. const i = this.items.findIndex(item => sortEntries(pair, item) < 0);
  546. if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair);
  547. } else {
  548. this.items.push(pair);
  549. }
  550. }
  551. delete(key) {
  552. const it = findPair(this.items, key);
  553. if (!it) return false;
  554. const del = this.items.splice(this.items.indexOf(it), 1);
  555. return del.length > 0;
  556. }
  557. get(key, keepScalar) {
  558. const it = findPair(this.items, key);
  559. const node = it && it.value;
  560. return !keepScalar && node instanceof Scalar ? node.value : node;
  561. }
  562. has(key) {
  563. return !!findPair(this.items, key);
  564. }
  565. set(key, value) {
  566. this.add(new Pair(key, value), true);
  567. }
  568. /**
  569. * @param ctx - Conversion context, originally set in Document#toJS()
  570. * @param {Class} Type - If set, forces the returned collection type
  571. * @returns Instance of Type, Map, or Object
  572. */
  573. toJSON(_, ctx, Type) {
  574. const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {};
  575. if (ctx && ctx.onCreate) ctx.onCreate(map);
  576. for (const item of this.items) item.addToJSMap(ctx, map);
  577. return map;
  578. }
  579. toString(ctx, onComment, onChompKeep) {
  580. if (!ctx) return JSON.stringify(this);
  581. for (const item of this.items) {
  582. if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
  583. }
  584. return super.toString(ctx, {
  585. blockItem: n => n.str,
  586. flowChars: {
  587. start: '{',
  588. end: '}'
  589. },
  590. isMap: true,
  591. itemIndent: ctx.indent || ''
  592. }, onComment, onChompKeep);
  593. }
  594. }
  595. const binaryOptions = {
  596. defaultType: _rollupPluginBabelHelpers.Type.BLOCK_LITERAL,
  597. lineWidth: 76
  598. };
  599. const boolOptions = {
  600. trueStr: 'true',
  601. falseStr: 'false'
  602. };
  603. const intOptions = {
  604. asBigInt: false
  605. };
  606. const nullOptions = {
  607. nullStr: 'null'
  608. };
  609. const strOptions = {
  610. defaultType: _rollupPluginBabelHelpers.Type.PLAIN,
  611. defaultKeyType: _rollupPluginBabelHelpers.Type.PLAIN,
  612. defaultQuoteSingle: false,
  613. doubleQuoted: {
  614. jsonEncoding: false,
  615. minMultiLineLength: 40
  616. },
  617. fold: {
  618. lineWidth: 80,
  619. minContentWidth: 20
  620. }
  621. };
  622. function resolveScalar(str, tags) {
  623. for (const {
  624. format,
  625. test,
  626. resolve
  627. } of tags) {
  628. if (test && test.test(str)) {
  629. let res = resolve(str);
  630. if (!(res instanceof Scalar)) res = new Scalar(res);
  631. if (format) res.format = format;
  632. return res;
  633. }
  634. }
  635. return new Scalar(str); // fallback to string
  636. }
  637. const FOLD_FLOW = 'flow';
  638. const FOLD_BLOCK = 'block';
  639. const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line
  640. // returns index of last newline in more-indented block
  641. const consumeMoreIndentedLines = (text, i) => {
  642. let ch = text[i + 1];
  643. while (ch === ' ' || ch === '\t') {
  644. do {
  645. ch = text[i += 1];
  646. } while (ch && ch !== '\n');
  647. ch = text[i + 1];
  648. }
  649. return i;
  650. };
  651. /**
  652. * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
  653. * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
  654. * terminated with `\n` and started with `indent`.
  655. *
  656. * @param {string} text
  657. * @param {string} indent
  658. * @param {string} [mode='flow'] `'block'` prevents more-indented lines
  659. * from being folded; `'quoted'` allows for `\` escapes, including escaped
  660. * newlines
  661. * @param {Object} options
  662. * @param {number} [options.indentAtStart] Accounts for leading contents on
  663. * the first line, defaulting to `indent.length`
  664. * @param {number} [options.lineWidth=80]
  665. * @param {number} [options.minContentWidth=20] Allow highly indented lines to
  666. * stretch the line width or indent content from the start
  667. * @param {function} options.onFold Called once if the text is folded
  668. * @param {function} options.onFold Called once if any line of text exceeds
  669. * lineWidth characters
  670. */
  671. function foldFlowLines(text, indent, mode, {
  672. indentAtStart,
  673. lineWidth = 80,
  674. minContentWidth = 20,
  675. onFold,
  676. onOverflow
  677. }) {
  678. if (!lineWidth || lineWidth < 0) return text;
  679. const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
  680. if (text.length <= endStep) return text;
  681. const folds = [];
  682. const escapedFolds = {};
  683. let end = lineWidth - indent.length;
  684. if (typeof indentAtStart === 'number') {
  685. if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0);else end = lineWidth - indentAtStart;
  686. }
  687. let split = undefined;
  688. let prev = undefined;
  689. let overflow = false;
  690. let i = -1;
  691. if (mode === FOLD_BLOCK) {
  692. i = consumeMoreIndentedLines(text, i);
  693. if (i !== -1) end = i + endStep;
  694. }
  695. for (let ch; ch = text[i += 1];) {
  696. if (mode === FOLD_QUOTED && ch === '\\') {
  697. switch (text[i + 1]) {
  698. case 'x':
  699. i += 3;
  700. break;
  701. case 'u':
  702. i += 5;
  703. break;
  704. case 'U':
  705. i += 9;
  706. break;
  707. default:
  708. i += 1;
  709. }
  710. }
  711. if (ch === '\n') {
  712. if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i);
  713. end = i + endStep;
  714. split = undefined;
  715. } else {
  716. if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') {
  717. // space surrounded by non-space can be replaced with newline + indent
  718. const next = text[i + 1];
  719. if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i;
  720. }
  721. if (i >= end) {
  722. if (split) {
  723. folds.push(split);
  724. end = split + endStep;
  725. split = undefined;
  726. } else if (mode === FOLD_QUOTED) {
  727. // white-space collected at end may stretch past lineWidth
  728. while (prev === ' ' || prev === '\t') {
  729. prev = ch;
  730. ch = text[i += 1];
  731. overflow = true;
  732. } // i - 2 accounts for not-dropped last char + newline-escaping \
  733. folds.push(i - 2);
  734. escapedFolds[i - 2] = true;
  735. end = i - 2 + endStep;
  736. split = undefined;
  737. } else {
  738. overflow = true;
  739. }
  740. }
  741. }
  742. prev = ch;
  743. }
  744. if (overflow && onOverflow) onOverflow();
  745. if (folds.length === 0) return text;
  746. if (onFold) onFold();
  747. let res = text.slice(0, folds[0]);
  748. for (let i = 0; i < folds.length; ++i) {
  749. const fold = folds[i];
  750. const end = folds[i + 1] || text.length;
  751. if (fold === 0) res = `\n${indent}${text.slice(0, end)}`;else {
  752. if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`;
  753. res += `\n${indent}${text.slice(fold + 1, end)}`;
  754. }
  755. }
  756. return res;
  757. }
  758. const getFoldOptions = ({
  759. indentAtStart
  760. }) => indentAtStart ? Object.assign({
  761. indentAtStart
  762. }, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will
  763. // presume that's starting a new document.
  764. const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str);
  765. function lineLengthOverLimit(str, limit) {
  766. const strLen = str.length;
  767. if (strLen <= limit) return false;
  768. for (let i = 0, start = 0; i < strLen; ++i) {
  769. if (str[i] === '\n') {
  770. if (i - start > limit) return true;
  771. start = i + 1;
  772. if (strLen - start <= limit) return false;
  773. }
  774. }
  775. return true;
  776. }
  777. function doubleQuotedString(value, ctx) {
  778. const {
  779. implicitKey
  780. } = ctx;
  781. const {
  782. jsonEncoding,
  783. minMultiLineLength
  784. } = strOptions.doubleQuoted;
  785. const json = JSON.stringify(value);
  786. if (jsonEncoding) return json;
  787. const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
  788. let str = '';
  789. let start = 0;
  790. for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
  791. if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
  792. // space before newline needs to be escaped to not be folded
  793. str += json.slice(start, i) + '\\ ';
  794. i += 1;
  795. start = i;
  796. ch = '\\';
  797. }
  798. if (ch === '\\') switch (json[i + 1]) {
  799. case 'u':
  800. {
  801. str += json.slice(start, i);
  802. const code = json.substr(i + 2, 4);
  803. switch (code) {
  804. case '0000':
  805. str += '\\0';
  806. break;
  807. case '0007':
  808. str += '\\a';
  809. break;
  810. case '000b':
  811. str += '\\v';
  812. break;
  813. case '001b':
  814. str += '\\e';
  815. break;
  816. case '0085':
  817. str += '\\N';
  818. break;
  819. case '00a0':
  820. str += '\\_';
  821. break;
  822. case '2028':
  823. str += '\\L';
  824. break;
  825. case '2029':
  826. str += '\\P';
  827. break;
  828. default:
  829. if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6);
  830. }
  831. i += 5;
  832. start = i + 1;
  833. }
  834. break;
  835. case 'n':
  836. if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
  837. i += 1;
  838. } else {
  839. // folding will eat first newline
  840. str += json.slice(start, i) + '\n\n';
  841. while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') {
  842. str += '\n';
  843. i += 2;
  844. }
  845. str += indent; // space after newline needs to be escaped to not be folded
  846. if (json[i + 2] === ' ') str += '\\';
  847. i += 1;
  848. start = i + 1;
  849. }
  850. break;
  851. default:
  852. i += 1;
  853. }
  854. }
  855. str = start ? str + json.slice(start) : json;
  856. return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx));
  857. }
  858. function singleQuotedString(value, ctx) {
  859. if (ctx.implicitKey) {
  860. if (/\n/.test(value)) return doubleQuotedString(value, ctx);
  861. } else {
  862. // single quoted string can't have leading or trailing whitespace around newline
  863. if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx);
  864. }
  865. const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
  866. const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
  867. return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx));
  868. }
  869. function blockString({
  870. comment,
  871. type,
  872. value
  873. }, ctx, onComment, onChompKeep) {
  874. // 1. Block can't end in whitespace unless the last line is non-empty.
  875. // 2. Strings consisting of only whitespace are best rendered explicitly.
  876. if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
  877. return doubleQuotedString(value, ctx);
  878. }
  879. const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');
  880. const indentSize = indent ? '2' : '1'; // root is at -1
  881. const literal = type === _rollupPluginBabelHelpers.Type.BLOCK_FOLDED ? false : type === _rollupPluginBabelHelpers.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth - indent.length);
  882. let header = literal ? '|' : '>';
  883. if (!value) return header + '\n';
  884. let wsStart = '';
  885. let wsEnd = '';
  886. value = value.replace(/[\n\t ]*$/, ws => {
  887. const n = ws.indexOf('\n');
  888. if (n === -1) {
  889. header += '-'; // strip
  890. } else if (value === ws || n !== ws.length - 1) {
  891. header += '+'; // keep
  892. if (onChompKeep) onChompKeep();
  893. }
  894. wsEnd = ws.replace(/\n$/, '');
  895. return '';
  896. }).replace(/^[\n ]*/, ws => {
  897. if (ws.indexOf(' ') !== -1) header += indentSize;
  898. const m = ws.match(/ +$/);
  899. if (m) {
  900. wsStart = ws.slice(0, -m[0].length);
  901. return m[0];
  902. } else {
  903. wsStart = ws;
  904. return '';
  905. }
  906. });
  907. if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`);
  908. if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`);
  909. if (comment) {
  910. header += ' #' + comment.replace(/ ?[\r\n]+/g, ' ');
  911. if (onComment) onComment();
  912. }
  913. if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`;
  914. if (literal) {
  915. value = value.replace(/\n+/g, `$&${indent}`);
  916. return `${header}\n${indent}${wsStart}${value}${wsEnd}`;
  917. }
  918. value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
  919. // ^ ind.line ^ empty ^ capture next empty lines only at end of indent
  920. .replace(/\n+/g, `$&${indent}`);
  921. const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold);
  922. return `${header}\n${indent}${body}`;
  923. }
  924. function plainString(item, ctx, onComment, onChompKeep) {
  925. const {
  926. comment,
  927. type,
  928. value
  929. } = item;
  930. const {
  931. actualString,
  932. implicitKey,
  933. indent,
  934. inFlow
  935. } = ctx;
  936. if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) {
  937. return doubleQuotedString(value, ctx);
  938. }
  939. if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
  940. const hasDouble = value.indexOf('"') !== -1;
  941. const hasSingle = value.indexOf("'") !== -1;
  942. let quotedString;
  943. if (hasDouble && !hasSingle) {
  944. quotedString = singleQuotedString;
  945. } else if (hasSingle && !hasDouble) {
  946. quotedString = doubleQuotedString;
  947. } else if (strOptions.defaultQuoteSingle) {
  948. quotedString = singleQuotedString;
  949. } else {
  950. quotedString = doubleQuotedString;
  951. } // not allowed:
  952. // - empty string, '-' or '?'
  953. // - start with an indicator character (except [?:-]) or /[?-] /
  954. // - '\n ', ': ' or ' \n' anywhere
  955. // - '#' not preceded by a non-space char
  956. // - end with ' ' or ':'
  957. return implicitKey || inFlow || value.indexOf('\n') === -1 ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
  958. }
  959. if (!implicitKey && !inFlow && type !== _rollupPluginBabelHelpers.Type.PLAIN && value.indexOf('\n') !== -1) {
  960. // Where allowed & type not set explicitly, prefer block style for multiline strings
  961. return blockString(item, ctx, onComment, onChompKeep);
  962. }
  963. if (indent === '' && containsDocumentMarker(value)) {
  964. ctx.forceBlockIndent = true;
  965. return blockString(item, ctx, onComment, onChompKeep);
  966. }
  967. const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and
  968. // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
  969. // and others in v1.1.
  970. if (actualString) {
  971. const {
  972. tags
  973. } = ctx.doc.schema;
  974. const resolved = resolveScalar(str, tags).value;
  975. if (typeof resolved !== 'string') return doubleQuotedString(value, ctx);
  976. }
  977. const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx));
  978. if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) {
  979. if (onComment) onComment();
  980. return addCommentBefore(body, indent, comment);
  981. }
  982. return body;
  983. }
  984. function stringifyString(item, ctx, onComment, onChompKeep) {
  985. const {
  986. defaultKeyType,
  987. defaultType
  988. } = strOptions;
  989. const {
  990. implicitKey,
  991. inFlow
  992. } = ctx;
  993. let {
  994. type,
  995. value
  996. } = item;
  997. if (typeof value !== 'string') {
  998. value = String(value);
  999. item = Object.assign({}, item, {
  1000. value
  1001. });
  1002. }
  1003. if (type !== _rollupPluginBabelHelpers.Type.QUOTE_DOUBLE) {
  1004. // force double quotes on control characters & unpaired surrogates
  1005. if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(value)) type = _rollupPluginBabelHelpers.Type.QUOTE_DOUBLE;
  1006. }
  1007. const _stringify = _type => {
  1008. switch (_type) {
  1009. case _rollupPluginBabelHelpers.Type.BLOCK_FOLDED:
  1010. case _rollupPluginBabelHelpers.Type.BLOCK_LITERAL:
  1011. return implicitKey || inFlow ? doubleQuotedString(value, ctx) // blocks are not valid inside flow containers
  1012. : blockString(item, ctx, onComment, onChompKeep);
  1013. case _rollupPluginBabelHelpers.Type.QUOTE_DOUBLE:
  1014. return doubleQuotedString(value, ctx);
  1015. case _rollupPluginBabelHelpers.Type.QUOTE_SINGLE:
  1016. return singleQuotedString(value, ctx);
  1017. case _rollupPluginBabelHelpers.Type.PLAIN:
  1018. return plainString(item, ctx, onComment, onChompKeep);
  1019. default:
  1020. return null;
  1021. }
  1022. };
  1023. let res = _stringify(type);
  1024. if (res === null) {
  1025. const t = implicitKey ? defaultKeyType : defaultType;
  1026. res = _stringify(t);
  1027. if (res === null) throw new Error(`Unsupported default string type ${t}`);
  1028. }
  1029. return res;
  1030. }
  1031. function stringifyNumber({
  1032. format,
  1033. minFractionDigits,
  1034. tag,
  1035. value
  1036. }) {
  1037. if (typeof value === 'bigint') return String(value);
  1038. if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf';
  1039. let n = JSON.stringify(value);
  1040. if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) {
  1041. let i = n.indexOf('.');
  1042. if (i < 0) {
  1043. i = n.length;
  1044. n += '.';
  1045. }
  1046. let d = minFractionDigits - (n.length - i - 1);
  1047. while (d-- > 0) n += '0';
  1048. }
  1049. return n;
  1050. }
  1051. exports.Alias = Alias;
  1052. exports.Collection = Collection;
  1053. exports.Node = Node;
  1054. exports.Pair = Pair;
  1055. exports.Scalar = Scalar;
  1056. exports.YAMLMap = YAMLMap;
  1057. exports.YAMLSeq = YAMLSeq;
  1058. exports.addComment = addComment;
  1059. exports.binaryOptions = binaryOptions;
  1060. exports.boolOptions = boolOptions;
  1061. exports.collectionFromPath = collectionFromPath;
  1062. exports.createNode = createNode;
  1063. exports.createPair = createPair;
  1064. exports.findPair = findPair;
  1065. exports.intOptions = intOptions;
  1066. exports.isEmptyPath = isEmptyPath;
  1067. exports.nullOptions = nullOptions;
  1068. exports.resolveScalar = resolveScalar;
  1069. exports.strOptions = strOptions;
  1070. exports.stringifyNumber = stringifyNumber;
  1071. exports.stringifyString = stringifyString;
  1072. exports.toJS = toJS;