@magnusopera/fscript 0.83.2 → 0.83.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Library.js CHANGED
@@ -1,55 +1,57 @@
1
1
 
2
2
  import { Record } from "./fable_modules/fable-library-js.5.13.0/Types.js";
3
- import { obj_type, class_type, record_type, list_type, string_type } from "./fable_modules/fable-library-js.5.13.0/Reflection.js";
3
+ import { option_type, obj_type, class_type, record_type, list_type, string_type } from "./fable_modules/fable-library-js.5.13.0/Reflection.js";
4
4
  import { Stmt_$reflection } from "./FScript.Language/Ast.js";
5
- import { ExternalFunction, MapKey, Value, Value_$reflection, ExternalFunction_$reflection } from "./FScript.Language/Value.js";
6
- import { inferProgramWithExterns, TypedStmt_$reflection } from "./FScript.Language/TypeInfer.js";
7
- import { Scheme, Type, Types_typeToString, Type_$reflection } from "./FScript.Language/Types.js";
8
- import { submit as submit_1, create, Session_$reflection } from "./FScript.Language/Interactive.js";
9
- import { defaultArg, value as value_18, some } from "./fable_modules/fable-library-js.5.13.0/Option.js";
10
- import { stringHash, compare, comparePrimitives, createObj, Exception } from "./fable_modules/fable-library-js.5.13.0/Util.js";
11
- import { concat } from "./fable_modules/fable-library-js.5.13.0/String.js";
5
+ import { ExtensionRegistration, ExternalFunction, MapKey, Value, ExternalCallContext_$reflection, Value_$reflection, ExtensionRegistration_$reflection } from "./FScript.Language/Value.js";
6
+ import { inferProgramWithRegistration, TypedStmt_$reflection } from "./FScript.Language/TypeInfer.js";
7
+ import { HostUnionDescriptor, HostTypeDescriptor, Scheme, Type, Types_ftvType, Types_typeToString, Type_$reflection } from "./FScript.Language/Types.js";
8
+ import { submit as submit_1, createWithRegistration, Session_$reflection } from "./FScript.Language/Interactive.js";
9
+ import { foldBack, find, tryFind as tryFind_1, choose, filter, sort, exists, singleton, collect, append, iterate as iterate_1, tail, head, isEmpty as isEmpty_1, fold, zip, iterateIndexed, empty, ofArray, length, map, toArray } from "./fable_modules/fable-library-js.5.13.0/List.js";
10
+ import { flatten, defaultArg, value as value_15, some } from "./fable_modules/fable-library-js.5.13.0/Option.js";
11
+ import { stringHash, disposeSafe, getEnumerator, curry2, compare, comparePrimitives, Exception } from "./fable_modules/fable-library-js.5.13.0/Util.js";
12
+ import { isNullOrWhiteSpace, concat } from "./fable_modules/fable-library-js.5.13.0/String.js";
12
13
  import { EvalError$, EvalException, TypeException, ParseException } from "./FScript.Language/Error.js";
13
14
  import { toInt32_unchecked, fromFloat64, toInt64_unchecked } from "./fable_modules/fable-library-js.5.13.0/BigInt.js";
14
15
  import { parse as parse_1 } from "./fable_modules/fable-library-js.5.13.0/Long.js";
15
16
  import { parse as parse_2 } from "./fable_modules/fable-library-js.5.13.0/Int32.js";
16
- import { choose, filter, sort, exists, singleton, collect, empty, ofArray, length, map, toArray } from "./fable_modules/fable-library-js.5.13.0/List.js";
17
- import { FSharpMap__get_Item, FSharpMap__TryFind, ofList, toList } from "./fable_modules/fable-library-js.5.13.0/Map.js";
17
+ import { FSharpMap__get_Count, FSharpMap__get_Keys, empty as empty_3, FSharpMap__get_Item, FSharpMap__TryFind, FSharpMap__ContainsKey, tryFind, iterate, ofList, toList } from "./fable_modules/fable-library-js.5.13.0/Map.js";
18
+ import { map as map_1, item } from "./fable_modules/fable-library-js.5.13.0/Array.js";
19
+ import { ofSeq, ofList as ofList_1, isSubset, FSharpSet__Add, FSharpSet__Contains, empty as empty_1, isEmpty } from "./fable_modules/fable-library-js.5.13.0/Set.js";
20
+ import { $007CRecordFields$007C_$007C, create, empty as empty_2, typeDefinitions, validateCall } from "./FScript.Language/HostInterop.js";
18
21
  import { parseProgramFromSourceWithIncludesResolver } from "./FScript.Language/IncludeResolver.js";
19
- import { invokeValue, evalProgramWithExterns, evalProgramWithExternsState } from "./FScript.Language/Eval.js";
22
+ import { invokeValue, evalProgramWithRegistration, evalProgramWithRegistrationState } from "./FScript.Language/Eval.js";
20
23
  import { List_distinct } from "./fable_modules/fable-library-js.5.13.0/Seq2.js";
21
- import { FSharpSet__Contains, ofList as ofList_1 } from "./fable_modules/fable-library-js.5.13.0/Set.js";
22
24
  import { valueToString } from "./FScript.Language/Pretty.js";
23
25
  import { Span, Position } from "./FScript.Language/Span.js";
24
26
 
