@thomasfosterau/effect-parse 0.3.0 → 0.4.1

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 (142) hide show
  1. package/README.md +3 -1
  2. package/dist/Ascii.d.ts +0 -2
  3. package/dist/Ascii.d.ts.map +1 -1
  4. package/dist/Ascii.js +6 -6
  5. package/dist/Ascii.js.map +1 -1
  6. package/dist/Binary.d.ts +0 -2
  7. package/dist/Binary.d.ts.map +1 -1
  8. package/dist/Binary.js +1 -2
  9. package/dist/Bits.d.ts +0 -2
  10. package/dist/Bits.d.ts.map +1 -1
  11. package/dist/Bits.js +2 -3
  12. package/dist/Bits.js.map +1 -1
  13. package/dist/Compiler.d.ts +0 -2
  14. package/dist/Compiler.d.ts.map +1 -1
  15. package/dist/Compiler.js +1 -2
  16. package/dist/Encoding.d.ts +0 -2
  17. package/dist/Encoding.d.ts.map +1 -1
  18. package/dist/Encoding.js +1 -2
  19. package/dist/Expression.d.ts +0 -2
  20. package/dist/Expression.d.ts.map +1 -1
  21. package/dist/Expression.js +44 -8
  22. package/dist/Expression.js.map +1 -1
  23. package/dist/Input.d.ts +32 -4
  24. package/dist/Input.d.ts.map +1 -1
  25. package/dist/Input.js +47 -8
  26. package/dist/Input.js.map +1 -1
  27. package/dist/Nom.d.ts +0 -2
  28. package/dist/Nom.d.ts.map +1 -1
  29. package/dist/Nom.js +1 -2
  30. package/dist/ParseError.d.ts +2 -4
  31. package/dist/ParseError.d.ts.map +1 -1
  32. package/dist/ParseError.js +6 -9
  33. package/dist/ParseError.js.map +1 -1
  34. package/dist/Parser.d.ts +6 -4
  35. package/dist/Parser.d.ts.map +1 -1
  36. package/dist/Parser.js +26 -24
  37. package/dist/Parser.js.map +1 -1
  38. package/dist/ParserSchema.d.ts +0 -2
  39. package/dist/ParserSchema.d.ts.map +1 -1
  40. package/dist/ParserSchema.js +3 -4
  41. package/dist/ParserSchema.js.map +1 -1
  42. package/dist/ParserStream.d.ts +0 -2
  43. package/dist/ParserStream.d.ts.map +1 -1
  44. package/dist/ParserStream.js +17 -10
  45. package/dist/ParserStream.js.map +1 -1
  46. package/dist/Syntax.d.ts +0 -2
  47. package/dist/Syntax.d.ts.map +1 -1
  48. package/dist/Syntax.js +13 -11
  49. package/dist/Syntax.js.map +1 -1
  50. package/dist/Text.d.ts +0 -2
  51. package/dist/Text.d.ts.map +1 -1
  52. package/dist/Text.js +1 -2
  53. package/dist/Token.d.ts +0 -2
  54. package/dist/Token.d.ts.map +1 -1
  55. package/dist/Token.js +1 -2
  56. package/dist/internal/compiler/closure.d.ts +5 -2
  57. package/dist/internal/compiler/closure.d.ts.map +1 -1
  58. package/dist/internal/compiler/closure.js +160 -92
  59. package/dist/internal/compiler/closure.js.map +1 -1
  60. package/dist/internal/compiler/entries.d.ts +0 -2
  61. package/dist/internal/compiler/entries.d.ts.map +1 -1
  62. package/dist/internal/compiler/entries.js +6 -7
  63. package/dist/internal/compiler/entries.js.map +1 -1
  64. package/dist/internal/compiler/first.d.ts +0 -2
  65. package/dist/internal/compiler/first.d.ts.map +1 -1
  66. package/dist/internal/compiler/first.js +10 -10
  67. package/dist/internal/compiler/first.js.map +1 -1
  68. package/dist/internal/compiler/jit.d.ts +0 -2
  69. package/dist/internal/compiler/jit.d.ts.map +1 -1
  70. package/dist/internal/compiler/jit.js +52 -51
  71. package/dist/internal/compiler/jit.js.map +1 -1
  72. package/dist/internal/compiler/registry.d.ts +0 -2
  73. package/dist/internal/compiler/registry.d.ts.map +1 -1
  74. package/dist/internal/compiler/registry.js +1 -2
  75. package/dist/internal/compiler/sets.d.ts +2 -2
  76. package/dist/internal/compiler/sets.d.ts.map +1 -1
  77. package/dist/internal/compiler/sets.js +8 -3
  78. package/dist/internal/compiler/sets.js.map +1 -1
  79. package/dist/internal/entries.d.ts +0 -2
  80. package/dist/internal/entries.d.ts.map +1 -1
  81. package/dist/internal/entries.js +2 -4
  82. package/dist/internal/entries.js.map +1 -1
  83. package/dist/internal/key.d.ts +10 -0
  84. package/dist/internal/key.d.ts.map +1 -0
  85. package/dist/internal/key.js +11 -0
  86. package/dist/internal/key.js.map +1 -0
  87. package/dist/internal/node.d.ts +11 -4
  88. package/dist/internal/node.d.ts.map +1 -1
  89. package/dist/internal/node.js +15 -3
  90. package/dist/internal/node.js.map +1 -1
  91. package/dist/internal/numbers.d.ts +0 -2
  92. package/dist/internal/numbers.d.ts.map +1 -1
  93. package/dist/internal/numbers.js +1 -2
  94. package/dist/internal/resume.d.ts +5 -6
  95. package/dist/internal/resume.d.ts.map +1 -1
  96. package/dist/internal/resume.js +1 -2
  97. package/dist/internal/resume.js.map +1 -1
  98. package/dist/internal/run.d.ts +0 -2
  99. package/dist/internal/run.d.ts.map +1 -1
  100. package/dist/internal/run.js +2 -3
  101. package/dist/internal/run.js.map +1 -1
  102. package/dist/internal/stack.d.ts +0 -2
  103. package/dist/internal/stack.d.ts.map +1 -1
  104. package/dist/internal/stack.js +1 -2
  105. package/dist/internal/syntax.d.ts +30 -20
  106. package/dist/internal/syntax.d.ts.map +1 -1
  107. package/dist/internal/syntax.js +73 -66
  108. package/dist/internal/syntax.js.map +1 -1
  109. package/dist/internal/text.d.ts +5 -2
  110. package/dist/internal/text.d.ts.map +1 -1
  111. package/dist/internal/text.js +14 -5
  112. package/dist/internal/text.js.map +1 -1
  113. package/dist/internal/ties.d.ts +0 -2
  114. package/dist/internal/ties.d.ts.map +1 -1
  115. package/dist/internal/ties.js +1 -2
  116. package/dist/internal/tokens.d.ts +10 -9
  117. package/dist/internal/tokens.d.ts.map +1 -1
  118. package/dist/internal/tokens.js +4 -8
  119. package/dist/internal/tokens.js.map +1 -1
  120. package/package.json +7 -7
  121. package/src/Ascii.ts +6 -5
  122. package/src/Bits.ts +1 -1
  123. package/src/Expression.ts +7 -6
  124. package/src/Input.ts +50 -11
  125. package/src/ParseError.ts +13 -9
  126. package/src/Parser.ts +30 -25
  127. package/src/ParserSchema.ts +1 -1
  128. package/src/ParserStream.ts +23 -9
  129. package/src/Syntax.ts +12 -9
  130. package/src/internal/compiler/closure.ts +202 -90
  131. package/src/internal/compiler/entries.ts +14 -11
  132. package/src/internal/compiler/first.ts +9 -8
  133. package/src/internal/compiler/jit.ts +95 -74
  134. package/src/internal/compiler/sets.ts +7 -0
  135. package/src/internal/entries.ts +2 -2
  136. package/src/internal/key.ts +11 -0
  137. package/src/internal/node.ts +19 -2
  138. package/src/internal/resume.ts +5 -4
  139. package/src/internal/run.ts +1 -1
  140. package/src/internal/syntax.ts +78 -87
  141. package/src/internal/text.ts +24 -4
  142. package/src/internal/tokens.ts +20 -13
@@ -1,7 +1,6 @@
1
1
  import * as Result from "effect/Result";
2
2
  import { Parser } from "./Parser.js";
3
3
  import * as Schema from "effect/Schema";
