@khanacademy/perseus-core 3.1.0 → 3.3.0

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 (132) hide show
  1. package/dist/data-schema.d.ts +57 -12
  2. package/dist/es/index.js +3251 -395
  3. package/dist/es/index.js.map +1 -1
  4. package/dist/index.d.ts +77 -1
  5. package/dist/index.js +3290 -394
  6. package/dist/index.js.map +1 -1
  7. package/dist/parse-perseus-json/error-tracking-parse-context.d.ts +9 -0
  8. package/dist/parse-perseus-json/exhaustive-test-tool/index.d.ts +2 -0
  9. package/dist/parse-perseus-json/general-purpose-parsers/any.d.ts +2 -0
  10. package/dist/parse-perseus-json/general-purpose-parsers/array.d.ts +2 -0
  11. package/dist/parse-perseus-json/general-purpose-parsers/array.typetest.d.ts +1 -0
  12. package/dist/parse-perseus-json/general-purpose-parsers/boolean.d.ts +2 -0
  13. package/dist/parse-perseus-json/general-purpose-parsers/constant.d.ts +4 -0
  14. package/dist/parse-perseus-json/general-purpose-parsers/convert.d.ts +2 -0
  15. package/dist/parse-perseus-json/general-purpose-parsers/defaulted.d.ts +2 -0
  16. package/dist/parse-perseus-json/general-purpose-parsers/discriminated-union.d.ts +21 -0
  17. package/dist/parse-perseus-json/general-purpose-parsers/discriminated-union.typetest.d.ts +1 -0
  18. package/dist/parse-perseus-json/general-purpose-parsers/enumeration.d.ts +2 -0
  19. package/dist/parse-perseus-json/general-purpose-parsers/enumeration.typetest.d.ts +1 -0
  20. package/dist/parse-perseus-json/general-purpose-parsers/index.d.ts +17 -0
  21. package/dist/parse-perseus-json/general-purpose-parsers/is-object.d.ts +1 -0
  22. package/dist/parse-perseus-json/general-purpose-parsers/nullable.d.ts +2 -0
  23. package/dist/parse-perseus-json/general-purpose-parsers/number.d.ts +2 -0
  24. package/dist/parse-perseus-json/general-purpose-parsers/object.d.ts +6 -0
  25. package/dist/parse-perseus-json/general-purpose-parsers/optional.d.ts +2 -0
  26. package/dist/parse-perseus-json/general-purpose-parsers/pair.d.ts +2 -0
  27. package/dist/parse-perseus-json/general-purpose-parsers/pipe-parsers.d.ts +7 -0
  28. package/dist/parse-perseus-json/general-purpose-parsers/pipe-parsers.typetest.d.ts +1 -0
  29. package/dist/parse-perseus-json/general-purpose-parsers/record.d.ts +2 -0
  30. package/dist/parse-perseus-json/general-purpose-parsers/string-to-number.d.ts +2 -0
  31. package/dist/parse-perseus-json/general-purpose-parsers/string.d.ts +2 -0
  32. package/dist/parse-perseus-json/general-purpose-parsers/test-helpers.d.ts +8 -0
  33. package/dist/parse-perseus-json/general-purpose-parsers/trio.d.ts +2 -0
  34. package/dist/parse-perseus-json/general-purpose-parsers/union.d.ts +7 -0
  35. package/dist/parse-perseus-json/general-purpose-parsers/union.typetest.d.ts +1 -0
  36. package/dist/parse-perseus-json/general-purpose-parsers/unknown.d.ts +2 -0
  37. package/dist/parse-perseus-json/index.d.ts +45 -0
  38. package/dist/parse-perseus-json/object-path.d.ts +2 -0
  39. package/dist/parse-perseus-json/parse-failure-detail.d.ts +2 -0
  40. package/dist/parse-perseus-json/parse.d.ts +3 -0
  41. package/dist/parse-perseus-json/parser-types.d.ts +30 -0
  42. package/dist/parse-perseus-json/perseus-parsers/categorizer-widget.d.ts +3 -0
  43. package/dist/parse-perseus-json/perseus-parsers/cs-program-widget.d.ts +3 -0
  44. package/dist/parse-perseus-json/perseus-parsers/definition-widget.d.ts +3 -0
  45. package/dist/parse-perseus-json/perseus-parsers/dropdown-widget.d.ts +3 -0
  46. package/dist/parse-perseus-json/perseus-parsers/explanation-widget.d.ts +3 -0
  47. package/dist/parse-perseus-json/perseus-parsers/expression-widget.d.ts +3 -0
  48. package/dist/parse-perseus-json/perseus-parsers/graded-group-set-widget.d.ts +3 -0
  49. package/dist/parse-perseus-json/perseus-parsers/graded-group-widget.d.ts +16 -0
  50. package/dist/parse-perseus-json/perseus-parsers/grapher-widget.d.ts +3 -0
  51. package/dist/parse-perseus-json/perseus-parsers/group-widget.d.ts +3 -0
  52. package/dist/parse-perseus-json/perseus-parsers/hint.d.ts +3 -0
  53. package/dist/parse-perseus-json/perseus-parsers/iframe-widget.d.ts +3 -0
  54. package/dist/parse-perseus-json/perseus-parsers/image-widget.d.ts +3 -0
  55. package/dist/parse-perseus-json/perseus-parsers/images-map.d.ts +5 -0
  56. package/dist/parse-perseus-json/perseus-parsers/input-number-widget.d.ts +3 -0
  57. package/dist/parse-perseus-json/perseus-parsers/interaction-widget.d.ts +3 -0
  58. package/dist/parse-perseus-json/perseus-parsers/interactive-graph-widget.d.ts +3 -0
  59. package/dist/parse-perseus-json/perseus-parsers/label-image-widget.d.ts +3 -0
  60. package/dist/parse-perseus-json/perseus-parsers/matcher-widget.d.ts +3 -0
  61. package/dist/parse-perseus-json/perseus-parsers/matrix-widget.d.ts +3 -0
  62. package/dist/parse-perseus-json/perseus-parsers/measurer-widget.d.ts +3 -0
  63. package/dist/parse-perseus-json/perseus-parsers/molecule-renderer-widget.d.ts +3 -0
  64. package/dist/parse-perseus-json/perseus-parsers/number-line-widget.d.ts +3 -0
  65. package/dist/parse-perseus-json/perseus-parsers/numeric-input-widget.d.ts +3 -0
  66. package/dist/parse-perseus-json/perseus-parsers/orderer-widget.d.ts +3 -0
  67. package/dist/parse-perseus-json/perseus-parsers/passage-ref-widget.d.ts +3 -0
  68. package/dist/parse-perseus-json/perseus-parsers/passage-widget.d.ts +3 -0
  69. package/dist/parse-perseus-json/perseus-parsers/perseus-article.d.ts +3 -0
  70. package/dist/parse-perseus-json/perseus-parsers/perseus-image-background.d.ts +3 -0
  71. package/dist/parse-perseus-json/perseus-parsers/perseus-item.d.ts +3 -0
  72. package/dist/parse-perseus-json/perseus-parsers/perseus-renderer.d.ts +3 -0
  73. package/dist/parse-perseus-json/perseus-parsers/phet-simulation-widget.d.ts +3 -0
  74. package/dist/parse-perseus-json/perseus-parsers/plotter-widget.d.ts +3 -0
  75. package/dist/parse-perseus-json/perseus-parsers/python-program-widget.d.ts +3 -0
  76. package/dist/parse-perseus-json/perseus-parsers/radio-widget.d.ts +3 -0
  77. package/dist/parse-perseus-json/perseus-parsers/sorter-widget.d.ts +3 -0
  78. package/dist/parse-perseus-json/perseus-parsers/table-widget.d.ts +3 -0
  79. package/dist/parse-perseus-json/perseus-parsers/versioned-widget-options.d.ts +36 -0
  80. package/dist/parse-perseus-json/perseus-parsers/video-widget.d.ts +3 -0
  81. package/dist/parse-perseus-json/perseus-parsers/widget.d.ts +7 -0
  82. package/dist/parse-perseus-json/perseus-parsers/widgets-map.d.ts +3 -0
  83. package/dist/parse-perseus-json/result.d.ts +16 -0
  84. package/dist/types.d.ts +12 -0
  85. package/dist/utils/deep-clone.d.ts +3 -0
  86. package/dist/utils/equality.d.ts +9 -0
  87. package/dist/utils/get-decimal-separator.d.ts +5 -0
  88. package/dist/utils/get-matrix-size.d.ts +2 -0
  89. package/dist/utils/grapher-types.d.ts +58 -0
  90. package/dist/utils/grapher-util.d.ts +20 -0
  91. package/dist/utils/is-real-json-parse.d.ts +1 -0
  92. package/dist/utils/widget-id-utils.d.ts +38 -0
  93. package/dist/widgets/categorizer/categorizer-util.d.ts +17 -0
  94. package/dist/widgets/categorizer/index.d.ts +5 -0
  95. package/dist/widgets/cs-program/index.d.ts +5 -0
  96. package/dist/widgets/definition/index.d.ts +5 -0
  97. package/dist/widgets/dropdown/index.d.ts +5 -0
  98. package/dist/widgets/explanation/index.d.ts +5 -0
  99. package/dist/widgets/expression/expression-upgrade.d.ts +10 -0
  100. package/dist/widgets/expression/expression-util.d.ts +19 -0
  101. package/dist/widgets/expression/index.d.ts +4 -0
  102. package/dist/widgets/graded-group/index.d.ts +5 -0
  103. package/dist/widgets/graded-group-set/index.d.ts +5 -0
  104. package/dist/widgets/group/index.d.ts +5 -0
  105. package/dist/widgets/iframe/index.d.ts +5 -0
  106. package/dist/widgets/image/index.d.ts +5 -0
  107. package/dist/widgets/input-number/index.d.ts +5 -0
  108. package/dist/widgets/interaction/index.d.ts +5 -0
  109. package/dist/widgets/interactive-graph/index.d.ts +5 -0
  110. package/dist/widgets/label-image/index.d.ts +5 -0
  111. package/dist/widgets/logic-export.types.d.ts +10 -0
  112. package/dist/widgets/matcher/index.d.ts +5 -0
  113. package/dist/widgets/matrix/index.d.ts +5 -0
  114. package/dist/widgets/measurer/index.d.ts +4 -0
  115. package/dist/widgets/measurer/measurer-upgrade.d.ts +10 -0
  116. package/dist/widgets/number-line/index.d.ts +5 -0
  117. package/dist/widgets/numeric-input/index.d.ts +5 -0
  118. package/dist/widgets/orderer/index.d.ts +5 -0
  119. package/dist/widgets/orderer/orderer-util.d.ts +16 -0
  120. package/dist/widgets/passage/index.d.ts +5 -0
  121. package/dist/widgets/passage-ref/index.d.ts +4 -0
  122. package/dist/widgets/passage-ref/passage-ref-upgrade.d.ts +7 -0
  123. package/dist/widgets/passage-ref-target/index.d.ts +5 -0
  124. package/dist/widgets/phet-simulation/index.d.ts +5 -0
  125. package/dist/widgets/plotter/index.d.ts +5 -0
  126. package/dist/widgets/python-program/index.d.ts +5 -0
  127. package/dist/widgets/radio/index.d.ts +4 -0
  128. package/dist/widgets/radio/radio-upgrade.d.ts +10 -0
  129. package/dist/widgets/sorter/index.d.ts +5 -0
  130. package/dist/widgets/table/index.d.ts +5 -0
  131. package/dist/widgets/video/index.d.ts +5 -0
  132. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -43,395 +43,103 @@ const addLibraryVersionToPerseusDebug = (libraryName, libraryVersion) => {
43
43
  }
44
44
  };
45
45
 
46
- // This file is processed by a Rollup plugin (replace) to inject the production
47
- const libName = "@khanacademy/perseus-core";
48
- const libVersion = "3.1.0";
49
- addLibraryVersionToPerseusDebug(libName, libVersion);
50
-
51
- /**
52
- * @typedef {Object} Errors utility for referencing the Perseus error taxonomy.
53
- */
54
- const Errors = Object.freeze({
55
- /**
56
- * @property {ErrorKind} Unknown The kind of error is not known.
57
- */
58
- Unknown: "Unknown",
59
- /**
60
- * @property {ErrorKind} Internal The error is internal to the executing code.
61
- */
62
- Internal: "Internal",
63
- /**
64
- * @property {ErrorKind} InvalidInput There was a problem with the provided
65
- * input, such as the wrong format or a null value.
66
- */
67
- InvalidInput: "InvalidInput",
68
- /**
69
- * @property {ErrorKind} NotAllowed There was a problem due to the state of
70
- * the system not matching the requested operation or input. For example,
71
- * trying to create a username that is valid, but is already taken by
72
- * another user. Use {@link InvalidInput} instead when the input isn't
73
- * valid regardless of the state of the system. Use {@link NotFound} when
74
- * the failure is due to not being able to find a resource.
75
- */
76
- NotAllowed: "NotAllowed",
77
- /**
78
- * @property {ErrorKind} TransientService There was a problem when making a
79
- * request to a service.
80
- */
81
- TransientService: "TransientService",
82
- /**
83
- * @property {ErrorKind} Service There was a non-transient problem when
84
- * making a request to service.
85
- */
86
- Service: "Service"
87
- });
46
+ // Current version.
47
+ var VERSION = '1.13.3';
88
48
 
89
- /**
90
- * @type {ErrorKind} The kind of error being reported
91
- */
49
+ // Establish the root object, `window` (`self`) in the browser, `global`
50
+ // on the server, or `this` in some virtual machines. We use `self`
51
+ // instead of `window` for `WebWorker` support.
52
+ var root = (typeof self == 'object' && self.self === self && self) ||
53
+ (typeof global == 'object' && global.global === global && global) ||
54
+ Function('return this')() ||
55
+ {};
92
56
 
93
- class PerseusError extends Error {
94
- kind;
95
- metadata;
96
- constructor(message, kind, options) {
97
- super(message);
98
- this.kind = kind;
99
- this.metadata = options?.metadata;
100
- }
101
- }
57
+ // Save bytes in the minified (but not gzipped) version:
58
+ var ArrayProto = Array.prototype, ObjProto = Object.prototype;
59
+ var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
102
60
 
103
- /**
104
- * The Perseus "data schema" file.
105
- *
106
- * This file, and the types in it, represents the "data schema" that Perseus
107
- * uses. The @khanacademy/perseus-editor package edits and produces objects
108
- * that conform to the types in this file. Similarly, the top-level renderers
109
- * in @khanacademy/perseus, consume objects that conform to these types.
110
- *
111
- * WARNING: This file should not import any types from elsewhere so that it is
112
- * easy to reason about changes that alter the Perseus schema. This helps
113
- * ensure that it is not changed accidentally when upgrading a dependant
114
- * package or other part of Perseus code. Note that TypeScript does type
115
- * checking via something called "structural typing". This means that as long
116
- * as the shape of a type matches, the name it goes by doesn't matter. As a
117
- * result, a `Coord` type that looks like this `[x: number, y: number]` is
118
- * _identical_, in TypeScript's eyes, to this `Vector2` type `[x: number, y:
119
- * number]`. Also, with tuples, the labels for each entry is ignored, so `[x:
120
- * number, y: number]` is compatible with `[min: number, max: number]`. The
121
- * labels are for humans, not TypeScript. :)
122
- *
123
- * If you make changes to types in this file, be very sure that:
124
- *
125
- * a) the changes are backwards compatible. If they are not, old data from
126
- * previous versions of the "schema" could become unrenderable, or worse,
127
- * introduce hard-to-diagnose bugs.
128
- * b) the parsing code (`util/parse-perseus-json/`) is updated to handle
129
- * the new format _as well as_ the old format.
130
- */
61
+ // Create quick reference variables for speed access to core prototypes.
62
+ var push = ArrayProto.push,
63
+ slice = ArrayProto.slice,
64
+ toString = ObjProto.toString,
65
+ hasOwnProperty = ObjProto.hasOwnProperty;
131
66
 
132
- // TODO(FEI-4010): Remove `Perseus` prefix for all types here
67
+ // Modern feature detection.
68
+ var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
69
+ supportsDataView = typeof DataView !== 'undefined';
133
70
 
134
- // Same name as Mafs
71
+ // All **ECMAScript 5+** native function implementations that we hope to use
72
+ // are declared here.
73
+ var nativeIsArray = Array.isArray,
74
+ nativeKeys = Object.keys,
75
+ nativeCreate = Object.create,
76
+ nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;
135
77
 
136
- /**
137
- * Our core set of Perseus widgets.
138
- *
139
- * This interface is the basis for "registering" all Perseus widget types.
140
- * There should be one key/value pair for each supported widget. If you create
141
- * a new widget, an entry should be added to this interface. Note that this
142
- * only registers the widget options type, you'll also need to register the
143
- * widget so that it's available at runtime (@see
144
- * {@link file://./widgets.ts#registerWidget}).
145
- *
146
- * Importantly, the key should be the name that is used in widget IDs. For most
147
- * widgets that is the same as the widget option's `type` field. In cases where
148
- * a widget has been deprecated and replaced with the deprecated-standin
149
- * widget, it should be the original widget type!
150
- *
151
- * If you define the widget outside of this package, you can still add the new
152
- * widget to this interface by writing the following in that package that
153
- * contains the widget. TypeScript will merge that definition of the
154
- * `PerseusWidgets` with the one defined below.
155
- *
156
- * ```typescript
157
- * declare module "@khanacademy/perseus" {
158
- * interface PerseusWidgetTypes {
159
- * // A new widget
160
- * "new-awesomeness": MyAwesomeNewWidget;
161
- *
162
- * // A deprecated widget
163
- * "super-old-widget": DeprecatedStandinWidget;
164
- * }
165
- * }
166
- *
167
- * // The new widget's options definition
168
- * type MyAwesomeNewWidget = WidgetOptions<'new-awesomeness', MyAwesomeNewWidgetOptions>;
169
- *
170
- * // The deprecated widget's options definition
171
- * type SuperOldWidget = WidgetOptions<'super-old-widget', object>;
172
- * ```
173
- *
174
- * This interface can be extended through the magic of TypeScript "Declaration
175
- * merging". Specifically, we augment this module and extend this interface.
176
- *
177
- * @see {@link https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation}
178
- */
78
+ // Create references to these builtin functions because we override them.
79
+ var _isNaN = isNaN,
80
+ _isFinite = isFinite;
179
81
 
180
- /**
181
- * A map of widget IDs to widget options. This is most often used as the type
182
- * for a set of widgets defined in a `PerseusItem` but can also be useful to
183
- * represent a function parameter where only `widgets` from a `PerseusItem` are
184
- * needed. Today Widget IDs are made up of the widget type and an incrementing
185
- * integer (eg. `interactive-graph 1` or `radio 3`). It is suggested to avoid
186
- * reading/parsing the widget id to derive any information from it, except in
187
- * the case of this map.
188
- *
189
- * @see {@link PerseusWidgetTypes} additional widgets can be added to this map type
190
- * by augmenting the PerseusWidgetTypes with new widget types!
191
- */
82
+ // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
83
+ var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
84
+ var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
85
+ 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
192
86
 
193
- /**
194
- * A "PerseusItem" is a classic Perseus item. It is rendered by the
195
- * `ServerItemRenderer` and the layout is pre-set.
196
- *
197
- * To render more complex Perseus items, see the `Item` type in the multi item
198
- * area.
199
- */
87
+ // The largest integer that can be represented exactly.
88
+ var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
200
89
 
201
- /**
202
- * A "PerseusArticle" is an item that is meant to be rendered as an article.
203
- * This item is never scored and is rendered by the `ArticleRenderer`.
204
- */
90
+ // Some functions take a variable number of arguments, or a few expected
91
+ // arguments at the beginning and then a variable number of values to operate
92
+ // on. This helper accumulates all remaining arguments past the function’s
93
+ // argument length (or an explicit `startIndex`), into an array that becomes
94
+ // the last argument. Similar to ES6’s "rest parameter".
95
+ function restArguments(func, startIndex) {
96
+ startIndex = startIndex == null ? func.length - 1 : +startIndex;
97
+ return function() {
98
+ var length = Math.max(arguments.length - startIndex, 0),
99
+ rest = Array(length),
100
+ index = 0;
101
+ for (; index < length; index++) {
102
+ rest[index] = arguments[index + startIndex];
103
+ }
104
+ switch (startIndex) {
105
+ case 0: return func.call(this, rest);
106
+ case 1: return func.call(this, arguments[0], rest);
107
+ case 2: return func.call(this, arguments[0], arguments[1], rest);
108
+ }
109
+ var args = Array(startIndex + 1);
110
+ for (index = 0; index < startIndex; index++) {
111
+ args[index] = arguments[index];
112
+ }
113
+ args[startIndex] = rest;
114
+ return func.apply(this, args);
115
+ };
116
+ }
205
117
 
206
- const ItemExtras = [
207
- // The user might benefit from using a Scientific Calculator. Provided on Khan Academy when true
208
- "calculator",
209
- // The user might benefit from using a statistics Chi Squared Table like https://people.richland.edu/james/lecture/m170/tbl-chi.html
210
- "chi2Table",
211
- // The user might benefit from a monthly payments calculator. Provided on Khan Academy when true
212
- "financialCalculatorMonthlyPayment",
213
- // The user might benefit from a total amount calculator. Provided on Khan Academy when true
214
- "financialCalculatorTotalAmount",
215
- // The user might benefit from a time to pay off calculator. Provided on Khan Academy when true
216
- "financialCalculatorTimeToPayOff",
217
- // The user might benefit from using a Periodic Table of Elements. Provided on Khan Academy when true
218
- "periodicTable",
219
- // The user might benefit from using a Periodic Table of Elements with key. Provided on Khan Academy when true
220
- "periodicTableWithKey",
221
- // The user might benefit from using a statistics T Table like https://www.statisticshowto.com/tables/t-distribution-table/
222
- "tTable",
223
- // The user might benefit from using a statistics Z Table like https://www.ztable.net/
224
- "zTable"];
118
+ // Is a given variable an object?
119
+ function isObject$1(obj) {
120
+ var type = typeof obj;
121
+ return type === 'function' || (type === 'object' && !!obj);
122
+ }
225
123
 
