json-schema-to-grammar.mjs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. // WARNING: This file was ported from json_schema_to_grammar.py, please fix bugs / add features there first.
  2. const SPACE_RULE = '| " " | "\\n" [ \\t]{0,20}';
  3. function _buildRepetition(itemRule, minItems, maxItems, opts={}) {
  4. if (minItems === 0 && maxItems === 1) {
  5. return `${itemRule}?`;
  6. }
  7. const separatorRule = opts.separatorRule ?? '';
  8. const itemRuleIsLiteral = opts.itemRuleIsLiteral ?? false
  9. if (separatorRule === '') {
  10. if (minItems === 1 && maxItems === undefined) {
  11. return `${itemRule}+`;
  12. } else if (minItems === 0 && maxItems === undefined) {
  13. return `${itemRule}*`;
  14. } else {
  15. return `${itemRule}{${minItems},${maxItems !== undefined ? maxItems : ''}}`;
  16. }
  17. }
  18. const result = itemRule + ' ' + _buildRepetition(`(${separatorRule} ${itemRule})`, minItems > 0 ? minItems - 1 : 0, maxItems !== undefined ? maxItems - 1 : undefined);
  19. return minItems === 0 ? `(${result})?` : result;
  20. }
  21. class BuiltinRule {
  22. constructor(content, deps) {
  23. this.content = content;
  24. this.deps = deps || [];
  25. }
  26. }
  27. const PRIMITIVE_RULES = {
  28. boolean : new BuiltinRule('("true" | "false") space', []),
  29. 'decimal-part' : new BuiltinRule('[0-9]{1,16}', []),
  30. 'integral-part': new BuiltinRule('[0] | [1-9] [0-9]{0,15}', []),
  31. number : new BuiltinRule('("-"? integral-part) ("." decimal-part)? ([eE] [-+]? integral-part)? space', ['integral-part', 'decimal-part']),
  32. integer : new BuiltinRule('("-"? integral-part) space', ['integral-part']),
  33. value : new BuiltinRule('object | array | string | number | boolean | null', ['object', 'array', 'string', 'number', 'boolean', 'null']),
  34. object : new BuiltinRule('"{" space ( string ":" space value ("," space string ":" space value)* )? "}" space', ['string', 'value']),
  35. array : new BuiltinRule('"[" space ( value ("," space value)* )? "]" space', ['value']),
  36. uuid : new BuiltinRule('"\\"" [0-9a-fA-F]{8} "-" [0-9a-fA-F]{4} "-" [0-9a-fA-F]{4} "-" [0-9a-fA-F]{4} "-" [0-9a-fA-F]{12} "\\"" space', []),
  37. char : new BuiltinRule(`[^"\\\\\\x7F\\x00-\\x1F] | [\\\\] (["\\\\bfnrt] | "u" [0-9a-fA-F]{4})`, []),
  38. string : new BuiltinRule(`"\\"" char* "\\"" space`, ['char']),
  39. null : new BuiltinRule('"null" space', []),
  40. };
  41. // TODO: support "uri", "email" string formats
  42. const STRING_FORMAT_RULES = {
  43. 'date' : new BuiltinRule('[0-9]{4} "-" ( "0" [1-9] | "1" [0-2] ) "-" ( \"0\" [1-9] | [1-2] [0-9] | "3" [0-1] )', []),
  44. 'time' : new BuiltinRule('([01] [0-9] | "2" [0-3]) ":" [0-5] [0-9] ":" [0-5] [0-9] ( "." [0-9]{3} )? ( "Z" | ( "+" | "-" ) ( [01] [0-9] | "2" [0-3] ) ":" [0-5] [0-9] )', []),
  45. 'date-time' : new BuiltinRule('date "T" time', ['date', 'time']),
  46. 'date-string' : new BuiltinRule('"\\"" date "\\"" space', ['date']),
  47. 'time-string' : new BuiltinRule('"\\"" time "\\"" space', ['time']),
  48. 'date-time-string': new BuiltinRule('"\\"" date-time "\\"" space', ['date-time']),
  49. }
  50. const RESERVED_NAMES = {'root': true, ...PRIMITIVE_RULES, ...STRING_FORMAT_RULES};
  51. const INVALID_RULE_CHARS_RE = /[^\dA-Za-z-]+/g;
  52. const GRAMMAR_LITERAL_ESCAPE_RE = /[\n\r"]/g;
  53. const GRAMMAR_RANGE_LITERAL_ESCAPE_RE = /[\n\r"\]\-\\]/g;
  54. const GRAMMAR_LITERAL_ESCAPES = { '\r': '\\r', '\n': '\\n', '"': '\\"', '-': '\\-', ']': '\\]' };
  55. const NON_LITERAL_SET = new Set('|.()[]{}*+?');
  56. const ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = new Set('[]()|{}*+?');
  57. export class SchemaConverter {
  58. constructor(options) {
  59. this._propOrder = options.prop_order || {};
  60. this._allowFetch = options.allow_fetch || false;
  61. this._dotall = options.dotall || false;
  62. this._rules = {'space': SPACE_RULE};
  63. this._refs = {};
  64. this._refsBeingResolved = new Set();
  65. }
  66. _formatLiteral(literal) {
  67. const escaped = literal.replace(
  68. GRAMMAR_LITERAL_ESCAPE_RE,
  69. m => GRAMMAR_LITERAL_ESCAPES[m]
  70. );
  71. return `"${escaped}"`;
  72. }
  73. _formatRangeChar(literal) {
  74. return JSON.stringify(literal).slice(1, -1).replace(
  75. GRAMMAR_RANGE_LITERAL_ESCAPE_RE,
  76. m => GRAMMAR_LITERAL_ESCAPES[m]
  77. );
  78. }
  79. _addRule(name, rule) {
  80. let escName = name.replace(INVALID_RULE_CHARS_RE, '-');
  81. let key = escName;
  82. if (escName in this._rules) {
  83. if (this._rules[escName] === rule) {
  84. return key;
  85. }
  86. let i = 0;
  87. while ((`${escName}${i}` in this._rules) && (this._rules[`${escName}${i}`] !== rule)) {
  88. i += 1;
  89. }
  90. key = `${escName}${i}`;
  91. }
  92. this._rules[key] = rule;
  93. return key;
  94. }
  95. async resolveRefs(schema, url) {
  96. const visit = async (n) => {
  97. if (Array.isArray(n)) {
  98. return Promise.all(n.map(visit));
  99. } else if (typeof n === 'object' && n !== null) {
  100. let ref = n.$ref;
  101. let target;
  102. if (ref !== undefined && !this._refs[ref]) {
  103. if (ref.startsWith('https://')) {
  104. if (!this._allowFetch) {
  105. throw new Error('Fetching remote schemas is not allowed (use --allow-fetch for force)');
  106. }
  107. const fetch = (await import('node-fetch')).default;
  108. const fragSplit = ref.split('#');
  109. const baseUrl = fragSplit[0];
  110. target = this._refs[baseUrl];
  111. if (!target) {
  112. target = await this.resolveRefs(await fetch(ref).then(res => res.json()), baseUrl);
  113. this._refs[baseUrl] = target;
  114. }
  115. if (fragSplit.length === 1 || fragSplit[fragSplit.length - 1] === '') {
  116. return target;
  117. }
  118. } else if (ref.startsWith('#/')) {
  119. target = schema;
  120. ref = `${url}${ref}`;
  121. n.$ref = ref;
  122. } else {
  123. throw new Error(`Unsupported ref ${ref}`);
  124. }
  125. const selectors = ref.split('#')[1].split('/').slice(1);
  126. for (const sel of selectors) {
  127. if (!target || !(sel in target)) {
  128. throw new Error(`Error resolving ref ${ref}: ${sel} not in ${JSON.stringify(target)}`);
  129. }
  130. target = target[sel];
  131. }
  132. this._refs[ref] = target;
  133. } else {
  134. await Promise.all(Object.values(n).map(visit));
  135. }
  136. }
  137. return n;
  138. };
  139. return visit(schema);
  140. }
  141. _generateUnionRule(name, altSchemas) {
  142. return altSchemas
  143. .map((altSchema, i) => this.visit(altSchema, `${name ?? ''}${name ? '-' : 'alternative-'}${i}`))
  144. .join(' | ');
  145. }
  146. _visitPattern(pattern, name) {
  147. if (!pattern.startsWith('^') || !pattern.endsWith('$')) {
  148. throw new Error('Pattern must start with "^" and end with "$"');
  149. }
  150. pattern = pattern.slice(1, -1);
  151. const subRuleIds = {};
  152. let i = 0;
  153. const length = pattern.length;
  154. const getDot = () => {
  155. let rule;
  156. if (this._dotall) {
  157. rule = '[\\U00000000-\\U0010FFFF]';
  158. } else {
  159. // Accept any character... except \n and \r line break chars (\x0A and \xOD)
  160. rule = '[^\\x0A\\x0D]';
  161. }
  162. return this._addRule('dot', rule);
  163. };
  164. const toRule = ([s, isLiteral]) => isLiteral ? "\"" + s + "\"" : s;
  165. const transform = () => {
  166. const start = i;
  167. // For each component of this sequence, store its string representation and whether it's a literal.
  168. // We only need a flat structure here to apply repetition operators to the last item, and
  169. // to merge literals at the and (we're parsing grouped ( sequences ) recursively and don't treat '|' specially
  170. // (GBNF's syntax is luckily very close to regular expressions!)
  171. const seq = [];
  172. const joinSeq = () => {
  173. const ret = [];
  174. for (const [isLiteral, g] of groupBy(seq, x => x[1])) {
  175. if (isLiteral) {
  176. ret.push([[...g].map(x => x[0]).join(''), true]);
  177. } else {
  178. ret.push(...g);
  179. }
  180. }
  181. if (ret.length === 1) {
  182. return ret[0];
  183. }
  184. return [ret.map(x => toRule(x)).join(' '), false];
  185. };
  186. while (i < length) {
  187. const c = pattern[i];
  188. if (c === '.') {
  189. seq.push([getDot(), false]);
  190. i += 1;
  191. } else if (c === '(') {
  192. i += 1;
  193. if (i < length) {
  194. if (pattern[i] === '?') {
  195. throw new Error(`Unsupported pattern syntax "${pattern[i]}" at index ${i} of /${pattern}/`);
  196. }
  197. }
  198. seq.push([`(${toRule(transform())})`, false]);
  199. } else if (c === ')') {
  200. i += 1;
  201. if (start <= 0 || pattern[start - 1] !== '(') {
  202. throw new Error(`Unbalanced parentheses; start = ${start}, i = ${i}, pattern = ${pattern}`);
  203. }
  204. return joinSeq();
  205. } else if (c === '[') {
  206. let squareBrackets = c;
  207. i += 1;
  208. while (i < length && pattern[i] !== ']') {
  209. if (pattern[i] === '\\') {
  210. squareBrackets += pattern.slice(i, i + 2);
  211. i += 2;
  212. } else {
  213. squareBrackets += pattern[i];
  214. i += 1;
  215. }
  216. }
  217. if (i >= length) {
  218. throw new Error(`Unbalanced square brackets; start = ${start}, i = ${i}, pattern = ${pattern}`);
  219. }
  220. squareBrackets += ']';
  221. i += 1;
  222. seq.push([squareBrackets, false]);
  223. } else if (c === '|') {
  224. seq.push(['|', false]);
  225. i += 1;
  226. } else if (c === '*' || c === '+' || c === '?') {
  227. seq[seq.length - 1] = [toRule(seq[seq.length - 1]) + c, false];
  228. i += 1;
  229. } else if (c === '{') {
  230. let curlyBrackets = c;
  231. i += 1;
  232. while (i < length && pattern[i] !== '}') {
  233. curlyBrackets += pattern[i];
  234. i += 1;
  235. }
  236. if (i >= length) {
  237. throw new Error(`Unbalanced curly brackets; start = ${start}, i = ${i}, pattern = ${pattern}`);
  238. }
  239. curlyBrackets += '}';
  240. i += 1;
  241. const nums = curlyBrackets.slice(1, -1).split(',').map(s => s.trim());
  242. let minTimes, maxTimes;
  243. if (nums.length === 1) {
  244. minTimes = parseInt(nums[0], 10);
  245. maxTimes = minTimes;
  246. } else {
  247. if (nums.length !== 2) {
  248. throw new Error(`Invalid quantifier ${curlyBrackets}`);
  249. }
  250. minTimes = nums[0] ? parseInt(nums[0], 10) : 0;
  251. maxTimes = nums[1] ? parseInt(nums[1], 10) : Infinity;
  252. }
  253. let [sub, subIsLiteral] = seq[seq.length - 1];
  254. if (!subIsLiteral) {
  255. let id = subRuleIds[sub];
  256. if (id === undefined) {
  257. id = this._addRule(`${name}-${Object.keys(subRuleIds).length + 1}`, sub);
  258. subRuleIds[sub] = id;
  259. }
  260. sub = id;
  261. }
  262. seq[seq.length - 1] = [
  263. _buildRepetition(subIsLiteral ? `"${sub}"` : sub, minTimes, maxTimes, {itemRuleIsLiteral: subIsLiteral}),
  264. false
  265. ];
  266. } else {
  267. let literal = '';
  268. while (i < length) {
  269. if (pattern[i] === '\\' && i < length - 1) {
  270. const next = pattern[i + 1];
  271. if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.has(next)) {
  272. i += 1;
  273. literal += pattern[i];
  274. i += 1;
  275. } else {
  276. literal += pattern.slice(i, i + 2);
  277. i += 2;
  278. }
  279. } else if (pattern[i] === '"') {
  280. literal += '\\"';
  281. i += 1;
  282. } else if (!NON_LITERAL_SET.has(pattern[i]) &&
  283. (i === length - 1 || literal === '' || pattern[i + 1] === '.' || !NON_LITERAL_SET.has(pattern[i+1]))) {
  284. literal += pattern[i];
  285. i += 1;
  286. } else {
  287. break;
  288. }
  289. }
  290. if (literal !== '') {
  291. seq.push([literal, true]);
  292. }
  293. }
  294. }
  295. return joinSeq();
  296. };
  297. return this._addRule(name, "\"\\\"\" " + toRule(transform()) + " \"\\\"\" space")
  298. }
  299. _resolveRef(ref) {
  300. let refName = ref.split('/').pop();
  301. if (!(refName in this._rules) && !this._refsBeingResolved.has(ref)) {
  302. this._refsBeingResolved.add(ref);
  303. const resolved = this._refs[ref];
  304. refName = this.visit(resolved, refName);
  305. this._refsBeingResolved.delete(ref);
  306. }
  307. return refName;
  308. }
  309. _generateConstantRule(value) {
  310. return this._formatLiteral(JSON.stringify(value));
  311. }
  312. visit(schema, name) {
  313. const schemaType = schema.type;
  314. const schemaFormat = schema.format;
  315. const ruleName = name in RESERVED_NAMES ? name + '-' : name == '' ? 'root' : name;
  316. const ref = schema.$ref;
  317. if (ref !== undefined) {
  318. return this._addRule(ruleName, this._resolveRef(ref));
  319. } else if (schema.oneOf || schema.anyOf) {
  320. return this._addRule(ruleName, this._generateUnionRule(name, schema.oneOf || schema.anyOf));
  321. } else if (Array.isArray(schemaType)) {
  322. return this._addRule(ruleName, this._generateUnionRule(name, schemaType.map(t => ({ type: t }))));
  323. } else if ('const' in schema) {
  324. return this._addRule(ruleName, this._generateConstantRule(schema.const));
  325. } else if ('enum' in schema) {
  326. const rule = schema.enum.map(v => this._generateConstantRule(v)).join(' | ');
  327. return this._addRule(ruleName, rule);
  328. } else if ((schemaType === undefined || schemaType === 'object') &&
  329. ('properties' in schema ||
  330. ('additionalProperties' in schema && schema.additionalProperties !== true))) {
  331. const required = new Set(schema.required || []);
  332. const properties = Object.entries(schema.properties ?? {});
  333. return this._addRule(ruleName, this._buildObjectRule(properties, required, name, schema.additionalProperties));
  334. } else if ((schemaType === undefined || schemaType === 'object') && 'allOf' in schema) {
  335. const required = new Set();
  336. const properties = [];
  337. const addComponent = (compSchema, isRequired) => {
  338. const ref = compSchema.$ref;
  339. if (ref !== undefined) {
  340. compSchema = this._refs[ref];
  341. }
  342. if ('properties' in compSchema) {
  343. for (const [propName, propSchema] of Object.entries(compSchema.properties)) {
  344. properties.push([propName, propSchema]);
  345. if (isRequired) {
  346. required.add(propName);
  347. }
  348. }
  349. }
  350. };
  351. for (const t of schema.allOf) {
  352. if ('anyOf' in t) {
  353. for (const tt of t.anyOf) {
  354. addComponent(tt, false);
  355. }
  356. } else {
  357. addComponent(t, true);
  358. }
  359. }
  360. return this._addRule(ruleName, this._buildObjectRule(properties, required, name, /* additionalProperties= */ false));
  361. } else if ((schemaType === undefined || schemaType === 'array') && ('items' in schema || 'prefixItems' in schema)) {
  362. const items = schema.items ?? schema.prefixItems;
  363. if (Array.isArray(items)) {
  364. return this._addRule(
  365. ruleName,
  366. '"[" space ' +
  367. items.map((item, i) => this.visit(item, `${name ?? ''}${name ? '-' : ''}tuple-${i}`)).join(' "," space ') +
  368. ' "]" space'
  369. );
  370. } else {
  371. const itemRuleName = this.visit(items, `${name ?? ''}${name ? '-' : ''}item`);
  372. const minItems = schema.minItems || 0;
  373. const maxItems = schema.maxItems;
  374. return this._addRule(ruleName, '"[" space ' + _buildRepetition(itemRuleName, minItems, maxItems, {separatorRule: '"," space'}) + ' "]" space');
  375. }
  376. } else if ((schemaType === undefined || schemaType === 'string') && 'pattern' in schema) {
  377. return this._visitPattern(schema.pattern, ruleName);
  378. } else if ((schemaType === undefined || schemaType === 'string') && /^uuid[1-5]?$/.test(schema.format || '')) {
  379. return this._addPrimitive(
  380. ruleName === 'root' ? 'root' : schemaFormat,
  381. PRIMITIVE_RULES['uuid']
  382. );
  383. } else if ((schemaType === undefined || schemaType === 'string') && `${schema.format}-string` in STRING_FORMAT_RULES) {
  384. const primName = `${schema.format}-string`
  385. return this._addRule(ruleName, this._addPrimitive(primName, STRING_FORMAT_RULES[primName]));
  386. } else if (schemaType === 'string' && ('minLength' in schema || 'maxLength' in schema)) {
  387. const charRuleName = this._addPrimitive('char', PRIMITIVE_RULES['char']);
  388. const minLen = schema.minLength || 0;
  389. const maxLen = schema.maxLength;
  390. return this._addRule(ruleName, '"\\\"" ' + _buildRepetition(charRuleName, minLen, maxLen) + ' "\\\"" space');
  391. } else if ((schemaType === 'object') || (Object.keys(schema).length === 0)) {
  392. return this._addRule(ruleName, this._addPrimitive('object', PRIMITIVE_RULES['object']));
  393. } else {
  394. if (!(schemaType in PRIMITIVE_RULES)) {
  395. throw new Error(`Unrecognized schema: ${JSON.stringify(schema)}`);
  396. }
  397. // TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
  398. return this._addPrimitive(ruleName === 'root' ? 'root' : schemaType, PRIMITIVE_RULES[schemaType]);
  399. }
  400. }
  401. _addPrimitive(name, rule) {
  402. let n = this._addRule(name, rule.content);
  403. for (const dep of rule.deps) {
  404. const depRule = PRIMITIVE_RULES[dep] || STRING_FORMAT_RULES[dep];
  405. if (!depRule) {
  406. throw new Error(`Rule ${dep} not known`);
  407. }
  408. if (!(dep in this._rules)) {
  409. this._addPrimitive(dep, depRule);
  410. }
  411. }
  412. return n;
  413. }
  414. _buildObjectRule(properties, required, name, additionalProperties) {
  415. const propOrder = this._propOrder;
  416. // sort by position in prop_order (if specified) then by original order
  417. const sortedProps = properties.map(([k]) => k).sort((a, b) => {
  418. const orderA = propOrder[a] || Infinity;
  419. const orderB = propOrder[b] || Infinity;
  420. return orderA - orderB || properties.findIndex(([k]) => k === a) - properties.findIndex(([k]) => k === b);
  421. });
  422. const propKvRuleNames = {};
  423. for (const [propName, propSchema] of properties) {
  424. const propRuleName = this.visit(propSchema, `${name ?? ''}${name ? '-' : ''}${propName}`);
  425. propKvRuleNames[propName] = this._addRule(
  426. `${name ?? ''}${name ? '-' : ''}${propName}-kv`,
  427. `${this._formatLiteral(JSON.stringify(propName))} space ":" space ${propRuleName}`
  428. );
  429. }
  430. const requiredProps = sortedProps.filter(k => required.has(k));
  431. const optionalProps = sortedProps.filter(k => !required.has(k));
  432. if (typeof additionalProperties === 'object' || additionalProperties === true) {
  433. const subName = `${name ?? ''}${name ? '-' : ''}additional`;
  434. const valueRule = this.visit(additionalProperties === true ? {} : additionalProperties, `${subName}-value`);
  435. propKvRuleNames['*'] = this._addRule(
  436. `${subName}-kv`,
  437. `${this._addPrimitive('string', PRIMITIVE_RULES['string'])} ":" space ${valueRule}`);
  438. optionalProps.push('*');
  439. }
  440. let rule = '"{" space ';
  441. rule += requiredProps.map(k => propKvRuleNames[k]).join(' "," space ');
  442. if (optionalProps.length > 0) {
  443. rule += ' (';
  444. if (requiredProps.length > 0) {
  445. rule += ' "," space ( ';
  446. }
  447. const getRecursiveRefs = (ks, firstIsOptional) => {
  448. const [k, ...rest] = ks;
  449. const kvRuleName = propKvRuleNames[k];
  450. let res;
  451. if (k === '*') {
  452. res = this._addRule(
  453. `${name ?? ''}${name ? '-' : ''}additional-kvs`,
  454. `${kvRuleName} ( "," space ` + kvRuleName + ` )*`
  455. )
  456. } else if (firstIsOptional) {
  457. res = `( "," space ${kvRuleName} )?`;
  458. } else {
  459. res = kvRuleName;
  460. }
  461. if (rest.length > 0) {
  462. res += ' ' + this._addRule(
  463. `${name ?? ''}${name ? '-' : ''}${k}-rest`,
  464. getRecursiveRefs(rest, true)
  465. );
  466. }
  467. return res;
  468. };
  469. rule += optionalProps.map((_, i) => getRecursiveRefs(optionalProps.slice(i), false)).join(' | ');
  470. if (requiredProps.length > 0) {
  471. rule += ' )';
  472. }
  473. rule += ' )?';
  474. }
  475. rule += ' "}" space';
  476. return rule;
  477. }
  478. formatGrammar() {
  479. let grammar = '';
  480. for (const [name, rule] of Object.entries(this._rules).sort(([a], [b]) => a.localeCompare(b))) {
  481. grammar += `${name} ::= ${rule}\n`;
  482. }
  483. return grammar;
  484. }
  485. }
  486. // Helper function to group elements by a key function
  487. function* groupBy(iterable, keyFn) {
  488. let lastKey = null;
  489. let group = [];
  490. for (const element of iterable) {
  491. const key = keyFn(element);
  492. if (lastKey !== null && key !== lastKey) {
  493. yield [lastKey, group];
  494. group = [];
  495. }
  496. group.push(element);
  497. lastKey = key;
  498. }
  499. if (group.length > 0) {
  500. yield [lastKey, group];
  501. }
  502. }