4
- //#region src/ParserSchema.d.ts
5
4
  /**
6
5
  * The key of the annotation that says how a schema is written as text
7
6
  * ({@link Annotation}), namespaced to this package so it cannot collide with
@@ -226,5 +225,4 @@ export declare const toPrinter: <S extends Schema.ConstraintCodec<unknown, unkno
226
225
  export declare const fromSchema: <S extends Schema.ConstraintCodec<unknown, unknown, never, never> & Schema.Top>(schema: S, options?: {
227
226
  readonly encode?: ((value: S["Type"]) => string) | undefined;
228
227
  }) => Schema.decodeTo<Schema.toType<S>, Schema.String>;
229
- //#endregion
230
228
  //# sourceMappingURL=ParserSchema.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ParserSchema.d.ts","names":[],"sources":["../src/ParserSchema.ts"],"mappings":";;;;;;;;;;;;qBA4Da;;YAGD;cACE;;;;;;gBAME,iBAAiB;;;;;;;;;;iBAWhB,QAAQ;;WAEd,WAAW,OAAO;;WAElB;;;;;;;;iBASM,aAAa,WAAW,OAAO,SAAS,OAAO,QAAQ,IAAI,OAAO;;;;;;;;qBA0CtE,OAAQ,GAAG,GAAG,QAAQ,OAAO,GAAG,mBAAmB,UAAU,QAAQ,OAAK,aAAa;;;;;;;;;;iBAuBnF,QAAQ;;;;;;;WAOd,SAAS,OAAO;;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AK,MAAM,MAAM,YAAY,kCAAkC;GACnF,UAAU,OAAO,KAAK,MAAM,GAAG,YAAY,WAAW,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAsDzD,WAAY,UAAU,OAAO,4BACxC,QAAQ,MACP,OAAO,WAAW,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAmCf,YAAa,UAAU,OAAO,mDACzC,QAAQ,QACL,OAAO,cAAc,OAAO,eAAe,OAAO;;;;;;;;;;;;;;;;;;;;;;;;qBAmC1C,aAAc,UAAU,OAAO,kDAAkD,OAAO,KACnG,QAAQ,GACR;WAAqB,WAAW,OAAO;MACtC,OAAO,SAAS,OAAO,OAAO,IAAI,OAAO"}
@@ -4,10 +4,10 @@ import * as P from "./Parser.js";
4
4
  import { describeLiteral } from "./internal/tokens.js";
5
5
  import * as Token from "./Token.js";
6
6
  import * as Option from "effect/Option";
7
+ import * as Arr from "effect/Array";
7
8
  import * as Ascii from "./Ascii.js";
8
9
  import * as Effect from "effect/Effect";
9
10
  import { dual } from "effect/Function";
10
- import * as Arr from "effect/Array";
11
11
  import * as Match from "effect/Match";
12
12
  import * as MutableHashMap from "effect/MutableHashMap";
13
13
  import * as Order from "effect/Order";
@@ -16,7 +16,7 @@ import * as Schema from "effect/Schema";
16
16
  import * as SchemaAST from "effect/SchemaAST";
17
17
  import * as SchemaIssue from "effect/SchemaIssue";
18
18
  import * as SchemaTransformation from "effect/SchemaTransformation";
19
- //#region src/ParserSchema.ts
19
+ // src/ParserSchema.ts
20
20
  /**
21
21
  * Effect `Schema`s and parsers, in both directions.
22
22
  *
@@ -255,7 +255,7 @@ const withStop = (ctx, text) => {
255
255
  if (text === void 0 || text === "" || ctx.stop.includes(text[0])) return ctx;
256
256
  return {
257
257
  ...ctx,
258
- stop: Arr.sort([...ctx.stop, text[0]], Order.String).join("")
258
+ stop: Arr.sort([...ctx.stop.split(""), text[0]], Order.String).join("")
259
259
  };
260
260
  };
261
261
  const at = (ctx, key) => ({
@@ -679,7 +679,6 @@ const unionPrinter = (ast, ctx) => {
679
679
  return issue ?? unwritable(ctx, "No member of the union can write this value", value);
680
680
  };
681
681
  };
682
- //#endregion
683
682
  export { annotate, annotationKey, fromSchema, make, toParser, toPrinter };
684
683
 
685
684
  //# sourceMappingURL=ParserSchema.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ParserSchema.js","names":[],"sources":["../src/ParserSchema.ts"],"sourcesContent":["/**\n * Effect `Schema`s and parsers, in both directions.\n *\n * {@link make} turns a parser over strings into a schema that decodes a\n * `string` into the parser's output. Parse errors become schema issues\n * carrying the rendered `ParseError` message. Encoding needs a printer,\n * supplied as `encode`; without one, encoding is forbidden.\n *\n * {@link toParser} goes the other way: it derives a parser from a schema,\n * guided by annotations ({@link annotate}) that say how each part is\n * written. {@link toPrinter} derives the printer that writes that text, and\n * {@link fromSchema} wraps both as a schema.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n * import { Ascii, Parser, ParserSchema, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const Version = ParserSchema.make(\n * Parser.struct({\n * major: Ascii.decUint,\n * minor: Parser.preceded(Token.literal(\".\"), Ascii.decUint)\n * }),\n * { encode: ({ major, minor }) => `${major}.${minor}` }\n * )\n *\n * Schema.decodeUnknownSync(Version)(\"1.2\") // { major: 1, minor: 2 }\n * Schema.encodeSync(Version)({ major: 3, minor: 4 }) // \"3.4\"\n * ```\n *\n * @since 0.1.0\n */\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport * as Match from \"effect/Match\"\nimport * as MutableHashMap from \"effect/MutableHashMap\"\nimport * as Option from \"effect/Option\"\nimport * as Order from \"effect/Order\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Record from \"effect/Record\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaAST from \"effect/SchemaAST\"\nimport * as SchemaIssue from \"effect/SchemaIssue\"\nimport * as SchemaTransformation from \"effect/SchemaTransformation\"\nimport * as Ascii from \"./Ascii.js\"\nimport type { Parser } from \"./Parser.js\"\nimport * as P from \"./Parser.js\"\nimport * as Token from \"./Token.js\"\nimport { describeLiteral } from \"./internal/tokens.js\"\n\n/**\n * The key of the annotation that says how a schema is written as text\n * ({@link Annotation}), namespaced to this package so it cannot collide with\n * another library's. {@link annotate} sets it.\n *\n * @since 0.3.0\n * @category annotations\n */\nexport const annotationKey = \"@thomasfosterau/effect-parse/ParserSchema\" as const\n\ndeclare module \"effect/Schema\" {\n namespace Annotations {\n interface Annotations {\n /**\n * How the schema is written as text, read by `ParserSchema.toParser`\n * and `ParserSchema.toPrinter`: a parser for the schema's type, or a\n * `ParserSchema.Grammar`.\n */\n readonly [annotationKey]?: Annotation<any> | undefined\n }\n }\n}\n\n/**\n * Options for {@link make}.\n *\n * @since 0.1.0\n * @category models\n */\nexport interface Options<A> {\n /** Prints a value back to a string. Without it, encoding fails. */\n readonly encode?: ((value: A) => string) | undefined\n /** A description of the decoded type, used by schema tooling. */\n readonly description?: string | undefined\n}\n\n/**\n * A schema decoding strings with a parser.\n *\n * @since 0.1.0\n * @category models\n */\nexport interface ParserSchema<A> extends Schema.decodeTo<Schema.declare<A>, Schema.String> {}\n\ntype Encode<A> = (value: A) => Result.Result<string, SchemaIssue.Issue>\n\nconst encodeWith =\n <A>(encode: (value: A) => string): Encode<A> =>\n (value) =>\n Result.succeed(encode(value))\n\nconst decodeWith = <T extends Schema.Top>(\n target: T,\n parser: Parser<T[\"Encoded\"], unknown, never, string>,\n encode: Encode<T[\"Encoded\"]> | undefined\n) =>\n Schema.String.pipe(\n Schema.decodeTo(\n target,\n SchemaTransformation.transformEffect<T[\"Encoded\"], string>({\n decode: (input, parseOptions) => {\n const result = P.parse(parser, input)\n return Result.isSuccess(result)\n ? Effect.succeed(result.success)\n : Effect.fail(new SchemaIssue.InvalidValue({ message: result.failure.message }, input, parseOptions))\n },\n encode: (value, parseOptions) => {\n if (encode === undefined) {\n return Effect.fail(new SchemaIssue.Forbidden({ message: \"Encoding is not supported\" }, value, parseOptions))\n }\n const result = encode(value)\n return Result.isSuccess(result) ? Effect.succeed(result.success) : Effect.fail(result.failure)\n }\n })\n )\n )\n\n/**\n * Creates a schema that decodes a string with `parser`, which must consume\n * the whole string.\n *\n * @since 0.1.0\n * @category constructors\n */\nexport const make = <A, E>(parser: Parser<A, E, never, string>, options?: Options<A>): ParserSchema<A> =>\n decodeWith(\n Schema.declare<A>(\n (_u): _u is A => true,\n options?.description !== undefined ? { description: options.description } : undefined\n ),\n parser,\n options?.encode === undefined ? undefined : encodeWith(options.encode)\n )\n\n// -----------------------------------------------------------------------------\n// Deriving parsers and printers from schemas\n// -----------------------------------------------------------------------------\n\n/**\n * How a schema is written as text, given in its annotation (see\n * {@link annotate}) and read by {@link toParser} and {@link toPrinter}.\n * Every field is optional; a schema without one is written as described on\n * {@link toParser}.\n *\n * @since 0.3.0\n * @category models\n */\nexport interface Grammar<A = unknown> {\n /**\n * Parses the schema's type outright, replacing what {@link toParser} would\n * derive. Its output is still validated against the schema's type and\n * checks, and its failures' causes become `SchemaError`s with their message.\n * Give a {@link Grammar.print} with it, or the schema cannot be printed.\n */\n readonly parser?: Parser<A, unknown, never, string> | undefined\n /** Writes a value as the text {@link Grammar.parser} reads, replacing what {@link toPrinter} would derive. */\n readonly print?: ((value: A) => string) | undefined\n /** Text written before the value. */\n readonly prefix?: string | undefined\n /** Text written after the value. */\n readonly suffix?: string | undefined\n /** Text written between the fields of a struct, the elements of a tuple or array, or the entries of a record. */\n readonly separator?: string | undefined\n /**\n * Text written between a key and its value. On a struct, it writes each\n * field as `key`, separator, value, in any order; records always need one.\n */\n readonly keySeparator?: string | undefined\n /**\n * Whether whitespace may surround the text this schema writes (its prefix,\n * suffix and separators), and whitespace around unannotated strings is\n * trimmed. Inherited by the schemas inside it. Printers write no\n * whitespace.\n */\n readonly whitespace?: boolean | undefined\n}\n\n/**\n * The value of the annotation under {@link annotationKey}: a\n * {@link Grammar}, or a parser for the schema's type (short for\n * `{ parser }`, which cannot be printed).\n *\n * @since 0.3.0\n * @category models\n */\nexport type Annotation<A = unknown> = Grammar<A> | Parser<A, unknown, never, string>\n\n/**\n * Annotates a schema with how it is written as text, for {@link toParser}\n * and {@link toPrinter}. The same as\n * `schema.annotate({ [ParserSchema.annotationKey]: annotation })`, except\n * that the parser's output must have the schema's type.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n * import { ParserSchema } from \"@thomasfosterau/effect-parse\"\n *\n * const Point = Schema.Struct({ x: Schema.Int, y: Schema.Int }).pipe(\n * ParserSchema.annotate({ prefix: \"(\", separator: \",\", suffix: \")\" })\n * )\n * ```\n *\n * @since 0.3.0\n * @category annotations\n */\nexport const annotate: {\n // A grammar without a parser constrains nothing\n <A = never>(\n annotation: Annotation<A>\n ): <S extends Schema.Top>(self: S & ([A] extends [S[\"Type\"]] ? unknown : never)) => S[\"Rebuild\"]\n <S extends Schema.Top>(self: S, annotation: Annotation<S[\"Type\"]>): S[\"Rebuild\"]\n} = /*#__PURE__*/ dual(2, <S extends Schema.Top>(self: S, annotation: Annotation<S[\"Type\"]>): S[\"Rebuild\"] =>\n self.annotate({ [annotationKey]: annotation })\n)\n\n/**\n * Derives a parser from a schema. The parser reads the text the schema's\n * annotations ({@link Grammar}) describe and returns a value of the schema's\n * type, which the schema's checks and transformations have already\n * validated; their failures become parse errors whose `cause` is the\n * `SchemaError`.\n *\n * Without an annotation, a schema is parsed as follows:\n *\n * - `String`: one or more characters up to the next separator, key\n * separator, suffix or literal around it (to the end of the input at the\n * top level).\n * - `Number`: a decimal number (`Ascii.float`), or a decimal integer when\n * the schema checks `isInt` (as `Schema.Int` does). `BigInt`: a decimal\n * integer. `Boolean`: `true` or `false`. `Null`: `null`. `Undefined` and\n * `Void`: nothing.\n * - `Literal`, `Enum` and `TemplateLiteral`: their text.\n * - `Struct` and `Tuple`: their fields or elements in order, between\n * separators; an optional one may be left out along with its separator.\n * `Array`: elements between separators.\n * - `Record`, and `Struct` with a `keySeparator`: `key`, key separator,\n * value entries in any order, between separators.\n * - `Union`: the first member that parses, in order (literals longest\n * first). `suspend`: recursion.\n * - A transformation (a `Class`, `NumberFromString`, ...): its encoded side,\n * decoded by the schema. A grammar on it with a separator applies to the\n * encoded side.\n *\n * A parser that fails where the schema starts reports the schema's\n * `identifier` annotation (or its `expected` annotation, unless that belongs\n * to a check) as what it expected. Other declarations, `Unknown`, `Any`,\n * symbols and `object` need a parser in their annotation; without one,\n * `toParser` throws. Transformations must decode synchronously.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n * import { Parser, ParserSchema } from \"@thomasfosterau/effect-parse\"\n *\n * const Version = Schema.Struct({ major: Schema.Int, minor: Schema.Int }).pipe(\n * ParserSchema.annotate({ separator: \".\" })\n * )\n *\n * Parser.parse(ParserSchema.toParser(Version), \"1.2\") // Result.succeed({ major: 1, minor: 2 })\n * ```\n *\n * @since 0.3.0\n * @category derivation\n */\nexport const toParser = <S extends Schema.ConstraintDecoder<unknown>>(\n schema: S\n): Parser<S[\"Type\"], Schema.SchemaError, never, string> => {\n const ast = schema.ast\n const parser = derive(ast, initial<AnyParser>())\n return grammarOf(ast).whitespace === true ? P.delimited(Ascii.multispace0, parser, Ascii.multispace0) : parser\n}\n\n/**\n * Derives a printer from a schema: it writes a value of the schema's type as\n * the text {@link toParser} reads, following the same annotations, with no\n * optional whitespace. Transformations encode the value first, and a\n * {@link Grammar.print} replaces the derived printer.\n *\n * The printer fails with a `SchemaError` when the value is not of the\n * schema's type, or cannot be written so that it reads back: a string that\n * is empty or contains a character that would end it (a separator, a\n * suffix), or a part annotated with a parser but no `print`. Where the\n * grammar is ambiguous (an optional field followed by a field of the same\n * type), the text can still read back as a different value;\n * {@link fromSchema} checks that it doesn't.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n * import { ParserSchema } from \"@thomasfosterau/effect-parse\"\n *\n * const Version = Schema.Struct({ major: Schema.Int, minor: Schema.Int }).pipe(\n * ParserSchema.annotate({ separator: \".\" })\n * )\n *\n * ParserSchema.toPrinter(Version)({ major: 1, minor: 2 }) // Result.succeed(\"1.2\")\n * ```\n *\n * @since 0.3.0\n * @category derivation\n */\nexport const toPrinter = <S extends Schema.ConstraintCodec<unknown, unknown, unknown, never>>(\n schema: S\n): ((value: S[\"Type\"]) => Result.Result<string, Schema.SchemaError>) => {\n const validate = typeDecoder(schema.ast)\n const print = printerOf(schema.ast, initial<Printer>())\n return (value) => {\n const valid = validate(value)\n if (Result.isFailure(valid)) return Result.fail(valid.failure)\n const out: Array<string> = []\n const issue = print(valid.success, out)\n return issue === undefined ? Result.succeed(out.join(\"\")) : Result.fail(schemaError(issue))\n }\n}\n\n/**\n * Creates a schema that decodes a string with the parser {@link toParser}\n * derives from `schema`, into `schema`'s type, and encodes with the printer\n * {@link toPrinter} derives, or with `encode` when given. A derived printer's\n * text is parsed back, and encoding fails unless it gives a value equivalent\n * to the one encoded, so decoding what was encoded always gives it back.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n * import { ParserSchema } from \"@thomasfosterau/effect-parse\"\n *\n * const Pair = ParserSchema.fromSchema(\n * Schema.Tuple([Schema.String, Schema.Number]).pipe(ParserSchema.annotate({ separator: \"=\" }))\n * )\n *\n * Schema.decodeUnknownSync(Pair)(\"width=10\") // [\"width\", 10]\n * Schema.encodeSync(Pair)([\"height\", 2]) // \"height=2\"\n * ```\n *\n * @since 0.3.0\n * @category constructors\n */\nexport const fromSchema = <S extends Schema.ConstraintCodec<unknown, unknown, never, never> & Schema.Top>(\n schema: S,\n options?: { readonly encode?: ((value: S[\"Type\"]) => string) | undefined }\n): Schema.decodeTo<Schema.toType<S>, Schema.String> => {\n const parser = toParser(schema)\n const encode = options?.encode\n return decodeWith<Schema.toType<S>>(\n Schema.toType(schema),\n parser,\n encode === undefined ? roundTrip(schema, parser) : encodeWith(encode)\n )\n}\n\n/** Prints with the derived printer, then checks that the text reads back as the value. */\nconst roundTrip = <S extends Schema.ConstraintCodec<unknown, unknown, never, never> & Schema.Top>(\n schema: S,\n parser: Parser<S[\"Type\"], Schema.SchemaError, never, string>\n): Encode<S[\"Type\"]> => {\n const print = toPrinter(schema)\n const equivalent = Schema.toEquivalence(Schema.toType(schema))\n return (value) =>\n Result.flatMap(\n Result.mapError(print(value), (error) => error.issue),\n (text) => {\n const back = P.parse(parser, text)\n return Result.isSuccess(back) && equivalent(back.success, value)\n ? Result.succeed(text)\n : Result.fail(\n new SchemaIssue.InvalidValue({\n message: `The value is written ${describeLiteral(text)}, which does not read back as the value`\n })\n )\n }\n )\n}\n\n// -----------------------------------------------------------------------------\n// The walk shared by parsers and printers\n// -----------------------------------------------------------------------------\n\ninterface Context<T> {\n /** Characters ending an unannotated string, sorted. */\n readonly stop: string\n readonly whitespace: boolean\n /** Grammar passed from a transformation to its encoded side. */\n readonly inherit: Grammar | undefined\n readonly path: ReadonlyArray<PropertyKey>\n /** What was derived for the recursive schemas met so far, by context. */\n readonly recursions: Array<Recursion<T>>\n}\n\ninterface Recursion<T> {\n readonly ast: SchemaAST.Suspend\n readonly key: string\n readonly derived: T\n}\n\nconst initial = <T>(): Context<T> => ({ stop: \"\", whitespace: false, inherit: undefined, path: [], recursions: [] })\n\n/** The annotation `key` on `ast`, from its last check back to the node, as `Schema.resolveAnnotations` resolves it. */\nconst lookup = (ast: SchemaAST.AST, key: string): unknown => {\n const checks = ast.checks\n if (checks !== undefined) {\n for (let i = checks.length - 1; i >= 0; i--) {\n const value = checks[i].annotations?.[key]\n if (value !== undefined) return value\n }\n }\n return ast.annotations?.[key]\n}\n\nconst grammarOf = (ast: SchemaAST.AST): Grammar => {\n const value = lookup(ast, annotationKey)\n if (value === undefined) return {}\n // SAFETY: the annotation is typed `Annotation`, a parser or a grammar\n return P.isParser(value) ? { parser: value as ForeignParser } : (value as Grammar)\n}\n\nconst isAnnotated = (ast: SchemaAST.AST): boolean => lookup(ast, annotationKey) !== undefined\n\nconst withStop = <T>(ctx: Context<T>, text: string | undefined): Context<T> => {\n if (text === undefined || text === \"\" || ctx.stop.includes(text[0])) return ctx\n return { ...ctx, stop: Arr.sort([...ctx.stop, text[0]], Order.String).join(\"\") }\n}\n\nconst at = <T>(ctx: Context<T>, key: PropertyKey): Context<T> => ({\n ...ctx,\n inherit: undefined,\n path: [...ctx.path, key]\n})\n\nconst where = <T>(ctx: Context<T>): string => `[${ctx.path.map(String).join(\", \")}]`\n\nconst unsupported = <T>(ast: SchemaAST.AST, ctx: Context<T>, what: string): never => {\n throw new TypeError(`ParserSchema: cannot derive a ${what} for ${ast._tag} at ${where(ctx)}; annotate it`)\n}\n\ninterface Resolved<T> {\n readonly grammar: Grammar\n readonly whitespace: boolean\n /** The context of what the node contains. */\n readonly inner: Context<T>\n}\n\n/** The node's grammar, with what its transformation passed down, and the context inside it. */\nconst resolve = <T>(ast: SchemaAST.AST, ctx: Context<T>): Resolved<T> => {\n const own = grammarOf(ast)\n const inherit = ctx.inherit\n const grammar: Grammar =\n inherit === undefined\n ? own\n : {\n ...own,\n separator: own.separator ?? inherit.separator,\n keySeparator: own.keySeparator ?? inherit.keySeparator\n }\n const whitespace = grammar.whitespace ?? ctx.whitespace\n return { grammar, whitespace, inner: { ...withStop(ctx, grammar.suffix), whitespace, inherit: undefined } }\n}\n\n/** The context of a transformation's encoded side, which the transformation's separators apply to. */\nconst encodedContext = <T>(grammar: Grammar, ctx: Context<T>): Context<T> => ({\n ...ctx,\n inherit: { separator: grammar.separator, keySeparator: grammar.keySeparator }\n})\n\n/**\n * The node with its chain of links ending at the type of its encoded side,\n * which is what the encoded side is parsed into and printed from.\n */\nconst linkTarget = (ast: SchemaAST.AST, links: SchemaAST.Encoding): SchemaAST.AST => {\n const last = links[links.length - 1]\n let target = SchemaAST.toType(ast)\n for (const link of links) {\n const source = link === last ? SchemaAST.toType(last.to) : link.to\n // SAFETY: `decodeTo` appends the link as it is, middleware included, as the schema's own links are\n target = SchemaAST.decodeTo(source, target, link.transformation as SchemaTransformation.Transformation<any, any>)\n }\n return target\n}\n\n/**\n * What is derived for a recursive schema: deriving it again in the same\n * context gives the same result, so the derivation ends.\n */\nconst recursive = <T>(ast: SchemaAST.Suspend, ctx: Context<T>, make: () => T): T => {\n const key = `${ctx.whitespace ? 1 : 0}${ctx.stop}`\n const known = ctx.recursions.find((r) => r.ast === ast && r.key === key)\n if (known !== undefined) return known.derived\n const derived = make()\n ctx.recursions.push({ ast, key, derived })\n return derived\n}\n\n/** The context for the items of a sequence: unannotated strings also stop at the separator. */\nconst itemContext = <T>(grammar: Grammar, ctx: Context<T>): Context<T> => withStop(ctx, grammar.separator)\n\n/** The rest element of an array schema, if any; elements after it are not supported. */\nconst restOf = <T>(ast: SchemaAST.Arrays, ctx: Context<T>, what: string): SchemaAST.AST | undefined => {\n const [head, ...after] = ast.rest\n // Elements after the rest would need the rest to stop short\n return Arr.isReadonlyArrayNonEmpty(after) ? unsupported(ast, ctx, what) : head\n}\n\n/** The contexts of an array schema's elements and its rest. */\nconst elementContexts = <T>(\n ast: SchemaAST.Arrays,\n rest: SchemaAST.AST | undefined,\n grammar: Grammar,\n ctx: Context<T>\n): ReadonlyArray<Context<T>> => {\n const n = ast.elements.length\n return ast.elements.map((_, i) => at(i < n - 1 || rest !== undefined ? itemContext(grammar, ctx) : ctx, i))\n}\n\n/** The contexts of a struct's fields, written in order. */\nconst fieldContexts = <T>(ast: SchemaAST.Objects, grammar: Grammar, ctx: Context<T>): ReadonlyArray<Context<T>> => {\n const fields = ast.propertySignatures\n return fields.map((field, i) => at(i < fields.length - 1 ? itemContext(grammar, ctx) : ctx, field.name))\n}\n\nconst isKeyed = (ast: SchemaAST.Objects, grammar: Grammar): boolean =>\n grammar.keySeparator !== undefined || Arr.isReadonlyArrayNonEmpty(ast.indexSignatures)\n\nconst keySeparatorOf = <T>(grammar: Grammar, ctx: Context<T>): string => {\n if (grammar.keySeparator === undefined) {\n throw new TypeError(`ParserSchema: a record at ${where(ctx)} needs a keySeparator in its annotation`)\n }\n return grammar.keySeparator\n}\n\n/** The field name of a struct in keyed form: a string. */\nconst keyName = <T>(ast: SchemaAST.Objects, field: SchemaAST.PropertySignature, ctx: Context<T>, what: string) =>\n Predicate.isString(field.name) ? field.name : unsupported(ast, ctx, what)\n\nconst propertyName = (key: PropertyKey): string | symbol => (Predicate.isNumber(key) ? String(key) : key)\n\n/** Whether a check (as `Schema.Int` has) restricts numbers to integers. */\nconst isIntegral = (checks: SchemaAST.Checks | undefined): boolean =>\n checks !== undefined &&\n checks.some((check) =>\n check instanceof SchemaAST.FilterGroup\n ? isIntegral(check.checks)\n : check.annotations?.arbitraryConstraint?.[\"number\"] === \"integer\"\n )\n\ntype LiteralValue = SchemaAST.Literal[\"literal\"]\n\n/** Literals with the longest text first, so a literal is never cut short by one it starts with. */\nconst byLength = <A extends LiteralValue>(values: ReadonlyArray<A>): Array<A> =>\n Arr.sort(\n values,\n Order.mapInput(Order.Number, (value: A) => -String(value).length)\n )\n\nconst isPlainLiteral = (ast: SchemaAST.AST): ast is SchemaAST.Literal =>\n SchemaAST.isLiteral(ast) && ast.encoding === undefined && !isAnnotated(ast)\n\n/** The literals of a union of plain literals, longest first, or `undefined`. */\nconst plainLiterals = (ast: SchemaAST.Union): ReadonlyArray<LiteralValue> | undefined => {\n const literals = Arr.filter(ast.types, isPlainLiteral)\n return literals.length === ast.types.length ? byLength(literals.map((member) => member.literal)) : undefined\n}\n\nconst schemaError = (issue: SchemaIssue.Issue) => new Schema.SchemaError(issue)\n\nconst decoder = (schema: Schema.ConstraintDecoder<unknown>) => Schema.decodeUnknownResult(schema)\n\n/** Decodes into the type of `ast`, checks included. */\nconst typeDecoder = (ast: SchemaAST.AST) => decoder(Schema.make<Schema.Codec<unknown>>(SchemaAST.toType(ast)))\n\n// -----------------------------------------------------------------------------\n// Parsers\n// -----------------------------------------------------------------------------\n\ntype AnyParser = Parser<any, Schema.SchemaError, never, string>\n\ntype ForeignParser = Parser<unknown, unknown, never, string>\n\nconst messageOf = (cause: unknown): string =>\n Predicate.isString(cause)\n ? cause\n : Predicate.hasProperty(cause, \"message\") && Predicate.isString(cause.message)\n ? cause.message\n : String(cause)\n\n/** A parser whose failures' causes are `SchemaError`s, as {@link toParser}'s are. */\nconst asSchemaErrors = (parser: ForeignParser): AnyParser =>\n P.mapError(parser, (cause) =>\n cause instanceof Schema.SchemaError\n ? cause\n : schemaError(new SchemaIssue.InvalidValue({ message: messageOf(cause) }))\n )\n\n/** Literal text, with optional whitespace around it. */\nconst text = (s: string, ws: boolean): AnyParser =>\n ws ? P.delimited(Ascii.multispace0, Token.literal(s), Ascii.multispace0) : Token.literal(s)\n\nconst derive = (ast: SchemaAST.AST, ctx: Context<AnyParser>): AnyParser => {\n const { grammar, inner, whitespace } = resolve(ast, ctx)\n let parser: AnyParser\n if (grammar.parser !== undefined) parser = P.tryMap(asSchemaErrors(grammar.parser), typeDecoder(ast))\n else if (ast.encoding !== undefined) parser = decoded(ast, ast.encoding, grammar, inner)\n else parser = checked(ast, structural(ast, grammar, inner))\n if (grammar.prefix !== undefined) parser = P.preceded(text(grammar.prefix, whitespace), parser)\n if (grammar.suffix !== undefined) parser = P.terminated(parser, text(grammar.suffix, whitespace))\n // A check's own `expected` describes the check, not the text\n const label = lookup(ast, \"identifier\") ?? ast.annotations?.expected\n return Predicate.isString(label) ? P.expected(parser, label) : parser\n}\n\n/** Runs the checks on `ast` (its filters) on the parser's output. */\nconst checked = (ast: SchemaAST.AST, parser: AnyParser): AnyParser =>\n ast.checks === undefined ? parser : P.tryMap(parser, decoder(Schema.Unknown.check(...ast.checks)))\n\n/**\n * Parses the encoded side of a transformation and decodes it. The encoded\n * side is parsed into its own type, so the last link decodes from that type\n * rather than from the fully encoded form.\n */\nconst decoded = (\n ast: SchemaAST.AST,\n links: SchemaAST.Encoding,\n grammar: Grammar,\n ctx: Context<AnyParser>\n): AnyParser => {\n const from = derive(links[links.length - 1].to, encodedContext(grammar, ctx))\n return P.tryMap(from, decoder(Schema.make<Schema.Codec<unknown>>(linkTarget(ast, links))))\n}\n\nconst structural = (ast: SchemaAST.AST, grammar: Grammar, ctx: Context<AnyParser>): AnyParser =>\n Match.valueTags(ast, {\n String: () => unannotatedString(ctx, 1),\n Number: (number) => (isIntegral(number.checks) ? integer : Ascii.float),\n BigInt: () => Ascii.decBigInt,\n Boolean: () => P.alt(P.as(Token.literal(\"true\"), true), P.as(Token.literal(\"false\"), false)),\n Null: () => P.as(Token.literal(\"null\"), null),\n Undefined: () => P.succeed(undefined),\n Void: () => P.succeed(undefined),\n Never: () => P.reject,\n Literal: (lit) => literal(lit.literal),\n Enum: (e) => P.alt(...byLength(e.enums.map(([, value]) => value)).map(literal)),\n TemplateLiteral: (template) => templateLiteral(template, ctx),\n Arrays: (arrays) => sequenceOf(arrays, grammar, ctx),\n Objects: (objects) =>\n isKeyed(objects, grammar) ? keyed(objects, grammar, ctx) : positional(objects, grammar, ctx),\n Union: (union) => alternatives(union, ctx),\n Suspend: (suspend) => recursive(suspend, ctx, () => P.suspend(() => derive(suspend.thunk(), ctx))),\n Declaration: (other) => unsupported(other, ctx, \"parser\"),\n Unknown: (other) => unsupported(other, ctx, \"parser\"),\n Any: (other) => unsupported(other, ctx, \"parser\"),\n Symbol: (other) => unsupported(other, ctx, \"parser\"),\n UniqueSymbol: (other) => unsupported(other, ctx, \"parser\"),\n ObjectKeyword: (other) => unsupported(other, ctx, \"parser\")\n })\n\nconst unannotatedString = (ctx: Context<AnyParser>, min: number): AnyParser => {\n const s = Token.takeTill(ctx.stop, { min })\n // Leading whitespace is skipped first, so it doesn't count towards `min`\n return ctx.whitespace\n ? P.preceded(\n Ascii.multispace0,\n P.map(s, (value) => value.trimEnd())\n )\n : s\n}\n\nconst integer: AnyParser = /*#__PURE__*/ asSchemaErrors(Ascii.decInt)\n\nconst literal = (value: LiteralValue): AnyParser => P.as(Token.literal(String(value)), value)\n\nconst templateLiteral = (ast: SchemaAST.TemplateLiteral, ctx: Context<AnyParser>): AnyParser =>\n P.taken(\n P.seq(\n ...ast.parts.map((part, i) => {\n const next = ast.parts[i + 1]\n const partCtx = next !== undefined && SchemaAST.isLiteral(next) ? withStop(ctx, String(next.literal)) : ctx\n // An interpolated string may be empty\n return SchemaAST.isString(part) && !isAnnotated(part)\n ? unannotatedString(partCtx, 0)\n : derive(part, at(partCtx, i))\n })\n )\n )\n\nconst alternatives = (ast: SchemaAST.Union, ctx: Context<AnyParser>): AnyParser => {\n const literals = plainLiterals(ast)\n return literals !== undefined\n ? P.alt(...literals.map(literal))\n : P.alt(...ast.types.map((member) => derive(member, ctx)))\n}\n\ninterface Item {\n readonly parser: AnyParser\n readonly optional: boolean\n}\n\ntype Values = Parser<Array<unknown>, Schema.SchemaError, never, string>\n\n/**\n * Parses `items` in order, then any number of `rest`, with `separator`\n * between the ones present. The output has the value of item `i` at index\n * `i` (a hole when an optional item is missing), then the rest.\n */\nconst sequence = (\n items: ReadonlyArray<Item>,\n rest: AnyParser | undefined,\n separator: AnyParser | undefined\n): Values => {\n const n = items.length\n const tail = (needSeparator: boolean): Values => {\n if (rest === undefined) return P.sync(() => new Array(n))\n const values =\n separator === undefined\n ? P.repeat(rest)\n : needSeparator\n ? P.repeat(P.preceded(separator, rest))\n : P.separated(rest, separator)\n return P.map(values, (xs) => {\n const out = new Array(n)\n for (let j = 0; j < xs.length; j++) out[n + j] = xs[j]\n return out\n })\n }\n // One parser per position and whether a separator comes first, at index `2 * i + needSeparator`\n const memo: Array<Values | undefined> = []\n const from = (i: number, needSeparator: boolean): Values => {\n const key = i * 2 + (needSeparator ? 1 : 0)\n const known = memo[key]\n if (known !== undefined) return known\n let parser: Values\n if (i === n) parser = tail(needSeparator)\n else {\n const item = items[i]\n const head = needSeparator && separator !== undefined ? P.preceded(separator, item.parser) : item.parser\n const present = P.map(P.seq(head, from(i + 1, true)), ([value, out]) => {\n out[i] = value\n return out\n })\n parser = item.optional ? P.alt(present, from(i + 1, needSeparator)) : present\n }\n memo[key] = parser\n return parser\n }\n return from(0, false)\n}\n\nconst separatorOf = (grammar: Grammar, ctx: Context<AnyParser>): AnyParser | undefined =>\n grammar.separator === undefined ? undefined : text(grammar.separator, ctx.whitespace)\n\nconst sequenceOf = (ast: SchemaAST.Arrays, grammar: Grammar, ctx: Context<AnyParser>): AnyParser => {\n const head = restOf(ast, ctx, \"parser\")\n const contexts = elementContexts(ast, head, grammar, ctx)\n const items = ast.elements.map((element, i) => ({\n parser: derive(element, contexts[i]),\n optional: SchemaAST.isOptional(element)\n }))\n const rest = head === undefined ? undefined : derive(head, at(itemContext(grammar, ctx), items.length))\n // Optional elements come last, so the present values are the first ones\n return P.map(sequence(items, rest, separatorOf(grammar, ctx)), (out) => out.filter((_, i) => i in out))\n}\n\nconst positional = (ast: SchemaAST.Objects, grammar: Grammar, ctx: Context<AnyParser>): AnyParser => {\n const fields = ast.propertySignatures\n const contexts = fieldContexts(ast, grammar, ctx)\n const items = fields.map((field, i) => ({\n parser: derive(field.type, contexts[i]),\n optional: SchemaAST.isOptional(field.type)\n }))\n return P.map(sequence(items, undefined, separatorOf(grammar, ctx)), (out) =>\n Record.fromEntries(fields.flatMap((field, i) => (i in out ? [[propertyName(field.name), out[i]] as const] : [])))\n )\n}\n\ntype Entry = readonly [key: string | symbol, value: unknown, known: boolean]\n\nconst keyed = (ast: SchemaAST.Objects, grammar: Grammar, ctx: Context<AnyParser>): AnyParser => {\n const keySeparator = keySeparatorOf(grammar, ctx)\n const between = text(keySeparator, ctx.whitespace)\n const valueCtx = itemContext(grammar, ctx)\n const known = ast.propertySignatures.map((field): AnyParser => {\n const name = keyName(ast, field, ctx, \"parser\")\n const value = derive(field.type, at(valueCtx, name))\n return P.map(P.preceded(P.seq(Token.literal(name), between), value), (v): Entry => [name, v, true])\n })\n const indexed = ast.indexSignatures.map((signature): AnyParser => {\n const key = derive(signature.parameter, at(withStop(ctx, keySeparator), \"<key>\"))\n const value = derive(signature.type, at(valueCtx, \"<value>\"))\n return P.map(P.separatedPair(key, between, value), ([k, v]): Entry => [propertyName(k), v, false])\n })\n const entry = P.alt(...known, ...indexed)\n const separator = separatorOf(grammar, ctx)\n const entries = separator === undefined ? P.repeat(entry) : P.separated(entry, separator)\n // A missing field fails where its entry could have been, as a syntax error, so a\n // failure further in (the entry that ended the repetition early) is reported instead\n const missing = ast.propertySignatures.map((field) =>\n P.expected(P.reject, describeLiteral(`${String(field.name)}${keySeparator}`))\n )\n return P.flatMap(\n P.tryMap(entries, (es: ReadonlyArray<Entry>) => assemble(ast, es)),\n ([value, absent]) => (absent === undefined ? P.succeed(value) : missing[absent])\n )\n}\n\n/**\n * Builds the object from its entries, declared fields first, rejecting\n * duplicate keys. Also returns the index of the first required field\n * missing, if any.\n */\nconst assemble = (\n ast: SchemaAST.Objects,\n entries: ReadonlyArray<Entry>\n): Result.Result<readonly [object, number | undefined], Schema.SchemaError> => {\n const values = MutableHashMap.empty<string | symbol, unknown>()\n for (const [key, value] of entries) {\n if (MutableHashMap.has(values, key)) {\n return Result.fail(\n schemaError(new SchemaIssue.Pointer([key], new SchemaIssue.InvalidValue({ message: \"Duplicate key\" })))\n )\n }\n MutableHashMap.set(values, key, value)\n }\n const out: Array<readonly [string | symbol, unknown]> = []\n let absent: number | undefined\n ast.propertySignatures.forEach((field, i) => {\n const name = propertyName(field.name)\n const value = MutableHashMap.get(values, name)\n if (Option.isSome(value)) out.push([name, value.value])\n else if (absent === undefined && !SchemaAST.isOptional(field.type)) absent = i\n })\n for (const [key, value, isKnown] of entries) if (!isKnown) out.push([key, value])\n return Result.succeed([Record.fromEntries(out), absent])\n}\n\n// -----------------------------------------------------------------------------\n// Printers\n// -----------------------------------------------------------------------------\n\n/**\n * Writes the text of a value, already validated against the schema's type,\n * to `out`, or returns why it cannot be written.\n */\ntype Printer = (value: any, out: Array<string>) => SchemaIssue.Issue | undefined\n\n/** The issue for a value that cannot be written at the node `ctx` is at. */\nconst unwritable = <T>(ctx: Context<T>, message: string, value: unknown): SchemaIssue.Issue => {\n const issue = new SchemaIssue.InvalidValue({ message }, value, { reportInput: true })\n return Arr.isReadonlyArrayNonEmpty(ctx.path) ? new SchemaIssue.Pointer(ctx.path, issue) : issue\n}\n\nconst writing =\n (show: (value: any) => string): Printer =>\n (value, out) => {\n out.push(show(value))\n return undefined\n }\n\nconst nothing: Printer = (_, __) => undefined\n\nconst printerOf = (ast: SchemaAST.AST, ctx: Context<Printer>): Printer => {\n const { grammar, inner } = resolve(ast, ctx)\n let print: Printer\n if (grammar.print !== undefined) print = writing(grammar.print)\n else if (grammar.parser !== undefined) print = unprintable(ctx)\n else if (ast.encoding !== undefined) print = encoded(ast, ast.encoding, grammar, inner)\n else print = printerFor(ast, grammar, inner)\n const prefix = grammar.prefix\n const suffix = grammar.suffix\n if (prefix === undefined && suffix === undefined) return print\n const inside = print\n return (value, out) => {\n if (prefix !== undefined) out.push(prefix)\n const issue = inside(value, out)\n if (suffix !== undefined) out.push(suffix)\n return issue\n }\n}\n\nconst unprintable =\n (ctx: Context<Printer>): Printer =>\n (value) =>\n unwritable(ctx, \"This value has a parser in its annotation but no print, so it cannot be written\", value)\n\n/** Encodes a transformation's value and prints its encoded side. */\nconst encoded = (ast: SchemaAST.AST, links: SchemaAST.Encoding, grammar: Grammar, ctx: Context<Printer>): Printer => {\n const to = printerOf(links[links.length - 1].to, encodedContext(grammar, ctx))\n const encode = Schema.encodeUnknownResult(Schema.make<Schema.Codec<unknown, unknown>>(linkTarget(ast, links)))\n return (value, out) => {\n const result = encode(value)\n return Result.isSuccess(result) ? to(result.success, out) : result.failure.issue\n }\n}\n\nconst printerFor = (ast: SchemaAST.AST, grammar: Grammar, ctx: Context<Printer>): Printer =>\n Match.valueTags(ast, {\n String: () => stringPrinter(ctx),\n Number: () => writing(String),\n BigInt: () => writing(String),\n Boolean: () => writing(String),\n Null: () => writing(String),\n Undefined: () => nothing,\n Void: () => nothing,\n Never: () => nothing,\n Literal: () => writing(String),\n Enum: () => writing(String),\n TemplateLiteral: () => writing(String),\n Arrays: (arrays) => arraysPrinter(arrays, grammar, ctx),\n Objects: (objects) =>\n isKeyed(objects, grammar) ? keyedPrinter(objects, grammar, ctx) : positionalPrinter(objects, grammar, ctx),\n Union: (union) => unionPrinter(union, ctx),\n Suspend: (suspend) =>\n recursive(suspend, ctx, () => {\n let print: Printer | undefined\n return (value, out) => (print ??= printerOf(suspend.thunk(), ctx))(value, out)\n }),\n Declaration: (other) => unsupported(other, ctx, \"printer\"),\n Unknown: (other) => unsupported(other, ctx, \"printer\"),\n Any: (other) => unsupported(other, ctx, \"printer\"),\n Symbol: (other) => unsupported(other, ctx, \"printer\"),\n UniqueSymbol: (other) => unsupported(other, ctx, \"printer\"),\n ObjectKeyword: (other) => unsupported(other, ctx, \"printer\")\n })\n\n/**\n * Writes a string as an unannotated string is parsed: refusing one that\n * would not read back, being empty or holding a character that ends it.\n */\nconst stringPrinter =\n (ctx: Context<Printer>): Printer =>\n (value: string, out) => {\n if (value === \"\") return unwritable(ctx, \"An empty string cannot be written here\", value)\n const stop = Arr.findFirst(Array.from(ctx.stop), (c) => value.includes(c))\n if (Option.isSome(stop)) {\n return unwritable(ctx, `A string containing ${describeLiteral(stop.value)} cannot be written here`, value)\n }\n if (ctx.whitespace && value.trim() !== value) {\n return unwritable(ctx, \"A string with whitespace around it cannot be written here\", value)\n }\n out.push(value)\n return undefined\n }\n\n/** Writes values with a separator between them, stopping at the first that cannot be written. */\nconst writeAll = (\n writes: ReadonlyArray<(out: Array<string>) => SchemaIssue.Issue | undefined>,\n separator: string,\n out: Array<string>\n): SchemaIssue.Issue | undefined => {\n for (let i = 0; i < writes.length; i++) {\n if (i > 0) out.push(separator)\n const issue = writes[i](out)\n if (issue !== undefined) return issue\n }\n return undefined\n}\n\nconst arraysPrinter = (ast: SchemaAST.Arrays, grammar: Grammar, ctx: Context<Printer>): Printer => {\n const head = restOf(ast, ctx, \"printer\")\n const contexts = elementContexts(ast, head, grammar, ctx)\n const elements = ast.elements.map((element, i) => printerOf(element, contexts[i]))\n const rest = head === undefined ? nothing : printerOf(head, at(itemContext(grammar, ctx), elements.length))\n const separator = grammar.separator ?? \"\"\n return (value: ReadonlyArray<unknown>, out) =>\n writeAll(\n value.map((element, i) => (o: Array<string>) => (elements[i] ?? rest)(element, o)),\n separator,\n out\n )\n}\n\nconst positionalPrinter = (ast: SchemaAST.Objects, grammar: Grammar, ctx: Context<Printer>): Printer => {\n const contexts = fieldContexts(ast, grammar, ctx)\n const fields = ast.propertySignatures.map((field, i) => ({\n name: propertyName(field.name),\n print: printerOf(field.type, contexts[i])\n }))\n const separator = grammar.separator ?? \"\"\n return (value: Record.ReadonlyRecord<string | symbol, unknown>, out) =>\n writeAll(\n fields\n .filter((field) => Record.has(value, field.name))\n .map((field) => (o: Array<string>) => field.print(value[field.name], o)),\n separator,\n out\n )\n}\n\nconst keyedPrinter = (ast: SchemaAST.Objects, grammar: Grammar, ctx: Context<Printer>): Printer => {\n const keySeparator = keySeparatorOf(grammar, ctx)\n const valueCtx = itemContext(grammar, ctx)\n const fields = ast.propertySignatures.map((field) => {\n const name = keyName(ast, field, ctx, \"printer\")\n return { name, print: printerOf(field.type, at(valueCtx, name)) }\n })\n const names = fields.map((field) => field.name)\n const indexed = ast.indexSignatures.map((signature) => ({\n is: Schema.is(Schema.make<Schema.Top>(SchemaAST.toType(signature.parameter))),\n key: printerOf(signature.parameter, at(withStop(ctx, keySeparator), \"<key>\")),\n value: printerOf(signature.type, at(valueCtx, \"<value>\"))\n }))\n const entry =\n (key: Printer, print: Printer, k: unknown, v: unknown) =>\n (out: Array<string>): SchemaIssue.Issue | undefined =>\n key(k, out) ?? (out.push(keySeparator), print(v, out))\n return (value: Record.ReadonlyRecord<string, unknown>, out) => {\n const writes = fields\n .filter((field) => Record.has(value, field.name))\n .map((field) => entry(writing(String), field.print, field.name, value[field.name]))\n for (const key of Record.keys(value)) {\n const signature = names.includes(key) ? undefined : indexed.find((s) => s.is(key))\n if (signature !== undefined) writes.push(entry(signature.key, signature.value, key, value[key]))\n }\n return writeAll(writes, grammar.separator ?? \"\", out)\n }\n}\n\n/** Writes a union's value with the first member it belongs to that can write it. */\nconst unionPrinter = (ast: SchemaAST.Union, ctx: Context<Printer>): Printer => {\n if (plainLiterals(ast) !== undefined) return writing(String)\n const members = ast.types.map((member) => ({\n is: Schema.is(Schema.make<Schema.Top>(SchemaAST.toType(member))),\n print: printerOf(member, ctx)\n }))\n return (value, out) => {\n let issue: SchemaIssue.Issue | undefined\n for (const member of members) {\n if (!member.is(value)) continue\n const mark = out.length\n issue = member.print(value, out)\n if (issue === undefined) return undefined\n out.length = mark\n }\n return issue ?? unwritable(ctx, \"No member of the union can write this value\", value)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,MAAa,gBAAgB;AAsC7B,MAAM,cACA,YACH,UACC,OAAO,QAAQ,OAAO,KAAK,CAAC;AAEhC,MAAM,cACJ,QACA,QACA,WAEA,OAAO,OAAO,KACZ,OAAO,SACL,QACA,qBAAqB,gBAAsC;CACzD,SAAS,OAAO,iBAAiB;EAC/B,MAAM,SAAS,EAAE,MAAM,QAAQ,KAAK;EACpC,OAAO,OAAO,UAAU,MAAM,IAC1B,OAAO,QAAQ,OAAO,OAAO,IAC7B,OAAO,KAAK,IAAI,YAAY,aAAa,EAAE,SAAS,OAAO,QAAQ,QAAQ,GAAG,OAAO,YAAY,CAAC;CACxG;CACA,SAAS,OAAO,iBAAiB;EAC/B,IAAI,WAAW,KAAA,GACb,OAAO,OAAO,KAAK,IAAI,YAAY,UAAU,EAAE,SAAS,4BAA4B,GAAG,OAAO,YAAY,CAAC;EAE7G,MAAM,SAAS,OAAO,KAAK;EAC3B,OAAO,OAAO,UAAU,MAAM,IAAI,OAAO,QAAQ,OAAO,OAAO,IAAI,OAAO,KAAK,OAAO,OAAO;CAC/F;AACF,CAAC,CACH,CACF;;;;;;;;AASF,MAAa,QAAc,QAAqC,YAC9D,WACE,OAAO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;CACtD;AACF;;AAGA,MAAM,gBAAgB,KAAsB,QAAmC;CAC7E,IAAI,cAAc,GAAG,MAAM,KAAA,GAAW,OAAO,QAAQ,MAAM;CAC3D,MAAM,UAAU,IAAI,MAAM,KAAK,YAAY;EACzC,IAAI,OAAO,GAAG,OAAO,KAAiB,UAAU,OAAO,MAAM,CAAC,CAAC;EAC/D,OAAO,UAAU,QAAQ,GAAG;CAC9B,EAAE;CACF,QAAQ,OAAO,QAAQ;EACrB,IAAI;EACJ,KAAK,MAAM,UAAU,SAAS;GAC5B,IAAI,CAAC,OAAO,GAAG,KAAK,GAAG;GACvB,MAAM,OAAO,IAAI;GACjB,QAAQ,OAAO,MAAM,OAAO,GAAG;GAC/B,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;GAChC,IAAI,SAAS;EACf;EACA,OAAO,SAAS,WAAW,KAAK,+CAA+C,KAAK;CACtF;AACF"}