226
- /**
227
- * The type representing the common structure of all widget's options. The
228
- * `Options` generic type represents the widget-specific option data.
229
- */
124
+ // Is a given value equal to null?
125
+ function isNull(obj) {
126
+ return obj === null;
127
+ }
230
128
 
231
- // prettier-ignore
129
+ // Is a given variable undefined?
130
+ function isUndefined(obj) {
131
+ return obj === void 0;
132
+ }
232
133
 
233
- // prettier-ignore
134
+ // Is a given value a boolean?
135
+ function isBoolean(obj) {
136
+ return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
137
+ }
234
138
 
235
- // prettier-ignore
236
-
237
- // prettier-ignore
238
-
239
- // prettier-ignore
240
-
241
- // prettier-ignore
242
-
243
- // prettier-ignore
244
-
245
- // prettier-ignore
246
-
247
- // prettier-ignore
248
-
249
- // prettier-ignore
250
-
251
- // prettier-ignore
252
-
253
- // prettier-ignore
254
-
255
- // prettier-ignore
256
-
257
- // prettier-ignore
258
-
259
- // prettier-ignore
260
-
261
- // prettier-ignore
262
-
263
- // prettier-ignore
264
-
265
- // prettier-ignore
266
-
267
- // prettier-ignore
268
-
269
- // prettier-ignore
270
-
271
- // prettier-ignore
272
-
273
- // prettier-ignore
274
-
275
- // prettier-ignore
276
-
277
- // prettier-ignore
278
-
279
- // prettier-ignore
280
-
281
- // prettier-ignore
282
-
283
- // prettier-ignore
284
-
285
- // prettier-ignore
286
-
287
- // prettier-ignore
288
-
289
- // prettier-ignore
290
-
291
- // prettier-ignore
292
-
293
- // prettier-ignore
294
-
295
- // prettier-ignore
296
-
297
- // prettier-ignore
298
-
299
- //prettier-ignore
300
-
301
- /**
302
- * A background image applied to various widgets.
303
- */
304
-
305
- /**
306
- * The type of markings to display on the graph.
307
- * - axes: shows the axes without the gride lines
308
- * - graph: shows the axes and the grid lines
309
- * - grid: shows only the grid lines
310
- * - none: shows no markings
311
- */
312
-
313
- const PerseusExpressionAnswerFormConsidered = ["correct", "wrong", "ungraded"];
314
-
315
- // 2D range: xMin, xMax, yMin, yMax
316
-
317
- const lockedFigureColorNames = ["blue", "green", "grayH", "purple", "pink", "orange", "red"];
318
- const lockedFigureColors = {
319
- blue: "#3D7586",
320
- green: "#447A53",
321
- grayH: "#3B3D45",
322
- purple: "#594094",
323
- pink: "#B25071",
324
- red: "#D92916",
325
- orange: "#946700"
326
- };
327
- const lockedFigureFillStyles = {
328
- none: 0,
329
- white: 1,
330
- translucent: 0.4,
331
- solid: 1
332
- };
333
-
334
- // Not associated with a specific figure
335
-
336
- const plotterPlotTypes = ["bar", "line", "pic", "histogram", "dotplot"];
337
-
338
- // Current version.
339
- var VERSION = '1.13.3';
340
-
341
- // Establish the root object, `window` (`self`) in the browser, `global`
342
- // on the server, or `this` in some virtual machines. We use `self`
343
- // instead of `window` for `WebWorker` support.
344
- var root = (typeof self == 'object' && self.self === self && self) ||
345
- (typeof global == 'object' && global.global === global && global) ||
346
- Function('return this')() ||
347
- {};
348
-
349
- // Save bytes in the minified (but not gzipped) version:
350
- var ArrayProto = Array.prototype, ObjProto = Object.prototype;
351
- var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
352
-
353
- // Create quick reference variables for speed access to core prototypes.
354
- var push = ArrayProto.push,
355
- slice = ArrayProto.slice,
356
- toString = ObjProto.toString,
357
- hasOwnProperty = ObjProto.hasOwnProperty;
358
-
359
- // Modern feature detection.
360
- var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
361
- supportsDataView = typeof DataView !== 'undefined';
362
-
363
- // All **ECMAScript 5+** native function implementations that we hope to use
364
- // are declared here.
365
- var nativeIsArray = Array.isArray,
366
- nativeKeys = Object.keys,
367
- nativeCreate = Object.create,
368
- nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;
369
-
370
- // Create references to these builtin functions because we override them.
371
- var _isNaN = isNaN,
372
- _isFinite = isFinite;
373
-
374
- // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
375
- var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
376
- var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
377
- 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
378
-
379
- // The largest integer that can be represented exactly.
380
- var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
381
-
382
- // Some functions take a variable number of arguments, or a few expected
383
- // arguments at the beginning and then a variable number of values to operate
384
- // on. This helper accumulates all remaining arguments past the function’s
385
- // argument length (or an explicit `startIndex`), into an array that becomes
386
- // the last argument. Similar to ES6’s "rest parameter".
387
- function restArguments(func, startIndex) {
388
- startIndex = startIndex == null ? func.length - 1 : +startIndex;
389
- return function() {
390
- var length = Math.max(arguments.length - startIndex, 0),
391
- rest = Array(length),
392
- index = 0;
393
- for (; index < length; index++) {
394
- rest[index] = arguments[index + startIndex];
395
- }
396
- switch (startIndex) {
397
- case 0: return func.call(this, rest);
398
- case 1: return func.call(this, arguments[0], rest);
399
- case 2: return func.call(this, arguments[0], arguments[1], rest);
400
- }
401
- var args = Array(startIndex + 1);
402
- for (index = 0; index < startIndex; index++) {
403
- args[index] = arguments[index];
404
- }
405
- args[startIndex] = rest;
406
- return func.apply(this, args);
407
- };
408
- }
409
-
410
- // Is a given variable an object?
411
- function isObject(obj) {
412
- var type = typeof obj;
413
- return type === 'function' || (type === 'object' && !!obj);
414
- }
415
-
416
- // Is a given value equal to null?
417
- function isNull(obj) {
418
- return obj === null;
419
- }
420
-
421
- // Is a given variable undefined?
422
- function isUndefined(obj) {
423
- return obj === void 0;
424
- }
425
-
426
- // Is a given value a boolean?
427
- function isBoolean(obj) {
428
- return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
429
- }
430
-
431
- // Is a given value a DOM element?
432
- function isElement(obj) {
433
- return !!(obj && obj.nodeType === 1);
434
- }
139
+ // Is a given value a DOM element?
140
+ function isElement(obj) {
141
+ return !!(obj && obj.nodeType === 1);
142
+ }
435
143
 
436
144
  // Internal function for creating a `toString`-based type tester.
