cactus-react-native 0.1.1 → 0.1.3

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