25
27
  export class ParsedProgramHandle extends Record {
26
- constructor(kind, program, externs) {
28
+ constructor(kind, program, registration) {
27
29
  super();
28
30
  this.kind = kind;
29
31
  this.program = program;
30
- this.externs = externs;
32
+ this.registration = registration;
31
33
  }
32
34
  }
33
35
 
34
36
  export function ParsedProgramHandle_$reflection() {
35
- return record_type("FScript.JavaScript.ParsedProgramHandle", [], ParsedProgramHandle, () => [["kind", string_type], ["program", list_type(Stmt_$reflection())], ["externs", list_type(ExternalFunction_$reflection())]]);
37
+ return record_type("FScript.JavaScript.ParsedProgramHandle", [], ParsedProgramHandle, () => [["kind", string_type], ["program", list_type(Stmt_$reflection())], ["registration", ExtensionRegistration_$reflection()]]);
36
38
  }
37
39
 
38
40
  export class TypedProgramHandle extends Record {
39
- constructor(kind, typedProgram, externs) {
41
+ constructor(kind, typedProgram, registration) {
40
42
  super();
41
43
  this.kind = kind;
42
44
  this.typedProgram = typedProgram;
43
- this.externs = externs;
45
+ this.registration = registration;
44
46
  }
45
47
  }
46
48
 
47
49
  export function TypedProgramHandle_$reflection() {
48
- return record_type("FScript.JavaScript.TypedProgramHandle", [], TypedProgramHandle, () => [["kind", string_type], ["typedProgram", list_type(TypedStmt_$reflection())], ["externs", list_type(ExternalFunction_$reflection())]]);
50
+ return record_type("FScript.JavaScript.TypedProgramHandle", [], TypedProgramHandle, () => [["kind", string_type], ["typedProgram", list_type(TypedStmt_$reflection())], ["registration", ExtensionRegistration_$reflection()]]);
49
51
  }
50
52
 
51
53
  export class LoadedScriptHandle extends Record {
52
- constructor(kind, typeDefs, env, exportedFunctionNames, exportedFunctionSet, exportedFunctions, exportedValueNames, exportedValueSet, exportedValues, lastValue, externs) {
54
+ constructor(kind, typeDefs, env, exportedFunctionNames, exportedFunctionSet, exportedFunctions, exportedFunctionTypes, exportedValueNames, exportedValueSet, exportedValues, lastValue, registration) {
53
55
  super();
54
56
  this.kind = kind;
55
57
  this.typeDefs = typeDefs;
@@ -57,30 +59,36 @@ export class LoadedScriptHandle extends Record {
57
59
  this.exportedFunctionNames = exportedFunctionNames;
58
60
  this.exportedFunctionSet = exportedFunctionSet;
59
61
  this.exportedFunctions = exportedFunctions;
62
+ this.exportedFunctionTypes = exportedFunctionTypes;
60
63
  this.exportedValueNames = exportedValueNames;
61
64
  this.exportedValueSet = exportedValueSet;
62
65
  this.exportedValues = exportedValues;
63
66
  this.lastValue = lastValue;
64
- this.externs = externs;
67
+ this.registration = registration;
65
68
  }
66
69
  }
67
70
 
68
71
  export function LoadedScriptHandle_$reflection() {
69
- return record_type("FScript.JavaScript.LoadedScriptHandle", [], LoadedScriptHandle, () => [["kind", string_type], ["typeDefs", class_type("Microsoft.FSharp.Collections.FSharpMap`2", [string_type, Type_$reflection()])], ["env", class_type("Microsoft.FSharp.Collections.FSharpMap`2", [string_type, Value_$reflection()])], ["exportedFunctionNames", list_type(string_type)], ["exportedFunctionSet", class_type("Microsoft.FSharp.Collections.FSharpSet`1", [string_type])], ["exportedFunctions", class_type("Microsoft.FSharp.Collections.FSharpMap`2", [string_type, Value_$reflection()])], ["exportedValueNames", list_type(string_type)], ["exportedValueSet", class_type("Microsoft.FSharp.Collections.FSharpSet`1", [string_type])], ["exportedValues", class_type("Microsoft.FSharp.Collections.FSharpMap`2", [string_type, Value_$reflection()])], ["lastValue", Value_$reflection()], ["externs", list_type(ExternalFunction_$reflection())]]);
72
+ return record_type("FScript.JavaScript.LoadedScriptHandle", [], LoadedScriptHandle, () => [["kind", string_type], ["typeDefs", class_type("Microsoft.FSharp.Collections.FSharpMap`2", [string_type, Type_$reflection()])], ["env", class_type("Microsoft.FSharp.Collections.FSharpMap`2", [string_type, Value_$reflection()])], ["exportedFunctionNames", list_type(string_type)], ["exportedFunctionSet", class_type("Microsoft.FSharp.Collections.FSharpSet`1", [string_type])], ["exportedFunctions", class_type("Microsoft.FSharp.Collections.FSharpMap`2", [string_type, Value_$reflection()])], ["exportedFunctionTypes", class_type("Microsoft.FSharp.Collections.FSharpMap`2", [string_type, Type_$reflection()])], ["exportedValueNames", list_type(string_type)], ["exportedValueSet", class_type("Microsoft.FSharp.Collections.FSharpSet`1", [string_type])], ["exportedValues", class_type("Microsoft.FSharp.Collections.FSharpMap`2", [string_type, Value_$reflection()])], ["lastValue", Value_$reflection()], ["registration", ExtensionRegistration_$reflection()]]);
70
73
  }
71
74
 
72
75
  export class SessionHandle extends Record {
73
- constructor(kind, interactiveSession, options, externs) {
76
+ constructor(kind, interactiveSession, options, registration) {
74
77
  super();
75
78
  this.kind = kind;
76
79
  this.interactiveSession = interactiveSession;
77
80
  this.options = options;
78
- this.externs = externs;
81
+ this.registration = registration;
79
82
  }
80
83
  }
81
84
 
82
85
  export function SessionHandle_$reflection() {
83
- return record_type("FScript.JavaScript.SessionHandle", [], SessionHandle, () => [["kind", string_type], ["interactiveSession", Session_$reflection()], ["options", obj_type], ["externs", list_type(ExternalFunction_$reflection())]]);
86
+ return record_type("FScript.JavaScript.SessionHandle", [], SessionHandle, () => [["kind", string_type], ["interactiveSession", Session_$reflection()], ["options", obj_type], ["registration", ExtensionRegistration_$reflection()]]);
87
+ }
88
+
89
+ function propertiesObject(entries) {
90
+ const _entries = toArray(entries);
91
+ return Object.fromEntries(_entries);
84
92
  }
85
93
 
86
94
  function tryGetProperty(name, value) {
@@ -104,7 +112,7 @@ function getRequiredProperty(name, value) {
104
112
  throw new Exception(concat("Missing required property \'", name, "\'"));
105
113
  }
106
114
  else {
107
- return value_18(matchValue);
115
+ return value_15(matchValue);
108
116
  }
109
117
  }
110
118
 
@@ -114,7 +122,7 @@ function isFScriptError(value) {
114
122
  return false;
115
123
  }
116
124
  else {
117
- return value_18(matchValue) === "fscript-error";
125
+ return value_15(matchValue) === "fscript-error";
118
126
  }
119
127
  }
120
128
 
@@ -181,6 +189,33 @@ function withStructuredErrors(work) {
181
189
  }
182
190
  }
183
191
 
192
+ const hostValues = new WeakMap();
193
+
194
+ const registrations = new WeakMap();
195
+
196
+ const boundaryHandles = new WeakMap();
197
+
198
+ const externDefinitions = new WeakMap();
199
+
200
+ class BoundaryHandle extends Record {
201
+ constructor(Value, Context, Signature) {
202
+ super();
203
+ this.Value = Value;
204
+ this.Context = Context;
205
+ this.Signature = Signature;
206
+ }
207
+ }
208
+
209
+ function BoundaryHandle_$reflection() {
210
+ return record_type("FScript.JavaScript.BoundaryHandle", [], BoundaryHandle, () => [["Value", Value_$reflection()], ["Context", option_type(ExternalCallContext_$reflection())], ["Signature", option_type(Type_$reflection())]]);
211
+ }
212
+
213
+ function rememberHandle(context, value, display) {
214
+ const handle = Object.freeze(display);
215
+ boundaryHandles.set(handle, (new BoundaryHandle(value, context, undefined)));
216
+ return handle;
217
+ }
218
+
184
219
  function int64FromObj(value) {
185
220
  const matchValue = typeof value;
186
221
  switch (matchValue) {
@@ -240,8 +275,9 @@ function mapKeyToTagged(key) {
240
275
  }
241
276
  }
242
277
 
243
- function valueToTagged(value) {
244
- let option_1;
278
+ function valueToTaggedWithContext(context, value) {
279
+ let _value, option_1;
280
+ const valueToTagged_1 = (value_1) => valueToTaggedWithContext(context, value_1);
245
281
  switch (value.tag) {
246
282
  case 1:
247
283
  return {
@@ -266,34 +302,43 @@ function valueToTagged(value) {
266
302
  case 5:
267
303
  return {
268
304
  kind: "list",
269
- values: toArray(map(valueToTagged, value.fields[0])),
305
+ values: toArray(map(valueToTagged_1, value.fields[0])),
270
306
  };
271
307
  case 6:
272
308
  return {
273
309
  kind: "tuple",
274
- values: toArray(map(valueToTagged, value.fields[0])),
310
+ values: toArray(map(valueToTagged_1, value.fields[0])),
275
311
  };
276
- case 16:
277
- throw new Exception("Host-managed values cannot cross the JavaScript facade");
312
+ case 16: {
313
+ let handle;
314
+ const _value_1 = {
315
+ kind: "host",
316
+ typeName: value.fields[0].Descriptor.Name,
317
+ fields: (_value = propertiesObject(map((tupledArg) => [tupledArg[0], valueToTagged_1(tupledArg[1])], toList(value.fields[0].Fields))), (() => { const visit = v => { if (v && typeof v === 'object' && !Object.isFrozen(v)) { for (const key of Object.keys(v)) visit(v[key]); Object.freeze(v); } }; visit(_value); return _value; })()),
318
+ };
319
+ handle = (Object.freeze(_value_1));
320
+ hostValues.set(handle, value);
321
+ return handle;
322
+ }
278
323
  case 7:
279
324
  return {
280
325
  kind: "record",
281
- fields: createObj(map((tupledArg) => [tupledArg[0], valueToTagged(tupledArg[1])], toList(value.fields[0]))),
326
+ fields: propertiesObject(map((tupledArg_1) => [tupledArg_1[0], valueToTagged_1(tupledArg_1[1])], toList(value.fields[0]))),
282
327
  };
283
328
  case 8:
284
329
  return {
285
330
  kind: "map",
286
- entries: toArray(map((tupledArg_1) => ({
287
- key: mapKeyToTagged(tupledArg_1[0]),
288
- value: valueToTagged(tupledArg_1[1]),
331
+ entries: toArray(map((tupledArg_2) => ({
332
+ key: mapKeyToTagged(tupledArg_2[0]),
333
+ value: valueToTagged_1(tupledArg_2[1]),
289
334
  }), toList(value.fields[0]))),
290
335
  };
291
336
  case 9:
292
337
  if (value.fields[0] != null) {
293
- const value_7 = value.fields[0];
338
+ const value_6 = value.fields[0];
294
339
  return {
295
340
  kind: "option",
296
- value: valueToTagged(value_7),
341
+ value: valueToTagged_1(value_6),
297
342
  };
298
343
  }
299
344
  else {
@@ -307,38 +352,38 @@ function valueToTagged(value) {
307
352
  kind: "union",
308
353
  typeName: value.fields[0],
309
354
  caseName: value.fields[1],
310
- value: defaultArg((option_1 = value.fields[2], (option_1 != null) ? some(valueToTagged(option_1)) : undefined), null),
355
+ value: defaultArg((option_1 = value.fields[2], (option_1 != null) ? some(valueToTagged_1(option_1)) : undefined), null),
311
356
  };
312
357
  case 11:
313
- return {
358
+ return rememberHandle(context, value, {
314
359
  kind: "opaque",
315
360
  valueType: "union-constructor",
316
361
  typeName: value.fields[0],
317
362
  caseName: value.fields[1],
318
- };
363
+ });
319
364
  case 12:
320
- return {
365
+ return rememberHandle(context, value, {
321
366
  kind: "type",
322
367
  name: Types_typeToString(value.fields[0]),
323
- };
368
+ });
324
369
  case 13:
325
- return {
370
+ return rememberHandle(context, value, {
326
371
  kind: "opaque",
327
372
  valueType: "task",
328
- };
373
+ });
329
374
  case 14:
330
- return {
375
+ return rememberHandle(context, value, {
331
376
  kind: "opaque",
332
377
  valueType: "function",
333
- };
378
+ });
334
379
  case 15:
335
- return {
380
+ return rememberHandle(context, value, {
336
381
  kind: "opaque",
337
382
  valueType: "external",
338
383
  name: value.fields[0].Name,
339
384
  applied: length(value.fields[1]),
340
385
  arity: value.fields[0].Arity,
341
- };
386
+ });
342
387
  default:
343
388
  return {
344
389
  kind: "unit",
@@ -346,11 +391,18 @@ function valueToTagged(value) {
346
391
  }
347
392
  }
348
393
 
394
+ function valueToTagged(value) {
395
+ return valueToTaggedWithContext(undefined, value);
396
+ }
397
+
349
398
  function valueFromJs(value) {
350
399
  let optionValue, payloadValue, payloadValue_1, payloadValue_2;
351
400
  if (typeof value === 'undefined' || value === null) {
352
401
  return Value.VUnit;
353
402
  }
403
+ else if (value != null && typeof value.then === 'function') {
404
+ throw new Exception("JavaScript externs must return synchronously; Promises are not supported");
405
+ }
354
406
  else if (Array.isArray(value)) {
355
407
  return new Value(/* VList */ 5, [map(valueFromJs, ofArray(value))]);
356
408
  }
@@ -378,18 +430,73 @@ function valueFromJs(value) {
378
430
  })]);
379
431
  }
380
432
  else {
381
- const matchValue_2 = value_18(matchValue_1);
433
+ const matchValue_2 = value_15(matchValue_1);
382
434
  switch (matchValue_2) {
435
+ case "host": {
436
+ const stored = hostValues.get(value);
437
+ if (typeof stored === 'undefined' || stored === null) {
438
+ throw new Exception("Invalid or forged host-value handle");
439
+ }
440
+ return stored;
441
+ }
442
+ case "opaque":
443
+ case "type": {
444
+ const stored_1 = boundaryHandles.get(value);
445
+ if (typeof stored_1 === 'undefined' || stored_1 === null) {
446
+ throw new Exception("Invalid or forged opaque handle");
447
+ }
448
+ const handle = stored_1;
449
+ const matchValue_3 = handle.Context;
450
+ let matchResult, context_1;
451
+ if (matchValue_3 == null) {
452
+ if (!(handle.Value.tag === 12)) {
453
+ matchResult = 1;
454
+ }
455
+ else {
456
+ matchResult = 2;
457
+ }
458
+ }
459
+ else if (!matchValue_3.IsActive()) {
460
+ matchResult = 0;
461
+ context_1 = matchValue_3;
462
+ }
463
+ else {
464
+ matchResult = 2;
465
+ }
466
+ switch (matchResult) {
467
+ case 0:
468
+ throw new Exception("Expired invocation handle");
469
+ case 1:
470
+ throw new Exception("Callable handles can only be used during their originating invocation");
471
+ default:
472
+ return handle.Value;
473
+ }
474
+ }
383
475
  case "unit":
384
476
  return Value.VUnit;
385
477
  case "int":
386
478
  return new Value(/* VInt */ 1, [int64FromObj(getRequiredProperty("value", value))]);
387
- case "float":
388
- return new Value(/* VFloat */ 2, [getRequiredProperty("value", value)]);
389
- case "bool":
390
- return new Value(/* VBool */ 3, [getRequiredProperty("value", value)]);
391
- case "string":
392
- return new Value(/* VString */ 4, [getRequiredProperty("value", value)]);
479
+ case "float": {
480
+ const number = getRequiredProperty("value", value);
481
+ if ((typeof number) !== "number") {
482
+ throw new Exception("Expected a JavaScript number in a float tag");
483
+ }
484
+ return new Value(/* VFloat */ 2, [number]);
485
+ }
486
+ case "bool": {
487
+ const flag = getRequiredProperty("value", value);
488
+ if ((typeof flag) !== "boolean") {
489
+ throw new Exception("Expected a JavaScript boolean in a bool tag");
490
+ }
491
+ return new Value(/* VBool */ 3, [flag]);
492
+ }
493
+ case "string": {
494
+ const text = getRequiredProperty("value", value);
495
+ if ((typeof text) !== "string") {
496
+ throw new Exception("Expected a JavaScript string in a string tag");
497
+ }
498
+ return new Value(/* VString */ 4, [text]);
499
+ }
393
500
  case "list":
394
501
  return new Value(/* VList */ 5, [map(valueFromJs, ofArray(getRequiredProperty("values", value)))]);
395
502
  case "tuple":
@@ -412,14 +519,14 @@ function valueFromJs(value) {
412
519
  Compare: (x_1, y_1) => (compare(x_1, y_1) | 0),
413
520
  })]);
414
521
  case "option": {
415
- const matchValue_3 = tryGetProperty("value", value);
416
- if (matchValue_3 != null) {
417
- if ((optionValue = value_18(matchValue_3), typeof optionValue === 'undefined' || optionValue === null)) {
418
- const optionValue_1 = value_18(matchValue_3);
522
+ const matchValue_5 = tryGetProperty("value", value);
523
+ if (matchValue_5 != null) {
524
+ if ((optionValue = value_15(matchValue_5), typeof optionValue === 'undefined' || optionValue === null)) {
525
+ const optionValue_1 = value_15(matchValue_5);
419
526
  return new Value(/* VOption */ 9, [undefined]);
420
527
  }
421
528
  else {
422
- const optionValue_2 = value_18(matchValue_3);
529
+ const optionValue_2 = value_15(matchValue_5);
423
530
  return new Value(/* VOption */ 9, [valueFromJs(optionValue_2)]);
424
531
  }
425
532
  }
@@ -429,8 +536,8 @@ function valueFromJs(value) {
429
536
  }
430
537
  case "union": {
431
538
  let payload;
432
- const matchValue_4 = tryGetProperty("value", value);
433
- payload = ((matchValue_4 != null) ? (((payloadValue = value_18(matchValue_4), typeof payloadValue === 'undefined' || payloadValue === null)) ? ((payloadValue_1 = value_18(matchValue_4), undefined)) : ((payloadValue_2 = value_18(matchValue_4), valueFromJs(payloadValue_2)))) : undefined);
539
+ const matchValue_6 = tryGetProperty("value", value);
540
+ payload = ((matchValue_6 != null) ? (((payloadValue = value_15(matchValue_6), typeof payloadValue === 'undefined' || payloadValue === null)) ? ((payloadValue_1 = value_15(matchValue_6), undefined)) : ((payloadValue_2 = value_15(matchValue_6), valueFromJs(payloadValue_2)))) : undefined);
434
541
  return new Value(/* VUnionCase */ 10, [getRequiredProperty("typeName", value), getRequiredProperty("caseName", value), payload]);
435
542
  }
436
543
  default:
@@ -453,23 +560,633 @@ function externsFromArray(value) {
453
560
  }
454
561
  }
455
562
 
456
- function externsFromOptions(options) {
457
- const matchValue = tryGetProperty("externs", options);
458
- if (matchValue == null) {
459
- return empty();
563
+ function tagSignature(definitions_mut, expected_mut, value_mut, tagged_mut) {
564
+ tagSignature:
565
+ while (true) {
566
+ const definitions = definitions_mut, expected = expected_mut, value = value_mut, tagged = tagged_mut;
567
+ const fields = (expectedFields, actualFields, taggedFields) => {
568
+ iterate((name, t) => {
569
+ const option_1 = tryFind(name, actualFields);
570
+ if (option_1 != null) {
571
+ tagSignature(definitions, t, option_1, taggedFields[name]);
572
+ }
573
+ }, expectedFields);
574
+ };
575
+ let matchResult, name_1, t_2, values, ts, values_1, t_4, v_3, ts_1, vs, host, ts_2, caseName, cases, v_4, t_6, values_2;
576
+ switch (expected.tag) {
577
+ case 12: {
578
+ matchResult = 0;
579
+ name_1 = expected.fields[0];
580
+ break;
581
+ }
582
+ case 11: {
583
+ matchResult = 1;
584
+ break;
585
+ }
586
+ case 5: {
587
+ if (value.tag === 5) {
588
+ matchResult = 2;
589
+ t_2 = expected.fields[0];
590
+ values = value.fields[0];
591
+ }
592
+ else {
593
+ matchResult = 9;
594
+ }
595
+ break;
596
+ }
597
+ case 7: {
598
+ if (value.tag === 6) {
599
+ matchResult = 3;
600
+ ts = expected.fields[0];
601
+ values_1 = value.fields[0];
602
+ }
603
+ else {
604
+ matchResult = 9;
605
+ }
606
+ break;
607
+ }
608
+ case 10: {
609
+ if (value.tag === 9) {
610
+ if (value.fields[0] != null) {
611
+ matchResult = 4;
612
+ t_4 = expected.fields[0];
613
+ v_3 = value.fields[0];
614
+ }
615
+ else {
616
+ matchResult = 9;
617
+ }
618
+ }
619
+ else {
620
+ matchResult = 9;
621
+ }
622
+ break;
623
+ }
624
+ case 8: {
625
+ if (value.tag === 7) {
626
+ matchResult = 5;
627
+ ts_1 = expected.fields[0];
628
+ vs = value.fields[0];
629
+ }
630
+ else {
631
+ matchResult = 9;
632
+ }
633
+ break;
634
+ }
635
+ case 17: {
636
+ if (value.tag === 16) {
637
+ matchResult = 6;
638
+ host = value.fields[0];
639
+ ts_2 = expected.fields[1];
640
+ }
641
+ else {
642
+ matchResult = 9;
643
+ }
644
+ break;
645
+ }
646
+ case 13: {
647
+ if (value.tag === 10) {
648
+ if (value.fields[2] != null) {
649
+ matchResult = 7;
650
+ caseName = value.fields[1];
651
+ cases = expected.fields[1];
652
+ v_4 = value.fields[2];
653
+ }
654
+ else {
655
+ matchResult = 9;
656
+ }
657
+ }
658
+ else {
659
+ matchResult = 9;
660
+ }
661
+ break;
662
+ }
663
+ case 9: {
664
+ if (value.tag === 8) {
665
+ matchResult = 8;
666
+ t_6 = expected.fields[1];
667
+ values_2 = value.fields[0];
668
+ }
669
+ else {
670
+ matchResult = 9;
671
+ }
672
+ break;
673
+ }
674
+ default:
675
+ matchResult = 9;
676
+ }
677
+ switch (matchResult) {
678
+ case 0: {
679
+ const option_3 = tryFind(name_1, definitions);
680
+ if (option_3 != null) {
681
+ definitions_mut = definitions;
682
+ expected_mut = option_3;
683
+ value_mut = value;
684
+ tagged_mut = tagged;
685
+ continue tagSignature;
686
+ }
687
+ break;
688
+ }
689
+ case 1: {
690
+ const stored = boundaryHandles.get(tagged);
691
+ if (!(typeof stored === 'undefined' || stored === null)) {
692
+ const handle = stored;
693
+ boundaryHandles.set(tagged, (new BoundaryHandle(handle.Value, handle.Context, expected)));
694
+ }
695
+ break;
696
+ }
697
+ case 2: {
698
+ const tags = tagged["values"];
699
+ iterateIndexed((i, v_1) => {
700
+ tagSignature(definitions, t_2, v_1, item(i, tags));
701
+ }, values);
702
+ break;
703
+ }
704
+ case 3: {
705
+ const tags_1 = tagged["values"];
706
+ iterateIndexed((i_1, tupledArg) => {
707
+ tagSignature(definitions, tupledArg[0], tupledArg[1], item(i_1, tags_1));
708
+ }, zip(ts, values_1));
709
+ break;
710
+ }
711
+ case 4: {
712
+ definitions_mut = definitions;
713
+ expected_mut = t_4;
714
+ value_mut = v_3;
715
+ tagged_mut = (tagged["value"]);
716
+ continue tagSignature;
717
+ break;
718
+ }
719
+ case 5: {
720
+ fields(ts_1, vs, tagged["fields"]);
721
+ break;
722
+ }
723
+ case 6: {
724
+ fields(ts_2, host.Fields, tagged["fields"]);
725
+ break;
726
+ }
727
+ case 7: {
728
+ const option_6 = flatten(tryFind(caseName, cases));
729
+ if (option_6 != null) {
730
+ definitions_mut = definitions;
731
+ expected_mut = option_6;
732
+ value_mut = v_4;
733
+ tagged_mut = (tagged["value"]);
734
+ continue tagSignature;
735
+ }
736
+ break;
737
+ }
738
+ case 8: {
739
+ const tags_2 = tagged["entries"];
740
+ iterateIndexed((i_2, tupledArg_1) => {
741
+ tagSignature(definitions, t_6, tupledArg_1[1], item(i_2, tags_2)["value"]);
742
+ }, toList(values_2));
743
+ break;
744
+ }
745
+ case 9: {
746
+ break;
747
+ }
748
+ }
749
+ break;
750
+ }
751
+ }
752
+
753
+ function buildExternal(definitions, definition) {
754
+ return withStructuredErrors(() => {
755
+ const name = getRequiredProperty("name", definition);
756
+ const arity = intFromObj(getRequiredProperty("arity", definition)) | 0;
757
+ const scheme = getRequiredProperty("scheme", definition);
758
+ const invoke_1 = getRequiredProperty("invoke", definition);
759
+ if ((typeof invoke_1) !== "function") {
760
+ throw new Exception("invoke must be a JavaScript function");
761
+ }
762
+ return new ExternalFunction(name, scheme, (context, args) => {
763
+ const check = () => {
764
+ if (!context.IsActive()) {
765
+ throw new Exception("Expired invocation context");
766
+ }
767
+ context.CheckRuntime();
768
+ };
769
+ const checkHandle = (value_3) => {
770
+ let origin;
771
+ if (!(typeof value_3 === 'undefined' || value_3 === null) && ((typeof value_3) === "object")) {
772
+ const stored = boundaryHandles.get(value_3);
773
+ if (!(typeof stored === 'undefined' || stored === null)) {
774
+ const handle = stored;
775
+ const matchValue = handle.Context;
776
+ let matchResult, origin_2, origin_3;
777
+ if (matchValue == null) {
778
+ if (!(handle.Value.tag === 12)) {
779
+ matchResult = 2;
780
+ }
781
+ else {
782
+ matchResult = 3;
783
+ }
784
+ }
785
+ else if ((origin = matchValue, !(Object.is(origin.Session, context.Session)))) {
786
+ matchResult = 0;
787
+ origin_2 = matchValue;
788
+ }
789
+ else if (!matchValue.IsActive()) {
790
+ matchResult = 1;
791
+ origin_3 = matchValue;
792
+ }
793
+ else {
794
+ matchResult = 3;
795
+ }
796
+ switch (matchResult) {
797
+ case 0: {
798
+ throw new Exception("Foreign invocation handle");
799
+ break;
800
+ }
801
+ case 1: {
802
+ throw new Exception("Expired invocation handle");
803
+ break;
804
+ }
805
+ case 2: {
806
+ throw new Exception("Callable handles require their originating invocation context");
807
+ break;
808
+ }
809
+ case 3: {
810
+ break;
811
+ }
812
+ }
813
+ }
814
+ else if (typeof (hostValues.get(value_3)) === 'undefined' || (hostValues.get(value_3)) === null) {
815
+ if (Array.isArray(value_3)) {
816
+ value_3.forEach(checkHandle);
817
+ }
818
+ else {
819
+ const array_1 = Object.keys(value_3);
820
+ array_1.forEach((key) => {
821
+ checkHandle(value_3[key]);
822
+ });
823
+ }
824
+ }
825
+ }
826
+ };
827
+ const convert = (value_5) => {
828
+ if (value_5 != null && typeof value_5.then === 'function') {
829
+ throw new Exception("JavaScript externs must return synchronously; Promises are not supported");
830
+ }
831
+ checkHandle(value_5);
832
+ return valueFromJs(value_5);
833
+ };
834
+ let api;
835
+ const _value = {
836
+ apply: (fn, arguments$) => {
837
+ check();
838
+ const handleObject = boundaryHandles.get(fn);
839
+ const fnValue = convert(fn);
840
+ const arguments$_1 = map(convert, ofArray(arguments$));
841
+ const signature = (typeof handleObject === 'undefined' || handleObject === null) ? undefined : handleObject.Signature;
842
+ let result;
843
+ if (signature == null) {
844
+ throw new Exception("Callback has no declared function signature");
845
+ }
846
+ else if (isEmpty(Types_ftvType(signature))) {
847
+ const signature_2 = signature;
848
+ result = validateCall(definitions, signature_2, arguments$_1, () => fold(context.Apply, fnValue, arguments$_1));
849
+ }
850
+ else {
851
+ throw new Exception("Callback invocation requires a closed function type; use HostFunctions.create");
852
+ }
853
+ const tagged = valueToTaggedWithContext(context, result);
854
+ const resultType = (count_mut, t_mut) => {
855
+ resultType:
856
+ while (true) {
857
+ const count = count_mut, t = t_mut;
858
+ if (count === 0) {
859
+ return t;
860
+ }
861
+ else if (t.tag === 11) {
862
+ count_mut = (count - 1);
863
+ t_mut = t.fields[1];
864
+ continue resultType;
865
+ }
866
+ else {
867
+ return undefined;
868
+ }
869
+ break;
870
+ }
871
+ };
872
+ let option_3;
873
+ const binder = curry2(resultType)(length(arguments$_1));
874
+ const option_1 = signature;
875
+ option_3 = ((option_1 != null) ? binder(option_1) : undefined);
876
+ if (option_3 != null) {
877
+ tagSignature(definitions, option_3, result, tagged);
878
+ }
879
+ return tagged;
880
+ },
881
+ spawnTask: (fn_1) => {
882
+ check();
883
+ return valueToTaggedWithContext(context, context.SpawnTask(convert(fn_1)));
884
+ },
885
+ awaitTask: (task) => {
886
+ check();
887
+ return valueToTaggedWithContext(context, context.AwaitTask(convert(task)));
888
+ },
889
+ checkRuntime: () => {
890
+ check();
891
+ },
892
+ };
893
+ api = (Object.freeze(_value));
894
+ const taggedArgs = map((value_9) => valueToTaggedWithContext(context, value_9), args);
895
+ const annotate = (signature_4_mut, values_mut, tags_mut) => {
896
+ annotate:
897
+ while (true) {
898
+ const signature_4 = signature_4_mut, values = values_mut, tags = tags_mut;
899
+ let matchResult_1, rest, t_3, tag, ts, v, vs;
900
+ if (signature_4.tag === 11) {
901
+ if (!isEmpty_1(values)) {
902
+ if (!isEmpty_1(tags)) {
903
+ matchResult_1 = 0;
904
+ rest = signature_4.fields[1];
905
+ t_3 = signature_4.fields[0];
906
+ tag = head(tags);
907
+ ts = tail(tags);
908
+ v = head(values);
909
+ vs = tail(values);
910
+ }
911
+ else {
912
+ matchResult_1 = 1;
913
+ }
914
+ }
915
+ else {
916
+ matchResult_1 = 1;
917
+ }
918
+ }
919
+ else {
920
+ matchResult_1 = 1;
921
+ }
922
+ switch (matchResult_1) {
923
+ case 0: {
924
+ tagSignature(definitions, t_3, v, tag);
925
+ signature_4_mut = rest;
926
+ values_mut = vs;
927
+ tags_mut = ts;
928
+ continue annotate;
929
+ break;
930
+ }
931
+ case 1: {
932
+ break;
933
+ }
934
+ }
935
+ break;
936
+ }
937
+ };
938
+ annotate(scheme.fields[1], args, taggedArgs);
939
+ return convert(invoke_1(toArray(taggedArgs), api));
940
+ }, arity);
941
+ });
942
+ }
943
+
944
+ function validateRegistration(registration_1) {
945
+ const definitions = typeDefinitions(registration_1, empty());
946
+ const validateType = (t_mut) => {
947
+ validateType:
948
+ while (true) {
949
+ const t = t_mut;
950
+ let matchResult, name_1, t_1, a, b, ts, fields, cases;
951
+ switch (t.tag) {
952
+ case 12: {
953
+ if (!FSharpMap__ContainsKey(definitions, t.fields[0])) {
954
+ matchResult = 0;
955
+ name_1 = t.fields[0];
956
+ }
957
+ else {
958
+ matchResult = 6;
959
+ }
960
+ break;
961
+ }
962
+ case 5: {
963
+ matchResult = 1;
964
+ t_1 = t.fields[0];
965
+ break;
966
+ }
967
+ case 10: {
968
+ matchResult = 1;
969
+ t_1 = t.fields[0];
970
+ break;
971
+ }
972
+ case 6: {
973
+ matchResult = 1;
974
+ t_1 = t.fields[0];
975
+ break;
976
+ }
977
+ case 11: {
978
+ matchResult = 2;
979
+ a = t.fields[0];
980
+ b = t.fields[1];
981
+ break;
982
+ }
983
+ case 9: {
984
+ matchResult = 2;
985
+ a = t.fields[0];
986
+ b = t.fields[1];
987
+ break;
988
+ }
989
+ case 7: {
990
+ matchResult = 3;
991
+ ts = t.fields[0];
992
+ break;
993
+ }
994
+ case 8: {
995
+ matchResult = 4;
996
+ fields = t.fields[0];
997
+ break;
998
+ }
999
+ case 17: {
1000
+ matchResult = 4;
1001
+ fields = t.fields[1];
1002
+ break;
1003
+ }
1004
+ case 18: {
1005
+ matchResult = 4;
1006
+ fields = t.fields[1];
1007
+ break;
1008
+ }
1009
+ case 13: {
1010
+ matchResult = 5;
1011
+ cases = t.fields[1];
1012
+ break;
1013
+ }
1014
+ default:
1015
+ matchResult = 6;
1016
+ }
1017
+ switch (matchResult) {
1018
+ case 0: {
1019
+ throw new Exception(concat("Unknown registered type \'", name_1, "\'"));
1020
+ break;
1021
+ }
1022
+ case 1: {
1023
+ t_mut = t_1;
1024
+ continue validateType;
1025
+ break;
1026
+ }
1027
+ case 2: {
1028
+ validateType(a);
1029
+ t_mut = b;
1030
+ continue validateType;
1031
+ break;
1032
+ }
1033
+ case 3: {
1034
+ iterate_1(validateType, ts);
1035
+ break;
1036
+ }
1037
+ case 4: {
1038
+ iterate((_arg, t_2) => {
1039
+ validateType(t_2);
1040
+ }, fields);
1041
+ break;
1042
+ }
1043
+ case 5: {
1044
+ iterate((_arg_1, t_3) => {
1045
+ const option = t_3;
1046
+ if (option != null) {
1047
+ validateType(option);
1048
+ }
1049
+ }, cases);
1050
+ break;
1051
+ }
1052
+ case 6: {
1053
+ break;
1054
+ }
1055
+ }
1056
+ break;
1057
+ }
1058
+ };
1059
+ iterate((_arg_2, t_4) => {
1060
+ validateType(t_4);
1061
+ if (!isEmpty(Types_ftvType(t_4))) {
1062
+ throw new Exception("Host descriptors require closed field and payload types");
1063
+ }
1064
+ }, definitions);
1065
+ const enumerator = getEnumerator(registration_1.Types);
1066
+ try {
1067
+ while (enumerator["System.Collections.IEnumerator.MoveNext"]()) {
1068
+ iterate((_arg_3, t_5) => {
1069
+ if (!isEmpty(Types_ftvType(t_5))) {
1070
+ throw new Exception("Host descriptors require closed field types");
1071
+ }
1072
+ }, enumerator["System.Collections.Generic.IEnumerator`1.get_Current"]().Fields);
1073
+ }
1074
+ }
1075
+ finally {
1076
+ disposeSafe(enumerator);
1077
+ }
1078
+ const enumerator_1 = getEnumerator(registration_1.Unions);
1079
+ try {
1080
+ while (enumerator_1["System.Collections.IEnumerator.MoveNext"]()) {
1081
+ iterate((_arg_4, t_6) => {
1082
+ const option_2 = t_6;
1083
+ if (option_2 != null) {
1084
+ if (!isEmpty(Types_ftvType(option_2))) {
1085
+ throw new Exception("Host descriptors require closed union payload types");
1086
+ }
1087
+ }
1088
+ }, enumerator_1["System.Collections.Generic.IEnumerator`1.get_Current"]().Cases);
1089
+ }
1090
+ }
1091
+ finally {
1092
+ disposeSafe(enumerator_1);
1093
+ }
1094
+ let names = empty_1({
1095
+ Compare: (x, y) => (comparePrimitives(x, y) | 0),
1096
+ });
1097
+ const enumerator_2 = getEnumerator(registration_1.Functions);
1098
+ try {
1099
+ while (enumerator_2["System.Collections.IEnumerator.MoveNext"]()) {
1100
+ const fn = enumerator_2["System.Collections.Generic.IEnumerator`1.get_Current"]();
1101
+ if (isNullOrWhiteSpace(fn.Name) ? true : FSharpSet__Contains(names, fn.Name)) {
1102
+ throw new Exception(concat("Host function name conflict: \'", fn.Name, "\'"));
1103
+ }
1104
+ if (fn.Arity < 0) {
1105
+ throw new Exception("Host function arity must not be negative");
1106
+ }
1107
+ names = FSharpSet__Add(names, fn.Name);
1108
+ const patternInput = fn.Scheme;
1109
+ const t_8 = patternInput.fields[1];
1110
+ const accepts = (count_mut, t_9_mut) => {
1111
+ accepts:
1112
+ while (true) {
1113
+ const count = count_mut, t_9 = t_9_mut;
1114
+ if (count === 0) {
1115
+ return true;
1116
+ }
1117
+ else if (t_9.tag === 11) {
1118
+ count_mut = (count - 1);
1119
+ t_9_mut = t_9.fields[1];
1120
+ continue accepts;
1121
+ }
1122
+ else {
1123
+ return false;
1124
+ }
1125
+ break;
1126
+ }
1127
+ };
1128
+ if (!accepts(fn.Arity, t_8)) {
1129
+ throw new Exception(`Scheme does not accept ${fn.Arity} arguments for '${fn.Name}'`);
1130
+ }
1131
+ if (!isSubset(Types_ftvType(t_8), ofList_1(patternInput.fields[0], {
1132
+ Compare: (x_1, y_1) => (comparePrimitives(x_1, y_1) | 0),
1133
+ }))) {
1134
+ throw new Exception(concat("Unbound scheme variables for \'", fn.Name, "\'"));
1135
+ }
1136
+ validateType(t_8);
1137
+ }
1138
+ }
1139
+ finally {
1140
+ disposeSafe(enumerator_2);
1141
+ }
1142
+ return new ExtensionRegistration(registration_1.Types, registration_1.Unions, map((fn_1) => {
1143
+ const definition = externDefinitions.get(fn_1);
1144
+ if (typeof definition === 'undefined' || definition === null) {
1145
+ return fn_1;
1146
+ }
1147
+ else {
1148
+ const prepared = buildExternal(definitions, definition);
1149
+ externDefinitions.set(prepared, definition);
1150
+ return prepared;
1151
+ }
1152
+ }, registration_1.Functions));
1153
+ }
1154
+
1155
+ function registrationFromHandle(value) {
1156
+ const stored = registrations.get(value);
1157
+ if (typeof stored === 'undefined' || stored === null) {
1158
+ throw new Exception("Expected an extension registration handle");
1159
+ }
1160
+ return stored;
1161
+ }
1162
+
1163
+ function registrationOverride(fallback, value) {
1164
+ if (typeof value === 'undefined' || value === null) {
1165
+ return fallback;
1166
+ }
1167
+ else if (Array.isArray(value)) {
1168
+ return validateRegistration(new ExtensionRegistration(fallback.Types, fallback.Unions, externsFromArray(value)));
460
1169
  }
461
1170
  else {
462
- return externsFromArray(value_18(matchValue));
1171
+ return registrationFromHandle(value);
463
1172
  }
464
1173
  }
465
1174
 
1175
+ function registrationFromOptions(options) {
1176
+ let option_1;
1177
+ let registration_1;
1178
+ const matchValue = tryGetProperty("registration", options);
1179
+ registration_1 = ((matchValue == null) ? empty_2 : registrationFromHandle(value_15(matchValue)));
1180
+ return validateRegistration(new ExtensionRegistration(registration_1.Types, registration_1.Unions, append(registration_1.Functions, defaultArg((option_1 = tryGetProperty("externs", options), (option_1 != null) ? externsFromArray(value_15(option_1)) : undefined), empty()))));
1181
+ }
1182
+
466
1183
  function optionString(name, fallback, options) {
467
1184
  const matchValue = tryGetProperty(name, options);
468
1185
  if (matchValue == null) {
469
1186
  return fallback;
470
1187
  }
471
1188
  else {
472
- return value_18(matchValue);
1189
+ return value_15(matchValue);
473
1190
  }
474
1191
  }
475
1192
 
@@ -482,21 +1199,21 @@ function resolverFromOptions(options) {
482
1199
  return undefined;
483
1200
  }
484
1201
  else {
485
- const sources = value_18(sourceMap);
1202
+ const sources = value_15(sourceMap);
486
1203
  const value_1 = sources[path];
487
1204
  return (typeof value_1 === 'undefined' || value_1 === null) ? undefined : value_1;
488
1205
  }
489
1206
  }
490
1207
  else {
491
- const resolve = value_18(callback);
1208
+ const resolve = value_15(callback);
492
1209
  const value = resolve(path);
493
1210
  return (typeof value === 'undefined' || value === null) ? undefined : value;
494
1211
  }
495
1212
  };
496
1213
  }
497
1214
 
498
- function parseSource(source, options, externs) {
499
- return new ParsedProgramHandle("program", parseProgramFromSourceWithIncludesResolver(optionString("rootDirectory", "/", options), optionString("entryFile", "/main.fss", options), source, resolverFromOptions(options)), externs);
1215
+ function parseSource(source, options, registration_1) {
1216
+ return new ParsedProgramHandle("program", parseProgramFromSourceWithIncludesResolver(optionString("rootDirectory", "/", options), optionString("entryFile", "/main.fss", options), source, resolverFromOptions(options)), registration_1);
500
1217
  }
501
1218
 
502
1219
  function isCallable(value) {
@@ -561,8 +1278,8 @@ function hasExpression(statements) {
561
1278
  }, statements);
562
1279
  }
563
1280
 
564
- function loadTyped(typed, externs) {
565
- const state = evalProgramWithExternsState(externs, typed);
1281
+ function loadTyped(typed, registration_1) {
1282
+ const state = evalProgramWithRegistrationState(registration_1, typed);
566
1283
  const exportedNames = sort(List_distinct(declaredExportedNames(typed), {
567
1284
  Equals: (x, y) => (x === y),
568
1285
  GetHashCode: (x) => (stringHash(x) | 0),
@@ -601,9 +1318,10 @@ function loadTyped(typed, externs) {
601
1318
  return !isCallable(matchValue_1);
602
1319
  }
603
1320
  }, exportedNames);
604
- return new LoadedScriptHandle("loaded", state.TypeDefs, state.Env, functionNames, functionSet, functions, valueNames, ofList_1(valueNames, {
1321
+ const valueSet = ofList_1(valueNames, {
605
1322
  Compare: (x_4, y_4) => (comparePrimitives(x_4, y_4) | 0),
606
- }), ofList(choose((name_3) => {
1323
+ });
1324
+ const values = ofList(choose((name_3) => {
607
1325
  const option_3 = FSharpMap__TryFind(state.Env, name_3);
608
1326
  if (option_3 != null) {
609
1327
  return [name_3, option_3];
@@ -613,32 +1331,70 @@ function loadTyped(typed, externs) {
613
1331
  }
614
1332
  }, valueNames), {
615
1333
  Compare: (x_5, y_5) => (comparePrimitives(x_5, y_5) | 0),
616
- }), state.LastValue, externs);
1334
+ });
1335
+ return new LoadedScriptHandle("loaded", state.TypeDefs, state.Env, functionNames, functionSet, functions, ofList(collect((_arg) => {
1336
+ let matchResult, name_4, t, bindings;
1337
+ switch (_arg.tag) {
1338
+ case 1: {
1339
+ if (_arg.fields[4]) {
1340
+ matchResult = 0;
1341
+ name_4 = _arg.fields[0];
1342
+ t = _arg.fields[2];
1343
+ }
1344
+ else {
1345
+ matchResult = 2;
1346
+ }
1347
+ break;
1348
+ }
1349
+ case 3: {
1350
+ if (_arg.fields[1]) {
1351
+ matchResult = 1;
1352
+ bindings = _arg.fields[0];
1353
+ }
1354
+ else {
1355
+ matchResult = 2;
1356
+ }
1357
+ break;
1358
+ }
1359
+ default:
1360
+ matchResult = 2;
1361
+ }
1362
+ switch (matchResult) {
1363
+ case 0:
1364
+ return singleton([name_4, t]);
1365
+ case 1:
1366
+ return map((tupledArg) => [tupledArg[0], tupledArg[2]], bindings);
1367
+ default:
1368
+ return empty();
1369
+ }
1370
+ }, typed), {
1371
+ Compare: (x_6, y_6) => (comparePrimitives(x_6, y_6) | 0),
1372
+ }), valueNames, valueSet, values, state.LastValue, registration_1);
617
1373
  }
618
1374
 
619
1375
  export function parse(source, options) {
620
- return withStructuredErrors(() => parseSource(source, options, externsFromOptions(options)));
1376
+ return withStructuredErrors(() => parseSource(source, options, registrationFromOptions(options)));
621
1377
  }
622
1378
 
623
1379
  export function infer(program, externs) {
624
1380
  return withStructuredErrors(() => {
625
1381
  const parsed = program;
626
- const externs_1 = (typeof externs === 'undefined' || externs === null) ? parsed.externs : externsFromArray(externs);
627
- return new TypedProgramHandle("typedProgram", inferProgramWithExterns(externs_1, parsed.program), externs_1);
1382
+ const registration_1 = registrationOverride(parsed.registration, externs);
1383
+ return new TypedProgramHandle("typedProgram", inferProgramWithRegistration(registration_1, parsed.program), registration_1);
628
1384
  });
629
1385
  }
630
1386
 
631
1387
  export function evaluate(typedProgram, externs) {
632
1388
  return withStructuredErrors(() => {
633
1389
  const typed = typedProgram;
634
- return valueToTagged(evalProgramWithExterns((typeof externs === 'undefined' || externs === null) ? typed.externs : externsFromArray(externs), typed.typedProgram));
1390
+ return valueToTagged(evalProgramWithRegistration(registrationOverride(typed.registration, externs), typed.typedProgram));
635
1391
  });
636
1392
  }
637
1393
 
638
1394
  export function load(source, options) {
639
1395
  return withStructuredErrors(() => {
640
- const externs = externsFromOptions(options);
641
- return loadTyped(inferProgramWithExterns(externs, parseSource(source, options, externs).program), externs);
1396
+ const registration_1 = registrationFromOptions(options);
1397
+ return loadTyped(inferProgramWithRegistration(registration_1, parseSource(source, options, registration_1).program), registration_1);
642
1398
  });
643
1399
  }
644
1400
 
@@ -648,15 +1404,15 @@ export function run(source, options) {
648
1404
 
649
1405
  export function createSession(options) {
650
1406
  return withStructuredErrors(() => {
651
- const externs = externsFromOptions(options);
652
- return new SessionHandle("session", create(externs), options, externs);
1407
+ const registration_1 = registrationFromOptions(options);
1408
+ return new SessionHandle("session", createWithRegistration(registration_1), options, registration_1);
653
1409
  });
654
1410
  }
655
1411
 
656
1412
  export function resetSession(session) {
657
1413
  return withStructuredErrors(() => {
658
1414
  const session_1 = session;
659
- session_1.interactiveSession = create(session_1.externs);
1415
+ session_1.interactiveSession = createWithRegistration(session_1.registration);
660
1416
  return session_1;
661
1417
  });
662
1418
  }
@@ -664,7 +1420,7 @@ export function resetSession(session) {
664
1420
  export function submit(session, source) {
665
1421
  return withStructuredErrors(() => {
666
1422
  const session_1 = session;
667
- const parsed = parseSource(source, session_1.options, session_1.externs);
1423
+ const parsed = parseSource(source, session_1.options, session_1.registration);
668
1424
  const submission = submit_1(session_1.interactiveSession, parsed.program);
669
1425
  session_1.interactiveSession = submission.Session;
670
1426
  const state = submission.State;
@@ -708,7 +1464,9 @@ export function invoke(loaded, name, args) {
708
1464
  throw new EvalException(new EvalError$(concat("Unknown exported function \'", name, "\'"), new Span(new Position(undefined, 0, 0), new Position(undefined, 0, 0))));
709
1465
  }
710
1466
  }
711
- return valueToTagged(invokeValue(loaded_1.typeDefs, FSharpMap__get_Item(loaded_1.exportedFunctions, name), (typeof args === 'undefined' || args === null) ? empty() : map(valueFromJs, ofArray(args))));
1467
+ const fnValue = FSharpMap__get_Item(loaded_1.exportedFunctions, name);
1468
+ const values = (typeof args === 'undefined' || args === null) ? empty() : map(valueFromJs, ofArray(args));
1469
+ return valueToTagged(validateCall(loaded_1.typeDefs, FSharpMap__get_Item(loaded_1.exportedFunctionTypes, name), values, () => invokeValue(loaded_1.typeDefs, fnValue, values)));
712
1470
  });
713
1471
  }
714
1472
 
@@ -731,30 +1489,257 @@ export const T = {
731
1489
  bool: Type.TBool,
732
1490
  string: Type.TString,
733
1491
  typeToken: Type.TTypeToken,
1492
+ named: (name) => (new Type(/* TNamed */ 12, [name])),
734
1493
  var: (value) => (new Type(/* TVar */ 15, [intFromObj(value)])),
735
1494
  list: (value_1) => (new Type(/* TList */ 5, [value_1])),
736
1495
  task: (value_2) => (new Type(/* TTask */ 6, [value_2])),
737
1496
  option: (value_3) => (new Type(/* TOption */ 10, [value_3])),
738
1497
  map: (value_4) => (new Type(/* TMap */ 9, [Type.TString, value_4])),
739
- tuple: (values) => (new Type(/* TTuple */ 7, [map((value_6) => value_6, ofArray(values))])),
740
- record: (fields) => (new Type(/* TRecord */ 8, [ofList(map((name) => [name, fields[name]], ofArray(Object.keys(fields))), {
1498
+ mapOf: (key, value_5) => (new Type(/* TMap */ 9, [key, value_5])),
1499
+ tuple: (values) => (new Type(/* TTuple */ 7, [map((value_7) => value_7, ofArray(values))])),
1500
+ record: (fields) => (new Type(/* TRecord */ 8, [ofList(map((name_1) => [name_1, fields[name_1]], ofArray(Object.keys(fields))), {
741
1501
  Compare: (x, y) => (comparePrimitives(x, y) | 0),
742
1502
  })])),
743
1503
  func: (left, right) => (new Type(/* TFun */ 11, [left, right])),
744
- scheme: (value_8) => (new Scheme(empty(), value_8)),
745
- forall: (vars, value_9) => (new Scheme(map((value_11) => (intFromObj(value_11) | 0), ofArray(vars)), value_9)),
1504
+ scheme: (value_9) => (new Scheme(empty(), value_9)),
1505
+ forall: (vars, value_10) => (new Scheme(map((value_12) => (intFromObj(value_12) | 0), ofArray(vars)), value_10)),
746
1506
  };
747
1507
 
748
1508
  export function extern(definition) {
1509
+ const fn = buildExternal(empty_3({
1510
+ Compare: (x, y) => (comparePrimitives(x, y) | 0),
1511
+ }), definition);
1512
+ let copied;
1513
+ const _value = {
1514
+ name: fn.Name,
1515
+ arity: fn.Arity,
1516
+ scheme: fn.Scheme,
1517
+ invoke: getRequiredProperty("invoke", definition),
1518
+ };
1519
+ copied = (Object.freeze(_value));
1520
+ externDefinitions.set(fn, copied);
1521
+ return fn;
1522
+ }
1523
+
1524
+ function fieldTypes(fields) {
1525
+ if (((typeof fields === 'undefined' || fields === null) ? true : ((typeof fields) !== "object")) ? true : (Array.isArray(fields))) {
1526
+ throw new Exception("fields must be an object of type descriptors");
1527
+ }
1528
+ return ofList(map((name) => {
1529
+ if (isNullOrWhiteSpace(name)) {
1530
+ throw new Exception("Visible field names must not be empty");
1531
+ }
1532
+ return [name, fields[name]];
1533
+ }, ofArray(Object.keys(fields))), {
1534
+ Compare: (x, y) => (comparePrimitives(x, y) | 0),
1535
+ });
1536
+ }
1537
+
1538
+ function describeType(definition) {
1539
+ let value_1, _value;
1540
+ const name = getRequiredProperty("name", definition);
1541
+ const fields_1 = fieldTypes(getRequiredProperty("fields", definition));
1542
+ let constructible;
1543
+ const matchValue = tryGetProperty("scriptConstructible", definition);
1544
+ if (matchValue != null) {
1545
+ if ((value_1 = value_15(matchValue), (typeof value_1) === "boolean")) {
1546
+ const value_2 = value_15(matchValue);
1547
+ constructible = value_2;
1548
+ }
1549
+ else {
1550
+ throw new Exception("scriptConstructible must be a boolean");
1551
+ }
1552
+ }
1553
+ else {
1554
+ constructible = false;
1555
+ }
1556
+ typeDefinitions(new ExtensionRegistration(singleton(new HostTypeDescriptor(name, fields_1, !constructible)), empty_2.Unions, empty_2.Functions), empty());
1557
+ const _value_1 = {
1558
+ name: name,
1559
+ fields: (_value = propertiesObject(map((tupledArg) => [tupledArg[0], tupledArg[1]], toList(fields_1))), (() => { const visit = v => { if (v && typeof v === 'object' && !Object.isFrozen(v)) { for (const key of Object.keys(v)) visit(v[key]); Object.freeze(v); } }; visit(_value); return _value; })()),
1560
+ scriptConstructible: constructible,
1561
+ };
1562
+ return Object.freeze(_value_1);
1563
+ }
1564
+
1565
+ function describeUnion(definition) {
1566
+ const name = getRequiredProperty("name", definition);
1567
+ const cases = getRequiredProperty("cases", definition);
1568
+ let copied;
1569
+ const _value = propertiesObject(ofArray(map_1((k) => [k, cases[k]], Object.keys(cases))));
1570
+ copied = (Object.freeze(_value));
1571
+ typeDefinitions(new ExtensionRegistration(empty_2.Types, singleton(new HostUnionDescriptor(name, ofList(map((k_1) => {
1572
+ const t = copied[k_1];
1573
+ return [k_1, (typeof t === 'undefined' || t === null) ? undefined : t];
1574
+ }, ofArray(Object.keys(copied))), {
1575
+ Compare: (x, y) => (comparePrimitives(x, y) | 0),
1576
+ }))), empty_2.Functions), empty());
1577
+ (() => { const visit = v => { if (v && typeof v === 'object' && !Object.isFrozen(v)) { for (const key of Object.keys(v)) visit(v[key]); Object.freeze(v); } }; visit(copied); return copied; })();
1578
+ const _value_1 = {
1579
+ name: name,
1580
+ cases: copied,
1581
+ };
1582
+ return Object.freeze(_value_1);
1583
+ }
1584
+
1585
+ /**
1586
+ * Build a registration from explicit JavaScript descriptors and extern functions.
1587
+ */
1588
+ export function registration(definition) {
749
1589
  return withStructuredErrors(() => {
750
- const name = getRequiredProperty("name", definition);
751
- const arity = intFromObj(getRequiredProperty("arity", definition)) | 0;
752
- const scheme = getRequiredProperty("scheme", definition);
753
- const invoke_1 = getRequiredProperty("invoke", definition);
754
- return new ExternalFunction(name, scheme, (_arg, args) => {
755
- let _arg_1;
756
- return valueFromJs((_arg_1 = toArray(map(valueToTagged, args)), invoke_1(_arg_1)));
757
- }, arity);
1590
+ const entries = (name) => {
1591
+ let option_1;
1592
+ return ofArray(defaultArg((option_1 = tryGetProperty(name, definition), (option_1 != null) ? value_15(option_1) : undefined), []));
1593
+ };
1594
+ const value_6 = validateRegistration(new ExtensionRegistration(map((d) => {
1595
+ const d_1 = describeType(d);
1596
+ return new HostTypeDescriptor(d_1["name"], fieldTypes(d_1["fields"]), !(d_1["scriptConstructible"]));
1597
+ }, entries("types")), map((d_2) => {
1598
+ const name_1 = getRequiredProperty("name", d_2);
1599
+ const cases = getRequiredProperty("cases", d_2);
1600
+ return new HostUnionDescriptor(name_1, ofList(map((k) => {
1601
+ const t = cases[k];
1602
+ return [k, (typeof t === 'undefined' || t === null) ? undefined : t];
1603
+ }, ofArray(Object.keys(cases))), {
1604
+ Compare: (x, y) => (comparePrimitives(x, y) | 0),
1605
+ }));
1606
+ }, entries("unions")), map((value_5) => value_5, entries("functions"))));
1607
+ let handle;
1608
+ const _value = {
1609
+ kind: "registration",
1610
+ };
1611
+ handle = (Object.freeze(_value));
1612
+ registrations.set(handle, value_6);
1613
+ return handle;
1614
+ });
1615
+ }
1616
+
1617
+ function validateHostValue(definitions, expected, value) {
1618
+ validateCall(definitions, new Type(/* TFun */ 11, [expected, Type.TUnit]), singleton(value), () => Value.VUnit);
1619
+ }
1620
+
1621
+ function wrapHost(registrationHandle, typeName, fields, payload) {
1622
+ const registration_1 = registrationFromHandle(registrationHandle);
1623
+ let descriptor;
1624
+ const option_1 = tryFind_1((d) => (d.Name === typeName), registration_1.Types);
1625
+ if (option_1 != null) {
1626
+ descriptor = option_1;
1627
+ }
1628
+ else {
1629
+ throw new Exception(concat("Unknown registered type \'", typeName, "\'"));
1630
+ }
1631
+ const values = ofList(map((k) => [k, valueFromJs(fields[k])], ofArray(Object.keys(fields))), {
1632
+ Compare: (x, y) => (comparePrimitives(x, y) | 0),
758
1633
  });
1634
+ if (!ofSeq(FSharpMap__get_Keys(values), {
1635
+ Compare: (x_1, y_1) => (comparePrimitives(x_1, y_1) | 0),
1636
+ }).Equals(ofSeq(FSharpMap__get_Keys(descriptor.Fields), {
1637
+ Compare: (x_2, y_2) => (comparePrimitives(x_2, y_2) | 0),
1638
+ }))) {
1639
+ throw new Exception(concat("Visible fields do not match \'", typeName, "\'"));
1640
+ }
1641
+ let value_2;
1642
+ if (descriptor.HostManaged) {
1643
+ value_2 = create(registration_1, typeName, values, payload);
1644
+ }
1645
+ else {
1646
+ if (!(typeof payload === 'undefined' || payload === null)) {
1647
+ throw new Exception("Script-constructible types cannot carry hidden payloads");
1648
+ }
1649
+ const value_1 = new Value(/* VRecord */ 7, [values]);
1650
+ validateHostValue(typeDefinitions(registration_1, empty()), new Type(/* TNamed */ 12, [typeName]), value_1);
1651
+ value_2 = value_1;
1652
+ }
1653
+ validateHostValue(typeDefinitions(registration_1, empty()), new Type(/* TNamed */ 12, [typeName]), value_2);
1654
+ return valueToTagged(value_2);
1655
+ }
1656
+
1657
+ function unwrapHost(registrationHandle, typeName, value) {
1658
+ const registration_1 = registrationFromHandle(registrationHandle);
1659
+ const definitions = typeDefinitions(registration_1, empty());
1660
+ if (!exists((d) => (d.Name === typeName), registration_1.Types)) {
1661
+ throw new Exception(concat("Unknown registered type \'", typeName, "\'"));
1662
+ }
1663
+ const value_1 = valueFromJs(value);
1664
+ validateHostValue(definitions, new Type(/* TNamed */ 12, [typeName]), value_1);
1665
+ switch (value_1.tag) {
1666
+ case 16:
1667
+ return value_1.fields[0].Payload;
1668
+ case 7: {
1669
+ const fields = value_1.fields[0];
1670
+ const descriptor = find((d_1) => (d_1.Name === typeName), registration_1.Types);
1671
+ if (FSharpMap__get_Count(fields) !== FSharpMap__get_Count(descriptor.Fields)) {
1672
+ throw new Exception(concat("Visible fields do not match \'", typeName, "\'"));
1673
+ }
1674
+ return propertiesObject(map((tupledArg) => [tupledArg[0], valueToTagged(tupledArg[1])], toList(fields)));
1675
+ }
1676
+ default:
1677
+ throw new Exception(concat("Expected registered type \'", typeName, "\'"));
1678
+ }
1679
+ }
1680
+
1681
+ function wrapUnion(registrationHandle, typeName, caseName, payload) {
1682
+ const registration_1 = registrationFromHandle(registrationHandle);
1683
+ if (tryFind_1((d) => (d.Name === typeName), registration_1.Unions) == null) {
1684
+ throw new Exception(concat("Unknown registered union \'", typeName, "\'"));
1685
+ }
1686
+ const value = new Value(/* VUnionCase */ 10, [typeName, caseName, (typeof payload === 'undefined' || payload === null) ? undefined : valueFromJs(payload)]);
1687
+ validateHostValue(typeDefinitions(registration_1, empty()), new Type(/* TNamed */ 12, [typeName]), value);
1688
+ return valueToTagged(value);
1689
+ }
1690
+
1691
+ function unwrapUnion(registrationHandle, typeName, value) {
1692
+ const registration_1 = registrationFromHandle(registrationHandle);
1693
+ if (!exists((d) => (d.Name === typeName), registration_1.Unions)) {
1694
+ throw new Exception(concat("Unknown registered union \'", typeName, "\'"));
1695
+ }
1696
+ const value_1 = valueFromJs(value);
1697
+ validateHostValue(typeDefinitions(registration_1, empty()), new Type(/* TNamed */ 12, [typeName]), value_1);
1698
+ return valueToTagged(value_1);
759
1699
  }
760
1700
 
1701
+ export const HostTypes = (() => {
1702
+ const _value = {
1703
+ describe: (definition) => withStructuredErrors(() => describeType(definition)),
1704
+ describeUnion: (definition_1) => withStructuredErrors(() => describeUnion(definition_1)),
1705
+ wrap: (registration_1, name, fields, payload) => withStructuredErrors(() => wrapHost(registration_1, name, fields, payload)),
1706
+ unwrap: (registration_2, name_1, value) => withStructuredErrors(() => unwrapHost(registration_2, name_1, value)),
1707
+ wrapUnion: (registration_3, name_2, caseName, payload_1) => withStructuredErrors(() => wrapUnion(registration_3, name_2, caseName, payload_1)),
1708
+ unwrapUnion: (registration_4, name_3, value_1) => withStructuredErrors(() => unwrapUnion(registration_4, name_3, value_1)),
1709
+ fields: (value_2) => withStructuredErrors(() => {
1710
+ const matchValue = valueFromJs(value_2);
1711
+ const activePatternResult = $007CRecordFields$007C_$007C(matchValue);
1712
+ if (activePatternResult != null) {
1713
+ const fields_1 = activePatternResult;
1714
+ return propertiesObject(map((tupledArg) => [tupledArg[0], valueToTagged(tupledArg[1])], toList(fields_1)));
1715
+ }
1716
+ else {
1717
+ throw new Exception("Expected a record or host value");
1718
+ }
1719
+ }),
1720
+ };
1721
+ return Object.freeze(_value);
1722
+ })();
1723
+
1724
+ export const HostFunctions = (() => {
1725
+ const _value = {
1726
+ create: (definition) => withStructuredErrors(() => {
1727
+ const parameters = ofArray(getRequiredProperty("parameters", definition));
1728
+ if (isEmpty_1(parameters)) {
1729
+ throw new Exception("Use parameters: [T.unit] for a parameterless script function");
1730
+ }
1731
+ const signature = foldBack((argument, result_1) => (new Type(/* TFun */ 11, [argument, result_1])), parameters, getRequiredProperty("result", definition));
1732
+ if (!isEmpty(Types_ftvType(signature))) {
1733
+ throw new Exception("HostFunctions.create requires closed types; use extern for polymorphic schemes");
1734
+ }
1735
+ return extern({
1736
+ name: getRequiredProperty("name", definition),
1737
+ arity: length(parameters),
1738
+ scheme: new Scheme(empty(), signature),
1739
+ invoke: getRequiredProperty("invoke", definition),
1740
+ });
1741
+ }),
1742
+ };
1743
+ return Object.freeze(_value);
1744
+ })();
1745
+