437
145
  function tagTester(name) {
@@ -522,7 +230,7 @@ function isNaN$1(obj) {
522
230
  }
523
231
 
524
232
  // Predicate-generating function. Often useful outside of Underscore.
525
- function constant(value) {
233
+ function constant$1(value) {
526
234
  return function() {
527
235
  return value;
528
236
  };
@@ -559,7 +267,7 @@ function isTypedArray(obj) {
559
267
  isBufferLike(obj) && typedArrayPattern.test(toString.call(obj));
560
268
  }
561
269
 
562
- var isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant(false);
270
+ var isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant$1(false);
563
271
 
564
272
  // Internal helper to obtain the `length` property of an object.
565
273
  var getLength = shallowProperty('length');
@@ -604,7 +312,7 @@ function collectNonEnumProps(obj, keys) {
604
312
  // Retrieve the names of an object's own properties.
605
313
  // Delegates to **ECMAScript 5**'s native `Object.keys`.
606
314
  function keys(obj) {
607
- if (!isObject(obj)) return [];
315
+ if (!isObject$1(obj)) return [];
608
316
  if (nativeKeys) return nativeKeys(obj);
609
317
  var keys = [];
610
318
  for (var key in obj) if (has$1(obj, key)) keys.push(key);
@@ -802,7 +510,7 @@ function isEqual(a, b) {
802
510
 
803
511
  // Retrieve all the enumerable property names of an object.
804
512
  function allKeys(obj) {
805
- if (!isObject(obj)) return [];
513
+ if (!isObject$1(obj)) return [];
806
514
  var keys = [];
807
515
  for (var key in obj) keys.push(key);
808
516
  // Ahem, IE < 9.
@@ -931,7 +639,7 @@ function ctor() {
931
639
 
932
640
  // An internal function for creating a new object that inherits from another.
933
641
  function baseCreate(prototype) {
934
- if (!isObject(prototype)) return {};
642
+ if (!isObject$1(prototype)) return {};
935
643
  if (nativeCreate) return nativeCreate(prototype);
936
644
  var Ctor = ctor();
937
645
  Ctor.prototype = prototype;
@@ -951,7 +659,7 @@ function create(prototype, props) {
951
659
 
952
660
  // Create a (shallow-cloned) duplicate of an object.
953
661
  function clone(obj) {
954
- if (!isObject(obj)) return obj;
662
+ if (!isObject$1(obj)) return obj;
955
663
  return isArray(obj) ? obj.slice() : extend({}, obj);
956
664
  }
957
665
 
@@ -1060,7 +768,7 @@ function optimizeCb(func, context, argCount) {
1060
768
  function baseIteratee(value, context, argCount) {
1061
769
  if (value == null) return identity;
1062
770
  if (isFunction$1(value)) return optimizeCb(value, context, argCount);
1063
- if (isObject(value) && !isArray(value)) return matcher(value);
771
+ if (isObject$1(value) && !isArray(value)) return matcher(value);
1064
772
  return property(value);
1065
773
  }
1066
774
 
@@ -1309,7 +1017,7 @@ function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
1309
1017
  if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
1310
1018
  var self = baseCreate(sourceFunc.prototype);
1311
1019
  var result = sourceFunc.apply(self, args);
1312
- if (isObject(result)) return result;
1020
+ if (isObject$1(result)) return result;
1313
1021
  return self;
1314
1022
  }
1315
1023
 
@@ -2071,7 +1779,7 @@ function uniq(array, isSorted, iteratee, context) {
2071
1779
 
2072
1780
  // Produce an array that contains the union: each distinct element from all of
2073
1781
  // the passed-in arrays.
2074
- var union = restArguments(function(arrays) {
1782
+ var union$1 = restArguments(function(arrays) {
2075
1783
  return uniq(flatten$1(arrays, true, true));
2076
1784
  });
2077
1785
 
@@ -2111,7 +1819,7 @@ var zip = restArguments(unzip);
2111
1819
  // Converts lists into objects. Pass either a single array of `[key, value]`
2112
1820
  // pairs, or two parallel arrays of the same length -- one of keys, and one of
2113
1821
  // the corresponding values. Passing by pairs is the reverse of `_.pairs`.
2114
- function object(list, values) {
1822
+ function object$1(list, values) {
2115
1823
  var result = {};
2116
1824
  for (var i = 0, length = getLength(list); i < length; i++) {
2117
1825
  if (values) {
@@ -2206,7 +1914,7 @@ var allExports = /*#__PURE__*/Object.freeze({
2206
1914
  __proto__: null,
2207
1915
  VERSION: VERSION,
2208
1916
  restArguments: restArguments,
2209
- isObject: isObject,
1917
+ isObject: isObject$1,
2210
1918
  isNull: isNull,
2211
1919
  isUndefined: isUndefined,
2212
1920
  isBoolean: isBoolean,
@@ -2250,7 +1958,7 @@ var allExports = /*#__PURE__*/Object.freeze({
2250
1958
  has: has,
2251
1959
  mapObject: mapObject$1,
2252
1960
  identity: identity,
2253
- constant: constant,
1961
+ constant: constant$1,
2254
1962
  noop: noop,
2255
1963
  toPath: toPath$1,
2256
1964
  property: property,
@@ -2339,25 +2047,2619 @@ var allExports = /*#__PURE__*/Object.freeze({
2339
2047
  without: without,
2340
2048
  uniq: uniq,
2341
2049
  unique: uniq,
2342
- union: union,
2050
+ union: union$1,
2343
2051
  intersection: intersection,
2344
2052
  difference: difference,
2345
2053
  unzip: unzip,
2346
2054
  transpose: unzip,
2347
2055
  zip: zip,
2348
- object: object,
2056
+ object: object$1,
2349
2057
  range: range,
2350
2058
  chunk: chunk,
2351
2059
  mixin: mixin,
2352
2060
  'default': _$1
2353
2061
  });
2354
2062
 
2355
- // Default Export
2063
+ // Default Export
2064
+
2065
+ // Add all of the Underscore functions to the wrapper object.
2066
+ var _ = mixin(allExports);
2067
+ // Legacy Node.js API.
2068
+ _._ = _;
2069
+
2070
+ function getMatrixSize(matrix) {
2071
+ const matrixSize = [1, 1];
2072
+
2073
+ // We need to find the widest row and tallest column to get the correct
2074
+ // matrix size.
2075
+ _(matrix).each((matrixRow, row) => {
2076
+ let rowWidth = 0;
2077
+ _(matrixRow).each((matrixCol, col) => {
2078
+ if (matrixCol != null && matrixCol.toString().length) {
2079
+ rowWidth = col + 1;
2080
+ }
2081
+ });
2082
+
2083
+ // Matrix width:
2084
+ matrixSize[1] = Math.max(matrixSize[1], rowWidth);
2085
+
2086
+ // Matrix height:
2087
+ if (rowWidth > 0) {
2088
+ matrixSize[0] = Math.max(matrixSize[0], row + 1);
2089
+ }
2090
+ });
2091
+ return matrixSize;
2092
+ }
2093
+
2094
+ /**
2095
+ * Get the character used for separating decimals.
2096
+ */
2097
+ const getDecimalSeparator = locale => {
2098
+ switch (locale) {
2099
+ // TODO(somewhatabstract): Remove this when Chrome supports the `ka`
2100
+ // locale properly.
2101
+ // https://github.com/formatjs/formatjs/issues/1526#issuecomment-559891201
2102
+ //
2103
+ // Supported locales in Chrome:
2104
+ // https://source.chromium.org/chromium/chromium/src/+/master:third_party/icu/scripts/chrome_ui_languages.list
2105
+ case "ka":
2106
+ return ",";
2107
+ default:
2108
+ const numberWithDecimalSeparator = 1.1;
2109
+ // TODO(FEI-3647): Update to use .formatToParts() once we no longer have to
2110
+ // support Safari 12.
2111
+ const match = new Intl.NumberFormat(locale).format(numberWithDecimalSeparator)
2112
+ // 0x661 is ARABIC-INDIC DIGIT ONE
2113
+ // 0x6F1 is EXTENDED ARABIC-INDIC DIGIT ONE
2114
+ .match(/[^\d\u0661\u06F1]/);
2115
+ return match?.[0] ?? ".";
2116
+ }
2117
+ };
2118
+
2119
+ /**
2120
+ * APPROXIMATE equality on numbers and primitives.
2121
+ */
2122
+ function approximateEqual(x, y) {
2123
+ if (typeof x === "number" && typeof y === "number") {
2124
+ return Math.abs(x - y) < 1e-9;
2125
+ }
2126
+ return x === y;
2127
+ }
2128
+
2129
+ /**
2130
+ * Deep APPROXIMATE equality on primitives, numbers, arrays, and objects.
2131
+ * Recursive.
2132
+ */
2133
+ function approximateDeepEqual(x, y) {
2134
+ if (Array.isArray(x) && Array.isArray(y)) {
2135
+ if (x.length !== y.length) {
2136
+ return false;
2137
+ }
2138
+ for (let i = 0; i < x.length; i++) {
2139
+ if (!approximateDeepEqual(x[i], y[i])) {
2140
+ return false;
2141
+ }
2142
+ }
2143
+ return true;
2144
+ }
2145
+ if (Array.isArray(x) || Array.isArray(y)) {
2146
+ return false;
2147
+ }
2148
+ if (typeof x === "function" && typeof y === "function") {
2149
+ return approximateEqual(x, y);
2150
+ }
2151
+ if (typeof x === "function" || typeof y === "function") {
2152
+ return false;
2153
+ }
2154
+ if (typeof x === "object" && typeof y === "object" && !!x && !!y) {
2155
+ return x === y || _.all(x, function (v, k) {
2156
+ // @ts-expect-error - TS2536 - Type 'CollectionKey<T>' cannot be used to index type 'T'.
2157
+ return approximateDeepEqual(y[k], v);
2158
+ }) && _.all(y, function (v, k) {
2159
+ // @ts-expect-error - TS2536 - Type 'CollectionKey<T>' cannot be used to index type 'T'.
2160
+ return approximateDeepEqual(x[k], v);
2161
+ });
2162
+ }
2163
+ if (typeof x === "object" && !!x || typeof y === "object" && !!y) {
2164
+ return false;
2165
+ }
2166
+ return approximateEqual(x, y);
2167
+ }
2168
+
2169
+ /**
2170
+ * Add a widget placeholder using the widget ID.
2171
+ * ex. addWidget("radio 1") => "[[☃ radio 1]]"
2172
+ *
2173
+ * @param {string} id
2174
+ * @returns {string}
2175
+ */
2176
+ function addWidget(id) {
2177
+ return `[[☃ ${id}]]`;
2178
+ }
2179
+
2180
+ /**
2181
+ * Regex for widget placeholders in a string.
2182
+ *
2183
+ * First capture group is the widget ID (ex. 'radio 1')
2184
+ * Second capture group is the widget type (ex. "radio)
2185
+ * exec return will look like: ['[[☃ radio 1]]', 'radio 1', 'radio']
2186
+ */
2187
+ function getWidgetRegex() {
2188
+ return /\[\[☃ ([A-Za-z0-9- ]+)\]\]/g;
2189
+ }
2190
+
2191
+ /**
2192
+ * Extract all widget IDs, which includes the widget type and instance number.
2193
+ * example output: ['radio 1', 'categorizer 1', 'categorizor 2']
2194
+ *
2195
+ * Content should contain Perseus widget placeholders,
2196
+ * which look like: '[[☃ radio 1]]'.
2197
+ *
2198
+ * @param {string} content
2199
+ * @returns {ReadonlyArray<string>} widgetIds
2200
+ */
2201
+ function getWidgetIdsFromContent(content) {
2202
+ const widgets = [];
2203
+ const localWidgetRegex = getWidgetRegex();
2204
+ let match = localWidgetRegex.exec(content);
2205
+ while (match !== null) {
2206
+ widgets.push(match[1]);
2207
+ match = localWidgetRegex.exec(content);
2208
+ }
2209
+ return widgets;
2210
+ }
2211
+
2212
+ /**
2213
+ * Get a list of widget IDs from content,
2214
+ * but only for specific widget types
2215
+ *
2216
+ * @param {string} type the type of widget (ie "radio")
2217
+ * @param {string} content the string to parse
2218
+ * @param {PerseusWidgetsMap} widgetMap widget ID to widget map
2219
+ * @returns {ReadonlyArray<string>} the widget type (ie "radio")
2220
+ */
2221
+ function getWidgetIdsFromContentByType(type, content, widgetMap) {
2222
+ const rv = [];
2223
+ const widgetIdsInContent = getWidgetIdsFromContent(content);
2224
+ widgetIdsInContent.forEach(widgetId => {
2225
+ const widget = widgetMap[widgetId];
2226
+ if (widget?.type === type) {
2227
+ rv.push(widgetId);
2228
+ }
2229
+ });
2230
+ return rv;
2231
+ }
2232
+
2233
+ // TODO(benchristel): in the future, we may want to make deepClone work for
2234
+ // Record<string, Cloneable> as well. Currently, it only does arrays.
2235
+
2236
+ function deepClone(obj) {
2237
+ if (Array.isArray(obj)) {
2238
+ return obj.map(deepClone);
2239
+ }
2240
+ return obj;
2241
+ }
2242
+
2243
+ const MOVABLES = {
2244
+ PLOT: "PLOT",
2245
+ PARABOLA: "PARABOLA",
2246
+ SINUSOID: "SINUSOID"
2247
+ };
2248
+
2249
+ // TODO(charlie): These really need to go into a utility file as they're being
2250
+ // used by both interactive-graph and now grapher.
2251
+ function canonicalSineCoefficients(coeffs) {
2252
+ // For a curve of the form f(x) = a * Sin(b * x - c) + d,
2253
+ // this function ensures that a, b > 0, and c is its
2254
+ // smallest possible positive value.
2255
+ let amplitude = coeffs[0];
2256
+ let angularFrequency = coeffs[1];
2257
+ let phase = coeffs[2];
2258
+ const verticalOffset = coeffs[3];
2259
+
2260
+ // Guarantee a > 0
2261
+ if (amplitude < 0) {
2262
+ amplitude *= -1;
2263
+ angularFrequency *= -1;
2264
+ phase *= -1;
2265
+ }
2266
+ const period = 2 * Math.PI;
2267
+ // Guarantee b > 0
2268
+ if (angularFrequency < 0) {
2269
+ angularFrequency *= -1;
2270
+ phase *= -1;
2271
+ phase += period / 2;
2272
+ }
2273
+
2274
+ // Guarantee c is smallest possible positive value
2275
+ while (phase > 0) {
2276
+ phase -= period;
2277
+ }
2278
+ while (phase < 0) {
2279
+ phase += period;
2280
+ }
2281
+ return [amplitude, angularFrequency, phase, verticalOffset];
2282
+ }
2283
+ function canonicalTangentCoefficients(coeffs) {
2284
+ // For a curve of the form f(x) = a * Tan(b * x - c) + d,
2285
+ // this function ensures that a, b > 0, and c is its
2286
+ // smallest possible positive value.
2287
+ let amplitude = coeffs[0];
2288
+ let angularFrequency = coeffs[1];
2289
+ let phase = coeffs[2];
2290
+ const verticalOffset = coeffs[3];
2291
+
2292
+ // Guarantee a > 0
2293
+ if (amplitude < 0) {
2294
+ amplitude *= -1;
2295
+ angularFrequency *= -1;
2296
+ phase *= -1;
2297
+ }
2298
+ const period = Math.PI;
2299
+ // Guarantee b > 0
2300
+ if (angularFrequency < 0) {
2301
+ angularFrequency *= -1;
2302
+ phase *= -1;
2303
+ phase += period / 2;
2304
+ }
2305
+
2306
+ // Guarantee c is smallest possible positive value
2307
+ while (phase > 0) {
2308
+ phase -= period;
2309
+ }
2310
+ while (phase < 0) {
2311
+ phase += period;
2312
+ }
2313
+ return [amplitude, angularFrequency, phase, verticalOffset];
2314
+ }
2315
+ const PlotDefaults = {
2316
+ areEqual: function (coeffs1, coeffs2) {
2317
+ return approximateDeepEqual(coeffs1, coeffs2);
2318
+ },
2319
+ movable: MOVABLES.PLOT,
2320
+ getPropsForCoeffs: function (coeffs) {
2321
+ return {
2322
+ // @ts-expect-error - TS2339 - Property 'getFunctionForCoeffs' does not exist on type '{ readonly areEqual: (coeffs1: any, coeffs2: any) => boolean; readonly Movable: any; readonly getPropsForCoeffs: (coeffs: any) => any; }'.
2323
+ fn: _.partial(this.getFunctionForCoeffs, coeffs)
2324
+ };
2325
+ }
2326
+ };
2327
+ const Linear = _.extend({}, PlotDefaults, {
2328
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/67aaf581e6d9ef9038c10558a1f70ac21c11c9f8.png",
2329
+ defaultCoords: [[0.25, 0.75], [0.75, 0.75]],
2330
+ getCoefficients: function (coords) {
2331
+ const p1 = coords[0];
2332
+ const p2 = coords[1];
2333
+ const denom = p2[0] - p1[0];
2334
+ const num = p2[1] - p1[1];
2335
+ if (denom === 0) {
2336
+ return;
2337
+ }
2338
+ const m = num / denom;
2339
+ const b = p2[1] - m * p2[0];
2340
+ return [m, b];
2341
+ },
2342
+ getFunctionForCoeffs: function (coeffs, x) {
2343
+ const m = coeffs[0];
2344
+ const b = coeffs[1];
2345
+ return m * x + b;
2346
+ },
2347
+ getEquationString: function (coords) {
2348
+ const coeffs = this.getCoefficients(coords);
2349
+ const m = coeffs[0];
2350
+ const b = coeffs[1];
2351
+ return "y = " + m.toFixed(3) + "x + " + b.toFixed(3);
2352
+ }
2353
+ });
2354
+ const Quadratic = _.extend({}, PlotDefaults, {
2355
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/e23d36e6fc29ee37174e92c9daba2a66677128ab.png",
2356
+ defaultCoords: [[0.5, 0.5], [0.75, 0.75]],
2357
+ movable: MOVABLES.PARABOLA,
2358
+ getCoefficients: function (coords) {
2359
+ const p1 = coords[0];
2360
+ const p2 = coords[1];
2361
+
2362
+ // Parabola with vertex (h, k) has form: y = a * (h - k)^2 + k
2363
+ const h = p1[0];
2364
+ const k = p1[1];
2365
+
2366
+ // Use these to calculate familiar a, b, c
2367
+ const a = (p2[1] - k) / ((p2[0] - h) * (p2[0] - h));
2368
+ const b = -2 * h * a;
2369
+ const c = a * h * h + k;
2370
+ return [a, b, c];
2371
+ },
2372
+ getFunctionForCoeffs: function (coeffs, x) {
2373
+ const a = coeffs[0];
2374
+ const b = coeffs[1];
2375
+ const c = coeffs[2];
2376
+ return (a * x + b) * x + c;
2377
+ },
2378
+ getPropsForCoeffs: function (coeffs) {
2379
+ return {
2380
+ a: coeffs[0],
2381
+ b: coeffs[1],
2382
+ c: coeffs[2]
2383
+ };
2384
+ },
2385
+ getEquationString: function (coords) {
2386
+ const coeffs = this.getCoefficients(coords);
2387
+ const a = coeffs[0];
2388
+ const b = coeffs[1];
2389
+ const c = coeffs[2];
2390
+ return "y = " + a.toFixed(3) + "x^2 + " + b.toFixed(3) + "x + " + c.toFixed(3);
2391
+ }
2392
+ });
2393
+ const Sinusoid = _.extend({}, PlotDefaults, {
2394
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/3d68e7718498475f53b206c2ab285626baf8857e.png",
2395
+ defaultCoords: [[0.5, 0.5], [0.6, 0.6]],
2396
+ movable: MOVABLES.SINUSOID,
2397
+ getCoefficients: function (coords) {
2398
+ const p1 = coords[0];
2399
+ const p2 = coords[1];
2400
+ const a = p2[1] - p1[1];
2401
+ const b = Math.PI / (2 * (p2[0] - p1[0]));
2402
+ const c = p1[0] * b;
2403
+ const d = p1[1];
2404
+ return [a, b, c, d];
2405
+ },
2406
+ getFunctionForCoeffs: function (coeffs, x) {
2407
+ const a = coeffs[0];
2408
+ const b = coeffs[1];
2409
+ const c = coeffs[2];
2410
+ const d = coeffs[3];
2411
+ return a * Math.sin(b * x - c) + d;
2412
+ },
2413
+ getPropsForCoeffs: function (coeffs) {
2414
+ return {
2415
+ a: coeffs[0],
2416
+ b: coeffs[1],
2417
+ c: coeffs[2],
2418
+ d: coeffs[3]
2419
+ };
2420
+ },
2421
+ getEquationString: function (coords) {
2422
+ const coeffs = this.getCoefficients(coords);
2423
+ const a = coeffs[0];
2424
+ const b = coeffs[1];
2425
+ const c = coeffs[2];
2426
+ const d = coeffs[3];
2427
+ return "y = " + a.toFixed(3) + " sin(" + b.toFixed(3) + "x - " + c.toFixed(3) + ") + " + d.toFixed(3);
2428
+ },
2429
+ areEqual: function (coeffs1, coeffs2) {
2430
+ return approximateDeepEqual(canonicalSineCoefficients(coeffs1), canonicalSineCoefficients(coeffs2));
2431
+ }
2432
+ });
2433
+ const Tangent = _.extend({}, PlotDefaults, {
2434
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/7db80d23c35214f98659fe1cf0765811c1bbfbba.png",
2435
+ defaultCoords: [[0.5, 0.5], [0.75, 0.75]],
2436
+ getCoefficients: function (coords) {
2437
+ const p1 = coords[0];
2438
+ const p2 = coords[1];
2439
+ const a = p2[1] - p1[1];
2440
+ const b = Math.PI / (4 * (p2[0] - p1[0]));
2441
+ const c = p1[0] * b;
2442
+ const d = p1[1];
2443
+ return [a, b, c, d];
2444
+ },
2445
+ getFunctionForCoeffs: function (coeffs, x) {
2446
+ const a = coeffs[0];
2447
+ const b = coeffs[1];
2448
+ const c = coeffs[2];
2449
+ const d = coeffs[3];
2450
+ return a * Math.tan(b * x - c) + d;
2451
+ },
2452
+ getEquationString: function (coords) {
2453
+ const coeffs = this.getCoefficients(coords);
2454
+ const a = coeffs[0];
2455
+ const b = coeffs[1];
2456
+ const c = coeffs[2];
2457
+ const d = coeffs[3];
2458
+ return "y = " + a.toFixed(3) + " sin(" + b.toFixed(3) + "x - " + c.toFixed(3) + ") + " + d.toFixed(3);
2459
+ },
2460
+ areEqual: function (coeffs1, coeffs2) {
2461
+ return approximateDeepEqual(canonicalTangentCoefficients(coeffs1), canonicalTangentCoefficients(coeffs2));
2462
+ }
2463
+ });
2464
+ const Exponential = _.extend({}, PlotDefaults, {
2465
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/9cbfad55525e3ce755a31a631b074670a5dad611.png",
2466
+ defaultCoords: [[0.5, 0.55], [0.75, 0.75]],
2467
+ defaultAsymptote: [[0, 0.5], [1.0, 0.5]],
2468
+ /**
2469
+ * Add extra constraints for movement of the points or asymptote (below):
2470
+ * newCoord: [x, y]
2471
+ * The end position of the point or asymptote endpoint
2472
+ * oldCoord: [x, y]
2473
+ * The old position of the point or asymptote endpoint
2474
+ * coords:
2475
+ * An array of coordinates representing the proposed end configuration
2476
+ * of the plot coordinates.
2477
+ * asymptote:
2478
+ * An array of coordinates representing the proposed end configuration
2479
+ * of the asymptote.
2480
+ *
2481
+ * Return: either a coordinate (to be used as the resulting coordinate of
2482
+ * the move) or a boolean, where `true` uses newCoord as the resulting
2483
+ * coordinate, and `false` uses oldCoord as the resulting coordinate.
2484
+ */
2485
+ extraCoordConstraint: function (newCoord, oldCoord, coords, asymptote, graph) {
2486
+ const y = asymptote[0][1];
2487
+ return _.all(coords, coord => coord[1] !== y);
2488
+ },
2489
+ extraAsymptoteConstraint: function (newCoord, oldCoord, coords, asymptote, graph) {
2490
+ const y = newCoord[1];
2491
+ const isValid = _.all(coords, coord => coord[1] > y) || _.all(coords, coord => coord[1] < y);
2492
+ if (isValid) {
2493
+ return [oldCoord[0], y];
2494
+ }
2495
+ // Snap the asymptote as close as possible, i.e., if the user moves
2496
+ // the mouse really quickly into an invalid region
2497
+ const oldY = oldCoord[1];
2498
+ const wasBelow = _.all(coords, coord => coord[1] > oldY);
2499
+ if (wasBelow) {
2500
+ const bottomMost = _.min(_.map(coords, coord => coord[1]));
2501
+ return [oldCoord[0], bottomMost - graph.snapStep[1]];
2502
+ }
2503
+ const topMost = _.max(_.map(coords, coord => coord[1]));
2504
+ return [oldCoord[0], topMost + graph.snapStep[1]];
2505
+ },
2506
+ allowReflectOverAsymptote: true,
2507
+ getCoefficients: function (coords, asymptote) {
2508
+ const p1 = coords[0];
2509
+ const p2 = coords[1];
2510
+ const c = asymptote[0][1];
2511
+ const b = Math.log((p1[1] - c) / (p2[1] - c)) / (p1[0] - p2[0]);
2512
+ const a = (p1[1] - c) / Math.exp(b * p1[0]);
2513
+ return [a, b, c];
2514
+ },
2515
+ getFunctionForCoeffs: function (coeffs, x) {
2516
+ const a = coeffs[0];
2517
+ const b = coeffs[1];
2518
+ const c = coeffs[2];
2519
+ return a * Math.exp(b * x) + c;
2520
+ },
2521
+ getEquationString: function (coords, asymptote) {
2522
+ if (!asymptote) {
2523
+ return null;
2524
+ }
2525
+ const coeffs = this.getCoefficients(coords, asymptote);
2526
+ const a = coeffs[0];
2527
+ const b = coeffs[1];
2528
+ const c = coeffs[2];
2529
+ return "y = " + a.toFixed(3) + "e^(" + b.toFixed(3) + "x) + " + c.toFixed(3);
2530
+ }
2531
+ });
2532
+ const Logarithm = _.extend({}, PlotDefaults, {
2533
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/f6491e99d34af34d924bfe0231728ad912068dc3.png",
2534
+ defaultCoords: [[0.55, 0.5], [0.75, 0.75]],
2535
+ defaultAsymptote: [[0.5, 0], [0.5, 1.0]],
2536
+ extraCoordConstraint: function (newCoord, oldCoord, coords, asymptote, graph) {
2537
+ const x = asymptote[0][0];
2538
+ return _.all(coords, coord => coord[0] !== x) && coords[0][1] !== coords[1][1];
2539
+ },
2540
+ extraAsymptoteConstraint: function (newCoord, oldCoord, coords, asymptote, graph) {
2541
+ const x = newCoord[0];
2542
+ const isValid = _.all(coords, coord => coord[0] > x) || _.all(coords, coord => coord[0] < x);
2543
+ if (isValid) {
2544
+ return [x, oldCoord[1]];
2545
+ }
2546
+ // Snap the asymptote as close as possible, i.e., if the user moves
2547
+ // the mouse really quickly into an invalid region
2548
+ const oldX = oldCoord[0];
2549
+ const wasLeft = _.all(coords, coord => coord[0] > oldX);
2550
+ if (wasLeft) {
2551
+ const leftMost = _.min(_.map(coords, coord => coord[0]));
2552
+ return [leftMost - graph.snapStep[0], oldCoord[1]];
2553
+ }
2554
+ const rightMost = _.max(_.map(coords, coord => coord[0]));
2555
+ return [rightMost + graph.snapStep[0], oldCoord[1]];
2556
+ },
2557
+ allowReflectOverAsymptote: true,
2558
+ getCoefficients: function (coords, asymptote) {
2559
+ // It's easiest to calculate the logarithm's coefficients by thinking
2560
+ // about it as the inverse of the exponential, so we flip x and y and
2561
+ // perform some algebra on the coefficients. This also unifies the
2562
+ // logic between the two 'models'.
2563
+ const flip = coord => [coord[1], coord[0]];
2564
+ const inverseCoeffs = Exponential.getCoefficients(_.map(coords, flip), _.map(asymptote, flip));
2565
+ if (inverseCoeffs) {
2566
+ const c = -inverseCoeffs[2] / inverseCoeffs[0];
2567
+ const b = 1 / inverseCoeffs[0];
2568
+ const a = 1 / inverseCoeffs[1];
2569
+ return [a, b, c];
2570
+ }
2571
+ },
2572
+ getFunctionForCoeffs: function (coeffs, x, asymptote) {
2573
+ const a = coeffs[0];
2574
+ const b = coeffs[1];
2575
+ const c = coeffs[2];
2576
+ return a * Math.log(b * x + c);
2577
+ },
2578
+ getEquationString: function (coords, asymptote) {
2579
+ if (!asymptote) {
2580
+ return null;
2581
+ }
2582
+ const coeffs = this.getCoefficients(coords, asymptote);
2583
+ const a = coeffs[0];
2584
+ const b = coeffs[1];
2585
+ const c = coeffs[2];
2586
+ return "y = ln(" + a.toFixed(3) + "x + " + b.toFixed(3) + ") + " + c.toFixed(3);
2587
+ }
2588
+ });
2589
+ const AbsoluteValue = _.extend({}, PlotDefaults, {
2590
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/8256a630175a0cb1d11de223d6de0266daf98721.png",
2591
+ defaultCoords: [[0.5, 0.5], [0.75, 0.75]],
2592
+ getCoefficients: function (coords) {
2593
+ const p1 = coords[0];
2594
+ const p2 = coords[1];
2595
+ const denom = p2[0] - p1[0];
2596
+ const num = p2[1] - p1[1];
2597
+ if (denom === 0) {
2598
+ return;
2599
+ }
2600
+ let m = Math.abs(num / denom);
2601
+ if (p2[1] < p1[1]) {
2602
+ m *= -1;
2603
+ }
2604
+ const horizontalOffset = p1[0];
2605
+ const verticalOffset = p1[1];
2606
+ return [m, horizontalOffset, verticalOffset];
2607
+ },
2608
+ getFunctionForCoeffs: function (coeffs, x) {
2609
+ const m = coeffs[0];
2610
+ const horizontalOffset = coeffs[1];
2611
+ const verticalOffset = coeffs[2];
2612
+ return m * Math.abs(x - horizontalOffset) + verticalOffset;
2613
+ },
2614
+ getEquationString: function (coords) {
2615
+ const coeffs = this.getCoefficients(coords);
2616
+ const m = coeffs[0];
2617
+ const horizontalOffset = coeffs[1];
2618
+ const verticalOffset = coeffs[2];
2619
+ return "y = " + m.toFixed(3) + "| x - " + horizontalOffset.toFixed(3) + "| + " + verticalOffset.toFixed(3);
2620
+ }
2621
+ });
2622
+
2623
+ /* Utility functions for dealing with graphing interfaces. */
2624
+ const functionTypeMapping = {
2625
+ linear: Linear,
2626
+ quadratic: Quadratic,
2627
+ sinusoid: Sinusoid,
2628
+ tangent: Tangent,
2629
+ exponential: Exponential,
2630
+ logarithm: Logarithm,
2631
+ absolute_value: AbsoluteValue
2632
+ };
2633
+ const allTypes = _.keys(functionTypeMapping);
2634
+ function functionForType(type) {
2635
+ // @ts-expect-error: TypeScript doesn't know how to use deal with generics
2636
+ // and conditional types in this way.
2637
+ return functionTypeMapping[type];
2638
+ }
2639
+
2640
+ var grapherUtil = /*#__PURE__*/Object.freeze({
2641
+ __proto__: null,
2642
+ MOVABLES: MOVABLES,
2643
+ allTypes: allTypes,
2644
+ functionForType: functionForType
2645
+ });
2646
+
2647
+ function isRealJSONParse(jsonParse) {
2648
+ const randomPhrase = buildRandomPhrase();
2649
+ const randomHintPhrase = buildRandomPhrase();
2650
+ const randomString = buildRandomString();
2651
+ const testingObject = JSON.stringify({
2652
+ answerArea: {
2653
+ calculator: false,
2654
+ chi2Table: false,
2655
+ financialCalculatorMonthlyPayment: false,
2656
+ financialCalculatorTimeToPayOff: false,
2657
+ financialCalculatorTotalAmount: false,
2658
+ periodicTable: false,
2659
+ periodicTableWithKey: false,
2660
+ tTable: false,
2661
+ zTable: false
2662
+ },
2663
+ hints: [randomHintPhrase, `=${Math.floor(Math.random() * 50) + 1}`],
2664
+ itemDataVersion: {
2665
+ major: 0,
2666
+ minor: 1
2667
+ },
2668
+ question: {
2669
+ content: `${randomPhrase}`,
2670
+ images: {},
2671
+ widgets: {
2672
+ expression1: {
2673
+ alignment: "default",
2674
+ graded: false,
2675
+ options: {
2676
+ answerForms: [{
2677
+ considered: "wrong",
2678
+ form: false,
2679
+ key: 0,
2680
+ simplify: false,
2681
+ value: `${randomString}`
2682
+ }],
2683
+ ariaLabel: "Answer",
2684
+ buttonSets: ["basic"],
2685
+ functions: ["f", "g", "h"],
2686
+ static: true,
2687
+ times: false,
2688
+ visibleLabel: "Answer"
2689
+ },
2690
+ static: true,
2691
+ type: "expression",
2692
+ version: {
2693
+ major: 1,
2694
+ minor: 0
2695
+ }
2696
+ }
2697
+ }
2698
+ }
2699
+ });
2700
+ const testJSON = buildTestData(testingObject.replace(/"/g, '\\"'));
2701
+ const parsedTestJSON = jsonParse(testJSON);
2702
+ const parsedTestItemData = parsedTestJSON.data.assessmentItem.item.itemData;
2703
+ return approximateDeepEqual(parsedTestItemData, testingObject);
2704
+ }
2705
+ function buildRandomString() {
2706
+ let capitalize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
2707
+ let randomString = "";
2708
+ const randomLength = Math.floor(Math.random() * 8) + 3;
2709
+ for (let i = 0; i < randomLength; i++) {
2710
+ const randomLetter = String.fromCharCode(97 + Math.floor(Math.random() * 26));
2711
+ randomString += capitalize && i === 0 ? randomLetter.toUpperCase() : randomLetter;
2712
+ }
2713
+ return randomString;
2714
+ }
2715
+ function buildRandomPhrase() {
2716
+ const phrases = [];
2717
+ const randomLength = Math.floor(Math.random() * 10) + 5;
2718
+ for (let i = 0; i < randomLength; i++) {
2719
+ phrases.push(buildRandomString(i === 0));
2720
+ }
2721
+ const modifierStart = ["**", "$"];
2722
+ const modifierEnd = ["**", "$"];
2723
+ const modifierIndex = Math.floor(Math.random() * modifierStart.length);
2724
+ return `${modifierStart[modifierIndex]}${phrases.join(" ")}${modifierEnd[modifierIndex]}`;
2725
+ }
2726
+ function buildTestData(testObject) {
2727
+ return `{"data":{"assessmentItem":{"__typename":"AssessmentItemOrError","error":null,"item":{"__typename":"AssessmentItem","id":"x890b3c70f3e8f4a6","itemData":"${testObject}","problemType":"Type 1","sha":"c7284a3ad65214b4e62bccce236d92f7f5d35941"}}}}`;
2728
+ }
2729
+
2730
+ process.env.NODE_ENV === 'production';
2731
+
2732
+ function success(value) {
2733
+ return {
2734
+ type: "success",
2735
+ value
2736
+ };
2737
+ }
2738
+ function failure(detail) {
2739
+ return {
2740
+ type: "failure",
2741
+ detail
2742
+ };
2743
+ }
2744
+ function isFailure(result) {
2745
+ return result.type === "failure";
2746
+ }
2747
+ function isSuccess(result) {
2748
+ return result.type === "success";
2749
+ }
2750
+
2751
+ // Result's `all` function is similar to Promise.all: given an array of
2752
+ // results, it returns success if all succeeded, and failure if any failed.
2753
+ function all(results) {
2754
+ let combineFailureDetails = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : a => a;
2755
+ const values = [];
2756
+ const failureDetails = [];
2757
+ for (const result of results) {
2758
+ if (result.type === "success") {
2759
+ values.push(result.value);
2760
+ } else {
2761
+ failureDetails.push(result.detail);
2762
+ }
2763
+ }
2764
+ if (failureDetails.length > 0) {
2765
+ return failure(failureDetails.reduce(combineFailureDetails));
2766
+ }
2767
+ return success(values);
2768
+ }
2769
+
2770
+ class ErrorTrackingParseContext {
2771
+ constructor(path) {
2772
+ this.path = path;
2773
+ }
2774
+ failure(expected, badValue) {
2775
+ return failure([{
2776
+ expected: wrapInArray(expected),
2777
+ badValue,
2778
+ path: this.path
2779
+ }]);
2780
+ }
2781
+ forSubtree(key) {
2782
+ return new ErrorTrackingParseContext([...this.path, key]);
2783
+ }
2784
+ success(value) {
2785
+ return success(value);
2786
+ }
2787
+ }
2788
+ function wrapInArray(a) {
2789
+ return Array.isArray(a) ? a : [a];
2790
+ }
2791
+
2792
+ function formatPath(path) {
2793
+ return "(root)" + path.map(formatPathSegment).join("");
2794
+ }
2795
+ function formatPathSegment(segment) {
2796
+ if (typeof segment === "string") {
2797
+ return validIdentifier.test(segment) ? "." + segment : `[${JSON.stringify(segment)}]`;
2798
+ }
2799
+ return `[${segment.toString()}]`;
2800
+ }
2801
+ const validIdentifier = /^[A-Za-z$_][A-Za-z$_0-9]*$/;
2802
+
2803
+ function message(failure) {
2804
+ const expected = conjoin(failure.expected);
2805
+ const path = formatPath(failure.path);
2806
+ const badValue = JSON.stringify(failure.badValue);
2807
+ return `At ${path} -- expected ${expected}, but got ${badValue}`;
2808
+ }
2809
+ function conjoin(items) {
2810
+ switch (items.length) {
2811
+ // TODO(benchristel): handle 0 if this is reused elsewhere.
2812
+ case 1:
2813
+ return items[0];
2814
+ case 2:
2815
+ return items.join(" or ");
2816
+ default:
2817
+ {
2818
+ const allButLast = items.slice(0, items.length - 1);
2819
+ const last = items[items.length - 1];
2820
+ return allButLast.join(", ") + ", or " + last;
2821
+ }
2822
+ }
2823
+ }
2824
+
2825
+ function parse(value, parser) {
2826
+ const result = parser(value, new ErrorTrackingParseContext([]));
2827
+ if (isFailure(result)) {
2828
+ return failure(result.detail.map(message).join("; "));
2829
+ }
2830
+ return result;
2831
+ }
2832
+
2833
+ const any = (rawValue, ctx) => ctx.success(rawValue);
2834
+
2835
+ function array(elementParser) {
2836
+ return (rawValue, ctx) => {
2837
+ if (!Array.isArray(rawValue)) {
2838
+ return ctx.failure("array", rawValue);
2839
+ }
2840
+ const elementResults = rawValue.map((elem, i) => elementParser(elem, ctx.forSubtree(i)));
2841
+ return all(elementResults, concat);
2842
+ };
2843
+ }
2844
+ function concat(a, b) {
2845
+ return [...a, ...b];
2846
+ }
2847
+
2848
+ function boolean(rawValue, ctx) {
2849
+ if (typeof rawValue === "boolean") {
2850
+ return ctx.success(rawValue);
2851
+ }
2852
+ return ctx.failure("boolean", rawValue);
2853
+ }
2854
+
2855
+ function constant(acceptedValue) {
2856
+ return (rawValue, ctx) => {
2857
+ if (rawValue !== acceptedValue) {
2858
+ return ctx.failure(String(JSON.stringify(acceptedValue)), rawValue);
2859
+ }
2860
+ return ctx.success(acceptedValue);
2861
+ };
2862
+ }
2863
+
2864
+ function enumeration() {
2865
+ for (var _len = arguments.length, acceptedValues = new Array(_len), _key = 0; _key < _len; _key++) {
2866
+ acceptedValues[_key] = arguments[_key];
2867
+ }
2868
+ return (rawValue, ctx) => {
2869
+ if (typeof rawValue === "string") {
2870
+ const index = acceptedValues.indexOf(rawValue);
2871
+ if (index > -1) {
2872
+ return ctx.success(acceptedValues[index]);
2873
+ }
2874
+ }
2875
+ const expected = acceptedValues.map(v => JSON.stringify(v));
2876
+ return ctx.failure(expected, rawValue);
2877
+ };
2878
+ }
2879
+
2880
+ function isObject(x) {
2881
+ return x != null && Object.getPrototypeOf(x) === Object.prototype;
2882
+ }
2883
+
2884
+ function nullable(parseValue) {
2885
+ return (rawValue, ctx) => {
2886
+ if (rawValue === null) {
2887
+ return ctx.success(rawValue);
2888
+ }
2889
+ return parseValue(rawValue, ctx);
2890
+ };
2891
+ }
2892
+
2893
+ const number = (rawValue, ctx) => {
2894
+ if (typeof rawValue === "number") {
2895
+ return ctx.success(rawValue);
2896
+ }
2897
+ return ctx.failure("number", rawValue);
2898
+ };
2899
+
2900
+ function object(schema) {
2901
+ return (rawValue, ctx) => {
2902
+ if (!isObject(rawValue)) {
2903
+ return ctx.failure("object", rawValue);
2904
+ }
2905
+ const ret = {
2906
+ ...rawValue
2907
+ };
2908
+ const mismatches = [];
2909
+ for (const [prop, propParser] of Object.entries(schema)) {
2910
+ const result = propParser(rawValue[prop], ctx.forSubtree(prop));
2911
+ if (isSuccess(result)) {
2912
+ if (result.value !== undefined || prop in rawValue) {
2913
+ ret[prop] = result.value;
2914
+ }
2915
+ } else {
2916
+ mismatches.push(...result.detail);
2917
+ }
2918
+ }
2919
+ if (mismatches.length > 0) {
2920
+ return failure(mismatches);
2921
+ }
2922
+ return ctx.success(ret);
2923
+ };
2924
+ }
2925
+
2926
+ function optional(parseValue) {
2927
+ return (rawValue, ctx) => {
2928
+ if (rawValue === undefined) {
2929
+ return ctx.success(rawValue);
2930
+ }
2931
+ return parseValue(rawValue, ctx);
2932
+ };
2933
+ }
2934
+
2935
+ function pair(parseA, parseB) {
2936
+ return (rawValue, ctx) => {
2937
+ if (!Array.isArray(rawValue)) {
2938
+ return ctx.failure("array", rawValue);
2939
+ }
2940
+ if (rawValue.length !== 2) {
2941
+ return ctx.failure("array of length 2", rawValue);
2942
+ }
2943
+ const [rawA, rawB] = rawValue;
2944
+ const resultA = parseA(rawA, ctx.forSubtree(0));
2945
+ if (isFailure(resultA)) {
2946
+ return resultA;
2947
+ }
2948
+ const resultB = parseB(rawB, ctx.forSubtree(1));
2949
+ if (isFailure(resultB)) {
2950
+ return resultB;
2951
+ }
2952
+ return ctx.success([resultA.value, resultB.value]);
2953
+ };
2954
+ }
2955
+
2956
+ function pipeParsers(p) {
2957
+ return new ParserPipeline(p);
2958
+ }
2959
+ class ParserPipeline {
2960
+ constructor(parser) {
2961
+ this.parser = parser;
2962
+ }
2963
+ then(nextParser) {
2964
+ return new ParserPipeline(composeParsers(this.parser, nextParser));
2965
+ }
2966
+ }
2967
+ function composeParsers(parserA, parserB) {
2968
+ return (rawValue, ctx) => {
2969
+ const partialResult = parserA(rawValue, ctx);
2970
+ if (isFailure(partialResult)) {
2971
+ return partialResult;
2972
+ }
2973
+ return parserB(partialResult.value, ctx);
2974
+ };
2975
+ }
2976
+
2977
+ function record(parseKey, parseValue) {
2978
+ return (rawValue, ctx) => {
2979
+ if (!isObject(rawValue)) {
2980
+ return ctx.failure("object", rawValue);
2981
+ }
2982
+ const result = {};
2983
+ const mismatches = [];
2984
+ for (const [key, value] of Object.entries(rawValue)) {
2985
+ const entryCtx = ctx.forSubtree(key);
2986
+ const keyResult = parseKey(key, entryCtx);
2987
+ if (isFailure(keyResult)) {
2988
+ mismatches.push(...keyResult.detail);
2989
+ }
2990
+ const valueResult = parseValue(value, entryCtx);
2991
+ if (isFailure(valueResult)) {
2992
+ mismatches.push(...valueResult.detail);
2993
+ }
2994
+ if (isSuccess(keyResult) && isSuccess(valueResult)) {
2995
+ result[keyResult.value] = valueResult.value;
2996
+ }
2997
+ }
2998
+ if (mismatches.length > 0) {
2999
+ return failure(mismatches);
3000
+ }
3001
+ return ctx.success(result);
3002
+ };
3003
+ }
3004
+
3005
+ const string = (rawValue, ctx) => {
3006
+ if (typeof rawValue === "string") {
3007
+ return ctx.success(rawValue);
3008
+ }
3009
+ return ctx.failure("string", rawValue);
3010
+ };
3011
+
3012
+ function trio(parseA, parseB, parseC) {
3013
+ return (rawValue, ctx) => {
3014
+ if (!Array.isArray(rawValue)) {
3015
+ return ctx.failure("array", rawValue);
3016
+ }
3017
+ if (rawValue.length !== 3) {
3018
+ return ctx.failure("array of length 3", rawValue);
3019
+ }
3020
+ const resultA = parseA(rawValue[0], ctx.forSubtree(0));
3021
+ if (isFailure(resultA)) {
3022
+ return resultA;
3023
+ }
3024
+ const resultB = parseB(rawValue[1], ctx.forSubtree(1));
3025
+ if (isFailure(resultB)) {
3026
+ return resultB;
3027
+ }
3028
+ const resultC = parseC(rawValue[2], ctx.forSubtree(2));
3029
+ if (isFailure(resultC)) {
3030
+ return resultC;
3031
+ }
3032
+ return ctx.success([resultA.value, resultB.value, resultC.value]);
3033
+ };
3034
+ }
3035
+
3036
+ function union(parseBranch) {
3037
+ return new UnionBuilder(parseBranch);
3038
+ }
3039
+ class UnionBuilder {
3040
+ constructor(parser) {
3041
+ this.parser = parser;
3042
+ }
3043
+ or(newBranch) {
3044
+ return new UnionBuilder(either(this.parser, newBranch));
3045
+ }
3046
+ }
3047
+ function either(parseA, parseB) {
3048
+ return (rawValue, ctx) => {
3049
+ const resultA = parseA(rawValue, ctx);
3050
+ if (isSuccess(resultA)) {
3051
+ return resultA;
3052
+ }
3053
+ return parseB(rawValue, ctx);
3054
+ };
3055
+ }
3056
+
3057
+ function defaulted(parser, fallback) {
3058
+ return (rawValue, ctx) => {
3059
+ if (rawValue == null) {
3060
+ return success(fallback(rawValue));
3061
+ }
3062
+ return parser(rawValue, ctx);
3063
+ };
3064
+ }
3065
+
3066
+ const parseImages = defaulted(record(string, object({
3067
+ width: number,
3068
+ height: number
3069
+ })), () => ({}));
3070
+
3071
+ function parseWidget(parseType, parseOptions) {
3072
+ return object({
3073
+ type: parseType,
3074
+ static: optional(boolean),
3075
+ graded: optional(boolean),
3076
+ alignment: optional(string),
3077
+ options: parseOptions,
3078
+ key: optional(number),
3079
+ version: optional(object({
3080
+ major: number,
3081
+ minor: number
3082
+ }))
3083
+ });
3084
+ }
3085
+ function parseWidgetWithVersion(parseVersion, parseType, parseOptions) {
3086
+ return object({
3087
+ type: parseType,
3088
+ static: optional(boolean),
3089
+ graded: optional(boolean),
3090
+ alignment: optional(string),
3091
+ options: parseOptions,
3092
+ key: optional(number),
3093
+ version: parseVersion
3094
+ });
3095
+ }
3096
+
3097
+ const parseCategorizerWidget = parseWidget(constant("categorizer"), object({
3098
+ items: array(string),
3099
+ categories: array(string),
3100
+ randomizeItems: defaulted(boolean, () => false),
3101
+ static: defaulted(boolean, () => false),
3102
+ values: array(defaulted(number, () => 0)),
3103
+ highlightLint: optional(boolean),
3104
+ linterContext: optional(object({
3105
+ contentType: string,
3106
+ paths: array(string),
3107
+ stack: array(string)
3108
+ }))
3109
+ }));
3110
+
3111
+ const parseCSProgramWidget = parseWidget(constant("cs-program"), object({
3112
+ programID: string,
3113
+ programType: any,
3114
+ settings: array(object({
3115
+ name: string,
3116
+ value: string
3117
+ })),
3118
+ showEditor: boolean,
3119
+ showButtons: boolean,
3120
+ height: number,
3121
+ static: defaulted(boolean, () => false)
3122
+ }));
3123
+
3124
+ const parseDefinitionWidget = parseWidget(constant("definition"), object({
3125
+ togglePrompt: string,
3126
+ definition: string,
3127
+ static: defaulted(boolean, () => false)
3128
+ }));
3129
+
3130
+ const parseDropdownWidget = parseWidget(constant("dropdown"), object({
3131
+ placeholder: defaulted(string, () => ""),
3132
+ ariaLabel: optional(string),
3133
+ visibleLabel: optional(string),
3134
+ static: defaulted(boolean, () => false),
3135
+ choices: array(object({
3136
+ content: string,
3137
+ correct: boolean
3138
+ }))
3139
+ }));
3140
+
3141
+ const parseExplanationWidget = parseWidget(constant("explanation"), object({
3142
+ showPrompt: string,
3143
+ hidePrompt: string,
3144
+ explanation: string,
3145
+ // We wrap parseWidgetsMap in a function here to make sure it is not
3146
+ // referenced before it is defined. There is an import cycle between
3147
+ // this file and widgets-map.ts that could cause it to be undefined.
3148
+ widgets: defaulted((rawVal, ctx) => parseWidgetsMap(rawVal, ctx), () => ({})),
3149
+ static: defaulted(boolean, () => false)
3150
+ }));
3151
+
3152
+ // Given a function, creates a PartialParser that converts one type to another
3153
+ // using that function. The returned parser never fails.
3154
+ function convert(f) {
3155
+ return (rawValue, ctx) => ctx.success(f(rawValue));
3156
+ }
3157
+
3158
+ /**
3159
+ * Creates a parser for a widget options type with multiple major versions. Old
3160
+ * versions are migrated to the latest version. The parse fails if the input
3161
+ * data does not match any of the versions.
3162
+ *
3163
+ * @example
3164
+ * const parseOptions = versionedWidgetOptions(3, parseOptionsV3)
3165
+ * .withMigrationFrom(2, parseOptionsV2, migrateV2ToV3)
3166
+ * .withMigrationFrom(1, parseOptionsV1, migrateV1ToV2)
3167
+ * .withMigrationFrom(0, parseOptionsV0, migrateV0ToV1)
3168
+ * .parser;
3169
+ *
3170
+ * @param latestMajorVersion the latest major version of the widget options.
3171
+ * @param parseLatest a {@link Parser} for the latest version of the widget
3172
+ * options.
3173
+ * @returns a builder object, to which migrations from earlier versions can be
3174
+ * added. Migrations must be added in "reverse chronological" order as in the
3175
+ * example above.
3176
+ */
3177
+ function versionedWidgetOptions(latestMajorVersion, parseLatest) {
3178
+ return new VersionedWidgetOptionsParserBuilder(latestMajorVersion, parseLatest, latest => latest, (raw, ctx) => ctx.failure("widget options with a known version number", raw));
3179
+ }
3180
+ class VersionedWidgetOptionsParserBuilder {
3181
+ parser;
3182
+ constructor(majorVersion, parseThisVersion, migrateToLatest, parseOtherVersions) {
3183
+ this.migrateToLatest = migrateToLatest;
3184
+ this.parseOtherVersions = parseOtherVersions;
3185
+ const parseThisVersionAndMigrateToLatest = pipeParsers(parseThisVersion).then(convert(this.migrateToLatest)).parser;
3186
+ this.parser = (raw, ctx) => {
3187
+ if (!isObject(raw)) {
3188
+ return ctx.failure("object", raw);
3189
+ }
3190
+ const versionParseResult = parseVersionedObject(raw, ctx);
3191
+ if (isFailure(versionParseResult)) {
3192
+ return versionParseResult;
3193
+ }
3194
+ if (versionParseResult.value.version.major !== majorVersion) {
3195
+ return this.parseOtherVersions(raw, ctx);
3196
+ }
3197
+ return parseThisVersionAndMigrateToLatest(raw, ctx);
3198
+ };
3199
+ }
3200
+
3201
+ /**
3202
+ * Add a migration from an old version of the widget options.
3203
+ */
3204
+ withMigrationFrom(majorVersion, parseOldVersion, migrateToNextVersion) {
3205
+ const parseOtherVersions = this.parser;
3206
+ const migrateToLatest = old => this.migrateToLatest(migrateToNextVersion(old));
3207
+ return new VersionedWidgetOptionsParserBuilder(majorVersion, parseOldVersion, migrateToLatest, parseOtherVersions);
3208
+ }
3209
+ }
3210
+ const parseVersionedObject = object({
3211
+ version: defaulted(object({
3212
+ major: number,
3213
+ minor: number
3214
+ }), () => ({
3215
+ major: 0,
3216
+ minor: 0
3217
+ }))
3218
+ });
3219
+
3220
+ const stringOrNumberOrNullOrUndefined = union(string).or(number).or(constant(null)).or(constant(undefined)).parser;
3221
+ const parsePossiblyInvalidAnswerForm = object({
3222
+ // `value` is the possibly invalid part of this. It should always be a
3223
+ // string, but some answer forms don't have it. The Expression widget
3224
+ // ignores invalid values, so we can safely filter them out during parsing.
3225
+ value: optional(string),
3226
+ form: defaulted(boolean, () => false),
3227
+ simplify: defaulted(boolean, () => false),
3228
+ considered: enumeration("correct", "wrong", "ungraded"),
3229
+ key: pipeParsers(stringOrNumberOrNullOrUndefined).then(convert(String)).parser
3230
+ });
3231
+ function removeInvalidAnswerForms(possiblyInvalid) {
3232
+ const valid = [];
3233
+ for (const answerForm of possiblyInvalid) {
3234
+ const {
3235
+ value
3236
+ } = answerForm;
3237
+ if (value != null) {
3238
+ // Copying the object seems to be needed to make TypeScript happy
3239
+ valid.push({
3240
+ ...answerForm,
3241
+ value
3242
+ });
3243
+ }
3244
+ }
3245
+ return valid;
3246
+ }
3247
+
3248
+ // NOTE(benchristel): I copied the default buttonSets from
3249
+ // expression.tsx. See the parse-perseus-json/README.md for
3250
+ // an explanation of why we want to duplicate the default here.
3251
+ const parseButtonSets = defaulted(array(enumeration("basic", "basic+div", "trig", "prealgebra", "logarithms", "basic relations", "advanced relations")), () => ["basic", "trig", "prealgebra", "logarithms"]);
3252
+ const version1 = object({
3253
+ major: constant(1),
3254
+ minor: number
3255
+ });
3256
+ const parseExpressionWidgetV1 = parseWidgetWithVersion(version1, constant("expression"), object({
3257
+ answerForms: pipeParsers(array(parsePossiblyInvalidAnswerForm)).then(convert(removeInvalidAnswerForms)).parser,
3258
+ functions: array(string),
3259
+ times: boolean,
3260
+ visibleLabel: optional(string),
3261
+ ariaLabel: optional(string),
3262
+ buttonSets: parseButtonSets,
3263
+ buttonsVisible: optional(enumeration("always", "never", "focused"))
3264
+ }));
3265
+ const version0 = optional(object({
3266
+ major: constant(0),
3267
+ minor: number
3268
+ }));
3269
+ const parseExpressionWidgetV0 = parseWidgetWithVersion(version0, constant("expression"), object({
3270
+ functions: array(string),
3271
+ times: boolean,
3272
+ visibleLabel: optional(string),
3273
+ ariaLabel: optional(string),
3274
+ form: boolean,
3275
+ simplify: boolean,
3276
+ value: string,
3277
+ buttonSets: parseButtonSets,
3278
+ buttonsVisible: optional(enumeration("always", "never", "focused"))
3279
+ }));
3280
+ function migrateV0ToV1(widget) {
3281
+ const {
3282
+ options
3283
+ } = widget;
3284
+ return {
3285
+ ...widget,
3286
+ version: {
3287
+ major: 1,
3288
+ minor: 0
3289
+ },
3290
+ options: {
3291
+ times: options.times,
3292
+ buttonSets: options.buttonSets,
3293
+ functions: options.functions,
3294
+ buttonsVisible: options.buttonsVisible,
3295
+ visibleLabel: options.visibleLabel,
3296
+ ariaLabel: options.ariaLabel,
3297
+ answerForms: [{
3298
+ considered: "correct",
3299
+ form: options.form,
3300
+ simplify: options.simplify,
3301
+ value: options.value
3302
+ }]
3303
+ }
3304
+ };
3305
+ }
3306
+ const parseExpressionWidget = versionedWidgetOptions(1, parseExpressionWidgetV1).withMigrationFrom(0, parseExpressionWidgetV0, migrateV0ToV1).parser;
3307
+
3308
+ const falseToNull = pipeParsers(constant(false)).then(convert(() => null)).parser;
3309
+ const parseGradedGroupWidgetOptions = object({
3310
+ title: defaulted(string, () => ""),
3311
+ hasHint: optional(nullable(boolean)),
3312
+ // This module has an import cycle with parsePerseusRenderer.
3313
+ // The anonymous function below ensures that we don't try to access
3314
+ // parsePerseusRenderer before it's defined.
3315
+ hint: union(falseToNull).or(constant(null)).or(constant(undefined)).or((rawVal, ctx) => parsePerseusRenderer(rawVal, ctx)).parser,
3316
+ content: string,
3317
+ // This module has an import cycle with parseWidgetsMap.
3318
+ // The anonymous function below ensures that we don't try to access
3319
+ // parseWidgetsMap before it's defined.
3320
+ widgets: (rawVal, ctx) => parseWidgetsMap(rawVal, ctx),
3321
+ widgetEnabled: optional(nullable(boolean)),
3322
+ immutableWidgets: optional(nullable(boolean)),
3323
+ images: record(string, object({
3324
+ width: number,
3325
+ height: number
3326
+ }))
3327
+ });
3328
+ const parseGradedGroupWidget = parseWidget(constant("graded-group"), parseGradedGroupWidgetOptions);
3329
+
3330
+ const parseGradedGroupSetWidget = parseWidget(constant("graded-group-set"), object({
3331
+ gradedGroups: array(parseGradedGroupWidgetOptions)
3332
+ }));
3333
+
3334
+ /**
3335
+ * discriminatedUnion() should be preferred over union() when parsing a
3336
+ * discriminated union type, because discriminatedUnion() produces more
3337
+ * understandable failure messages. It takes the discriminant as the source of
3338
+ * truth for which variant is to be parsed, and expects the other data to match
3339
+ * that variant.
3340
+ */
3341
+ function discriminatedUnionOn(discriminantKey) {
3342
+ const noMoreBranches = (raw, ctx) => {
3343
+ if (!isObject(raw)) {
3344
+ return ctx.failure("object", raw);
3345
+ }
3346
+ return ctx.forSubtree(discriminantKey).failure("a valid value", raw[discriminantKey]);
3347
+ };
3348
+ return new DiscriminatedUnionBuilder(discriminantKey, noMoreBranches);
3349
+ }
3350
+ class DiscriminatedUnionBuilder {
3351
+ constructor(discriminantKey, parser) {
3352
+ this.discriminantKey = discriminantKey;
3353
+ this.parser = parser;
3354
+ }
3355
+ withBranch(discriminantValue, parseNewVariant) {
3356
+ const parseNewBranch = discriminatedUnionBranch(this.discriminantKey, discriminantValue, parseNewVariant, this.parser);
3357
+ return new DiscriminatedUnionBuilder(this.discriminantKey, parseNewBranch);
3358
+ }
3359
+ }
3360
+ function discriminatedUnionBranch(discriminantKey, discriminantValue, parseVariant, parseOtherBranches) {
3361
+ return (raw, ctx) => {
3362
+ if (!isObject(raw)) {
3363
+ return ctx.failure("object", raw);
3364
+ }
3365
+ if (raw[discriminantKey] === discriminantValue) {
3366
+ return parseVariant(raw, ctx);
3367
+ }
3368
+ return parseOtherBranches(raw, ctx);
3369
+ };
3370
+ }
3371
+
3372
+ const pairOfNumbers$3 = pair(number, number);
3373
+ const pairOfPoints = pair(pairOfNumbers$3, pairOfNumbers$3);
3374
+ const parseGrapherWidget = parseWidget(constant("grapher"), object({
3375
+ availableTypes: array(enumeration("absolute_value", "exponential", "linear", "logarithm", "quadratic", "sinusoid", "tangent")),
3376
+ correct: discriminatedUnionOn("type").withBranch("absolute_value", object({
3377
+ type: constant("absolute_value"),
3378
+ coords: nullable(pairOfPoints)
3379
+ })).withBranch("exponential", object({
3380
+ type: constant("exponential"),
3381
+ asymptote: pairOfPoints,
3382
+ coords: nullable(pairOfPoints)
3383
+ })).withBranch("linear", object({
3384
+ type: constant("linear"),
3385
+ coords: nullable(pairOfPoints)
3386
+ })).withBranch("logarithm", object({
3387
+ type: constant("logarithm"),
3388
+ asymptote: pairOfPoints,
3389
+ coords: nullable(pairOfPoints)
3390
+ })).withBranch("quadratic", object({
3391
+ type: constant("quadratic"),
3392
+ coords: nullable(pairOfPoints)
3393
+ })).withBranch("sinusoid", object({
3394
+ type: constant("sinusoid"),
3395
+ coords: nullable(pairOfPoints)
3396
+ })).withBranch("tangent", object({
3397
+ type: constant("tangent"),
3398
+ coords: nullable(pairOfPoints)
3399
+ })).parser,
3400
+ graph: object({
3401
+ backgroundImage: object({
3402
+ bottom: optional(number),
3403
+ height: optional(number),
3404
+ left: optional(number),
3405
+ scale: optional(number),
3406
+ url: optional(nullable(string)),
3407
+ width: optional(number)
3408
+ }),
3409
+ box: optional(pairOfNumbers$3),
3410
+ editableSettings: optional(array(enumeration("graph", "snap", "image", "measure"))),
3411
+ gridStep: optional(pairOfNumbers$3),
3412
+ labels: pair(string, string),
3413
+ markings: enumeration("graph", "none", "grid"),
3414
+ range: pair(pairOfNumbers$3, pairOfNumbers$3),
3415
+ rulerLabel: constant(""),
3416
+ rulerTicks: number,
3417
+ showProtractor: optional(boolean),
3418
+ showRuler: optional(boolean),
3419
+ showTooltips: optional(boolean),
3420
+ snapStep: optional(pairOfNumbers$3),
3421
+ step: pairOfNumbers$3,
3422
+ valid: optional(union(boolean).or(string).parser)
3423
+ })
3424
+ }));
3425
+
3426
+ const parseGroupWidget = parseWidget(constant("group"),
3427
+ // This module has an import cycle with parsePerseusRenderer.
3428
+ // The anonymous function below ensures that we don't try to access
3429
+ // parsePerseusRenderer before it's defined.
3430
+ (rawVal, ctx) => parsePerseusRenderer(rawVal, ctx));
3431
+
3432
+ const parseIframeWidget = parseWidget(constant("iframe"), object({
3433
+ url: string,
3434
+ settings: optional(array(object({
3435
+ name: string,
3436
+ value: string
3437
+ }))),
3438
+ width: union(number).or(string).parser,
3439
+ height: union(number).or(string).parser,
3440
+ allowFullScreen: defaulted(boolean, () => false),
3441
+ allowTopNavigation: optional(boolean),
3442
+ static: defaulted(boolean, () => false)
3443
+ }));
3444
+
3445
+ const stringToNumber = (rawValue, ctx) => {
3446
+ if (typeof rawValue === "number") {
3447
+ return ctx.success(rawValue);
3448
+ }
3449
+ const parsedNumber = +rawValue;
3450
+ if (rawValue === "" || isNaN(parsedNumber)) {
3451
+ return ctx.failure("a number or numeric string", rawValue);
3452
+ }
3453
+ return ctx.success(parsedNumber);
3454
+ };
3455
+
3456
+ function emptyToZero(x) {
3457
+ return x === "" ? 0 : x;
3458
+ }
3459
+ const imageDimensionToNumber = pipeParsers(union(number).or(string).parser)
3460
+ // In this specific case, empty string is equivalent to zero. An empty
3461
+ // string parses to either NaN (using parseInt) or 0 (using unary +) and
3462
+ // CSS will treat NaN as invalid and default to 0 instead.
3463
+ .then(convert(emptyToZero)).then(stringToNumber).parser;
3464
+ const parsePerseusImageBackground = object({
3465
+ url: optional(nullable(string)),
3466
+ width: optional(imageDimensionToNumber),
3467
+ height: optional(imageDimensionToNumber),
3468
+ top: optional(imageDimensionToNumber),
3469
+ left: optional(imageDimensionToNumber),
3470
+ bottom: optional(imageDimensionToNumber),
3471
+ scale: optional(imageDimensionToNumber)
3472
+ });
3473
+
3474
+ const pairOfNumbers$2 = pair(number, number);
3475
+ const parseImageWidget = parseWidget(constant("image"), object({
3476
+ title: optional(string),
3477
+ caption: optional(string),
3478
+ alt: optional(string),
3479
+ backgroundImage: parsePerseusImageBackground,
3480
+ static: optional(boolean),
3481
+ labels: optional(array(object({
3482
+ content: string,
3483
+ alignment: string,
3484
+ coordinates: array(number)
3485
+ }))),
3486
+ range: optional(pair(pairOfNumbers$2, pairOfNumbers$2)),
3487
+ box: optional(pairOfNumbers$2)
3488
+ }));
3489
+
3490
+ const booleanToString = (rawValue, ctx) => {
3491
+ if (typeof rawValue === "boolean") {
3492
+ return ctx.success(String(rawValue));
3493
+ }
3494
+ return ctx.failure("boolean", rawValue);
3495
+ };
3496
+ const parseInputNumberWidget = parseWidget(constant("input-number"), object({
3497
+ answerType: optional(enumeration("number", "decimal", "integer", "rational", "improper", "mixed", "percent", "pi")),
3498
+ inexact: optional(boolean),
3499
+ maxError: optional(union(number).or(string).parser),
3500
+ rightAlign: optional(boolean),
3501
+ simplify: enumeration("required", "optional", "enforced"),
3502
+ size: enumeration("normal", "small"),
3503
+ // TODO(benchristel): there are some content items where value is a
3504
+ // boolean, even though that makes no sense. We should figure out if
3505
+ // those content items are actually published anywhere, and consider
3506
+ // updating them.
3507
+ value: union(number).or(string).or(booleanToString).parser,
3508
+ customKeypad: optional(boolean)
3509
+ }));
3510
+
3511
+ const pairOfNumbers$1 = pair(number, number);
3512
+ const stringOrEmpty = defaulted(string, () => "");
3513
+ const parseKey = pipeParsers(optional(string)).then(convert(String)).parser;
3514
+ const parseFunctionElement = object({
3515
+ type: constant("function"),
3516
+ key: parseKey,
3517
+ options: object({
3518
+ value: string,
3519
+ funcName: string,
3520
+ rangeMin: string,
3521
+ rangeMax: string,
3522
+ color: string,
3523
+ strokeDasharray: string,
3524
+ strokeWidth: number
3525
+ })
3526
+ });
3527
+ const parseLabelElement = object({
3528
+ type: constant("label"),
3529
+ key: parseKey,
3530
+ options: object({
3531
+ label: string,
3532
+ color: string,
3533
+ coordX: string,
3534
+ coordY: string
3535
+ })
3536
+ });
3537
+ const parseLineElement = object({
3538
+ type: constant("line"),
3539
+ key: parseKey,
3540
+ options: object({
3541
+ color: string,
3542
+ startX: string,
3543
+ startY: string,
3544
+ endX: string,
3545
+ endY: string,
3546
+ strokeDasharray: string,
3547
+ strokeWidth: number,
3548
+ arrows: string
3549
+ })
3550
+ });
3551
+ const parseMovableLineElement = object({
3552
+ type: constant("movable-line"),
3553
+ key: parseKey,
3554
+ options: object({
3555
+ startX: string,
3556
+ startY: string,
3557
+ startSubscript: number,
3558
+ endX: string,
3559
+ endY: string,
3560
+ endSubscript: number,
3561
+ constraint: string,
3562
+ snap: number,
3563
+ constraintFn: string,
3564
+ constraintXMin: string,
3565
+ constraintXMax: string,
3566
+ constraintYMin: string,
3567
+ constraintYMax: string
3568
+ })
3569
+ });
3570
+ const parseMovablePointElement = object({
3571
+ type: constant("movable-point"),
3572
+ key: parseKey,
3573
+ options: object({
3574
+ startX: string,
3575
+ startY: string,
3576
+ varSubscript: number,
3577
+ constraint: string,
3578
+ snap: number,
3579
+ constraintFn: string,
3580
+ constraintXMin: stringOrEmpty,
3581
+ constraintXMax: stringOrEmpty,
3582
+ constraintYMin: stringOrEmpty,
3583
+ constraintYMax: stringOrEmpty
3584
+ })
3585
+ });
3586
+ const parseParametricElement = object({
3587
+ type: constant("parametric"),
3588
+ key: parseKey,
3589
+ options: object({
3590
+ x: string,
3591
+ y: string,
3592
+ rangeMin: string,
3593
+ rangeMax: string,
3594
+ color: string,
3595
+ strokeDasharray: string,
3596
+ strokeWidth: number
3597
+ })
3598
+ });
3599
+ const parsePointElement = object({
3600
+ type: constant("point"),
3601
+ key: parseKey,
3602
+ options: object({
3603
+ color: string,
3604
+ coordX: string,
3605
+ coordY: string
3606
+ })
3607
+ });
3608
+ const parseRectangleElement = object({
3609
+ type: constant("rectangle"),
3610
+ key: parseKey,
3611
+ options: object({
3612
+ color: string,
3613
+ coordX: string,
3614
+ coordY: string,
3615
+ width: string,
3616
+ height: string
3617
+ })
3618
+ });
3619
+ const parseInteractionWidget = parseWidget(constant("interaction"), object({
3620
+ static: defaulted(boolean, () => false),
3621
+ graph: object({
3622
+ editableSettings: optional(array(enumeration("canvas", "graph"))),
3623
+ box: pairOfNumbers$1,
3624
+ labels: array(string),
3625
+ range: pair(pairOfNumbers$1, pairOfNumbers$1),
3626
+ gridStep: pairOfNumbers$1,
3627
+ markings: enumeration("graph", "grid", "none"),
3628
+ snapStep: optional(pairOfNumbers$1),
3629
+ valid: optional(union(boolean).or(string).parser),
3630
+ backgroundImage: optional(parsePerseusImageBackground),
3631
+ showProtractor: optional(boolean),
3632
+ showRuler: optional(boolean),
3633
+ rulerLabel: optional(string),
3634
+ rulerTicks: optional(number),
3635
+ tickStep: pairOfNumbers$1
3636
+ }),
3637
+ elements: array(discriminatedUnionOn("type").withBranch("function", parseFunctionElement).withBranch("label", parseLabelElement).withBranch("line", parseLineElement).withBranch("movable-line", parseMovableLineElement).withBranch("movable-point", parseMovablePointElement).withBranch("parametric", parseParametricElement).withBranch("point", parsePointElement).withBranch("rectangle", parseRectangleElement).parser)
3638
+ }));
3639
+
3640
+ /**
3641
+ * The Perseus "data schema" file.
3642
+ *
3643
+ * This file, and the types in it, represents the "data schema" that Perseus
3644
+ * uses. The @khanacademy/perseus-editor package edits and produces objects
3645
+ * that conform to the types in this file. Similarly, the top-level renderers
3646
+ * in @khanacademy/perseus, consume objects that conform to these types.
3647
+ *
3648
+ * WARNING: This file should not import any types from elsewhere so that it is
3649
+ * easy to reason about changes that alter the Perseus schema. This helps
3650
+ * ensure that it is not changed accidentally when upgrading a dependant
3651
+ * package or other part of Perseus code. Note that TypeScript does type
3652
+ * checking via something called "structural typing". This means that as long
3653
+ * as the shape of a type matches, the name it goes by doesn't matter. As a
3654
+ * result, a `Coord` type that looks like this `[x: number, y: number]` is
3655
+ * _identical_, in TypeScript's eyes, to this `Vector2` type `[x: number, y:
3656
+ * number]`. Also, with tuples, the labels for each entry is ignored, so `[x:
3657
+ * number, y: number]` is compatible with `[min: number, max: number]`. The
3658
+ * labels are for humans, not TypeScript. :)
3659
+ *
3660
+ * If you make changes to types in this file, be very sure that:
3661
+ *
3662
+ * a) the changes are backwards compatible. If they are not, old data from
3663
+ * previous versions of the "schema" could become unrenderable, or worse,
3664
+ * introduce hard-to-diagnose bugs.
3665
+ * b) the parsing code (`util/parse-perseus-json/`) is updated to handle
3666
+ * the new format _as well as_ the old format.
3667
+ */
3668
+
3669
+ // TODO(FEI-4010): Remove `Perseus` prefix for all types here
3670
+
3671
+ // Same name as Mafs
3672
+
3673
+ /**
3674
+ * A utility type that constructs a widget map from a "registry interface".
3675
+ * The keys of the registry should be the widget type (aka, "categorizer" or
3676
+ * "radio", etc) and the value should be the option type stored in the value
3677
+ * of the map.
3678
+ *
3679
+ * You can think of this as a type that generates another type. We use
3680
+ * "registry interfaces" as a way to keep a set of widget types to their data
3681
+ * type in several places in Perseus. This type then allows us to generate a
3682
+ * map type that maps a widget id to its data type and keep strong typing by
3683
+ * widget id.
3684
+ *
3685
+ * For example, given a fictitious registry such as this:
3686
+ *
3687
+ * ```
3688
+ * interface DummyRegistry {
3689
+ * categorizer: { categories: ReadonlyArray<string> };
3690
+ * dropdown: { choices: ReadonlyArray<string> }:
3691
+ * }
3692
+ * ```
3693
+ *
3694
+ * If we create a DummyMap using this helper:
3695
+ *
3696
+ * ```
3697
+ * type DummyMap = MakeWidgetMap<DummyRegistry>;
3698
+ * ```
3699
+ *
3700
+ * We'll get a map that looks like this:
3701
+ *
3702
+ * ```
3703
+ * type DummyMap = {
3704
+ * `categorizer ${number}`: { categories: ReadonlyArray<string> };
3705
+ * `dropdown ${number}`: { choices: ReadonlyArray<string> };
3706
+ * }
3707
+ * ```
3708
+ *
3709
+ * We use interfaces for the registries so that they can be extended in cases
3710
+ * where the consuming app brings along their own widgets. Interfaces in
3711
+ * TypeScript are always open (ie. you can extend them) whereas types aren't.
3712
+ */
3713
+
3714
+ /**
3715
+ * Our core set of Perseus widgets.
3716
+ *
3717
+ * This interface is the basis for "registering" all Perseus widget types.
3718
+ * There should be one key/value pair for each supported widget. If you create
3719
+ * a new widget, an entry should be added to this interface. Note that this
3720
+ * only registers the widget options type, you'll also need to register the
3721
+ * widget so that it's available at runtime (@see
3722
+ * {@link file://./widgets.ts#registerWidget}).
3723
+ *
3724
+ * Importantly, the key should be the name that is used in widget IDs. For most
3725
+ * widgets that is the same as the widget option's `type` field. In cases where
3726
+ * a widget has been deprecated and replaced with the deprecated-standin
3727
+ * widget, it should be the original widget type!
3728
+ *
3729
+ * If you define the widget outside of this package, you can still add the new
3730
+ * widget to this interface by writing the following in that package that
3731
+ * contains the widget. TypeScript will merge that definition of the
3732
+ * `PerseusWidgets` with the one defined below.
3733
+ *
3734
+ * ```typescript
3735
+ * declare module "@khanacademy/perseus-core" {
3736
+ * interface PerseusWidgetTypes {
3737
+ * // A new widget
3738
+ * "new-awesomeness": MyAwesomeNewWidget;
3739
+ *
3740
+ * // A deprecated widget
3741
+ * "super-old-widget": DeprecatedStandinWidget;
3742
+ * }
3743
+ * }
3744
+ *
3745
+ * // The new widget's options definition
3746
+ * type MyAwesomeNewWidget = WidgetOptions<'new-awesomeness', MyAwesomeNewWidgetOptions>;
3747
+ *
3748
+ * // The deprecated widget's options definition
3749
+ * type SuperOldWidget = WidgetOptions<'super-old-widget', object>;
3750
+ * ```
3751
+ *
3752
+ * This interface can be extended through the magic of TypeScript "Declaration
3753
+ * merging". Specifically, we augment this module and extend this interface.
3754
+ *
3755
+ * @see {@link https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation}
3756
+ */
3757
+
3758
+ /**
3759
+ * A map of widget IDs to widget options. This is most often used as the type
3760
+ * for a set of widgets defined in a `PerseusItem` but can also be useful to
3761
+ * represent a function parameter where only `widgets` from a `PerseusItem` are
3762
+ * needed. Today Widget IDs are made up of the widget type and an incrementing
3763
+ * integer (eg. `interactive-graph 1` or `radio 3`). It is suggested to avoid
3764
+ * reading/parsing the widget id to derive any information from it, except in
3765
+ * the case of this map.
3766
+ *
3767
+ * @see {@link PerseusWidgetTypes} additional widgets can be added to this map type
3768
+ * by augmenting the PerseusWidgetTypes with new widget types!
3769
+ */
3770
+
3771
+ /**
3772
+ * PerseusWidget is a union of all the different types of widget options that
3773
+ * Perseus knows about.
3774
+ *
3775
+ * Thanks to it being based on PerseusWidgetTypes interface, this union is
3776
+ * automatically extended to include widgets used in tests without those widget
3777
+ * option types seeping into our production types.
3778
+ *
3779
+ * @see MockWidget for an example
3780
+ */
3781
+
3782
+ /**
3783
+ * A "PerseusItem" is a classic Perseus item. It is rendered by the
3784
+ * `ServerItemRenderer` and the layout is pre-set.
3785
+ *
3786
+ * To render more complex Perseus items, see the `Item` type in the multi item
3787
+ * area.
3788
+ */
3789
+
3790
+ /**
3791
+ * A "PerseusArticle" is an item that is meant to be rendered as an article.
3792
+ * This item is never scored and is rendered by the `ArticleRenderer`.
3793
+ */
3794
+
3795
+ const ItemExtras = [
3796
+ // The user might benefit from using a Scientific Calculator. Provided on Khan Academy when true
3797
+ "calculator",
3798
+ // The user might benefit from using a statistics Chi Squared Table like https://people.richland.edu/james/lecture/m170/tbl-chi.html
3799
+ "chi2Table",
3800
+ // The user might benefit from a monthly payments calculator. Provided on Khan Academy when true
3801
+ "financialCalculatorMonthlyPayment",
3802
+ // The user might benefit from a total amount calculator. Provided on Khan Academy when true
3803
+ "financialCalculatorTotalAmount",
3804
+ // The user might benefit from a time to pay off calculator. Provided on Khan Academy when true
3805
+ "financialCalculatorTimeToPayOff",
3806
+ // The user might benefit from using a Periodic Table of Elements. Provided on Khan Academy when true
3807
+ "periodicTable",
3808
+ // The user might benefit from using a Periodic Table of Elements with key. Provided on Khan Academy when true
3809
+ "periodicTableWithKey",
3810
+ // The user might benefit from using a statistics T Table like https://www.statisticshowto.com/tables/t-distribution-table/
3811
+ "tTable",
3812
+ // The user might benefit from using a statistics Z Table like https://www.ztable.net/
3813
+ "zTable"];
3814
+
3815
+ /**
3816
+ * The type representing the common structure of all widget's options. The
3817
+ * `Options` generic type represents the widget-specific option data.
3818
+ */
3819
+
3820
+ // prettier-ignore
3821
+
3822
+ // prettier-ignore
3823
+
3824
+ // prettier-ignore
3825
+
3826
+ // prettier-ignore
3827
+
3828
+ // prettier-ignore
3829
+
3830
+ // prettier-ignore
3831
+
3832
+ // prettier-ignore
3833
+
3834
+ // prettier-ignore
3835
+
3836
+ // prettier-ignore
3837
+
3838
+ // prettier-ignore
3839
+
3840
+ // prettier-ignore
3841
+
3842
+ // prettier-ignore
3843
+
3844
+ // prettier-ignore
3845
+
3846
+ // prettier-ignore
3847
+
3848
+ // prettier-ignore
3849
+
3850
+ // prettier-ignore
3851
+
3852
+ // prettier-ignore
3853
+
3854
+ // prettier-ignore
3855
+
3856
+ // prettier-ignore
3857
+
3858
+ // prettier-ignore
3859
+
3860
+ // prettier-ignore
3861
+
3862
+ // prettier-ignore
3863
+
3864
+ // prettier-ignore
3865
+
3866
+ // prettier-ignore
3867
+
3868
+ // prettier-ignore
3869
+
3870
+ // prettier-ignore
3871
+
3872
+ // prettier-ignore
3873
+
3874
+ // prettier-ignore
3875
+
3876
+ // prettier-ignore
3877
+
3878
+ // prettier-ignore
3879
+
3880
+ // prettier-ignore
3881
+
3882
+ // prettier-ignore
3883
+
3884
+ // prettier-ignore
3885
+
3886
+ //prettier-ignore
3887
+
3888
+ /**
3889
+ * A background image applied to various widgets.
3890
+ */
3891
+
3892
+ /**
3893
+ * The type of markings to display on the graph.
3894
+ * - axes: shows the axes without the gride lines
3895
+ * - graph: shows the axes and the grid lines
3896
+ * - grid: shows only the grid lines
3897
+ * - none: shows no markings
3898
+ */
3899
+
3900
+ const PerseusExpressionAnswerFormConsidered = ["correct", "wrong", "ungraded"];
3901
+
3902
+ // 2D range: xMin, xMax, yMin, yMax
3903
+
3904
+ const lockedFigureColorNames = ["blue", "green", "grayH", "purple", "pink", "orange", "red"];
3905
+ const lockedFigureColors = {
3906
+ blue: "#3D7586",
3907
+ green: "#447A53",
3908
+ grayH: "#3B3D45",
3909
+ purple: "#594094",
3910
+ pink: "#B25071",
3911
+ red: "#D92916",
3912
+ orange: "#946700"
3913
+ };
3914
+ const lockedFigureFillStyles = {
3915
+ none: 0,
3916
+ white: 1,
3917
+ translucent: 0.4,
3918
+ solid: 1
3919
+ };
3920
+
3921
+ // Not associated with a specific figure
3922
+
3923
+ const plotterPlotTypes = ["bar", "line", "pic", "histogram", "dotplot"];
3924
+
3925
+ // Used to represent 2-D points and ranges
3926
+ const pairOfNumbers = pair(number, number);
3927
+ const parsePerseusGraphTypeAngle = object({
3928
+ type: constant("angle"),
3929
+ showAngles: optional(boolean),
3930
+ allowReflexAngles: optional(boolean),
3931
+ angleOffsetDeg: optional(number),
3932
+ snapDegrees: optional(number),
3933
+ match: optional(constant("congruent")),
3934
+ coords: optional(trio(pairOfNumbers, pairOfNumbers, pairOfNumbers)),
3935
+ startCoords: optional(trio(pairOfNumbers, pairOfNumbers, pairOfNumbers))
3936
+ });
3937
+ const parsePerseusGraphTypeCircle = object({
3938
+ type: constant("circle"),
3939
+ center: optional(pairOfNumbers),
3940
+ radius: optional(number),
3941
+ startCoords: optional(object({
3942
+ center: pairOfNumbers,
3943
+ radius: number
3944
+ })),
3945
+ // TODO: remove coord? it's legacy.
3946
+ coord: optional(pairOfNumbers)
3947
+ });
3948
+ const parsePerseusGraphTypeLinear = object({
3949
+ type: constant("linear"),
3950
+ coords: optional(nullable(pair(pairOfNumbers, pairOfNumbers))),
3951
+ startCoords: optional(pair(pairOfNumbers, pairOfNumbers)),
3952
+ // TODO: remove coord? it's legacy.
3953
+ coord: optional(pairOfNumbers)
3954
+ });
3955
+ const parsePerseusGraphTypeLinearSystem = object({
3956
+ type: constant("linear-system"),
3957
+ // TODO(benchristel): default coords to empty array?
3958
+ coords: optional(nullable(array(pair(pairOfNumbers, pairOfNumbers)))),
3959
+ startCoords: optional(array(pair(pairOfNumbers, pairOfNumbers))),
3960
+ // TODO: remove coord? it's legacy.
3961
+ coord: optional(pairOfNumbers)
3962
+ });
3963
+ const parsePerseusGraphTypeNone = object({
3964
+ type: constant("none")
3965
+ });
3966
+ const parsePerseusGraphTypePoint = object({
3967
+ type: constant("point"),
3968
+ numPoints: optional(union(number).or(constant("unlimited")).parser),
3969
+ coords: optional(nullable(array(pairOfNumbers))),
3970
+ startCoords: optional(array(pairOfNumbers)),
3971
+ // TODO: remove coord? it's legacy.
3972
+ coord: optional(pairOfNumbers)
3973
+ });
3974
+ const parsePerseusGraphTypePolygon = object({
3975
+ type: constant("polygon"),
3976
+ numSides: optional(union(number).or(constant("unlimited")).parser),
3977
+ showAngles: optional(boolean),
3978
+ showSides: optional(boolean),
3979
+ snapTo: optional(enumeration("grid", "angles", "sides")),
3980
+ match: optional(enumeration("similar", "congruent", "approx", "exact")),
3981
+ startCoords: optional(array(pairOfNumbers)),
3982
+ // TODO: remove coord? it's legacy.
3983
+ coord: optional(pairOfNumbers)
3984
+ });
3985
+ const parsePerseusGraphTypeQuadratic = object({
3986
+ type: constant("quadratic"),
3987
+ coords: optional(nullable(trio(pairOfNumbers, pairOfNumbers, pairOfNumbers))),
3988
+ startCoords: optional(trio(pairOfNumbers, pairOfNumbers, pairOfNumbers)),
3989
+ // TODO: remove coord? it's legacy.
3990
+ coord: optional(pairOfNumbers)
3991
+ });
3992
+ const parsePerseusGraphTypeRay = object({
3993
+ type: constant("ray"),
3994
+ coords: optional(nullable(pair(pairOfNumbers, pairOfNumbers))),
3995
+ startCoords: optional(pair(pairOfNumbers, pairOfNumbers)),
3996
+ // TODO: remove coord? it's legacy.
3997
+ coord: optional(pairOfNumbers)
3998
+ });
3999
+ const parsePerseusGraphTypeSegment = object({
4000
+ type: constant("segment"),
4001
+ // TODO(benchristel): default numSegments?
4002
+ numSegments: optional(number),
4003
+ coords: optional(nullable(array(pair(pairOfNumbers, pairOfNumbers)))),
4004
+ startCoords: optional(array(pair(pairOfNumbers, pairOfNumbers))),
4005
+ // TODO: remove coord? it's legacy.
4006
+ coord: optional(pairOfNumbers)
4007
+ });
4008
+ const parsePerseusGraphTypeSinusoid = object({
4009
+ type: constant("sinusoid"),
4010
+ coords: optional(nullable(array(pairOfNumbers))),
4011
+ startCoords: optional(array(pairOfNumbers)),
4012
+ // TODO: remove coord? it's legacy.
4013
+ coord: optional(pairOfNumbers)
4014
+ });
4015
+ const parsePerseusGraphType = discriminatedUnionOn("type").withBranch("angle", parsePerseusGraphTypeAngle).withBranch("circle", parsePerseusGraphTypeCircle).withBranch("linear", parsePerseusGraphTypeLinear).withBranch("linear-system", parsePerseusGraphTypeLinearSystem).withBranch("none", parsePerseusGraphTypeNone).withBranch("point", parsePerseusGraphTypePoint).withBranch("polygon", parsePerseusGraphTypePolygon).withBranch("quadratic", parsePerseusGraphTypeQuadratic).withBranch("ray", parsePerseusGraphTypeRay).withBranch("segment", parsePerseusGraphTypeSegment).withBranch("sinusoid", parsePerseusGraphTypeSinusoid).parser;
4016
+ const parseLockedFigureColor = enumeration(...lockedFigureColorNames);
4017
+ const parseLockedFigureFillType = enumeration("none", "white", "translucent", "solid");
4018
+ const parseLockedLineStyle = enumeration("solid", "dashed");
4019
+ const parseLockedLabelType = object({
4020
+ type: constant("label"),
4021
+ coord: pairOfNumbers,
4022
+ text: string,
4023
+ color: parseLockedFigureColor,
4024
+ size: enumeration("small", "medium", "large")
4025
+ });
4026
+ const parseLockedPointType = object({
4027
+ type: constant("point"),
4028
+ coord: pairOfNumbers,
4029
+ color: parseLockedFigureColor,
4030
+ filled: boolean,
4031
+ // TODO(benchristel): default labels to empty array?
4032
+ labels: optional(array(parseLockedLabelType)),
4033
+ ariaLabel: optional(string)
4034
+ });
4035
+ const parseLockedLineType = object({
4036
+ type: constant("line"),
4037
+ kind: enumeration("line", "ray", "segment"),
4038
+ points: pair(parseLockedPointType, parseLockedPointType),
4039
+ color: parseLockedFigureColor,
4040
+ lineStyle: parseLockedLineStyle,
4041
+ showPoint1: defaulted(boolean, () => false),
4042
+ showPoint2: defaulted(boolean, () => false),
4043
+ // TODO(benchristel): default labels to empty array?
4044
+ labels: optional(array(parseLockedLabelType)),
4045
+ ariaLabel: optional(string)
4046
+ });
4047
+ const parseLockedVectorType = object({
4048
+ type: constant("vector"),
4049
+ points: pair(pairOfNumbers, pairOfNumbers),
4050
+ color: parseLockedFigureColor,
4051
+ // TODO(benchristel): default labels to empty array?
4052
+ labels: optional(array(parseLockedLabelType)),
4053
+ ariaLabel: optional(string)
4054
+ });
4055
+ const parseLockedEllipseType = object({
4056
+ type: constant("ellipse"),
4057
+ center: pairOfNumbers,
4058
+ radius: pairOfNumbers,
4059
+ angle: number,
4060
+ color: parseLockedFigureColor,
4061
+ fillStyle: parseLockedFigureFillType,
4062
+ strokeStyle: parseLockedLineStyle,
4063
+ // TODO(benchristel): default labels to empty array?
4064
+ labels: optional(array(parseLockedLabelType)),
4065
+ ariaLabel: optional(string)
4066
+ });
4067
+ const parseLockedPolygonType = object({
4068
+ type: constant("polygon"),
4069
+ points: array(pairOfNumbers),
4070
+ color: parseLockedFigureColor,
4071
+ showVertices: boolean,
4072
+ fillStyle: parseLockedFigureFillType,
4073
+ strokeStyle: parseLockedLineStyle,
4074
+ // TODO(benchristel): default labels to empty array?
4075
+ labels: optional(array(parseLockedLabelType)),
4076
+ ariaLabel: optional(string)
4077
+ });
4078
+ const parseLockedFunctionType = object({
4079
+ type: constant("function"),
4080
+ color: parseLockedFigureColor,
4081
+ strokeStyle: parseLockedLineStyle,
4082
+ equation: string,
4083
+ directionalAxis: enumeration("x", "y"),
4084
+ domain: optional(pairOfNumbers),
4085
+ // TODO(benchristel): default labels to empty array?
4086
+ labels: optional(array(parseLockedLabelType)),
4087
+ ariaLabel: optional(string)
4088
+ });
4089
+ const parseLockedFigure = discriminatedUnionOn("type").withBranch("point", parseLockedPointType).withBranch("line", parseLockedLineType).withBranch("vector", parseLockedVectorType).withBranch("ellipse", parseLockedEllipseType).withBranch("polygon", parseLockedPolygonType).withBranch("function", parseLockedFunctionType).withBranch("label", parseLockedLabelType).parser;
4090
+ const parseInteractiveGraphWidget = parseWidget(constant("interactive-graph"), object({
4091
+ step: pairOfNumbers,
4092
+ // TODO(benchristel): rather than making gridStep and snapStep
4093
+ // optional, we should duplicate the defaulting logic from the
4094
+ // InteractiveGraph component. See parse-perseus-json/README.md for
4095
+ // why.
4096
+ gridStep: optional(pairOfNumbers),
4097
+ snapStep: optional(pairOfNumbers),
4098
+ backgroundImage: optional(parsePerseusImageBackground),
4099
+ markings: enumeration("graph", "grid", "none"),
4100
+ labels: optional(array(string)),
4101
+ showProtractor: boolean,
4102
+ showRuler: optional(boolean),
4103
+ showTooltips: optional(boolean),
4104
+ rulerLabel: optional(string),
4105
+ rulerTicks: optional(number),
4106
+ range: pair(pairOfNumbers, pairOfNumbers),
4107
+ // NOTE(benchristel): I copied the default graph from
4108
+ // interactive-graph.tsx. See the parse-perseus-json/README.md for
4109
+ // an explanation of why we want to duplicate the default here.
4110
+ graph: defaulted(parsePerseusGraphType, () => ({
4111
+ type: "linear"
4112
+ })),
4113
+ correct: parsePerseusGraphType,
4114
+ // TODO(benchristel): default lockedFigures to empty array
4115
+ lockedFigures: optional(array(parseLockedFigure)),
4116
+ fullGraphLabel: optional(string),
4117
+ fullGraphAriaDescription: optional(string)
4118
+ }));
4119
+
4120
+ const parseLabelImageWidget = parseWidget(constant("label-image"), object({
4121
+ choices: array(string),
4122
+ imageUrl: string,
4123
+ imageAlt: string,
4124
+ imageHeight: number,
4125
+ imageWidth: number,
4126
+ markers: array(object({
4127
+ answers: array(string),
4128
+ label: string,
4129
+ x: number,
4130
+ y: number
4131
+ })),
4132
+ hideChoicesFromInstructions: boolean,
4133
+ multipleAnswers: boolean,
4134
+ static: defaulted(boolean, () => false)
4135
+ }));
4136
+
4137
+ const parseMatcherWidget = parseWidget(constant("matcher"), object({
4138
+ labels: array(string),
4139
+ left: array(string),
4140
+ right: array(string),
4141
+ orderMatters: boolean,
4142
+ padding: boolean
4143
+ }));
4144
+
4145
+ const numberOrString = union(number).or(string).parser;
4146
+ const numeric = pipeParsers(defaulted(numberOrString, () => NaN)).then(stringToNumber).parser;
4147
+ const parseMatrixWidget = parseWidget(defaulted(constant("matrix"), () => "matrix"), object({
4148
+ prefix: optional(string),
4149
+ suffix: optional(string),
4150
+ answers: array(array(numeric)),
4151
+ cursorPosition: optional(array(number)),
4152
+ matrixBoardSize: array(number),
4153
+ static: optional(boolean)
4154
+ }));
4155
+
4156
+ const parseMeasurerWidget = parseWidget(constant("measurer"), object({
4157
+ // The default value for image comes from measurer.tsx.
4158
+ // See parse-perseus-json/README.md for why we want to duplicate the
4159
+ // defaults here.
4160
+ image: defaulted(parsePerseusImageBackground, () => ({
4161
+ url: null,
4162
+ top: 0,
4163
+ left: 0
4164
+ })),
4165
+ showProtractor: boolean,
4166
+ showRuler: boolean,
4167
+ rulerLabel: string,
4168
+ rulerTicks: number,
4169
+ rulerPixels: number,
4170
+ rulerLength: number,
4171
+ box: pair(number, number),
4172
+ // TODO(benchristel): static is not used. Remove it?
4173
+ static: defaulted(boolean, () => false)
4174
+ }));
4175
+
4176
+ const parseMoleculeRendererWidget = parseWidget(constant("molecule-renderer"), object({
4177
+ widgetId: string,
4178
+ rotationAngle: optional(number),
4179
+ smiles: optional(string)
4180
+ }));
4181
+
4182
+ const emptyStringToNull = pipeParsers(constant("")).then(convert(() => null)).parser;
4183
+ const parseNumberLineWidget = parseWidget(constant("number-line"), object({
4184
+ range: array(number),
4185
+ labelRange: array(nullable(union(number).or(emptyStringToNull).parser)),
4186
+ labelStyle: string,
4187
+ labelTicks: boolean,
4188
+ isTickCtrl: optional(nullable(boolean)),
4189
+ divisionRange: array(number),
4190
+ numDivisions: optional(nullable(number)),
4191
+ // NOTE(benchristel): I copied the default snapDivisions from
4192
+ // number-line.tsx. See the parse-perseus-json/README.md for
4193
+ // an explanation of why we want to duplicate the default here.
4194
+ snapDivisions: defaulted(number, () => 2),
4195
+ tickStep: optional(nullable(number)),
4196
+ correctRel: optional(nullable(string)),
4197
+ correctX: nullable(number),
4198
+ initialX: optional(nullable(number)),
4199
+ showTooltips: optional(boolean),
4200
+ static: defaulted(boolean, () => false)
4201
+ }));
4202
+
4203
+ const parseMathFormat = enumeration("integer", "mixed", "improper", "proper", "decimal", "percent", "pi");
4204
+ const parseNumericInputWidget = parseWidget(constant("numeric-input"), object({
4205
+ answers: array(object({
4206
+ message: string,
4207
+ // TODO(benchristel): value should never be null or undefined,
4208
+ // but we have some content where it is anyway. If we backfill
4209
+ // the data, simplify this.
4210
+ value: optional(nullable(number)),
4211
+ status: string,
4212
+ answerForms: optional(array(parseMathFormat)),
4213
+ strict: boolean,
4214
+ maxError: optional(nullable(number)),
4215
+ // TODO(benchristel): simplify should never be a boolean, but we
4216
+ // have some content where it is anyway. If we ever backfill
4217
+ // the data, we should simplify `simplify`.
4218
+ simplify: optional(nullable(union(string).or(pipeParsers(boolean).then(convert(String)).parser).parser))
4219
+ })),
4220
+ labelText: optional(string),
4221
+ size: string,
4222
+ coefficient: defaulted(boolean, () => false),
4223
+ rightAlign: optional(boolean),
4224
+ static: defaulted(boolean, () => false),
4225
+ answerForms: optional(array(object({
4226
+ name: parseMathFormat,
4227
+ simplify: optional(nullable(enumeration("required", "correct", "enforced", "optional")))
4228
+ })))
4229
+ }));
4230
+
4231
+ // There is an import cycle between orderer-widget.ts and perseus-renderer.ts.
4232
+ // This wrapper ensures that we don't refer to parsePerseusRenderer before
4233
+ // it's defined.
4234
+ function parseRenderer(rawValue, ctx) {
4235
+ return parsePerseusRenderer(rawValue, ctx);
4236
+ }
4237
+ const largeToAuto = (height, ctx) => {
4238
+ if (height === "large") {
4239
+ return ctx.success("auto");
4240
+ }
4241
+ return ctx.success(height);
4242
+ };
4243
+ const parseOrdererWidget = parseWidget(constant("orderer"), object({
4244
+ options: defaulted(array(parseRenderer), () => []),
4245
+ correctOptions: array(parseRenderer),
4246
+ otherOptions: array(parseRenderer),
4247
+ height: pipeParsers(enumeration("normal", "auto", "large")).then(largeToAuto).parser,
4248
+ layout: defaulted(enumeration("horizontal", "vertical"), () => "horizontal")
4249
+ }));
4250
+
4251
+ const parsePassageRefWidget = parseWidget(constant("passage-ref"), object({
4252
+ passageNumber: number,
4253
+ referenceNumber: number,
4254
+ summaryText: optional(string)
4255
+ }));
4256
+
4257
+ const parsePassageWidget = parseWidget(constant("passage"), object({
4258
+ footnotes: defaulted(string, () => ""),
4259
+ passageText: string,
4260
+ passageTitle: defaulted(string, () => ""),
4261
+ showLineNumbers: boolean,
4262
+ static: defaulted(boolean, () => false)
4263
+ }));
4264
+
4265
+ const parsePhetSimulationWidget = parseWidget(constant("phet-simulation"), object({
4266
+ url: string,
4267
+ description: string
4268
+ }));
4269
+
4270
+ const parsePlotterWidget = parseWidget(constant("plotter"), object({
4271
+ labels: array(string),
4272
+ categories: array(string),
4273
+ type: enumeration(...plotterPlotTypes),
4274
+ maxY: number,
4275
+ // The default value for scaleY comes from plotter.tsx.
4276
+ // See parse-perseus-json/README.md for why we want to duplicate the
4277
+ // defaults here.
4278
+ scaleY: defaulted(number, () => 1),
4279
+ labelInterval: optional(nullable(number)),
4280
+ // The default value for snapsPerLine comes from plotter.tsx.
4281
+ // See parse-perseus-json/README.md for why we want to duplicate the
4282
+ // defaults here.
4283
+ snapsPerLine: defaulted(number, () => 2),
4284
+ starting: array(number),
4285
+ correct: array(number),
4286
+ picUrl: optional(nullable(string)),
4287
+ picSize: optional(nullable(number)),
4288
+ picBoxHeight: optional(nullable(number)),
4289
+ // NOTE(benchristel): I copied the default plotDimensions from
4290
+ // plotter.tsx. See the parse-perseus-json/README.md for an explanation
4291
+ // of why we want to duplicate the defaults here.
4292
+ plotDimensions: defaulted(array(number), () => [380, 300])
4293
+ }));
4294
+
4295
+ const parsePythonProgramWidget = parseWidget(constant("python-program"), object({
4296
+ programID: string,
4297
+ height: number
4298
+ }));
4299
+
4300
+ const parseRadioWidget = parseWidget(constant("radio"), object({
4301
+ choices: array(object({
4302
+ content: defaulted(string, () => ""),
4303
+ clue: optional(string),
4304
+ correct: optional(boolean),
4305
+ isNoneOfTheAbove: optional(boolean),
4306
+ // deprecated
4307
+ // There is an import cycle between radio-widget.ts and
4308
+ // widgets-map.ts. The anonymous function below ensures that we
4309
+ // don't refer to parseWidgetsMap before it's defined.
4310
+ widgets: optional((rawVal, ctx) => parseWidgetsMap(rawVal, ctx))
4311
+ })),
4312
+ hasNoneOfTheAbove: optional(boolean),
4313
+ countChoices: optional(boolean),
4314
+ randomize: optional(boolean),
4315
+ multipleSelect: optional(boolean),
4316
+ deselectEnabled: optional(boolean),
4317
+ // deprecated
4318
+ onePerLine: optional(boolean),
4319
+ // deprecated
4320
+ displayCount: optional(any),
4321
+ // v0 props
4322
+ // `noneOfTheAbove` is still in use (but only set to `false`).
4323
+ noneOfTheAbove: optional(constant(false))
4324
+ }));
4325
+
4326
+ const parseSorterWidget = parseWidget(constant("sorter"), object({
4327
+ correct: array(string),
4328
+ padding: boolean,
4329
+ layout: enumeration("horizontal", "vertical")
4330
+ }));
4331
+
4332
+ const parseTableWidget = parseWidget(constant("table"), object({
4333
+ headers: array(string),
4334
+ rows: number,
4335
+ columns: number,
4336
+ answers: array(array(string))
4337
+ }));
4338
+
4339
+ const parseVideoWidget = parseWidget(constant("video"), object({
4340
+ location: string,
4341
+ static: optional(boolean)
4342
+ }));
4343
+
4344
+ const parseWidgetsMap = (rawValue, ctx) => {
4345
+ if (!isObject(rawValue)) {
4346
+ return ctx.failure("PerseusWidgetsMap", rawValue);
4347
+ }
4348
+ const widgetsMap = {};
4349
+ for (const key of Object.keys(rawValue)) {
4350
+ // parseWidgetsMapEntry modifies the widgetsMap. This is kind of gross,
4351
+ // but it's the only way I could find to make TypeScript check the key
4352
+ // against the widget type.
4353
+ const entryResult = parseWidgetsMapEntry([key, rawValue[key]], widgetsMap, ctx.forSubtree(key));
4354
+ if (isFailure(entryResult)) {
4355
+ return entryResult;
4356
+ }
4357
+ }
4358
+ return ctx.success(widgetsMap);
4359
+ };
4360
+ const parseWidgetsMapEntry = (_ref, widgetMap, ctx) => {
4361
+ let [id, widget] = _ref;
4362
+ const idComponentsResult = parseWidgetIdComponents(id.split(" "), ctx.forSubtree("(widget ID)"));
4363
+ if (isFailure(idComponentsResult)) {
4364
+ return idComponentsResult;
4365
+ }
4366
+ const [type, n] = idComponentsResult.value;
4367
+ function parseAndAssign(key, parse) {
4368
+ const widgetResult = parse(widget, ctx);
4369
+ if (isFailure(widgetResult)) {
4370
+ return widgetResult;
4371
+ }
4372
+ widgetMap[key] = widgetResult.value;
4373
+ return ctx.success(undefined);
4374
+ }
4375
+ switch (type) {
4376
+ case "categorizer":
4377
+ return parseAndAssign(`categorizer ${n}`, parseCategorizerWidget);
4378
+ case "cs-program":
4379
+ return parseAndAssign(`cs-program ${n}`, parseCSProgramWidget);
4380
+ case "definition":
4381
+ return parseAndAssign(`definition ${n}`, parseDefinitionWidget);
4382
+ case "dropdown":
4383
+ return parseAndAssign(`dropdown ${n}`, parseDropdownWidget);
4384
+ case "explanation":
4385
+ return parseAndAssign(`explanation ${n}`, parseExplanationWidget);
4386
+ case "expression":
4387
+ return parseAndAssign(`expression ${n}`, parseExpressionWidget);
4388
+ case "grapher":
4389
+ return parseAndAssign(`grapher ${n}`, parseGrapherWidget);
4390
+ case "group":
4391
+ return parseAndAssign(`group ${n}`, parseGroupWidget);
4392
+ case "graded-group":
4393
+ return parseAndAssign(`graded-group ${n}`, parseGradedGroupWidget);
4394
+ case "graded-group-set":
4395
+ return parseAndAssign(`graded-group-set ${n}`, parseGradedGroupSetWidget);
4396
+ case "iframe":
4397
+ return parseAndAssign(`iframe ${n}`, parseIframeWidget);
4398
+ case "image":
4399
+ return parseAndAssign(`image ${n}`, parseImageWidget);
4400
+ case "input-number":
4401
+ return parseAndAssign(`input-number ${n}`, parseInputNumberWidget);
4402
+ case "interaction":
4403
+ return parseAndAssign(`interaction ${n}`, parseInteractionWidget);
4404
+ case "interactive-graph":
4405
+ return parseAndAssign(`interactive-graph ${n}`, parseInteractiveGraphWidget);
4406
+ case "label-image":
4407
+ return parseAndAssign(`label-image ${n}`, parseLabelImageWidget);
4408
+ case "matcher":
4409
+ return parseAndAssign(`matcher ${n}`, parseMatcherWidget);
4410
+ case "matrix":
4411
+ return parseAndAssign(`matrix ${n}`, parseMatrixWidget);
4412
+ case "measurer":
4413
+ return parseAndAssign(`measurer ${n}`, parseMeasurerWidget);
4414
+ case "molecule-renderer":
4415
+ return parseAndAssign(`molecule-renderer ${n}`, parseMoleculeRendererWidget);
4416
+ case "number-line":
4417
+ return parseAndAssign(`number-line ${n}`, parseNumberLineWidget);
4418
+ case "numeric-input":
4419
+ return parseAndAssign(`numeric-input ${n}`, parseNumericInputWidget);
4420
+ case "orderer":
4421
+ return parseAndAssign(`orderer ${n}`, parseOrdererWidget);
4422
+ case "passage":
4423
+ return parseAndAssign(`passage ${n}`, parsePassageWidget);
4424
+ case "passage-ref":
4425
+ return parseAndAssign(`passage-ref ${n}`, parsePassageRefWidget);
4426
+ case "passage-ref-target":
4427
+ // NOTE(benchristel): as of 2024-11-12, passage-ref-target is only
4428
+ // used in test content. See:
4429
+ // https://www.khanacademy.org/devadmin/content/search?query=widget:passage-ref-target
4430
+ return parseAndAssign(`passage-ref-target ${n}`, any);
4431
+ case "phet-simulation":
4432
+ return parseAndAssign(`phet-simulation ${n}`, parsePhetSimulationWidget);
4433
+ case "plotter":
4434
+ return parseAndAssign(`plotter ${n}`, parsePlotterWidget);
4435
+ case "python-program":
4436
+ return parseAndAssign(`python-program ${n}`, parsePythonProgramWidget);
4437
+ case "radio":
4438
+ return parseAndAssign(`radio ${n}`, parseRadioWidget);
4439
+ case "sorter":
4440
+ return parseAndAssign(`sorter ${n}`, parseSorterWidget);
4441
+ case "table":
4442
+ return parseAndAssign(`table ${n}`, parseTableWidget);
4443
+ case "video":
4444
+ return parseAndAssign(`video ${n}`, parseVideoWidget);
4445
+ case "sequence":
4446
+ // sequence is a deprecated widget type, and the corresponding
4447
+ // widget component no longer exists.
4448
+ return parseAndAssign(`sequence ${n}`, parseDeprecatedWidget);
4449
+ case "lights-puzzle":
4450
+ return parseAndAssign(`lights-puzzle ${n}`, parseDeprecatedWidget);
4451
+ case "simulator":
4452
+ return parseAndAssign(`simulator ${n}`, parseDeprecatedWidget);
4453
+ case "transformer":
4454
+ return parseAndAssign(`transformer ${n}`, parseDeprecatedWidget);
4455
+ default:
4456
+ return parseAndAssign(`${type} ${n}`, parseWidget(constant(type), any));
4457
+ }
4458
+ };
4459
+ const parseDeprecatedWidget = parseWidget(
4460
+ // Ignore the incoming widget type and hardcode "deprecated-standin"
4461
+ (_, ctx) => ctx.success("deprecated-standin"),
4462
+ // Allow any widget options
4463
+ object({}));
4464
+ const parseStringToPositiveInt = (rawValue, ctx) => {
4465
+ if (typeof rawValue !== "string" || !/^[1-9][0-9]*$/.test(rawValue)) {
4466
+ return ctx.failure("a string representing a positive integer", rawValue);
4467
+ }
4468
+ return ctx.success(+rawValue);
4469
+ };
4470
+ const parseWidgetIdComponents = pair(string, parseStringToPositiveInt);
4471
+
4472
+ const parsePerseusRenderer = defaulted(object({
4473
+ // TODO(benchristel): content is also defaulted to empty string in
4474
+ // renderer.tsx. See if we can remove one default or the other.
4475
+ content: defaulted(string, () => ""),
4476
+ // This module has an import cycle with parseWidgetsMap, because the
4477
+ // `group` widget can contain another renderer.
4478
+ // The anonymous function below ensures that we don't try to access
4479
+ // parseWidgetsMap before it's defined.
4480
+ widgets: defaulted((rawVal, ctx) => parseWidgetsMap(rawVal, ctx), () => ({})),
4481
+ metadata: optional(array(string)),
4482
+ images: parseImages
4483
+ }),
4484
+ // Default value
4485
+ () => ({
4486
+ content: "",
4487
+ widgets: {},
4488
+ images: {}
4489
+ }));
4490
+
4491
+ const parsePerseusArticle = union(parsePerseusRenderer).or(array(parsePerseusRenderer)).parser;
4492
+
4493
+ const parseHint = object({
4494
+ replace: optional(boolean),
4495
+ content: string,
4496
+ widgets: defaulted(parseWidgetsMap, () => ({})),
4497
+ metadata: optional(array(string)),
4498
+ images: parseImages
4499
+ });
4500
+
4501
+ const parsePerseusItem$1 = object({
4502
+ question: parsePerseusRenderer,
4503
+ hints: defaulted(array(parseHint), () => []),
4504
+ answerArea: pipeParsers(defaulted(object({}), () => ({}))).then(migrateAnswerArea).then(record(enumeration(...ItemExtras), boolean)).parser,
4505
+ itemDataVersion: optional(object({
4506
+ major: number,
4507
+ minor: number
4508
+ })),
4509
+ // Deprecated field
4510
+ answer: any
4511
+ });
2356
4512
 
2357
- // Add all of the Underscore functions to the wrapper object.
2358
- var _ = mixin(allExports);
2359
- // Legacy Node.js API.
2360
- _._ = _;
4513
+ // Some answerAreas have extra fields, like:
4514
+ //
4515
+ // "answerArea": {
4516
+ // "type": "multiple",
4517
+ // "options": {
4518
+ // "content": "",
4519
+ // "images": {},
4520
+ // "widgets": {}
4521
+ // }
4522
+ // }
4523
+ //
4524
+ // The "type" and "options" fields don't seem to be used anywhere. This
4525
+ // migration function removes them.
4526
+ function migrateAnswerArea(rawValue, ctx) {
4527
+ const {
4528
+ type: _,
4529
+ options: __,
4530
+ ...rest
4531
+ } = rawValue;
4532
+ return ctx.success(rest);
4533
+ }
4534
+
4535
+ /**
4536
+ * Helper to parse PerseusItem JSON
4537
+ * Why not just use JSON.parse? We want:
4538
+ * - To make sure types are correct
4539
+ * - To give us a central place to validate/transform output if needed
4540
+ * @deprecated - use parseAndMigratePerseusItem instead
4541
+ * @param {string} json - the stringified PerseusItem JSON
4542
+ * @returns {PerseusItem} the parsed PerseusItem object
4543
+ */
4544
+ function parsePerseusItem(json) {
4545
+ // Try to block a cheating vector which relies on monkey-patching
4546
+ // JSON.parse
4547
+ if (isRealJSONParse(JSON.parse)) {
4548
+ return JSON.parse(json);
4549
+ }
4550
+ throw new Error("Something went wrong.");
4551
+ }
4552
+ /**
4553
+ * Parses a PerseusItem from a JSON string, migrates old formats to the latest
4554
+ * schema, and runtime-typechecks the result. Use this to parse assessmentItem
4555
+ * data.
4556
+ *
4557
+ * @returns a {@link Result} of the parsed PerseusItem. If the result is a
4558
+ * failure, it will contain an error message describing where in the tree
4559
+ * parsing failed.
4560
+ * @throws SyntaxError if the argument is not well-formed JSON.
4561
+ */
4562
+ function parseAndMigratePerseusItem(json) {
4563
+ throwErrorIfCheatingDetected();
4564
+ const object = JSON.parse(json);
4565
+ const result = parse(object, parsePerseusItem$1);
4566
+ if (isFailure(result)) {
4567
+ return failure({
4568
+ message: result.detail,
4569
+ invalidObject: object
4570
+ });
4571
+ }
4572
+ return result;
4573
+ }
4574
+
4575
+ /**
4576
+ * Parses a PerseusArticle from a JSON string, migrates old formats to the
4577
+ * latest schema, and runtime-typechecks the result.
4578
+ *
4579
+ * @returns a {@link Result} of the parsed PerseusArticle. If the result is a
4580
+ * failure, it will contain an error message describing where in the tree
4581
+ * parsing failed.
4582
+ * @throws SyntaxError if the argument is not well-formed JSON.
4583
+ */
4584
+ function parseAndMigratePerseusArticle(json) {
4585
+ throwErrorIfCheatingDetected();
4586
+ const object = JSON.parse(json);
4587
+ const result = parse(object, parsePerseusArticle);
4588
+ if (isFailure(result)) {
4589
+ return failure({
4590
+ message: result.detail,
4591
+ invalidObject: object
4592
+ });
4593
+ }
4594
+ return result;
4595
+ }
4596
+
4597
+ /**
4598
+ * Tries to block a cheating vector that relies on monkey-patching JSON.parse.
4599
+ */
4600
+ // TODO(LEMS-2331): delete this function once server-side scoring is done.
4601
+ function throwErrorIfCheatingDetected() {
4602
+ if (!isRealJSONParse(JSON.parse)) {
4603
+ throw new Error("Something went wrong.");
4604
+ }
4605
+ }
4606
+
4607
+ // This file is processed by a Rollup plugin (replace) to inject the production
4608
+ const libName = "@khanacademy/perseus-core";
4609
+ const libVersion = "3.3.0";
4610
+ addLibraryVersionToPerseusDebug(libName, libVersion);
4611
+
4612
+ /**
4613
+ * @typedef {Object} Errors utility for referencing the Perseus error taxonomy.
4614
+ */
4615
+ const Errors = Object.freeze({
4616
+ /**
4617
+ * @property {ErrorKind} Unknown The kind of error is not known.
4618
+ */
4619
+ Unknown: "Unknown",
4620
+ /**
4621
+ * @property {ErrorKind} Internal The error is internal to the executing code.
4622
+ */
4623
+ Internal: "Internal",
4624
+ /**
4625
+ * @property {ErrorKind} InvalidInput There was a problem with the provided
4626
+ * input, such as the wrong format or a null value.
4627
+ */
4628
+ InvalidInput: "InvalidInput",
4629
+ /**
4630
+ * @property {ErrorKind} NotAllowed There was a problem due to the state of
4631
+ * the system not matching the requested operation or input. For example,
4632
+ * trying to create a username that is valid, but is already taken by
4633
+ * another user. Use {@link InvalidInput} instead when the input isn't
4634
+ * valid regardless of the state of the system. Use {@link NotFound} when
4635
+ * the failure is due to not being able to find a resource.
4636
+ */
4637
+ NotAllowed: "NotAllowed",
4638
+ /**
4639
+ * @property {ErrorKind} TransientService There was a problem when making a
4640
+ * request to a service.
4641
+ */
4642
+ TransientService: "TransientService",
4643
+ /**
4644
+ * @property {ErrorKind} Service There was a non-transient problem when
4645
+ * making a request to service.
4646
+ */
4647
+ Service: "Service"
4648
+ });
4649
+
4650
+ /**
4651
+ * @type {ErrorKind} The kind of error being reported
4652
+ */
4653
+
4654
+ class PerseusError extends Error {
4655
+ kind;
4656
+ metadata;
4657
+ constructor(message, kind, options) {
4658
+ super(message);
4659
+ this.kind = kind;
4660
+ this.metadata = options?.metadata;
4661
+ }
4662
+ }
2361
4663
 
2362
4664
  /**
2363
4665
  * _ utilities for objects
@@ -2403,16 +4705,610 @@ const mapObject = function (obj, lambda) {
2403
4705
  return result;
2404
4706
  };
2405
4707
 
4708
+ const defaultWidgetOptions$u = {
4709
+ items: [],
4710
+ categories: [],
4711
+ values: [],
4712
+ randomizeItems: false
4713
+ };
4714
+ const categorizerWidgetLogic = {
4715
+ name: "categorizer",
4716
+ defaultWidgetOptions: defaultWidgetOptions$u
4717
+ };
4718
+
4719
+ const DEFAULT_HEIGHT = 400;
4720
+ const defaultWidgetOptions$t = {
4721
+ programID: "",
4722
+ programType: null,
4723
+ settings: [{
4724
+ name: "",
4725
+ value: ""
4726
+ }],
4727
+ showEditor: false,
4728
+ showButtons: false,
4729
+ height: DEFAULT_HEIGHT
4730
+ };
4731
+ const csProgramWidgetLogic = {
4732
+ name: "cs-program",
4733
+ defaultWidgetOptions: defaultWidgetOptions$t
4734
+ };
4735
+
4736
+ const defaultWidgetOptions$s = {
4737
+ togglePrompt: "",
4738
+ definition: ""
4739
+ };
4740
+ const definitionWidgetLogic = {
4741
+ name: "definition",
4742
+ defaultWidgetOptions: defaultWidgetOptions$s
4743
+ };
4744
+
4745
+ const defaultWidgetOptions$r = {
4746
+ placeholder: "",
4747
+ choices: [{
4748
+ content: "",
4749
+ correct: false
4750
+ }]
4751
+ };
4752
+ const dropdownWidgetLogic = {
4753
+ name: "definition",
4754
+ defaultWidgetOptions: defaultWidgetOptions$r
4755
+ };
4756
+
4757
+ const defaultWidgetOptions$q = {
4758
+ showPrompt: "Explain",
4759
+ hidePrompt: "Hide explanation",
4760
+ explanation: "explanation goes here\n\nmore explanation",
4761
+ widgets: {}
4762
+ };
4763
+ const explanationWidgetLogic = {
4764
+ name: "explanation",
4765
+ defaultWidgetOptions: defaultWidgetOptions$q
4766
+ };
4767
+
4768
+ const currentVersion$3 = {
4769
+ major: 1,
4770
+ minor: 0
4771
+ };
4772
+ const widgetOptionsUpgrades$2 = {
4773
+ "1": v0options => ({
4774
+ times: v0options.times,
4775
+ buttonSets: v0options.buttonSets,
4776
+ functions: v0options.functions,
4777
+ buttonsVisible: v0options.buttonsVisible,
4778
+ visibleLabel: v0options.visibleLabel,
4779
+ ariaLabel: v0options.ariaLabel,
4780
+ answerForms: [{
4781
+ considered: "correct",
4782
+ form: v0options.form,
4783
+ simplify: v0options.simplify,
4784
+ value: v0options.value
4785
+ }]
4786
+ })
4787
+ };
4788
+ const defaultWidgetOptions$p = {
4789
+ answerForms: [],
4790
+ times: false,
4791
+ buttonSets: ["basic"],
4792
+ functions: ["f", "g", "h"]
4793
+ };
4794
+
4795
+ const expressionWidgetLogic = {
4796
+ name: "expression",
4797
+ version: currentVersion$3,
4798
+ widgetOptionsUpgrades: widgetOptionsUpgrades$2,
4799
+ defaultWidgetOptions: defaultWidgetOptions$p
4800
+ };
4801
+
4802
+ const defaultWidgetOptions$o = {
4803
+ title: "",
4804
+ content: "",
4805
+ widgets: {},
4806
+ images: {},
4807
+ hint: null
4808
+ };
4809
+ const GradedGroupWidgetLogic = {
4810
+ name: "graded-group",
4811
+ defaultWidgetOptions: defaultWidgetOptions$o
4812
+ };
4813
+
4814
+ const defaultWidgetOptions$n = {
4815
+ gradedGroups: []
4816
+ };
4817
+ const GradedGroupSetWidgetLogic = {
4818
+ name: "graded-group-set",
4819
+ defaultWidgetOptions: defaultWidgetOptions$n
4820
+ };
4821
+
4822
+ const defaultWidgetOptions$m = {
4823
+ content: "",
4824
+ widgets: {},
4825
+ images: {},
4826
+ // `undefined` instead of `null` so that getDefaultProps works for
4827
+ // `the GroupMetadataEditor`
4828
+ metadata: undefined
4829
+ };
4830
+ const GroupWidgetLogic = {
4831
+ name: "group",
4832
+ defaultWidgetOptions: defaultWidgetOptions$m
4833
+ };
4834
+
4835
+ const defaultWidgetOptions$l = {
4836
+ url: "",
4837
+ settings: [{
4838
+ name: "",
4839
+ value: ""
4840
+ }],
4841
+ width: "400",
4842
+ height: "400",
4843
+ allowFullScreen: false,
4844
+ allowTopNavigation: false
4845
+ };
4846
+ const iframeWidgetLogic = {
4847
+ name: "iframe",
4848
+ defaultWidgetOptions: defaultWidgetOptions$l
4849
+ };
4850
+
4851
+ const defaultWidgetOptions$k = {
4852
+ title: "",
4853
+ range: [[0, 10], [0, 10]],
4854
+ box: [400, 400],
4855
+ backgroundImage: {
4856
+ url: null,
4857
+ width: 0,
4858
+ height: 0
4859
+ },
4860
+ labels: [],
4861
+ alt: "",
4862
+ caption: ""
4863
+ };
4864
+ const imageWidgetLogic = {
4865
+ name: "image",
4866
+ defaultWidgetOptions: defaultWidgetOptions$k
4867
+ };
4868
+
4869
+ const defaultWidgetOptions$j = {
4870
+ value: 0,
4871
+ simplify: "required",
4872
+ size: "normal",
4873
+ inexact: false,
4874
+ maxError: 0.1,
4875
+ answerType: "number",
4876
+ rightAlign: false
4877
+ };
4878
+ const inputNumberWidgetLogic = {
4879
+ name: "input-number",
4880
+ defaultWidgetOptions: defaultWidgetOptions$j
4881
+ };
4882
+
4883
+ const defaultWidgetOptions$i = {
4884
+ graph: {
4885
+ box: [400, 400],
4886
+ labels: ["x", "y"],
4887
+ range: [[-10, 10], [-10, 10]],
4888
+ tickStep: [1, 1],
4889
+ gridStep: [1, 1],
4890
+ markings: "graph"
4891
+ },
4892
+ elements: []
4893
+ };
4894
+ const interactionWidgetLogic = {
4895
+ name: "interaction",
4896
+ defaultWidgetOptions: defaultWidgetOptions$i
4897
+ };
4898
+
4899
+ const defaultWidgetOptions$h = {
4900
+ labels: ["x", "y"],
4901
+ range: [[-10, 10], [-10, 10]],
4902
+ step: [1, 1],
4903
+ backgroundImage: {
4904
+ url: null
4905
+ },
4906
+ markings: "graph",
4907
+ showTooltips: false,
4908
+ showProtractor: false,
4909
+ graph: {
4910
+ type: "linear"
4911
+ },
4912
+ correct: {
4913
+ type: "linear",
4914
+ coords: null
4915
+ }
4916
+ };
4917
+ const interactiveGraphWidgetLogic = {
4918
+ name: "interactive-graph",
4919
+ defaultWidgetOptions: defaultWidgetOptions$h
4920
+ };
4921
+
4922
+ const defaultWidgetOptions$g = {
4923
+ choices: [],
4924
+ imageAlt: "",
4925
+ imageUrl: "",
4926
+ imageWidth: 0,
4927
+ imageHeight: 0,
4928
+ markers: [],
4929
+ multipleAnswers: false,
4930
+ hideChoicesFromInstructions: false
4931
+ };
4932
+ const labelImageWidgetLogic = {
4933
+ name: "label-image",
4934
+ defaultWidgetOptions: defaultWidgetOptions$g
4935
+ };
4936
+
4937
+ const defaultWidgetOptions$f = {
4938
+ left: ["$x$", "$y$", "$z$"],
4939
+ right: ["$1$", "$2$", "$3$"],
4940
+ labels: ["test", "label"],
4941
+ orderMatters: false,
4942
+ padding: true
4943
+ };
4944
+ const matcherWidgetLogic = {
4945
+ name: "matcher",
4946
+ defaultWidgetOptions: defaultWidgetOptions$f
4947
+ };
4948
+
4949
+ const defaultWidgetOptions$e = {
4950
+ matrixBoardSize: [3, 3],
4951
+ answers: [[]],
4952
+ prefix: "",
4953
+ suffix: "",
4954
+ cursorPosition: [0, 0]
4955
+ };
4956
+ const matrixWidgetLogic = {
4957
+ name: "matrix",
4958
+ defaultWidgetOptions: defaultWidgetOptions$e
4959
+ };
4960
+
4961
+ const currentVersion$2 = {
4962
+ major: 1,
4963
+ minor: 0
4964
+ };
4965
+ const widgetOptionsUpgrades$1 = {
4966
+ "1": v0options => {
4967
+ const {
4968
+ imageUrl,
4969
+ imageTop,
4970
+ imageLeft,
4971
+ ...rest
4972
+ } = v0options;
4973
+ return {
4974
+ ...rest,
4975
+ image: {
4976
+ url: imageUrl,
4977
+ top: imageTop,
4978
+ left: imageLeft
4979
+ }
4980
+ };
4981
+ }
4982
+ };
4983
+ const defaultWidgetOptions$d = {
4984
+ box: [480, 480],
4985
+ image: {},
4986
+ showProtractor: true,
4987
+ showRuler: false,
4988
+ rulerLabel: "",
4989
+ rulerTicks: 10,
4990
+ rulerPixels: 40,
4991
+ rulerLength: 10
4992
+ };
4993
+
4994
+ const measurerWidgetLogic = {
4995
+ name: "measurer",
4996
+ version: currentVersion$2,
4997
+ widgetOptionsUpgrades: widgetOptionsUpgrades$1,
4998
+ defaultWidgetOptions: defaultWidgetOptions$d
4999
+ };
5000
+
5001
+ const defaultWidgetOptions$c = {
5002
+ range: [0, 10],
5003
+ labelRange: [null, null],
5004
+ labelStyle: "decimal",
5005
+ labelTicks: true,
5006
+ divisionRange: [1, 12],
5007
+ numDivisions: 5,
5008
+ snapDivisions: 2,
5009
+ tickStep: null,
5010
+ correctRel: "eq",
5011
+ correctX: null,
5012
+ initialX: null,
5013
+ showTooltips: false
5014
+ };
5015
+ const numberLineWidgetLogic = {
5016
+ name: "number-line",
5017
+ defaultWidgetOptions: defaultWidgetOptions$c
5018
+ };
5019
+
5020
+ const defaultWidgetOptions$b = {
5021
+ answers: [{
5022
+ value: null,
5023
+ status: "correct",
5024
+ message: "",
5025
+ simplify: "required",
5026
+ answerForms: [],
5027
+ strict: false,
5028
+ maxError: null
5029
+ }],
5030
+ size: "normal",
5031
+ coefficient: false,
5032
+ labelText: "",
5033
+ rightAlign: false
5034
+ };
5035
+ const numericInputWidgetLogic = {
5036
+ name: "numeric-input",
5037
+ defaultWidgetOptions: defaultWidgetOptions$b
5038
+ };
5039
+
5040
+ const defaultWidgetOptions$a = {
5041
+ correctOptions: [{
5042
+ content: "$x$"
5043
+ }],
5044
+ otherOptions: [{
5045
+ content: "$y$"
5046
+ }],
5047
+ height: "normal",
5048
+ layout: "horizontal"
5049
+ };
5050
+ const ordererWidgetLogic = {
5051
+ name: "orderer",
5052
+ defaultWidgetOptions: defaultWidgetOptions$a
5053
+ };
5054
+
5055
+ const defaultWidgetOptions$9 = {
5056
+ passageTitle: "",
5057
+ passageText: "",
5058
+ footnotes: "",
5059
+ showLineNumbers: true
5060
+ };
5061
+ const passageWidgetLogic = {
5062
+ name: "passage",
5063
+ defaultWidgetOptions: defaultWidgetOptions$9
5064
+ };
5065
+
5066
+ const currentVersion$1 = {
5067
+ major: 0,
5068
+ minor: 1
5069
+ };
5070
+ const defaultWidgetOptions$8 = {
5071
+ passageNumber: 1,
5072
+ referenceNumber: 1,
5073
+ summaryText: ""
5074
+ };
5075
+
5076
+ const passageRefWidgetLogic = {
5077
+ name: "passageRef",
5078
+ version: currentVersion$1,
5079
+ defaultWidgetOptions: defaultWidgetOptions$8
5080
+ };
5081
+
5082
+ const defaultWidgetOptions$7 = {
5083
+ content: ""
5084
+ };
5085
+ const passageRefTargetWidgetLogic = {
5086
+ name: "passageRefTarget",
5087
+ defaultWidgetOptions: defaultWidgetOptions$7
5088
+ };
5089
+
5090
+ const defaultWidgetOptions$6 = {
5091
+ url: "",
5092
+ description: ""
5093
+ };
5094
+ const PhetSimulationWidgetLogic = {
5095
+ name: "phet-simulation",
5096
+ defaultWidgetOptions: defaultWidgetOptions$6
5097
+ };
5098
+
5099
+ const defaultWidgetOptions$5 = {
5100
+ scaleY: 1,
5101
+ maxY: 10,
5102
+ snapsPerLine: 2,
5103
+ correct: [1],
5104
+ starting: [1],
5105
+ type: "bar",
5106
+ labels: ["", ""],
5107
+ categories: [""],
5108
+ picSize: 30,
5109
+ picBoxHeight: 36,
5110
+ plotDimensions: [275, 200],
5111
+ labelInterval: 1,
5112
+ picUrl: null
5113
+ };
5114
+ const plotterWidgetLogic = {
5115
+ name: "plotter",
5116
+ defaultWidgetOptions: defaultWidgetOptions$5
5117
+ };
5118
+
5119
+ const defaultWidgetOptions$4 = {
5120
+ programID: "",
5121
+ height: 400
5122
+ };
5123
+ const pythonProgramWidgetLogic = {
5124
+ name: "python-program",
5125
+ defaultWidgetOptions: defaultWidgetOptions$4
5126
+ };
5127
+
5128
+ const currentVersion = {
5129
+ major: 1,
5130
+ minor: 0
5131
+ };
5132
+ const widgetOptionsUpgrades = {
5133
+ "1": v0props => {
5134
+ const {
5135
+ noneOfTheAbove,
5136
+ ...rest
5137
+ } = v0props;
5138
+ if (noneOfTheAbove) {
5139
+ throw new Error("radio widget v0 no longer supports auto noneOfTheAbove");
5140
+ }
5141
+ return {
5142
+ ...rest,
5143
+ hasNoneOfTheAbove: false
5144
+ };
5145
+ }
5146
+ };
5147
+ const defaultWidgetOptions$3 = {
5148
+ choices: [{}, {}, {}, {}],
5149
+ displayCount: null,
5150
+ randomize: false,
5151
+ hasNoneOfTheAbove: false,
5152
+ multipleSelect: false,
5153
+ countChoices: false,
5154
+ deselectEnabled: false
5155
+ };
5156
+
5157
+ const radioWidgetLogic = {
5158
+ name: "radio",
5159
+ version: currentVersion,
5160
+ widgetOptionsUpgrades: widgetOptionsUpgrades,
5161
+ defaultWidgetOptions: defaultWidgetOptions$3
5162
+ };
5163
+
5164
+ const defaultWidgetOptions$2 = {
5165
+ correct: ["$x$", "$y$", "$z$"],
5166
+ layout: "horizontal",
5167
+ padding: true
5168
+ };
5169
+ const sorterWidgetLogic = {
5170
+ name: "sorter",
5171
+ defaultWidgetOptions: defaultWidgetOptions$2
5172
+ };
5173
+
5174
+ const defaultRows = 4;
5175
+ const defaultColumns = 1;
5176
+
5177
+ // initialize a 2D array
5178
+ // (defaultRows x defaultColumns) of empty strings
5179
+ const answers = new Array(defaultRows).fill(0).map(() => new Array(defaultColumns).fill(""));
5180
+ const defaultWidgetOptions$1 = {
5181
+ headers: [""],
5182
+ rows: defaultRows,
5183
+ columns: defaultColumns,
5184
+ answers: answers
5185
+ };
5186
+ const tableWidgetLogic = {
5187
+ name: "table",
5188
+ defaultWidgetOptions: defaultWidgetOptions$1
5189
+ };
5190
+
5191
+ const defaultWidgetOptions = {
5192
+ location: ""
5193
+ };
5194
+ const videoWidgetLogic = {
5195
+ name: "video",
5196
+ defaultWidgetOptions
5197
+ };
5198
+
5199
+ /**
5200
+ * For details on the individual options, see the
5201
+ * PerseusOrdererWidgetOptions type
5202
+ */
5203
+
5204
+ /**
5205
+ * Given a PerseusOrdererWidgetOptions object, return a new object with only
5206
+ * the public options that should be exposed to the client.
5207
+ */
5208
+ function getOrdererPublicWidgetOptions(options) {
5209
+ return {
5210
+ options: options.options,
5211
+ height: options.height,
5212
+ layout: options.layout
5213
+ };
5214
+ }
5215
+
5216
+ /**
5217
+ * For details on the individual options, see the
5218
+ * PerseusCategorizerWidgetOptions type
5219
+ */
5220
+
5221
+ /**
5222
+ * Given a PerseusCategorizerWidgetOptions object, return a new object with only
5223
+ * the public options that should be exposed to the client.
5224
+ */
5225
+ function getCategorizerPublicWidgetOptions(options) {
5226
+ return {
5227
+ items: options.items,
5228
+ categories: options.categories,
5229
+ randomizeItems: options.randomizeItems,
5230
+ static: options.static
5231
+ };
5232
+ }
5233
+
5234
+ /**
5235
+ * For details on the individual options, see the
5236
+ * PerseusExpressionWidgetOptions type
5237
+ */
5238
+
5239
+ /**
5240
+ * Given a PerseusExpressionWidgetOptions object, return a new object with only
5241
+ * the public options that should be exposed to the client.
5242
+ */
5243
+ function getExpressionPublicWidgetOptions(options) {
5244
+ return {
5245
+ buttonSets: options.buttonSets,
5246
+ functions: options.functions,
5247
+ times: options.times,
5248
+ visibleLabel: options.visibleLabel,
5249
+ ariaLabel: options.ariaLabel,
5250
+ buttonsVisible: options.buttonsVisible
5251
+ };
5252
+ }
5253
+
2406
5254
  exports.Errors = Errors;
5255
+ exports.GrapherUtil = grapherUtil;
2407
5256
  exports.ItemExtras = ItemExtras;
2408
5257
  exports.PerseusError = PerseusError;
2409
5258
  exports.PerseusExpressionAnswerFormConsidered = PerseusExpressionAnswerFormConsidered;
2410
5259
  exports.addLibraryVersionToPerseusDebug = addLibraryVersionToPerseusDebug;
5260
+ exports.addWidget = addWidget;
5261
+ exports.approximateDeepEqual = approximateDeepEqual;
5262
+ exports.approximateEqual = approximateEqual;
5263
+ exports.categorizerLogic = categorizerWidgetLogic;
5264
+ exports.csProgramLogic = csProgramWidgetLogic;
5265
+ exports.deepClone = deepClone;
5266
+ exports.definitionLogic = definitionWidgetLogic;
5267
+ exports.dropdownLogic = dropdownWidgetLogic;
5268
+ exports.explanationLogic = explanationWidgetLogic;
5269
+ exports.expressionLogic = expressionWidgetLogic;
5270
+ exports.getCategorizerPublicWidgetOptions = getCategorizerPublicWidgetOptions;
5271
+ exports.getDecimalSeparator = getDecimalSeparator;
5272
+ exports.getExpressionPublicWidgetOptions = getExpressionPublicWidgetOptions;
5273
+ exports.getMatrixSize = getMatrixSize;
5274
+ exports.getOrdererPublicWidgetOptions = getOrdererPublicWidgetOptions;
5275
+ exports.getWidgetIdsFromContent = getWidgetIdsFromContent;
5276
+ exports.getWidgetIdsFromContentByType = getWidgetIdsFromContentByType;
5277
+ exports.gradedGroupLogic = GradedGroupWidgetLogic;
5278
+ exports.gradedGroupSetLogic = GradedGroupSetWidgetLogic;
5279
+ exports.groupLogic = GroupWidgetLogic;
5280
+ exports.iframeLogic = iframeWidgetLogic;
5281
+ exports.imageLogic = imageWidgetLogic;
5282
+ exports.inputNumberLogic = inputNumberWidgetLogic;
5283
+ exports.interactionLogic = interactionWidgetLogic;
5284
+ exports.interactiveGraphLogic = interactiveGraphWidgetLogic;
5285
+ exports.isFailure = isFailure;
5286
+ exports.isSuccess = isSuccess;
5287
+ exports.labelImageLogic = labelImageWidgetLogic;
2411
5288
  exports.libVersion = libVersion;
2412
5289
  exports.lockedFigureColorNames = lockedFigureColorNames;
2413
5290
  exports.lockedFigureColors = lockedFigureColors;
2414
5291
  exports.lockedFigureFillStyles = lockedFigureFillStyles;
2415
5292
  exports.mapObject = mapObject;
5293
+ exports.matcherLogic = matcherWidgetLogic;
5294
+ exports.matrixLogic = matrixWidgetLogic;
5295
+ exports.measurerLogic = measurerWidgetLogic;
5296
+ exports.numberLineLogic = numberLineWidgetLogic;
5297
+ exports.numericInputLogic = numericInputWidgetLogic;
5298
+ exports.ordererLogic = ordererWidgetLogic;
5299
+ exports.parseAndMigratePerseusArticle = parseAndMigratePerseusArticle;
5300
+ exports.parseAndMigratePerseusItem = parseAndMigratePerseusItem;
5301
+ exports.parsePerseusItem = parsePerseusItem;
5302
+ exports.passageLogic = passageWidgetLogic;
5303
+ exports.passageRefLogic = passageRefWidgetLogic;
5304
+ exports.passageRefTargetLogic = passageRefTargetWidgetLogic;
5305
+ exports.phetSimulationLogic = PhetSimulationWidgetLogic;
5306
+ exports.plotterLogic = plotterWidgetLogic;
2416
5307
  exports.plotterPlotTypes = plotterPlotTypes;
2417
5308
  exports.pluck = pluck;
5309
+ exports.pythonProgramLogic = pythonProgramWidgetLogic;
5310
+ exports.radioLogic = radioWidgetLogic;
5311
+ exports.sorterLogic = sorterWidgetLogic;
5312
+ exports.tableLogic = tableWidgetLogic;
5313
+ exports.videoLogic = videoWidgetLogic;
2418
5314
  //# sourceMappingURL=index.js.map