1
+ {"version":3,"file":"ParserSchema.js","names":[],"sources":["../src/ParserSchema.ts"],"sourcesContent":["/**\n * Effect `Schema`s and parsers, in both directions.\n *\n * {@link make} turns a parser over strings into a schema that decodes a\n * `string` into the parser's output. Parse errors become schema issues\n * carrying the rendered `ParseError` message. Encoding needs a printer,\n * supplied as `encode`; without one, encoding is forbidden.\n *\n * {@link toParser} goes the other way: it derives a parser from a schema,\n * guided by annotations ({@link annotate}) that say how each part is\n * written. {@link toPrinter} derives the printer that writes that text, and\n * {@link fromSchema} wraps both as a schema.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n * import { Ascii, Parser, ParserSchema, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const Version = ParserSchema.make(\n * Parser.struct({\n * major: Ascii.decUint,\n * minor: Parser.preceded(Token.literal(\".\"), Ascii.decUint)\n * }),\n * { encode: ({ major, minor }) => `${major}.${minor}` }\n * )\n *\n * Schema.decodeUnknownSync(Version)(\"1.2\") // { major: 1, minor: 2 }\n * Schema.encodeSync(Version)({ major: 3, minor: 4 }) // \"3.4\"\n * ```\n *\n * @since 0.1.0\n */\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport * as Match from \"effect/Match\"\nimport * as MutableHashMap from \"effect/MutableHashMap\"\nimport * as Option from \"effect/Option\"\nimport * as Order from \"effect/Order\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Record from \"effect/Record\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaAST from \"effect/SchemaAST\"\nimport * as SchemaIssue from \"effect/SchemaIssue\"\nimport * as SchemaTransformation from \"effect/SchemaTransformation\"\nimport * as Ascii from \"./Ascii.js\"\nimport type { Parser } from \"./Parser.js\"\nimport * as P from \"./Parser.js\"\nimport * as Token from \"./Token.js\"\nimport { describeLiteral } from \"./internal/tokens.js\"\n\n/**\n * The key of the annotation that says how a schema is written as text\n * ({@link Annotation}), namespaced to this package so it cannot collide with\n * another library's. {@link annotate} sets it.\n *\n * @since 0.3.0\n * @category annotations\n */\nexport const annotationKey = \"@thomasfosterau/effect-parse/ParserSchema\" as const\n\ndeclare module \"effect/Schema\" {\n namespace Annotations {\n interface Annotations {\n /**\n * How the schema is written as text, read by `ParserSchema.toParser`\n * and `ParserSchema.toPrinter`: a parser for the schema's type, or a\n * `ParserSchema.Grammar`.\n */\n readonly [annotationKey]?: Annotation<any> | undefined\n }\n }\n}\n\n/**\n * Options for {@link make}.\n *\n * @since 0.1.0\n * @category models\n */\nexport interface Options<A> {\n /** Prints a value back to a string. Without it, encoding fails. */\n readonly encode?: ((value: A) => string) | undefined\n /** A description of the decoded type, used by schema tooling. */\n readonly description?: string | undefined\n}\n\n/**\n * A schema decoding strings with a parser.\n *\n * @since 0.1.0\n * @category models\n */\nexport interface ParserSchema<A> extends Schema.decodeTo<Schema.declare<A>, Schema.String> {}\n\ntype Encode<A> = (value: A) => Result.Result<string, SchemaIssue.Issue>\n\nconst encodeWith =\n <A>(encode: (value: A) => string): Encode<A> =>\n (value) =>\n Result.succeed(encode(value))\n\nconst decodeWith = <T extends Schema.Top>(\n target: T,\n parser: Parser<T[\"Encoded\"], unknown, never, string>,\n encode: Encode<T[\"Encoded\"]> | undefined\n) =>\n Schema.String.pipe(\n Schema.decodeTo(\n target,\n SchemaTransformation.transformEffect<T[\"Encoded\"], string>({\n decode: (input, parseOptions) => {\n const result = P.parse(parser, input)\n return Result.isSuccess(result)\n ? Effect.succeed(result.success)\n : Effect.fail(new SchemaIssue.InvalidValue({ message: result.failure.message }, input, parseOptions))\n },\n encode: (value, parseOptions) => {\n if (encode === undefined) {\n return Effect.fail(new SchemaIssue.Forbidden({ message: \"Encoding is not supported\" }, value, parseOptions))\n }\n const result = encode(value)\n return Result.isSuccess(result) ? Effect.succeed(result.success) : Effect.fail(result.failure)\n }\n })\n )\n )\n\n/**\n * Creates a schema that decodes a string with `parser`, which must consume\n * the whole string.\n *\n * @since 0.1.0\n * @category constructors\n */\nexport const make = <A, E>(parser: Parser<A, E, never, string>, options?: Options<A>): ParserSchema<A> =>\n decodeWith(\n Schema.declare<A>(\n (_u): _u is A => true,\n options?.description !== undefined ? { description: options.description } : undefined\n ),\n parser,\n options?.encode === undefined ? undefined : encodeWith(options.encode)\n )\n\n// -----------------------------------------------------------------------------\n// Deriving parsers and printers from schemas\n// -----------------------------------------------------------------------------\n\n/**\n * How a schema is written as text, given in its annotation (see\n * {@link annotate}) and read by {@link toParser} and {@link toPrinter}.\n * Every field is optional; a schema without one is written as described on\n * {@link toParser}.\n *\n * @since 0.3.0\n * @category models\n */\nexport interface Grammar<A = unknown> {\n /**\n * Parses the schema's type outright, replacing what {@link toParser} would\n * derive. Its output is still validated against the schema's type and\n * checks, and its failures' causes become `SchemaError`s with their message.\n * Give a {@link Grammar.print} with it, or the schema cannot be printed.\n */\n readonly parser?: Parser<A, unknown, never, string> | undefined\n /** Writes a value as the text {@link Grammar.parser} reads, replacing what {@link toPrinter} would derive. */\n readonly print?: ((value: A) => string) | undefined\n /** Text written before the value. */\n readonly prefix?: string | undefined\n /** Text written after the value. */\n readonly suffix?: string | undefined\n /** Text written between the fields of a struct, the elements of a tuple or array, or the entries of a record. */\n readonly separator?: string | undefined\n /**\n * Text written between a key and its value. On a struct, it writes each\n * field as `key`, separator, value, in any order; records always need one.\n */\n readonly keySeparator?: string | undefined\n /**\n * Whether whitespace may surround the text this schema writes (its prefix,\n * suffix and separators), and whitespace around unannotated strings is\n * trimmed. Inherited by the schemas inside it. Printers write no\n * whitespace.\n */\n readonly whitespace?: boolean | undefined\n}\n\n/**\n * The value of the annotation under {@link annotationKey}: a\n * {@link Grammar}, or a parser for the schema's type (short for\n * `{ parser }`, which cannot be printed).\n *\n * @since 0.3.0\n * @category models\n */\nexport type Annotation<A = unknown> = Grammar<A> | Parser<A, unknown, never, string>\n\n/**\n * Annotates a schema with how it is written as text, for {@link toParser}\n * and {@link toPrinter}. The same as\n * `schema.annotate({ [ParserSchema.annotationKey]: annotation })`, except\n * that the parser's output must have the schema's type.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n * import { ParserSchema } from \"@thomasfosterau/effect-parse\"\n *\n * const Point = Schema.Struct({ x: Schema.Int, y: Schema.Int }).pipe(\n * ParserSchema.annotate({ prefix: \"(\", separator: \",\", suffix: \")\" })\n * )\n * ```\n *\n * @since 0.3.0\n * @category annotations\n */\nexport const annotate: {\n // A grammar without a parser constrains nothing\n <A = never>(\n annotation: Annotation<A>\n ): <S extends Schema.Top>(self: S & ([A] extends [S[\"Type\"]] ? unknown : never)) => S[\"Rebuild\"]\n <S extends Schema.Top>(self: S, annotation: Annotation<S[\"Type\"]>): S[\"Rebuild\"]\n} = /*#__PURE__*/ dual(2, <S extends Schema.Top>(self: S, annotation: Annotation<S[\"Type\"]>): S[\"Rebuild\"] =>\n self.annotate({ [annotationKey]: annotation })\n)\n\n/**\n * Derives a parser from a schema. The parser reads the text the schema's\n * annotations ({@link Grammar}) describe and returns a value of the schema's\n * type, which the schema's checks and transformations have already\n * validated; their failures become parse errors whose `cause` is the\n * `SchemaError`.\n *\n * Without an annotation, a schema is parsed as follows:\n *\n * - `String`: one or more characters up to the next separator, key\n * separator, suffix or literal around it (to the end of the input at the\n * top level).\n * - `Number`: a decimal number (`Ascii.float`), or a decimal integer when\n * the schema checks `isInt` (as `Schema.Int` does). `BigInt`: a decimal\n * integer. `Boolean`: `true` or `false`. `Null`: `null`. `Undefined` and\n * `Void`: nothing.\n * - `Literal`, `Enum` and `TemplateLiteral`: their text.\n * - `Struct` and `Tuple`: their fields or elements in order, between\n * separators; an optional one may be left out along with its separator.\n * `Array`: elements between separators.\n * - `Record`, and `Struct` with a `keySeparator`: `key`, key separator,\n * value entries in any order, between separators.\n * - `Union`: the first member that parses, in order (literals longest\n * first). `suspend`: recursion.\n * - A transformation (a `Class`, `NumberFromString`, ...): its encoded side,\n * decoded by the schema. A grammar on it with a separator applies to the\n * encoded side.\n *\n * A parser that fails where the schema starts reports the schema's\n * `identifier` annotation (or its `expected` annotation, unless that belongs\n * to a check) as what it expected. Other declarations, `Unknown`, `Any`,\n * symbols and `object` need a parser in their annotation; without one,\n * `toParser` throws. Transformations must decode synchronously.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n * import { Parser, ParserSchema } from \"@thomasfosterau/effect-parse\"\n *\n * const Version = Schema.Struct({ major: Schema.Int, minor: Schema.Int }).pipe(\n * ParserSchema.annotate({ separator: \".\" })\n * )\n *\n * Parser.parse(ParserSchema.toParser(Version), \"1.2\") // Result.succeed({ major: 1, minor: 2 })\n * ```\n *\n * @since 0.3.0\n * @category derivation\n */\nexport const toParser = <S extends Schema.ConstraintDecoder<unknown>>(\n schema: S\n): Parser<S[\"Type\"], Schema.SchemaError, never, string> => {\n const ast = schema.ast\n const parser = derive(ast, initial<AnyParser>())\n return grammarOf(ast).whitespace === true ? P.delimited(Ascii.multispace0, parser, Ascii.multispace0) : parser\n}\n\n/**\n * Derives a printer from a schema: it writes a value of the schema's type as\n * the text {@link toParser} reads, following the same annotations, with no\n * optional whitespace. Transformations encode the value first, and a\n * {@link Grammar.print} replaces the derived printer.\n *\n * The printer fails with a `SchemaError` when the value is not of the\n * schema's type, or cannot be written so that it reads back: a string that\n * is empty or contains a character that would end it (a separator, a\n * suffix), or a part annotated with a parser but no `print`. Where the\n * grammar is ambiguous (an optional field followed by a field of the same\n * type), the text can still read back as a different value;\n * {@link fromSchema} checks that it doesn't.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n * import { ParserSchema } from \"@thomasfosterau/effect-parse\"\n *\n * const Version = Schema.Struct({ major: Schema.Int, minor: Schema.Int }).pipe(\n * ParserSchema.annotate({ separator: \".\" })\n * )\n *\n * ParserSchema.toPrinter(Version)({ major: 1, minor: 2 }) // Result.succeed(\"1.2\")\n * ```\n *\n * @since 0.3.0\n * @category derivation\n */\nexport const toPrinter = <S extends Schema.ConstraintCodec<unknown, unknown, unknown, never>>(\n schema: S\n): ((value: S[\"Type\"]) => Result.Result<string, Schema.SchemaError>) => {\n const validate = typeDecoder(schema.ast)\n const print = printerOf(schema.ast, initial<Printer>())\n return (value) => {\n const valid = validate(value)\n if (Result.isFailure(valid)) return Result.fail(valid.failure)\n const out: Array<string> = []\n const issue = print(valid.success, out)\n return issue === undefined ? Result.succeed(out.join(\"\")) : Result.fail(schemaError(issue))\n }\n}\n\n/**\n * Creates a schema that decodes a string with the parser {@link toParser}\n * derives from `schema`, into `schema`'s type, and encodes with the printer\n * {@link toPrinter} derives, or with `encode` when given. A derived printer's\n * text is parsed back, and encoding fails unless it gives a value equivalent\n * to the one encoded, so decoding what was encoded always gives it back.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n * import { ParserSchema } from \"@thomasfosterau/effect-parse\"\n *\n * const Pair = ParserSchema.fromSchema(\n * Schema.Tuple([Schema.String, Schema.Number]).pipe(ParserSchema.annotate({ separator: \"=\" }))\n * )\n *\n * Schema.decodeUnknownSync(Pair)(\"width=10\") // [\"width\", 10]\n * Schema.encodeSync(Pair)([\"height\", 2]) // \"height=2\"\n * ```\n *\n * @since 0.3.0\n * @category constructors\n */\nexport const fromSchema = <S extends Schema.ConstraintCodec<unknown, unknown, never, never> & Schema.Top>(\n schema: S,\n options?: { readonly encode?: ((value: S[\"Type\"]) => string) | undefined }\n): Schema.decodeTo<Schema.toType<S>, Schema.String> => {\n const parser = toParser(schema)\n const encode = options?.encode\n return decodeWith<Schema.toType<S>>(\n Schema.toType(schema),\n parser,\n encode === undefined ? roundTrip(schema, parser) : encodeWith(encode)\n )\n}\n\n/** Prints with the derived printer, then checks that the text reads back as the value. */\nconst roundTrip = <S extends Schema.ConstraintCodec<unknown, unknown, never, never> & Schema.Top>(\n schema: S,\n parser: Parser<S[\"Type\"], Schema.SchemaError, never, string>\n): Encode<S[\"Type\"]> => {\n const print = toPrinter(schema)\n const equivalent = Schema.toEquivalence(Schema.toType(schema))\n return (value) =>\n Result.flatMap(\n Result.mapError(print(value), (error) => error.issue),\n (text) => {\n const back = P.parse(parser, text)\n return Result.isSuccess(back) && equivalent(back.success, value)\n ? Result.succeed(text)\n : Result.fail(\n new SchemaIssue.InvalidValue({\n message: `The value is written ${describeLiteral(text)}, which does not read back as the value`\n })\n )\n }\n )\n}\n\n// -----------------------------------------------------------------------------\n// The walk shared by parsers and printers\n// -----------------------------------------------------------------------------\n\ninterface Context<T> {\n /** Characters ending an unannotated string, sorted. */\n readonly stop: string\n readonly whitespace: boolean\n /** Grammar passed from a transformation to its encoded side. */\n readonly inherit: Grammar | undefined\n readonly path: ReadonlyArray<PropertyKey>\n /** What was derived for the recursive schemas met so far, by context. */\n readonly recursions: Array<Recursion<T>>\n}\n\ninterface Recursion<T> {\n readonly ast: SchemaAST.Suspend\n readonly key: string\n readonly derived: T\n}\n\nconst initial = <T>(): Context<T> => ({ stop: \"\", whitespace: false, inherit: undefined, path: [], recursions: [] })\n\n/** The annotation `key` on `ast`, from its last check back to the node, as `Schema.resolveAnnotations` resolves it. */\nconst lookup = (ast: SchemaAST.AST, key: string): unknown => {\n const checks = ast.checks\n if (checks !== undefined) {\n for (let i = checks.length - 1; i >= 0; i--) {\n const value = checks[i].annotations?.[key]\n if (value !== undefined) return value\n }\n }\n return ast.annotations?.[key]\n}\n\nconst grammarOf = (ast: SchemaAST.AST): Grammar => {\n const value = lookup(ast, annotationKey)\n if (value === undefined) return {}\n // SAFETY: the annotation is typed `Annotation`, a parser or a grammar\n return P.isParser(value) ? { parser: value as ForeignParser } : (value as Grammar)\n}\n\nconst isAnnotated = (ast: SchemaAST.AST): boolean => lookup(ast, annotationKey) !== undefined\n\nconst withStop = <T>(ctx: Context<T>, text: string | undefined): Context<T> => {\n if (text === undefined || text === \"\" || ctx.stop.includes(text[0])) return ctx\n return { ...ctx, stop: Arr.sort([...ctx.stop.split(\"\"), text[0]], Order.String).join(\"\") }\n}\n\nconst at = <T>(ctx: Context<T>, key: PropertyKey): Context<T> => ({\n ...ctx,\n inherit: undefined,\n path: [...ctx.path, key]\n})\n\nconst where = <T>(ctx: Context<T>): string => `[${ctx.path.map(String).join(\", \")}]`\n\nconst unsupported = <T>(ast: SchemaAST.AST, ctx: Context<T>, what: string): never => {\n throw new TypeError(`ParserSchema: cannot derive a ${what} for ${ast._tag} at ${where(ctx)}; annotate it`)\n}\n\ninterface Resolved<T> {\n readonly grammar: Grammar\n readonly whitespace: boolean\n /** The context of what the node contains. */\n readonly inner: Context<T>\n}\n\n/** The node's grammar, with what its transformation passed down, and the context inside it. */\nconst resolve = <T>(ast: SchemaAST.AST, ctx: Context<T>): Resolved<T> => {\n const own = grammarOf(ast)\n const inherit = ctx.inherit\n const grammar: Grammar =\n inherit === undefined\n ? own\n : {\n ...own,\n separator: own.separator ?? inherit.separator,\n keySeparator: own.keySeparator ?? inherit.keySeparator\n }\n const whitespace = grammar.whitespace ?? ctx.whitespace\n return { grammar, whitespace, inner: { ...withStop(ctx, grammar.suffix), whitespace, inherit: undefined } }\n}\n\n/** The context of a transformation's encoded side, which the transformation's separators apply to. */\nconst encodedContext = <T>(grammar: Grammar, ctx: Context<T>): Context<T> => ({\n ...ctx,\n inherit: { separator: grammar.separator, keySeparator: grammar.keySeparator }\n})\n\n/**\n * The node with its chain of links ending at the type of its encoded side,\n * which is what the encoded side is parsed into and printed from.\n */\nconst linkTarget = (ast: SchemaAST.AST, links: SchemaAST.Encoding): SchemaAST.AST => {\n const last = links[links.length - 1]\n let target = SchemaAST.toType(ast)\n for (const link of links) {\n const source = link === last ? SchemaAST.toType(last.to) : link.to\n // SAFETY: `decodeTo` appends the link as it is, middleware included, as the schema's own links are\n target = SchemaAST.decodeTo(source, target, link.transformation as SchemaTransformation.Transformation<any, any>)\n }\n return target\n}\n\n/**\n * What is derived for a recursive schema: deriving it again in the same\n * context gives the same result, so the derivation ends.\n */\nconst recursive = <T>(ast: SchemaAST.Suspend, ctx: Context<T>, make: () => T): T => {\n const key = `${ctx.whitespace ? 1 : 0}${ctx.stop}`\n const known = ctx.recursions.find((r) => r.ast === ast && r.key === key)\n if (known !== undefined) return known.derived\n const derived = make()\n ctx.recursions.push({ ast, key, derived })\n return derived\n}\n\n/** The context for the items of a sequence: unannotated strings also stop at the separator. */\nconst itemContext = <T>(grammar: Grammar, ctx: Context<T>): Context<T> => withStop(ctx, grammar.separator)\n\n/** The rest element of an array schema, if any; elements after it are not supported. */\nconst restOf = <T>(ast: SchemaAST.Arrays, ctx: Context<T>, what: string): SchemaAST.AST | undefined => {\n const [head, ...after] = ast.rest\n // Elements after the rest would need the rest to stop short\n return Arr.isReadonlyArrayNonEmpty(after) ? unsupported(ast, ctx, what) : head\n}\n\n/** The contexts of an array schema's elements and its rest. */\nconst elementContexts = <T>(\n ast: SchemaAST.Arrays,\n rest: SchemaAST.AST | undefined,\n grammar: Grammar,\n ctx: Context<T>\n): ReadonlyArray<Context<T>> => {\n const n = ast.elements.length\n return ast.elements.map((_, i) => at(i < n - 1 || rest !== undefined ? itemContext(grammar, ctx) : ctx, i))\n}\n\n/** The contexts of a struct's fields, written in order. */\nconst fieldContexts = <T>(ast: SchemaAST.Objects, grammar: Grammar, ctx: Context<T>): ReadonlyArray<Context<T>> => {\n const fields = ast.propertySignatures\n return fields.map((field, i) => at(i < fields.length - 1 ? itemContext(grammar, ctx) : ctx, field.name))\n}\n\nconst isKeyed = (ast: SchemaAST.Objects, grammar: Grammar): boolean =>\n grammar.keySeparator !== undefined || Arr.isReadonlyArrayNonEmpty(ast.indexSignatures)\n\nconst keySeparatorOf = <T>(grammar: Grammar, ctx: Context<T>): string => {\n if (grammar.keySeparator === undefined) {\n throw new TypeError(`ParserSchema: a record at ${where(ctx)} needs a keySeparator in its annotation`)\n }\n return grammar.keySeparator\n}\n\n/** The field name of a struct in keyed form: a string. */\nconst keyName = <T>(ast: SchemaAST.Objects, field: SchemaAST.PropertySignature, ctx: Context<T>, what: string) =>\n Predicate.isString(field.name) ? field.name : unsupported(ast, ctx, what)\n\nconst propertyName = (key: PropertyKey): string | symbol => (Predicate.isNumber(key) ? String(key) : key)\n\n/** Whether a check (as `Schema.Int` has) restricts numbers to integers. */\nconst isIntegral = (checks: SchemaAST.Checks | undefined): boolean =>\n checks !== undefined &&\n checks.some((check) =>\n check instanceof SchemaAST.FilterGroup\n ? isIntegral(check.checks)\n : check.annotations?.arbitraryConstraint?.[\"number\"] === \"integer\"\n )\n\ntype LiteralValue = SchemaAST.Literal[\"literal\"]\n\n/** Literals with the longest text first, so a literal is never cut short by one it starts with. */\nconst byLength = <A extends LiteralValue>(values: ReadonlyArray<A>): Array<A> =>\n Arr.sort(\n values,\n Order.mapInput(Order.Number, (value: A) => -String(value).length)\n )\n\nconst isPlainLiteral = (ast: SchemaAST.AST): ast is SchemaAST.Literal =>\n SchemaAST.isLiteral(ast) && ast.encoding === undefined && !isAnnotated(ast)\n\n/** The literals of a union of plain literals, longest first, or `undefined`. */\nconst plainLiterals = (ast: SchemaAST.Union): ReadonlyArray<LiteralValue> | undefined => {\n const literals = Arr.filter(ast.types, isPlainLiteral)\n return literals.length === ast.types.length ? byLength(literals.map((member) => member.literal)) : undefined\n}\n\nconst schemaError = (issue: SchemaIssue.Issue) => new Schema.SchemaError(issue)\n\nconst decoder = (schema: Schema.ConstraintDecoder<unknown>) => Schema.decodeUnknownResult(schema)\n\n/** Decodes into the type of `ast`, checks included. */\nconst typeDecoder = (ast: SchemaAST.AST) => decoder(Schema.make<Schema.Codec<unknown>>(SchemaAST.toType(ast)))\n\n// -----------------------------------------------------------------------------\n// Parsers\n// -----------------------------------------------------------------------------\n\ntype AnyParser = Parser<any, Schema.SchemaError, never, string>\n\ntype ForeignParser = Parser<unknown, unknown, never, string>\n\nconst messageOf = (cause: unknown): string =>\n Predicate.isString(cause)\n ? cause\n : Predicate.hasProperty(cause, \"message\") && Predicate.isString(cause.message)\n ? cause.message\n : String(cause)\n\n/** A parser whose failures' causes are `SchemaError`s, as {@link toParser}'s are. */\nconst asSchemaErrors = (parser: ForeignParser): AnyParser =>\n P.mapError(parser, (cause) =>\n cause instanceof Schema.SchemaError\n ? cause\n : schemaError(new SchemaIssue.InvalidValue({ message: messageOf(cause) }))\n )\n\n/** Literal text, with optional whitespace around it. */\nconst text = (s: string, ws: boolean): AnyParser =>\n ws ? P.delimited(Ascii.multispace0, Token.literal(s), Ascii.multispace0) : Token.literal(s)\n\nconst derive = (ast: SchemaAST.AST, ctx: Context<AnyParser>): AnyParser => {\n const { grammar, inner, whitespace } = resolve(ast, ctx)\n let parser: AnyParser\n if (grammar.parser !== undefined) parser = P.tryMap(asSchemaErrors(grammar.parser), typeDecoder(ast))\n else if (ast.encoding !== undefined) parser = decoded(ast, ast.encoding, grammar, inner)\n else parser = checked(ast, structural(ast, grammar, inner))\n if (grammar.prefix !== undefined) parser = P.preceded(text(grammar.prefix, whitespace), parser)\n if (grammar.suffix !== undefined) parser = P.terminated(parser, text(grammar.suffix, whitespace))\n // A check's own `expected` describes the check, not the text\n const label = lookup(ast, \"identifier\") ?? ast.annotations?.expected\n return Predicate.isString(label) ? P.expected(parser, label) : parser\n}\n\n/** Runs the checks on `ast` (its filters) on the parser's output. */\nconst checked = (ast: SchemaAST.AST, parser: AnyParser): AnyParser =>\n ast.checks === undefined ? parser : P.tryMap(parser, decoder(Schema.Unknown.check(...ast.checks)))\n\n/**\n * Parses the encoded side of a transformation and decodes it. The encoded\n * side is parsed into its own type, so the last link decodes from that type\n * rather than from the fully encoded form.\n */\nconst decoded = (\n ast: SchemaAST.AST,\n links: SchemaAST.Encoding,\n grammar: Grammar,\n ctx: Context<AnyParser>\n): AnyParser => {\n const from = derive(links[links.length - 1].to, encodedContext(grammar, ctx))\n return P.tryMap(from, decoder(Schema.make<Schema.Codec<unknown>>(linkTarget(ast, links))))\n}\n\nconst structural = (ast: SchemaAST.AST, grammar: Grammar, ctx: Context<AnyParser>): AnyParser =>\n Match.valueTags(ast, {\n String: () => unannotatedString(ctx, 1),\n Number: (number) => (isIntegral(number.checks) ? integer : Ascii.float),\n BigInt: () => Ascii.decBigInt,\n Boolean: () => P.alt(P.as(Token.literal(\"true\"), true), P.as(Token.literal(\"false\"), false)),\n Null: () => P.as(Token.literal(\"null\"), null),\n Undefined: () => P.succeed(undefined),\n Void: () => P.succeed(undefined),\n Never: () => P.reject,\n Literal: (lit) => literal(lit.literal),\n Enum: (e) => P.alt(...byLength(e.enums.map(([, value]) => value)).map(literal)),\n TemplateLiteral: (template) => templateLiteral(template, ctx),\n Arrays: (arrays) => sequenceOf(arrays, grammar, ctx),\n Objects: (objects) =>\n isKeyed(objects, grammar) ? keyed(objects, grammar, ctx) : positional(objects, grammar, ctx),\n Union: (union) => alternatives(union, ctx),\n Suspend: (suspend) => recursive(suspend, ctx, () => P.suspend(() => derive(suspend.thunk(), ctx))),\n Declaration: (other) => unsupported(other, ctx, \"parser\"),\n Unknown: (other) => unsupported(other, ctx, \"parser\"),\n Any: (other) => unsupported(other, ctx, \"parser\"),\n Symbol: (other) => unsupported(other, ctx, \"parser\"),\n UniqueSymbol: (other) => unsupported(other, ctx, \"parser\"),\n ObjectKeyword: (other) => unsupported(other, ctx, \"parser\")\n })\n\nconst unannotatedString = (ctx: Context<AnyParser>, min: number): AnyParser => {\n const s = Token.takeTill(ctx.stop, { min })\n // Leading whitespace is skipped first, so it doesn't count towards `min`\n return ctx.whitespace\n ? P.preceded(\n Ascii.multispace0,\n P.map(s, (value) => value.trimEnd())\n )\n : s\n}\n\nconst integer: AnyParser = /*#__PURE__*/ asSchemaErrors(Ascii.decInt)\n\nconst literal = (value: LiteralValue): AnyParser => P.as(Token.literal(String(value)), value)\n\nconst templateLiteral = (ast: SchemaAST.TemplateLiteral, ctx: Context<AnyParser>): AnyParser =>\n P.taken(\n P.seq(\n ...ast.parts.map((part, i) => {\n const next = ast.parts[i + 1]\n const partCtx = next !== undefined && SchemaAST.isLiteral(next) ? withStop(ctx, String(next.literal)) : ctx\n // An interpolated string may be empty\n return SchemaAST.isString(part) && !isAnnotated(part)\n ? unannotatedString(partCtx, 0)\n : derive(part, at(partCtx, i))\n })\n )\n )\n\nconst alternatives = (ast: SchemaAST.Union, ctx: Context<AnyParser>): AnyParser => {\n const literals = plainLiterals(ast)\n return literals !== undefined\n ? P.alt(...literals.map(literal))\n : P.alt(...ast.types.map((member) => derive(member, ctx)))\n}\n\ninterface Item {\n readonly parser: AnyParser\n readonly optional: boolean\n}\n\ntype Values = Parser<Array<unknown>, Schema.SchemaError, never, string>\n\n/**\n * Parses `items` in order, then any number of `rest`, with `separator`\n * between the ones present. The output has the value of item `i` at index\n * `i` (a hole when an optional item is missing), then the rest.\n */\nconst sequence = (\n items: ReadonlyArray<Item>,\n rest: AnyParser | undefined,\n separator: AnyParser | undefined\n): Values => {\n const n = items.length\n const tail = (needSeparator: boolean): Values => {\n if (rest === undefined) return P.sync(() => new Array(n))\n const values =\n separator === undefined\n ? P.repeat(rest)\n : needSeparator\n ? P.repeat(P.preceded(separator, rest))\n : P.separated(rest, separator)\n return P.map(values, (xs) => {\n const out = new Array(n)\n for (let j = 0; j < xs.length; j++) out[n + j] = xs[j]\n return out\n })\n }\n // One parser per position and whether a separator comes first, at index `2 * i + needSeparator`\n const memo: Array<Values | undefined> = []\n const from = (i: number, needSeparator: boolean): Values => {\n const key = i * 2 + (needSeparator ? 1 : 0)\n const known = memo[key]\n if (known !== undefined) return known\n let parser: Values\n if (i === n) parser = tail(needSeparator)\n else {\n const item = items[i]\n const head = needSeparator && separator !== undefined ? P.preceded(separator, item.parser) : item.parser\n const present = P.map(P.seq(head, from(i + 1, true)), ([value, out]) => {\n out[i] = value\n return out\n })\n parser = item.optional ? P.alt(present, from(i + 1, needSeparator)) : present\n }\n memo[key] = parser\n return parser\n }\n return from(0, false)\n}\n\nconst separatorOf = (grammar: Grammar, ctx: Context<AnyParser>): AnyParser | undefined =>\n grammar.separator === undefined ? undefined : text(grammar.separator, ctx.whitespace)\n\nconst sequenceOf = (ast: SchemaAST.Arrays, grammar: Grammar, ctx: Context<AnyParser>): AnyParser => {\n const head = restOf(ast, ctx, \"parser\")\n const contexts = elementContexts(ast, head, grammar, ctx)\n const items = ast.elements.map((element, i) => ({\n parser: derive(element, contexts[i]),\n optional: SchemaAST.isOptional(element)\n }))\n const rest = head === undefined ? undefined : derive(head, at(itemContext(grammar, ctx), items.length))\n // Optional elements come last, so the present values are the first ones\n return P.map(sequence(items, rest, separatorOf(grammar, ctx)), (out) => out.filter((_, i) => i in out))\n}\n\nconst positional = (ast: SchemaAST.Objects, grammar: Grammar, ctx: Context<AnyParser>): AnyParser => {\n const fields = ast.propertySignatures\n const contexts = fieldContexts(ast, grammar, ctx)\n const items = fields.map((field, i) => ({\n parser: derive(field.type, contexts[i]),\n optional: SchemaAST.isOptional(field.type)\n }))\n return P.map(sequence(items, undefined, separatorOf(grammar, ctx)), (out) =>\n Record.fromEntries(fields.flatMap((field, i) => (i in out ? [[propertyName(field.name), out[i]] as const] : [])))\n )\n}\n\ntype Entry = readonly [key: string | symbol, value: unknown, known: boolean]\n\nconst keyed = (ast: SchemaAST.Objects, grammar: Grammar, ctx: Context<AnyParser>): AnyParser => {\n const keySeparator = keySeparatorOf(grammar, ctx)\n const between = text(keySeparator, ctx.whitespace)\n const valueCtx = itemContext(grammar, ctx)\n const known = ast.propertySignatures.map((field): AnyParser => {\n const name = keyName(ast, field, ctx, \"parser\")\n const value = derive(field.type, at(valueCtx, name))\n return P.map(P.preceded(P.seq(Token.literal(name), between), value), (v): Entry => [name, v, true])\n })\n const indexed = ast.indexSignatures.map((signature): AnyParser => {\n const key = derive(signature.parameter, at(withStop(ctx, keySeparator), \"<key>\"))\n const value = derive(signature.type, at(valueCtx, \"<value>\"))\n return P.map(P.separatedPair(key, between, value), ([k, v]): Entry => [propertyName(k), v, false])\n })\n const entry = P.alt(...known, ...indexed)\n const separator = separatorOf(grammar, ctx)\n const entries = separator === undefined ? P.repeat(entry) : P.separated(entry, separator)\n // A missing field fails where its entry could have been, as a syntax error, so a\n // failure further in (the entry that ended the repetition early) is reported instead\n const missing = ast.propertySignatures.map((field) =>\n P.expected(P.reject, describeLiteral(`${String(field.name)}${keySeparator}`))\n )\n return P.flatMap(\n P.tryMap(entries, (es: ReadonlyArray<Entry>) => assemble(ast, es)),\n ([value, absent]) => (absent === undefined ? P.succeed(value) : missing[absent])\n )\n}\n\n/**\n * Builds the object from its entries, declared fields first, rejecting\n * duplicate keys. Also returns the index of the first required field\n * missing, if any.\n */\nconst assemble = (\n ast: SchemaAST.Objects,\n entries: ReadonlyArray<Entry>\n): Result.Result<readonly [object, number | undefined], Schema.SchemaError> => {\n const values = MutableHashMap.empty<string | symbol, unknown>()\n for (const [key, value] of entries) {\n if (MutableHashMap.has(values, key)) {\n return Result.fail(\n schemaError(new SchemaIssue.Pointer([key], new SchemaIssue.InvalidValue({ message: \"Duplicate key\" })))\n )\n }\n MutableHashMap.set(values, key, value)\n }\n const out: Array<readonly [string | symbol, unknown]> = []\n let absent: number | undefined\n ast.propertySignatures.forEach((field, i) => {\n const name = propertyName(field.name)\n const value = MutableHashMap.get(values, name)\n if (Option.isSome(value)) out.push([name, value.value])\n else if (absent === undefined && !SchemaAST.isOptional(field.type)) absent = i\n })\n for (const [key, value, isKnown] of entries) if (!isKnown) out.push([key, value])\n return Result.succeed([Record.fromEntries(out), absent])\n}\n\n// -----------------------------------------------------------------------------\n// Printers\n// -----------------------------------------------------------------------------\n\n/**\n * Writes the text of a value, already validated against the schema's type,\n * to `out`, or returns why it cannot be written.\n */\ntype Printer = (value: any, out: Array<string>) => SchemaIssue.Issue | undefined\n\n/** The issue for a value that cannot be written at the node `ctx` is at. */\nconst unwritable = <T>(ctx: Context<T>, message: string, value: unknown): SchemaIssue.Issue => {\n const issue = new SchemaIssue.InvalidValue({ message }, value, { reportInput: true })\n return Arr.isReadonlyArrayNonEmpty(ctx.path) ? new SchemaIssue.Pointer(ctx.path, issue) : issue\n}\n\nconst writing =\n (show: (value: any) => string): Printer =>\n (value, out) => {\n out.push(show(value))\n return undefined\n }\n\nconst nothing: Printer = (_, __) => undefined\n\nconst printerOf = (ast: SchemaAST.AST, ctx: Context<Printer>): Printer => {\n const { grammar, inner } = resolve(ast, ctx)\n let print: Printer\n if (grammar.print !== undefined) print = writing(grammar.print)\n else if (grammar.parser !== undefined) print = unprintable(ctx)\n else if (ast.encoding !== undefined) print = encoded(ast, ast.encoding, grammar, inner)\n else print = printerFor(ast, grammar, inner)\n const prefix = grammar.prefix\n const suffix = grammar.suffix\n if (prefix === undefined && suffix === undefined) return print\n const inside = print\n return (value, out) => {\n if (prefix !== undefined) out.push(prefix)\n const issue = inside(value, out)\n if (suffix !== undefined) out.push(suffix)\n return issue\n }\n}\n\nconst unprintable =\n (ctx: Context<Printer>): Printer =>\n (value) =>\n unwritable(ctx, \"This value has a parser in its annotation but no print, so it cannot be written\", value)\n\n/** Encodes a transformation's value and prints its encoded side. */\nconst encoded = (ast: SchemaAST.AST, links: SchemaAST.Encoding, grammar: Grammar, ctx: Context<Printer>): Printer => {\n const to = printerOf(links[links.length - 1].to, encodedContext(grammar, ctx))\n const encode = Schema.encodeUnknownResult(Schema.make<Schema.Codec<unknown, unknown>>(linkTarget(ast, links)))\n return (value, out) => {\n const result = encode(value)\n return Result.isSuccess(result) ? to(result.success, out) : result.failure.issue\n }\n}\n\nconst printerFor = (ast: SchemaAST.AST, grammar: Grammar, ctx: Context<Printer>): Printer =>\n Match.valueTags(ast, {\n String: () => stringPrinter(ctx),\n Number: () => writing(String),\n BigInt: () => writing(String),\n Boolean: () => writing(String),\n Null: () => writing(String),\n Undefined: () => nothing,\n Void: () => nothing,\n Never: () => nothing,\n Literal: () => writing(String),\n Enum: () => writing(String),\n TemplateLiteral: () => writing(String),\n Arrays: (arrays) => arraysPrinter(arrays, grammar, ctx),\n Objects: (objects) =>\n isKeyed(objects, grammar) ? keyedPrinter(objects, grammar, ctx) : positionalPrinter(objects, grammar, ctx),\n Union: (union) => unionPrinter(union, ctx),\n Suspend: (suspend) =>\n recursive(suspend, ctx, () => {\n let print: Printer | undefined\n return (value, out) => (print ??= printerOf(suspend.thunk(), ctx))(value, out)\n }),\n Declaration: (other) => unsupported(other, ctx, \"printer\"),\n Unknown: (other) => unsupported(other, ctx, \"printer\"),\n Any: (other) => unsupported(other, ctx, \"printer\"),\n Symbol: (other) => unsupported(other, ctx, \"printer\"),\n UniqueSymbol: (other) => unsupported(other, ctx, \"printer\"),\n ObjectKeyword: (other) => unsupported(other, ctx, \"printer\")\n })\n\n/**\n * Writes a string as an unannotated string is parsed: refusing one that\n * would not read back, being empty or holding a character that ends it.\n */\nconst stringPrinter =\n (ctx: Context<Printer>): Printer =>\n (value: string, out) => {\n if (value === \"\") return unwritable(ctx, \"An empty string cannot be written here\", value)\n const stop = Arr.findFirst(Array.from(ctx.stop), (c) => value.includes(c))\n if (Option.isSome(stop)) {\n return unwritable(ctx, `A string containing ${describeLiteral(stop.value)} cannot be written here`, value)\n }\n if (ctx.whitespace && value.trim() !== value) {\n return unwritable(ctx, \"A string with whitespace around it cannot be written here\", value)\n }\n out.push(value)\n return undefined\n }\n\n/** Writes values with a separator between them, stopping at the first that cannot be written. */\nconst writeAll = (\n writes: ReadonlyArray<(out: Array<string>) => SchemaIssue.Issue | undefined>,\n separator: string,\n out: Array<string>\n): SchemaIssue.Issue | undefined => {\n for (let i = 0; i < writes.length; i++) {\n if (i > 0) out.push(separator)\n const issue = writes[i](out)\n if (issue !== undefined) return issue\n }\n return undefined\n}\n\nconst arraysPrinter = (ast: SchemaAST.Arrays, grammar: Grammar, ctx: Context<Printer>): Printer => {\n const head = restOf(ast, ctx, \"printer\")\n const contexts = elementContexts(ast, head, grammar, ctx)\n const elements = ast.elements.map((element, i) => printerOf(element, contexts[i]))\n const rest = head === undefined ? nothing : printerOf(head, at(itemContext(grammar, ctx), elements.length))\n const separator = grammar.separator ?? \"\"\n return (value: ReadonlyArray<unknown>, out) =>\n writeAll(\n value.map((element, i) => (o: Array<string>) => (elements[i] ?? rest)(element, o)),\n separator,\n out\n )\n}\n\nconst positionalPrinter = (ast: SchemaAST.Objects, grammar: Grammar, ctx: Context<Printer>): Printer => {\n const contexts = fieldContexts(ast, grammar, ctx)\n const fields = ast.propertySignatures.map((field, i) => ({\n name: propertyName(field.name),\n print: printerOf(field.type, contexts[i])\n }))\n const separator = grammar.separator ?? \"\"\n return (value: Record.ReadonlyRecord<string | symbol, unknown>, out) =>\n writeAll(\n fields\n .filter((field) => Record.has(value, field.name))\n .map((field) => (o: Array<string>) => field.print(value[field.name], o)),\n separator,\n out\n )\n}\n\nconst keyedPrinter = (ast: SchemaAST.Objects, grammar: Grammar, ctx: Context<Printer>): Printer => {\n const keySeparator = keySeparatorOf(grammar, ctx)\n const valueCtx = itemContext(grammar, ctx)\n const fields = ast.propertySignatures.map((field) => {\n const name = keyName(ast, field, ctx, \"printer\")\n return { name, print: printerOf(field.type, at(valueCtx, name)) }\n })\n const names = fields.map((field) => field.name)\n const indexed = ast.indexSignatures.map((signature) => ({\n is: Schema.is(Schema.make<Schema.Top>(SchemaAST.toType(signature.parameter))),\n key: printerOf(signature.parameter, at(withStop(ctx, keySeparator), \"<key>\")),\n value: printerOf(signature.type, at(valueCtx, \"<value>\"))\n }))\n const entry =\n (key: Printer, print: Printer, k: unknown, v: unknown) =>\n (out: Array<string>): SchemaIssue.Issue | undefined =>\n key(k, out) ?? (out.push(keySeparator), print(v, out))\n return (value: Record.ReadonlyRecord<string, unknown>, out) => {\n const writes = fields\n .filter((field) => Record.has(value, field.name))\n .map((field) => entry(writing(String), field.print, field.name, value[field.name]))\n for (const key of Record.keys(value)) {\n const signature = names.includes(key) ? undefined : indexed.find((s) => s.is(key))\n if (signature !== undefined) writes.push(entry(signature.key, signature.value, key, value[key]))\n }\n return writeAll(writes, grammar.separator ?? \"\", out)\n }\n}\n\n/** Writes a union's value with the first member it belongs to that can write it. */\nconst unionPrinter = (ast: SchemaAST.Union, ctx: Context<Printer>): Printer => {\n if (plainLiterals(ast) !== undefined) return writing(String)\n const members = ast.types.map((member) => ({\n is: Schema.is(Schema.make<Schema.Top>(SchemaAST.toType(member))),\n print: printerOf(member, ctx)\n }))\n return (value, out) => {\n let issue: SchemaIssue.Issue | undefined\n for (const member of members) {\n if (!member.is(value)) continue\n const mark = out.length\n issue = member.print(value, out)\n if (issue === undefined) return undefined\n out.length = mark\n }\n return issue ?? unwritable(ctx, \"No member of the union can write this value\", value)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,MAAa,gBAAgB;AAsC7B,MAAM,cACA,YACH,UACC,OAAO,QAAQ,OAAO,KAAK,CAAC;AAEhC,MAAM,cACJ,QACA,QACA,WAEA,OAAO,OAAO,KACZ,OAAO,SACL,QACA,qBAAqB,gBAAsC;CACzD,SAAS,OAAO,iBAAiB;EAC/B,MAAM,SAAS,EAAE,MAAM,QAAQ,KAAK;EACpC,OAAO,OAAO,UAAU,MAAM,IAC1B,OAAO,QAAQ,OAAO,OAAO,IAC7B,OAAO,KAAK,IAAI,YAAY,aAAa,EAAE,SAAS,OAAO,QAAQ,QAAQ,GAAG,OAAO,YAAY,CAAC;CACxG;CAC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AM,GAAG,MAAM,OAAO,MAAM,MAAM,MAAM,MAAM,KAAK,CAAC;EACpF,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GAAG;GACpC,MAAM,YAAY,MAAM,SAAS,GAAG,IAAI,KAAA,IAAY,QAAQ,MAAM,MAAM,EAAE,GAAG,GAAG,CAAC;GACjF,IAAI,cAAc,KAAA,GAAW,OAAO,KAAK,MAAM,UAAU,KAAK,UAAU,OAAO,KAAK,MAAM,IAAI,CAAC;EACjG;EACA,OAAO,SAAS,QAAQ,QAAQ,aAAa,IAAI,GAAG;CACtD;AACF;;AAGA,MAAM,gBAAgB,KAAsB,QAAmC;CAC7E,IAAI,cAAc,GAAG,MAAM,KAAA,GAAW,OAAO,QAAQ,MAAM;CAC3D,MAAM,UAAU,IAAI,MAAM,KAAK,YAAY;EACzC,IAAI,OAAO,GAAG,OAAO,KAAiB,UAAU,OAAO,MAAM,CAAC,CAAC;EAC/D,OAAO,UAAU,QAAQ,GAAG;CAC9B,EAAE;CACF,QAAQ,OAAO,QAAQ;EACrB,IAAI;EACJ,KAAK,MAAM,UAAU,SAAS;GAC5B,IAAI,CAAC,OAAO,GAAG,KAAK,GAAG;GACvB,MAAM,OAAO,IAAI;GACjB,QAAQ,OAAO,MAAM,OAAO,GAAG;GAC/B,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;GAChC,IAAI,SAAS;EACf;EACA,OAAO,SAAS,WAAW,KAAK,+CAA+C,KAAK;CACtF;AACF"}
@@ -3,7 +3,6 @@ import { Parser } from "./Parser.js";
3
3
  import * as Effect from "effect/Effect";
4
4
  import * as ParseError from "./ParseError.js";
5
5
  import * as Stream from "effect/Stream";
6
- //#region src/ParserStream.d.ts
7
6
  /**
8
7
  * Input kinds that can be streamed in chunks.
9
8
  *
@@ -128,6 +127,5 @@ export declare const parseResponse: {
128
127
  <A, E, R>(parser: Parser<A, E, R, Uint8Array>): (self: Response) => Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>;
129
128
  <A, E, R>(self: Response, parser: Parser<A, E, R, Uint8Array>): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>;
130
129
  };
131
- //#endregion
132
130
  export {};
133
131
  //# sourceMappingURL=ParserStream.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ParserStream.d.ts","names":[],"sources":["../src/ParserStream.ts"],"mappings":";;;;;;;;;;;;YA8CY,qBAAqB,aAAa;;;;;;;iBA8B7B,iBAAiB;;WAEvB,QAAQ,OAAO;;;;;;;;;;;;;;;;;;qBAmBb;GACV,GAAG,GAAG,GAAG,UAAU,WAClB,QAAQ,OAAO,GAAG,GAAG,GAAG,IACxB,UAAU,iBAAiB,MACzB,IAAI,IAAI,MAAM,OAAO,OAAO,OAAO,IAAI,IAAI,QAAQ,OAAO,OAAO,GAAG,KAAK,WAAW,WAAW,IAAI,KAAK;GAC3G,UAAU,WAAW,IAAI,IAAI,GAAG,GAAG,GAClC,MAAM,OAAO,OAAO,OAAO,QAAQ,KAAK,IAAI,KAC5C,QAAQ,OAAO,GAAG,GAAG,GAAG,IACxB,UAAU,iBAAiB,KAC1B,OAAO,OAAO,GAAG,KAAK,WAAW,WAAW,IAAI,KAAK;;;;;;;;;;;;;;;;;;;;;;;;qBAiM7C;GACV,GAAG,GAAG,GAAG,UAAU,WAClB,QAAQ,OAAO,GAAG,GAAG,GAAG,IACxB,UAAU,iBAAiB,MACzB,IAAI,IAAI,MAAM,OAAO,OAAO,OAAO,IAAI,IAAI,QAAQ,OAAO,OAAO,GAAG,KAAK,WAAW,WAAW,IAAI,KAAK;GAC3G,UAAU,WAAW,IAAI,IAAI,GAAG,GAAG,GAClC,MAAM,OAAO,OAAO,OAAO,QAAQ,KAAK,IAAI,KAC5C,QAAQ,OAAO,GAAG,GAAG,GAAG,IACxB,UAAU,iBAAiB,KAC1B,OAAO,OAAO,GAAG,KAAK,WAAW,WAAW,IAAI,KAAK;;;;;;;;;;;;qBA2B7C,gCAAgC;WAAyC;;;;;;;;;;;;;;;;;;;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IAAI,MAAM,OAAO,OAAO,OAAO,IAAI,IAAI,QAAQ,OAAO,OAAO,GAAG,KAAK,WAAW,WAAW,IAAI,KAAK;GAC3G,UAAU,WAAW,IAAI,IAAI,GAAG,GAAG,GAClC,MAAM,OAAO,OAAO,OAAO,QAAQ,KAAK,IAAI,KAC5C,QAAQ,OAAO,GAAG,GAAG,GAAG,IACxB,UAAU,iBAAiB,KAC1B,OAAO,OAAO,GAAG,KAAK,WAAW,WAAW,IAAI,KAAK;;;;;;;;;;;;qBA2B7C,gCAAgC;WAAyC;;;;;;;;;;;;;;;;;;;;;;;qBAuBzE;GACV,GAAG,GAAG,GACL,QAAQ,OAAO,GAAG,GAAG,GAAG,eACtB,MAAM,eAAe,iBAAiB,OAAO,OAAO,GAAG,WAAW,WAAW,KAAK,WAAW;GAChG,GAAG,GAAG,GACL,MAAM,eAAe,cACrB,QAAQ,OAAO,GAAG,GAAG,GAAG,cACvB,OAAO,OAAO,GAAG,WAAW,WAAW,KAAK,WAAW;;;;;;;;;;;;;;;;;;;;;qBAiC/C;GACV,GAAG,GAAG,GACL,QAAQ,OAAO,GAAG,GAAG,GAAG,eACtB,MAAM,aAAa,OAAO,OAAO,GAAG,WAAW,WAAW,KAAK,WAAW;GAC7E,GAAG,GAAG,GACL,MAAM,UACN,QAAQ,OAAO,GAAG,GAAG,GAAG,cACvB,OAAO,OAAO,GAAG,WAAW,WAAW,KAAK,WAAW"}
@@ -1,6 +1,7 @@
1
1
  import * as Predicate from "effect/Predicate";
2
2
  import { Fail, Failure, State, fromSource } from "./Input.js";
3
3
  import * as Registry from "./internal/compiler/registry.js";
4
+ import { isEmptyUnits } from "./internal/text.js";
4
5
  import * as Data from "effect/Data";
5
6
  import * as Effect from "effect/Effect";
6
7
  import { dual } from "effect/Function";
@@ -8,7 +9,7 @@ import * as ParseError from "./ParseError.js";
8
9
  import * as Run from "./internal/run.js";
9
10
  import * as Stack from "./internal/stack.js";
10
11
  import * as Stream from "effect/Stream";
11
- //#region src/ParserStream.ts
12
+ // src/ParserStream.ts
12
13
  /**
13
14
  * Running parsers over Effect `Stream`s of input chunks.
14
15
  *
@@ -34,10 +35,11 @@ import * as Stream from "effect/Stream";
34
35
  *
35
36
  * @since 0.1.0
36
37
  */
37
- const concat = (a, b) => {
38
+ const concat = (first, b) => {
39
+ const a = first;
38
40
  if (Predicate.isString(a)) return a + b;
39
41
  if (a instanceof Uint8Array) {
40
- if (a.length === 0) return b;
42
+ if (a.byteLength === 0) return b;
41
43
  const out = new Uint8Array(a.length + b.length);
42
44
  out.set(a);
43
45
  out.set(b, a.length);
@@ -116,6 +118,7 @@ var Incremental = class {
116
118
  /** The input length at the last attempt, and where that attempt ran out of input. */
117
119
  attempted = 0;
118
120
  restart = 0;
121
+ pushed = 0;
119
122
  /** Set once an attempt settles: a success (with its end offset) or a definite failure. */
120
123
  settled;
121
124
  constructor(parser, context, empty) {
@@ -152,17 +155,21 @@ var Incremental = class {
152
155
  }
153
156
  }
154
157
  push(chunk) {
155
- if (chunk.length === 0) return;
158
+ if (isEmptyUnits(chunk)) return;
156
159
  this.append(chunk);
157
160
  if (this.settled !== void 0) return;
161
+ if (++this.pushed === 1) return;
158
162
  const added = this.length - this.attempted;
159
163
  if (added < (this.attempted - this.restart) / 2) return;
160
164
  if (this.kind === 0 && added < this.attempted / 8) return;
161
165
  this.attempt();
162
166
  }
163
- /** The step attempts run: the parser's resumable compiled code if it was compiled, else the interpreter. */
164
- step(state) {
165
- return Stack.run(Registry.stepFor(this.parser, state, true) ?? this.parser.step, state);
167
+ /**
168
+ * The step attempts run: the parser's compiled code if it was compiled
169
+ * (the resumable build, unless `resumable` is false), else the interpreter.
170
+ */
171
+ step(state, resumable = true) {
172
+ return Stack.run(Registry.stepFor(this.parser, state, resumable) ?? this.parser.step, state);
166
173
  }
167
174
  attempt() {
168
175
  const state = new State(this.input(), {
@@ -185,8 +192,9 @@ var Incremental = class {
185
192
  if (settled.pos === this.length) return Effect.succeed(settled.value);
186
193
  } else if (settled === void 0) {
187
194
  const state = new State(this.input(), { context: this.context });
188
- state.resume = this.resume;
189
- const a = this.step(state);
195
+ const resumable = this.attempted > 0;
196
+ if (resumable) state.resume = this.resume;
197
+ const a = this.step(state, resumable);
190
198
  if (a !== Fail && state.pos === state.end) return Effect.succeed(a);
191
199
  }
192
200
  const all = this.input();
@@ -276,7 +284,6 @@ const parseReadable = /*#__PURE__*/ dual(2, (self, parser) => parseAll(Stream.fr
276
284
  * @category combinators
277
285
  */
278
286
  const parseResponse = /*#__PURE__*/ dual(2, (self, parser) => parseReadable(self.body ?? new ReadableStream({ start: (c) => c.close() }), parser));
279
- //#endregion
280
287
  export { ReadError, parseAll, parseMany, parseReadable, parseResponse };
281
288
 
282
289
  //# sourceMappingURL=ParserStream.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ParserStream.js","names":[],"sources":["../src/ParserStream.ts"],"sourcesContent":["/**\n * Running parsers over Effect `Stream`s of input chunks.\n *\n * This is where nom's and winnow's *partial* (streaming) parsing meets\n * Effect: chunks are buffered and the parser runs in partial mode, so a\n * value split across chunk boundaries is reported as `Incomplete` and\n * retried once more data arrives. When the stream ends, the leftover input\n * is parsed in complete mode.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n * import { Ascii, Parser, ParserStream, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const line = Parser.terminated(Ascii.decInt, Token.literal(\"\\n\"))\n *\n * const program = Stream.make(\"1\\n2\", \"3\\n\", \"4\\n\").pipe(\n * ParserStream.parseMany(line),\n * Stream.runCollect\n * )\n * // Effect.runSync(program) => [1, 23, 4]\n * ```\n *\n * @since 0.1.0\n */\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\nimport type { BinaryInput, Input, Source } from \"./Input.js\"\nimport { Fail, Failure, fromSource, State } from \"./Input.js\"\nimport * as ParseError from \"./ParseError.js\"\nimport * as Registry from \"./internal/compiler/registry.js\"\nimport type * as Resume from \"./internal/resume.js\"\nimport * as Run from \"./internal/run.js\"\nimport * as Stack from \"./internal/stack.js\"\nimport type { Parser } from \"./Parser.js\"\n\n/**\n * Input kinds that can be streamed in chunks.\n *\n * @since 0.1.0\n * @category models\n */\nexport type Chunkable = string | Uint8Array | ReadonlyArray<unknown>\n\nconst concat = <I extends Chunkable>(a: I, b: I): I => {\n if (Predicate.isString(a)) return (a + (b as string)) as I\n if (a instanceof Uint8Array) {\n if (a.length === 0) return b\n const out = new Uint8Array(a.length + (b as Uint8Array).length)\n out.set(a)\n out.set(b as Uint8Array, a.length)\n return out as I\n }\n return [...a, ...(b as ReadonlyArray<unknown>)] as unknown as I\n}\n\nconst sliceFrom = <I extends Chunkable>(input: I, offset: number): I =>\n (Predicate.isString(input) ? input.slice(offset) : input.slice(offset)) as I\n\nconst noProgress = (input: Input, offset: number) =>\n ParseError.fromFailure<never>(\n input,\n new Failure(offset, \"Assert\", [], [], false, undefined, \"`parseMany` parsers must always consume\", 0),\n \"Cut\"\n )\n\n/**\n * Options for {@link parseMany}.\n *\n * @since 0.1.0\n * @category models\n */\nexport interface ParseManyOptions<I> {\n /** The empty input, used to initialise the buffer (inferred from the first chunk if omitted). */\n readonly empty?: Source<I> | undefined\n}\n\n/**\n * Transforms a stream of input chunks into a stream of parsed values by\n * applying `parser` repeatedly. Each application must consume input.\n *\n * Services required by the parser are taken from the stream's context.\n * Error offsets are relative to the internal buffer of unconsumed input,\n * which is also the `input` of the reported `ParseError`.\n *\n * A parser compiled with the `Compiler` module runs compiled, with the\n * build that handles partial input (see `Parser.run`); a value that fails\n * or needs more input is parsed again interpreted, so errors and\n * `Incomplete` are the interpreter's.\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseMany: {\n <A, E, R, I extends Chunkable>(\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): <E0, R0>(self: Stream.Stream<Source<I>, E0, R0>) => Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R>\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<NoInfer<I>>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R>\n} = /*#__PURE__*/ dual(\n (args) => Stream.isStream(args[0]),\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<I>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R> =>\n Stream.suspend(() => {\n const step = parser.step\n let buffer: I | undefined = options?.empty === undefined ? undefined : fromSource<I>(options.empty)\n\n const drain = (context: any, partial: boolean): Effect.Effect<Array<A>, ParseError.ParseError<E>> => {\n const out: Array<A> = []\n if (buffer === undefined) return Effect.succeed(out)\n const input = buffer\n // One state for the whole buffer, reset before each value\n const state = new State(input)\n let offset = 0\n while (offset < input.length) {\n state.reset(offset, { partial, context })\n const a = Run.runOn(parser, step, state)\n if (a === Fail) {\n if (partial && state.mode === \"Incomplete\") break\n return Effect.fail(ParseError.fromFailure<E>(input, state.reportedFailure(), state.mode, state.encoding))\n }\n if (state.pos === offset) return Effect.fail(noProgress(input, offset))\n out.push(a)\n offset = state.pos\n }\n buffer = sliceFrom(input, offset)\n return Effect.succeed(out)\n }\n\n const feed = (source: Source<I>) =>\n Effect.flatMap(Effect.context<R>(), (context) =>\n Effect.suspend(() => {\n const chunk = fromSource<I>(source)\n buffer = buffer === undefined ? chunk : concat(buffer, chunk)\n return drain(context, true)\n })\n )\n\n const finish = Effect.flatMap(Effect.context<R>(), (context) => Effect.suspend(() => drain(context, false)))\n\n return self.pipe(\n Stream.mapEffect(feed),\n Stream.flattenIterable,\n Stream.concat(Stream.unwrap(Effect.map(finish, Stream.fromIterable)))\n )\n })\n)\n\n/**\n * Parses a stream of chunks incrementally, as one input. Chunks are parsed\n * as they arrive, in partial mode; when the parser runs out of input, its\n * repetitions keep checkpoints (see `internal/resume.ts`), so the next\n * attempt carries on from where the last one stopped instead of starting\n * over.\n */\nclass Incremental<A, E, I extends Chunkable> {\n private kind: 0 | 1 | 2 | undefined\n private text = \"\"\n private bytes = new Uint8Array(0)\n private items: Array<unknown> = []\n private length = 0\n private readonly resume: Resume.Checkpoints = new Map()\n /** The input length at the last attempt, and where that attempt ran out of input. */\n private attempted = 0\n private restart = 0\n /** Set once an attempt settles: a success (with its end offset) or a definite failure. */\n private settled: { readonly value: A; readonly pos: number } | \"failed\" | undefined\n\n constructor(\n private readonly parser: Parser<A, E, any, I>,\n private readonly context: Context.Context<never>,\n empty: I | undefined\n ) {\n if (empty !== undefined) this.append(empty)\n }\n\n private append(chunk: I): void {\n if (Predicate.isString(chunk)) {\n this.kind ??= 0\n this.text += chunk\n this.length += chunk.length\n } else if (chunk instanceof Uint8Array) {\n this.kind ??= 1\n const needed = this.length + chunk.length\n if (needed > this.bytes.length) {\n // Grow geometrically, so appending costs amortized constant time per byte\n const grown = new Uint8Array(Math.max(needed, this.bytes.length * 2, 4096))\n grown.set(this.bytes.subarray(0, this.length))\n this.bytes = grown\n }\n this.bytes.set(chunk, this.length)\n this.length = needed\n } else {\n this.kind ??= 2\n for (let i = 0; i < chunk.length; i++) this.items.push(chunk[i])\n this.length = this.items.length\n }\n }\n\n private input(): I {\n switch (this.kind) {\n case 1:\n return this.bytes.subarray(0, this.length) as I\n case 2:\n // Items are only appended between attempts, after each state has read its `end`\n return this.items as unknown as I\n default:\n return this.text as I\n }\n }\n\n push(chunk: I): void {\n if (chunk.length === 0) return\n this.append(chunk)\n if (this.settled !== undefined) return\n // An attempt re-reads what the last one could not finish, from `restart`;\n // waiting until at least half as much new input has arrived keeps the\n // total work linear in the input. Strings are also copied when they are\n // flattened, so they wait for a fraction of the whole input too.\n const added = this.length - this.attempted\n if (added < (this.attempted - this.restart) / 2) return\n if (this.kind === 0 && added < this.attempted / 8) return\n this.attempt()\n }\n\n /** The step attempts run: the parser's resumable compiled code if it was compiled, else the interpreter. */\n private step(state: State<I>): unknown {\n return Stack.run(Registry.stepFor(this.parser, state, true) ?? this.parser.step, state)\n }\n\n private attempt(): void {\n const state = new State(this.input(), { partial: true, context: this.context })\n state.resume = this.resume\n const a = this.step(state)\n this.attempted = this.length\n if (a !== Fail) {\n this.settled = { value: a as A, pos: state.pos }\n } else if (state.mode === \"Incomplete\") {\n this.restart = state.failure.offset\n } else {\n this.settled = \"failed\"\n }\n }\n\n finish(): Effect.Effect<A, ParseError.ParseError<E>> {\n const settled = this.settled\n if (settled !== undefined && settled !== \"failed\") {\n if (settled.pos === this.length) return Effect.succeed(settled.value)\n } else if (settled === undefined) {\n // The last attempt, in complete mode, resumes from the checkpoints too\n const state = new State(this.input(), { context: this.context })\n state.resume = this.resume\n const a = this.step(state)\n if (a !== Fail && state.pos === state.end) return Effect.succeed(a as A)\n }\n // The error comes from an ordinary parse of the whole input, so it is the\n // same as if the input had been parsed in one go\n const all = this.input()\n const state = new State(all, { context: this.context })\n const a = Stack.run(this.parser.step, state)\n if (a !== Fail && state.pos === state.end) return Effect.succeed(a)\n if (a !== Fail) state.backtrack(\"Eof\", [\"end of input\"])\n return Effect.fail(ParseError.fromFailure<E>(all, state.reportedFailure(), state.mode, state.encoding))\n }\n}\n\n/**\n * Parses an entire stream of chunks as a single complete input.\n *\n * Parsing does not wait for the stream to end: each chunk is parsed as it\n * arrives, in partial mode, and when the parser runs out of input its\n * repetitions (`repeat`, `separated`, `fold`, `escaped`, ...) remember how\n * far they got, so that the next attempt resumes there rather than starting\n * over. A large document, such as the body of a `fetch` response, is\n * therefore parsed while it downloads, and is ready soon after its last\n * byte. Use {@link parseReadable} or {@link parseResponse} for web streams.\n *\n * The result and any `ParseError` are those of parsing the whole input at\n * once: errors are reported once the stream has ended, by an ordinary\n * interpreted parse of the whole input. A parser compiled with the\n * `Compiler` module streams compiled too (with a build that handles partial\n * input), which is several times faster. As with compiled parsers,\n * callbacks should be pure: the elements parsed before a checkpoint are\n * not parsed again, and on failure everything is parsed again.\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseAll: {\n <A, E, R, I extends Chunkable>(\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): <E0, R0>(self: Stream.Stream<Source<I>, E0, R0>) => Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R>\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<NoInfer<I>>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R>\n} = /*#__PURE__*/ dual(\n (args) => Stream.isStream(args[0]),\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<I>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R> =>\n Effect.flatMap(Effect.context<R>(), (context) =>\n Effect.suspend(() => {\n const empty = options?.empty === undefined ? undefined : fromSource<I>(options.empty)\n const incremental = new Incremental(parser, context as Context.Context<never>, empty)\n return Effect.flatMap(\n Stream.runForEach(self, (chunk) => Effect.sync(() => incremental.push(fromSource<I>(chunk)))),\n () => Effect.suspend(() => incremental.finish())\n )\n })\n )\n)\n\n/**\n * An error reading a `ReadableStream` given to {@link parseReadable} or\n * {@link parseResponse}.\n *\n * @since 0.1.0\n * @category errors\n */\nexport class ReadError extends /*#__PURE__*/ Data.TaggedError(\"ReadError\")<{ readonly cause: unknown }> {}\n\n/**\n * Parses a web `ReadableStream` of bytes, such as the body of a `fetch`\n * response, incrementally (see {@link parseAll}): the bytes are parsed as\n * they arrive, without waiting for the end of the stream or decoding them\n * first. Use a byte parser, e.g. one built from `Text.utf8`.\n *\n * @example\n * ```ts\n * import { Effect } from \"effect\"\n * import { Parser, ParserStream, Text } from \"@thomasfosterau/effect-parse\"\n *\n * const csvLine = Parser.separated(Text.utf8.takeTill(\",\\n\"), Text.utf8.literal(\",\"))\n * const csv = Parser.separated(csvLine, Text.utf8.literal(\"\\n\"))\n *\n * const response = await fetch(\"https://example.com/data.csv\")\n * const rows = await Effect.runPromise(ParserStream.parseReadable(response.body!, csv))\n * ```\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseReadable: {\n <A, E, R>(\n parser: Parser<A, E, R, Uint8Array>\n ): (self: ReadableStream<BinaryInput>) => Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n <A, E, R>(\n self: ReadableStream<BinaryInput>,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n} = /*#__PURE__*/ dual(\n 2,\n <A, E, R>(\n self: ReadableStream<BinaryInput>,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R> =>\n parseAll(\n Stream.fromReadableStream({ evaluate: () => self, onError: (cause) => new ReadError({ cause }) }),\n parser,\n { empty: new Uint8Array(0) }\n )\n)\n\n/**\n * Parses the body of a `fetch` `Response` incrementally, as it downloads\n * (see {@link parseReadable}). A response without a body is parsed as empty\n * input. The status is not checked.\n *\n * @example\n * ```ts\n * import { Effect } from \"effect\"\n * import { Parser, ParserStream, Text } from \"@thomasfosterau/effect-parse\"\n *\n * const lines = Parser.separated(Text.utf8.tillLineEnding, Text.utf8.lineEnding)\n *\n * const response = await fetch(\"https://example.com/log.txt\")\n * const value = await Effect.runPromise(ParserStream.parseResponse(response, lines))\n * ```\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseResponse: {\n <A, E, R>(\n parser: Parser<A, E, R, Uint8Array>\n ): (self: Response) => Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n <A, E, R>(\n self: Response,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n} = /*#__PURE__*/ dual(\n 2,\n <A, E, R>(\n self: Response,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R> =>\n parseReadable(self.body ?? new ReadableStream<Uint8Array>({ start: (c) => c.close() }), parser)\n)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAM,UAA+B,GAAM,MAAY;CACrD,IAAI,UAAU,SAAS,CAAC,GAAG,OAAQ,IAAK;CACxC,IAAI,aAAa,YAAY;EAC3B,IAAI,EAAE,WAAW,GAAG,OAAO;EAC3B,MAAM,MAAM,IAAI,WAAW,EAAE,SAAU,EAAiB,MAAM;EAC9D,IAAI,IAAI,CAAC;EACT,IAAI,IAAI,GAAiB,EAAE,MAAM;EACjC,OAAO;CACT;CACA,OAAO,CAAC,GAAG,GAAG,GAAI,CAA4B;AAChD;AAEA,MAAM,aAAkC,OAAU,WAC/C,UAAU,SAAS,KAAK,IAAI,MAAM,MAAM,MAAM,IAAI,MAAM,MAAM,MAAM;AAEvE,MAAM,cAAc,OAAc,WAChC,WAAW,YACT,OACA,IAAI,QAAQ,QAAQ,UAAU,CAAC,GAAG,CAAC,GAAG,OAAO,KAAA,GAAW,2CAA2C,CAAC,GACpG,KACF;;;;;;;;;;;;;;;;;AA6BF,MAAa,YAUK,oBACf,SAAS,OAAO,SAAS,KAAK,EAAE,IAE/B,MACA,QACA,YAEA,OAAO,cAAc;CACnB,MAAM,OAAO,OAAO;CACpB,IAAI,SAAwB,SAAS,UAAU,KAAA,IAAY,KAAA,IAAY,WAAc,QAAQ,KAAK;CAElG,MAAM,SAAS,SAAc,YAAwE;EACnG,MAAM,MAAgB,CAAC;EACvB,IAAI,WAAW,KAAA,GAAW,OAAO,OAAO,QAAQ,GAAG;EACnD,MAAM,QAAQ;EAEd,MAAM,QAAQ,IAAI,MAAM,KAAK;EAC7B,IAAI,SAAS;EACb,OAAO,SAAS,MAAM,QAAQ;GAC5B,MAAM,MAAM,QAAQ;IAAE;IAAS;GAAQ,CAAC;GACxC,MA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AU,KAAA,IAAY,KAAA,IAAY,WAAc,QAAQ,KAAK,CACA;CACpF,OAAO,OAAO,QACZ,OAAO,WAAW,OAAO,UAAU,OAAO,WAAW,YAAY,KAAK,WAAc,KAAK,CAAC,CAAC,CAAC,SACtF,OAAO,cAAc,YAAY,OAAO,CAAC,CACjD;AACF,CAAC,CACH,CACJ;;;;;;;;AASA,IAAa,YAAb,eAA6C,mBAAK,YAAY,WAAW,EAAA,CAA+B,CAAC;;;;;;;;;;;;;;;;;;;;;;AAuBzG,MAAa,gBAQK,mBAChB,IAEE,MACA,WAEA,SACE,OAAO,mBAAmB;CAAE,gBAAgB;CAAM,UAAU,UAAU,IAAI,UAAU,EAAE,MAAM,CAAC;AAAE,CAAC,GAChG,QACA,EAAE,uBAAO,IAAI,WAAW,CAAC,EAAE,CAC7B,CACJ;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,gBAQK,mBAChB,IAEE,MACA,WAEA,cAAc,KAAK,QAAQ,IAAI,eAA2B,EAAE,QAAQ,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAClG"}
1
+ {"version":3,"file":"ParserStream.js","names":[],"sources":["../src/ParserStream.ts"],"sourcesContent":["/**\n * Running parsers over Effect `Stream`s of input chunks.\n *\n * This is where nom's and winnow's *partial* (streaming) parsing meets\n * Effect: chunks are buffered and the parser runs in partial mode, so a\n * value split across chunk boundaries is reported as `Incomplete` and\n * retried once more data arrives. When the stream ends, the leftover input\n * is parsed in complete mode.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n * import { Ascii, Parser, ParserStream, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const line = Parser.terminated(Ascii.decInt, Token.literal(\"\\n\"))\n *\n * const program = Stream.make(\"1\\n2\", \"3\\n\", \"4\\n\").pipe(\n * ParserStream.parseMany(line),\n * Stream.runCollect\n * )\n * // Effect.runSync(program) => [1, 23, 4]\n * ```\n *\n * @since 0.1.0\n */\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\nimport type { BinaryInput, Input, Source } from \"./Input.js\"\nimport { Fail, Failure, fromSource, State } from \"./Input.js\"\nimport * as ParseError from \"./ParseError.js\"\nimport * as Registry from \"./internal/compiler/registry.js\"\nimport type * as Resume from \"./internal/resume.js\"\nimport * as Run from \"./internal/run.js\"\nimport * as Stack from \"./internal/stack.js\"\nimport { isEmptyUnits } from \"./internal/text.js\"\nimport type { Parser } from \"./Parser.js\"\n\n/**\n * Input kinds that can be streamed in chunks.\n *\n * @since 0.1.0\n * @category models\n */\nexport type Chunkable = string | Uint8Array | ReadonlyArray<unknown>\n\nconst concat = <I extends Chunkable>(first: I, b: I): I => {\n // Widened so the checks below narrow it (a type parameter does not narrow).\n const a: Chunkable = first\n if (Predicate.isString(a)) return (a + (b as string)) as I\n if (a instanceof Uint8Array) {\n if (a.byteLength === 0) return b\n const out = new Uint8Array(a.length + (b as Uint8Array).length)\n out.set(a)\n out.set(b as Uint8Array, a.length)\n return out as I\n }\n return [...a, ...(b as ReadonlyArray<unknown>)] as unknown as I\n}\n\nconst sliceFrom = <I extends Chunkable>(input: I, offset: number): I =>\n (Predicate.isString(input) ? input.slice(offset) : input.slice(offset)) as I\n\nconst noProgress = (input: Input, offset: number) =>\n ParseError.fromFailure<never>(\n input,\n new Failure(offset, \"Assert\", [], [], false, undefined, \"`parseMany` parsers must always consume\", 0),\n \"Cut\"\n )\n\n/**\n * Options for {@link parseMany}.\n *\n * @since 0.1.0\n * @category models\n */\nexport interface ParseManyOptions<I> {\n /** The empty input, used to initialise the buffer (inferred from the first chunk if omitted). */\n readonly empty?: Source<I> | undefined\n}\n\n/**\n * Transforms a stream of input chunks into a stream of parsed values by\n * applying `parser` repeatedly. Each application must consume input.\n *\n * Services required by the parser are taken from the stream's context.\n * Error offsets are relative to the internal buffer of unconsumed input,\n * which is also the `input` of the reported `ParseError`.\n *\n * A parser compiled with the `Compiler` module runs compiled, with the\n * build that handles partial input (see `Parser.run`); a value that fails\n * or needs more input is parsed again interpreted, so errors and\n * `Incomplete` are the interpreter's.\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseMany: {\n <A, E, R, I extends Chunkable>(\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): <E0, R0>(self: Stream.Stream<Source<I>, E0, R0>) => Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R>\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<NoInfer<I>>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R>\n} = /*#__PURE__*/ dual(\n (args) => Stream.isStream(args[0]),\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<I>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R> =>\n Stream.suspend(() => {\n const step = parser.step\n let buffer: I | undefined = options?.empty === undefined ? undefined : fromSource<I>(options.empty)\n\n const drain = (context: any, partial: boolean): Effect.Effect<Array<A>, ParseError.ParseError<E>> => {\n const out: Array<A> = []\n if (buffer === undefined) return Effect.succeed(out)\n const input = buffer\n // One state for the whole buffer, reset before each value\n const state = new State(input)\n let offset = 0\n while (offset < input.length) {\n state.reset(offset, { partial, context })\n const a = Run.runOn(parser, step, state)\n if (a === Fail) {\n if (partial && state.mode === \"Incomplete\") break\n return Effect.fail(ParseError.fromFailure<E>(input, state.reportedFailure(), state.mode, state.encoding))\n }\n if (state.pos === offset) return Effect.fail(noProgress(input, offset))\n out.push(a)\n offset = state.pos\n }\n buffer = sliceFrom(input, offset)\n return Effect.succeed(out)\n }\n\n const feed = (source: Source<I>) =>\n Effect.flatMap(Effect.context<R>(), (context) =>\n Effect.suspend(() => {\n const chunk = fromSource<I>(source)\n buffer = buffer === undefined ? chunk : concat(buffer, chunk)\n return drain(context, true)\n })\n )\n\n const finish = Effect.flatMap(Effect.context<R>(), (context) => Effect.suspend(() => drain(context, false)))\n\n return self.pipe(\n Stream.mapEffect(feed),\n Stream.flattenIterable,\n Stream.concat(Stream.unwrap(Effect.map(finish, Stream.fromIterable)))\n )\n })\n)\n\n/**\n * Parses a stream of chunks incrementally, as one input. Chunks are parsed\n * as they arrive, in partial mode; when the parser runs out of input, its\n * repetitions keep checkpoints (see `internal/resume.ts`), so the next\n * attempt carries on from where the last one stopped instead of starting\n * over.\n */\nclass Incremental<A, E, I extends Chunkable> {\n private kind: 0 | 1 | 2 | undefined\n private text = \"\"\n private bytes = new Uint8Array(0)\n private items: Array<unknown> = []\n private length = 0\n private readonly resume: Resume.Checkpoints = new Map()\n /** The input length at the last attempt, and where that attempt ran out of input. */\n private attempted = 0\n private restart = 0\n private pushed = 0\n /** Set once an attempt settles: a success (with its end offset) or a definite failure. */\n private settled: { readonly value: A; readonly pos: number } | \"failed\" | undefined\n\n constructor(\n private readonly parser: Parser<A, E, any, I>,\n private readonly context: Context.Context<never>,\n empty: I | undefined\n ) {\n if (empty !== undefined) this.append(empty)\n }\n\n private append(chunk: I): void {\n if (Predicate.isString(chunk)) {\n this.kind ??= 0\n this.text += chunk\n this.length += chunk.length\n } else if (chunk instanceof Uint8Array) {\n this.kind ??= 1\n const needed = this.length + chunk.length\n if (needed > this.bytes.length) {\n // Grow geometrically, so appending costs amortized constant time per byte\n const grown = new Uint8Array(Math.max(needed, this.bytes.length * 2, 4096))\n grown.set(this.bytes.subarray(0, this.length))\n this.bytes = grown\n }\n this.bytes.set(chunk, this.length)\n this.length = needed\n } else {\n this.kind ??= 2\n for (let i = 0; i < chunk.length; i++) this.items.push(chunk[i])\n this.length = this.items.length\n }\n }\n\n private input(): I {\n switch (this.kind) {\n case 1:\n return this.bytes.subarray(0, this.length) as I\n case 2:\n // Items are only appended between attempts, after each state has read its `end`\n return this.items as unknown as I\n default:\n return this.text as I\n }\n }\n\n push(chunk: I): void {\n if (isEmptyUnits(chunk)) return\n this.append(chunk)\n if (this.settled !== undefined) return\n // The first attempt waits for a second chunk: an input that arrives in\n // one chunk (most small responses) is parsed once, by `finish`, instead\n // of once in partial mode and again in complete mode, since a repetition\n // that completes without resuming keeps no checkpoint\n if (++this.pushed === 1) return\n // An attempt re-reads what the last one could not finish, from `restart`;\n // waiting until at least half as much new input has arrived keeps the\n // total work linear in the input. Strings are also copied when they are\n // flattened, so they wait for a fraction of the whole input too.\n const added = this.length - this.attempted\n if (added < (this.attempted - this.restart) / 2) return\n if (this.kind === 0 && added < this.attempted / 8) return\n this.attempt()\n }\n\n /**\n * The step attempts run: the parser's compiled code if it was compiled\n * (the resumable build, unless `resumable` is false), else the interpreter.\n */\n private step(state: State<I>, resumable = true): unknown {\n return Stack.run(Registry.stepFor(this.parser, state, resumable) ?? this.parser.step, state)\n }\n\n private attempt(): void {\n const state = new State(this.input(), { partial: true, context: this.context })\n state.resume = this.resume\n const a = this.step(state)\n this.attempted = this.length\n if (a !== Fail) {\n this.settled = { value: a as A, pos: state.pos }\n } else if (state.mode === \"Incomplete\") {\n this.restart = state.failure.offset\n } else {\n this.settled = \"failed\"\n }\n }\n\n finish(): Effect.Effect<A, ParseError.ParseError<E>> {\n const settled = this.settled\n if (settled !== undefined && settled !== \"failed\") {\n if (settled.pos === this.length) return Effect.succeed(settled.value)\n } else if (settled === undefined) {\n // The last attempt, in complete mode, resumes from the checkpoints too;\n // with no attempt before it, it is an ordinary parse\n const state = new State(this.input(), { context: this.context })\n const resumable = this.attempted > 0\n if (resumable) state.resume = this.resume\n const a = this.step(state, resumable)\n if (a !== Fail && state.pos === state.end) return Effect.succeed(a as A)\n }\n // The error comes from an ordinary parse of the whole input, so it is the\n // same as if the input had been parsed in one go\n const all = this.input()\n const state = new State(all, { context: this.context })\n const a = Stack.run(this.parser.step, state)\n if (a !== Fail && state.pos === state.end) return Effect.succeed(a)\n if (a !== Fail) state.backtrack(\"Eof\", [\"end of input\"])\n return Effect.fail(ParseError.fromFailure<E>(all, state.reportedFailure(), state.mode, state.encoding))\n }\n}\n\n/**\n * Parses an entire stream of chunks as a single complete input.\n *\n * Parsing does not wait for the stream to end: each chunk is parsed as it\n * arrives, in partial mode, and when the parser runs out of input its\n * repetitions (`repeat`, `separated`, `fold`, `escaped`, ...) remember how\n * far they got, so that the next attempt resumes there rather than starting\n * over. A large document, such as the body of a `fetch` response, is\n * therefore parsed while it downloads, and is ready soon after its last\n * byte. Use {@link parseReadable} or {@link parseResponse} for web streams.\n *\n * The result and any `ParseError` are those of parsing the whole input at\n * once: errors are reported once the stream has ended, by an ordinary\n * interpreted parse of the whole input. A parser compiled with the\n * `Compiler` module streams compiled too (with a build that handles partial\n * input), which is several times faster. As with compiled parsers,\n * callbacks should be pure: the elements parsed before a checkpoint are\n * not parsed again, and on failure everything is parsed again.\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseAll: {\n <A, E, R, I extends Chunkable>(\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): <E0, R0>(self: Stream.Stream<Source<I>, E0, R0>) => Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R>\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<NoInfer<I>>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R>\n} = /*#__PURE__*/ dual(\n (args) => Stream.isStream(args[0]),\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<I>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R> =>\n Effect.flatMap(Effect.context<R>(), (context) =>\n Effect.suspend(() => {\n const empty = options?.empty === undefined ? undefined : fromSource<I>(options.empty)\n const incremental = new Incremental(parser, context as Context.Context<never>, empty)\n return Effect.flatMap(\n Stream.runForEach(self, (chunk) => Effect.sync(() => incremental.push(fromSource<I>(chunk)))),\n () => Effect.suspend(() => incremental.finish())\n )\n })\n )\n)\n\n/**\n * An error reading a `ReadableStream` given to {@link parseReadable} or\n * {@link parseResponse}.\n *\n * @since 0.1.0\n * @category errors\n */\nexport class ReadError extends /*#__PURE__*/ Data.TaggedError(\"ReadError\")<{ readonly cause: unknown }> {}\n\n/**\n * Parses a web `ReadableStream` of bytes, such as the body of a `fetch`\n * response, incrementally (see {@link parseAll}): the bytes are parsed as\n * they arrive, without waiting for the end of the stream or decoding them\n * first. Use a byte parser, e.g. one built from `Text.utf8`.\n *\n * @example\n * ```ts\n * import { Effect } from \"effect\"\n * import { Parser, ParserStream, Text } from \"@thomasfosterau/effect-parse\"\n *\n * const csvLine = Parser.separated(Text.utf8.takeTill(\",\\n\"), Text.utf8.literal(\",\"))\n * const csv = Parser.separated(csvLine, Text.utf8.literal(\"\\n\"))\n *\n * const response = await fetch(\"https://example.com/data.csv\")\n * const rows = await Effect.runPromise(ParserStream.parseReadable(response.body!, csv))\n * ```\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseReadable: {\n <A, E, R>(\n parser: Parser<A, E, R, Uint8Array>\n ): (self: ReadableStream<BinaryInput>) => Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n <A, E, R>(\n self: ReadableStream<BinaryInput>,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n} = /*#__PURE__*/ dual(\n 2,\n <A, E, R>(\n self: ReadableStream<BinaryInput>,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R> =>\n parseAll(\n Stream.fromReadableStream({ evaluate: () => self, onError: (cause) => new ReadError({ cause }) }),\n parser,\n { empty: new Uint8Array(0) }\n )\n)\n\n/**\n * Parses the body of a `fetch` `Response` incrementally, as it downloads\n * (see {@link parseReadable}). A response without a body is parsed as empty\n * input. The status is not checked.\n *\n * @example\n * ```ts\n * import { Effect } from \"effect\"\n * import { Parser, ParserStream, Text } from \"@thomasfosterau/effect-parse\"\n *\n * const lines = Parser.separated(Text.utf8.tillLineEnding, Text.utf8.lineEnding)\n *\n * const response = await fetch(\"https://example.com/log.txt\")\n * const value = await Effect.runPromise(ParserStream.parseResponse(response, lines))\n * ```\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseResponse: {\n <A, E, R>(\n parser: Parser<A, E, R, Uint8Array>\n ): (self: Response) => Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n <A, E, R>(\n self: Response,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n} = /*#__PURE__*/ dual(\n 2,\n <A, E, R>(\n self: Response,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R> =>\n parseReadable(self.body ?? new ReadableStream<Uint8Array>({ start: (c) => c.close() }), parser)\n)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,UAA+B,OAAU,MAAY;CAEzD,MAAM,IAAe;CACrB,IAAI,UAAU,SAAS,CAAC,GAAG,OAAQ,IAAK;CACxC,IAAI,aAAa,YAAY;EAC3B,IAAI,EAAE,eAAe,GAAG,OAAO;EAC/B,MAAM,MAAM,IAAI,WAAW,EAAE,SAAU,EAAiB,MAAM;EAC9D,IAAI,IAAI,CAAC;EACT,IAAI,IAAI,GAAiB,EAAE,MAAM;EACjC,OAAO;CACT;CACA,OAAO,CAAC,GAAG,GAAG,GAAI,CAA4B;AAChD;AAEA,MAAM,aAAkC,OAAU,WAC/C,UAAU,SAAS,KAAK,IAAI,MAAM,MAAM,MAAM,IAAI,MAAM,MAAM,MAAM;AAEvE,MAAM,cAAc,OAAc,WAChC,WAAW,YACT,OACA,IAAI,QAAQ,QAAQ,UAAU,CAAC,GAAG,CAAC,GAAG,O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KAAK,QAAQ,IAAI,eAA2B,EAAE,QAAQ,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAClG"}
package/dist/Syntax.d.ts CHANGED
@@ -4,7 +4,6 @@ import * as Option from "effect/Option";
4
4
  import * as Context from "effect/Context";
5
5
  import * as ParseError from "./ParseError.js";
6
6
  import { ErrorInfo, Green } from "./internal/syntax.js";
7
- //#region src/Syntax.d.ts
8
7
  /**
9
8
  * Marks a parser as a rule of the syntax tree: in a {@link parse}, each
10
9
  * match becomes a named node of the given kind, spanning the input it
@@ -396,6 +395,5 @@ export declare const replace: <A, E>(tree: Tree<A, E, string>, start: number, en
396
395
  * @category parsing
397
396
  */
398
397
  export declare const diff: <I extends Input>(before: I, after: I) => Edit | undefined;
399
- //#endregion
400
398
  export {};
401
399
  //# sourceMappingURL=Syntax.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Syntax.d.ts","names":[],"sources":["../src/Syntax.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;qBAkGa;GACV,gBAAgB,GAAG,GAAG,GAAG,UAAU,OAAO,MAAM,OAAO,GAAG,GAAG,GAAG,OAAO,OAAO,GAAG,GAAG,GAAG;GACvF,GAAG,GAAG,GAAG,UAAU,OAAO,MAAM,OAAO,GAAG,GAAG,GAAG,IAAI,eAAe,OAAO,GAAG,GAAG,GAAG;;;;;;;;;;;;;;;;;;;qBAwBzE;GACV,iBAAiB,GAAG,GAAG,GAAG,UAAU,OAAO,MAAM,OAAO,GAAG,GAAG,GAAG,OAAO,OAAO,GAAG,GAAG,GAAG;GACxF,GAAG,GAAG,GAAG,UAAU,OAAO,MAAM,OAAO,GAAG,GAAG,GAAG,IAAI,gBAAgB,OAAO,GAAG,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;qBAkC1E;GACV,gBAAgB,GAAG,GAAG,GAAG,UAAU,OAAO,MAAM,OAAO,GAAG,GAAG,GAAG,OAAO,OAAO,GAAG,GAAG,GAAG;GACvF,GAA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