initial commit of actions

This commit is contained in:
Dominik Polakovics Polakovics 2026-01-31 18:56:04 +01:00
commit 949ece5785
44660 changed files with 12034344 additions and 0 deletions

View file

@ -0,0 +1,12 @@
module.exports = {
parser: '@typescript-eslint/parser',
extends: ['plugin:@typescript-eslint/recommended', 'prettier/@typescript-eslint', 'plugin:prettier/recommended'],
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
},
rules: {
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/no-inferrable-types': 'off',
},
};

1
github/codeql-action-v2/node_modules/ts-poet/.nvmrc generated vendored Normal file
View file

@ -0,0 +1 @@
16.4.0

View file

@ -0,0 +1,6 @@
{
"printWidth": 120,
"bracketSpacing": true,
"singleQuote": true,
"trailingComma": "es5"
}

View file

@ -0,0 +1,315 @@
public final class CodeBlockTest {
@Test public void equalsAndHashCode() {
CodeBlock a = CodeBlock.builder().build();
CodeBlock b = CodeBlock.builder().build();
assertThat(a.equals(b)).isTrue();
assertThat(a.hashCode()).isEqualTo(b.hashCode());
a = CodeBlock.builder().add("$L", "taco").build();
b = CodeBlock.builder().add("$L", "taco").build();
assertThat(a.equals(b)).isTrue();
assertThat(a.hashCode()).isEqualTo(b.hashCode());
}
@Test public void of() {
CodeBlock a = CodeBlock.of("$L taco", "delicious");
assertThat(a.toString()).isEqualTo("delicious taco");
}
@Test public void isEmpty() {
assertTrue(CodeBlock.builder().isEmpty());
assertTrue(CodeBlock.builder().add("").isEmpty());
assertFalse(CodeBlock.builder().add(" ").isEmpty());
}
@Test public void indentCannotBeIndexed() {
try {
CodeBlock.builder().add("$1>", "taco").build();
fail();
} catch (IllegalArgumentException exp) {
assertThat(exp)
.hasMessageThat()
.isEqualTo("$$, $>, $<, $[, $], $W, and $Z may not have an index");
}
}
@Test public void deindentCannotBeIndexed() {
try {
CodeBlock.builder().add("$1<", "taco").build();
fail();
} catch (IllegalArgumentException exp) {
assertThat(exp)
.hasMessageThat()
.isEqualTo("$$, $>, $<, $[, $], $W, and $Z may not have an index");
}
}
@Test public void dollarSignEscapeCannotBeIndexed() {
try {
CodeBlock.builder().add("$1$", "taco").build();
fail();
} catch (IllegalArgumentException exp) {
assertThat(exp)
.hasMessageThat()
.isEqualTo("$$, $>, $<, $[, $], $W, and $Z may not have an index");
}
}
@Test public void statementBeginningCannotBeIndexed() {
try {
CodeBlock.builder().add("$1[", "taco").build();
fail();
} catch (IllegalArgumentException exp) {
assertThat(exp)
.hasMessageThat()
.isEqualTo("$$, $>, $<, $[, $], $W, and $Z may not have an index");
}
}
@Test public void statementEndingCannotBeIndexed() {
try {
CodeBlock.builder().add("$1]", "taco").build();
fail();
} catch (IllegalArgumentException exp) {
assertThat(exp)
.hasMessageThat()
.isEqualTo("$$, $>, $<, $[, $], $W, and $Z may not have an index");
}
}
@Test public void nameFormatCanBeIndexed() {
CodeBlock block = CodeBlock.builder().add("$1N", "taco").build();
assertThat(block.toString()).isEqualTo("taco");
}
@Test public void literalFormatCanBeIndexed() {
CodeBlock block = CodeBlock.builder().add("$1L", "taco").build();
assertThat(block.toString()).isEqualTo("taco");
}
@Test public void stringFormatCanBeIndexed() {
CodeBlock block = CodeBlock.builder().add("$1S", "taco").build();
assertThat(block.toString()).isEqualTo("\"taco\"");
}
@Test public void typeFormatCanBeIndexed() {
CodeBlock block = CodeBlock.builder().add("$1T", String.class).build();
assertThat(block.toString()).isEqualTo("java.lang.String");
}
@Test public void simpleNamedArgument() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("text", "taco");
CodeBlock block = CodeBlock.builder().addNamed("$text:S", map).build();
assertThat(block.toString()).isEqualTo("\"taco\"");
}
@Test public void repeatedNamedArgument() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("text", "tacos");
CodeBlock block = CodeBlock.builder()
.addNamed("\"I like \" + $text:S + \". Do you like \" + $text:S + \"?\"", map)
.build();
assertThat(block.toString()).isEqualTo(
"\"I like \" + \"tacos\" + \". Do you like \" + \"tacos\" + \"?\"");
}
@Test public void namedAndNoArgFormat() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("text", "tacos");
CodeBlock block = CodeBlock.builder()
.addNamed("$>\n$text:L for $$3.50", map).build();
assertThat(block.toString()).isEqualTo("\n tacos for $3.50");
}
@Test public void missingNamedArgument() {
try {
Map<String, Object> map = new LinkedHashMap<>();
CodeBlock.builder().addNamed("$text:S", map).build();
fail();
} catch(IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("Missing named argument for $text");
}
}
@Test public void lowerCaseNamed() {
try {
Map<String, Object> map = new LinkedHashMap<>();
map.put("Text", "tacos");
CodeBlock block = CodeBlock.builder().addNamed("$Text:S", map).build();
fail();
} catch(IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("argument 'Text' must start with a lowercase character");
}
}
@Test public void multipleNamedArguments() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("pipe", System.class);
map.put("text", "tacos");
CodeBlock block = CodeBlock.builder()
.addNamed("$pipe:T.out.println(\"Let's eat some $text:L\");", map)
.build();
assertThat(block.toString()).isEqualTo(
"java.lang.System.out.println(\"Let's eat some tacos\");");
}
@Test public void namedNewline() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("clazz", Integer.class);
CodeBlock block = CodeBlock.builder().addNamed("$clazz:T\n", map).build();
assertThat(block.toString()).isEqualTo("java.lang.Integer\n");
}
@Test public void danglingNamed() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("clazz", Integer.class);
try {
CodeBlock.builder().addNamed("$clazz:T$", map).build();
fail();
} catch(IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("dangling $ at end");
}
}
@Test public void indexTooHigh() {
try {
CodeBlock.builder().add("$2T", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("index 2 for '$2T' not in range (received 1 arguments)");
}
}
@Test public void indexIsZero() {
try {
CodeBlock.builder().add("$0T", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("index 0 for '$0T' not in range (received 1 arguments)");
}
}
@Test public void indexIsNegative() {
try {
CodeBlock.builder().add("$-1T", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("invalid format string: '$-1T'");
}
}
@Test public void indexWithoutFormatType() {
try {
CodeBlock.builder().add("$1", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("dangling format characters in '$1'");
}
}
@Test public void indexWithoutFormatTypeNotAtStringEnd() {
try {
CodeBlock.builder().add("$1 taco", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("invalid format string: '$1 taco'");
}
}
@Test public void indexButNoArguments() {
try {
CodeBlock.builder().add("$1T").build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("index 1 for '$1T' not in range (received 0 arguments)");
}
}
@Test public void formatIndicatorAlone() {
try {
CodeBlock.builder().add("$", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("dangling format characters in '$'");
}
}
@Test public void formatIndicatorWithoutIndexOrFormatType() {
try {
CodeBlock.builder().add("$ tacoString", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("invalid format string: '$ tacoString'");
}
}
@Test public void sameIndexCanBeUsedWithDifferentFormats() {
CodeBlock block = CodeBlock.builder()
.add("$1T.out.println($1S)", ClassName.get(System.class))
.build();
assertThat(block.toString()).isEqualTo("java.lang.System.out.println(\"java.lang.System\")");
}
@Test public void tooManyStatementEnters() {
CodeBlock codeBlock = CodeBlock.builder().add("$[$[").build();
try {
// We can't report this error until rendering type because code blocks might be composed.
codeBlock.toString();
fail();
} catch (IllegalStateException expected) {
assertThat(expected).hasMessageThat().isEqualTo("statement enter $[ followed by statement enter $[");
}
}
@Test public void statementExitWithoutStatementEnter() {
CodeBlock codeBlock = CodeBlock.builder().add("$]").build();
try {
// We can't report this error until rendering type because code blocks might be composed.
codeBlock.toString();
fail();
} catch (IllegalStateException expected) {
assertThat(expected).hasMessageThat().isEqualTo("statement exit $] has no matching statement enter $[");
}
}
@Test public void join() {
List<CodeBlock> codeBlocks = new ArrayList<>();
codeBlocks.add(CodeBlock.of("$S", "hello"));
codeBlocks.add(CodeBlock.of("$T", ClassName.get("world", "World")));
codeBlocks.add(CodeBlock.of("need tacos"));
CodeBlock joined = CodeBlock.join(codeBlocks, " || ");
assertThat(joined.toString()).isEqualTo("\"hello\" || world.World || need tacos");
}
@Test public void joining() {
List<CodeBlock> codeBlocks = new ArrayList<>();
codeBlocks.add(CodeBlock.of("$S", "hello"));
codeBlocks.add(CodeBlock.of("$T", ClassName.get("world", "World")));
codeBlocks.add(CodeBlock.of("need tacos"));
CodeBlock joined = codeBlocks.stream().collect(CodeBlock.joining(" || "));
assertThat(joined.toString()).isEqualTo("\"hello\" || world.World || need tacos");
}
@Test public void joiningSingle() {
List<CodeBlock> codeBlocks = new ArrayList<>();
codeBlocks.add(CodeBlock.of("$S", "hello"));
CodeBlock joined = codeBlocks.stream().collect(CodeBlock.joining(" || "));
assertThat(joined.toString()).isEqualTo("\"hello\"");
}
@Test public void joiningWithPrefixAndSuffix() {
List<CodeBlock> codeBlocks = new ArrayList<>();
codeBlocks.add(CodeBlock.of("$S", "hello"));
codeBlocks.add(CodeBlock.of("$T", ClassName.get("world", "World")));
codeBlocks.add(CodeBlock.of("need tacos"));
CodeBlock joined = codeBlocks.stream().collect(CodeBlock.joining(" || ", "start {", "} end"));
assertThat(joined.toString()).isEqualTo("start {\"hello\" || world.World || need tacos} end");
}
}

View file

@ -0,0 +1,315 @@
public final class CodeBlockTest {
@Test public void equalsAndHashCode() {
CodeBlock a = CodeBlock.builder().build();
CodeBlock b = CodeBlock.builder().build();
assertThat(a.equals(b)).isTrue();
assertThat(a.hashCode()).isEqualTo(b.hashCode());
a = CodeBlock.builder().add("$L", "taco").build();
b = CodeBlock.builder().add("$L", "taco").build();
assertThat(a.equals(b)).isTrue();
assertThat(a.hashCode()).isEqualTo(b.hashCode());
}
@Test public void of() {
CodeBlock a = CodeBlock.of("$L taco", "delicious");
assertThat(a.toString()).isEqualTo("delicious taco");
}
@Test public void isEmpty() {
assertTrue(CodeBlock.builder().isEmpty());
assertTrue(CodeBlock.builder().add("").isEmpty());
assertFalse(CodeBlock.builder().add(" ").isEmpty());
}
@Test public void indentCannotBeIndexed() {
try {
CodeBlock.builder().add("$1>", "taco").build();
fail();
} catch (IllegalArgumentException exp) {
assertThat(exp)
.hasMessageThat()
.isEqualTo("$$, $>, $<, $[, $], $W, and $Z may not have an index");
}
}
@Test public void deindentCannotBeIndexed() {
try {
CodeBlock.builder().add("$1<", "taco").build();
fail();
} catch (IllegalArgumentException exp) {
assertThat(exp)
.hasMessageThat()
.isEqualTo("$$, $>, $<, $[, $], $W, and $Z may not have an index");
}
}
@Test public void dollarSignEscapeCannotBeIndexed() {
try {
CodeBlock.builder().add("$1$", "taco").build();
fail();
} catch (IllegalArgumentException exp) {
assertThat(exp)
.hasMessageThat()
.isEqualTo("$$, $>, $<, $[, $], $W, and $Z may not have an index");
}
}
@Test public void statementBeginningCannotBeIndexed() {
try {
CodeBlock.builder().add("$1[", "taco").build();
fail();
} catch (IllegalArgumentException exp) {
assertThat(exp)
.hasMessageThat()
.isEqualTo("$$, $>, $<, $[, $], $W, and $Z may not have an index");
}
}
@Test public void statementEndingCannotBeIndexed() {
try {
CodeBlock.builder().add("$1]", "taco").build();
fail();
} catch (IllegalArgumentException exp) {
assertThat(exp)
.hasMessageThat()
.isEqualTo("$$, $>, $<, $[, $], $W, and $Z may not have an index");
}
}
@Test public void nameFormatCanBeIndexed() {
CodeBlock block = CodeBlock.builder().add("$1N", "taco").build();
assertThat(block.toString()).isEqualTo("taco");
}
@Test public void literalFormatCanBeIndexed() {
CodeBlock block = CodeBlock.builder().add("$1L", "taco").build();
assertThat(block.toString()).isEqualTo("taco");
}
@Test public void stringFormatCanBeIndexed() {
CodeBlock block = CodeBlock.builder().add("$1S", "taco").build();
assertThat(block.toString()).isEqualTo("\"taco\"");
}
@Test public void typeFormatCanBeIndexed() {
CodeBlock block = CodeBlock.builder().add("$1T", String.class).build();
assertThat(block.toString()).isEqualTo("java.lang.String");
}
@Test public void simpleNamedArgument() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("text", "taco");
CodeBlock block = CodeBlock.builder().addNamed("$text:S", map).build();
assertThat(block.toString()).isEqualTo("\"taco\"");
}
@Test public void repeatedNamedArgument() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("text", "tacos");
CodeBlock block = CodeBlock.builder()
.addNamed("\"I like \" + $text:S + \". Do you like \" + $text:S + \"?\"", map)
.build();
assertThat(block.toString()).isEqualTo(
"\"I like \" + \"tacos\" + \". Do you like \" + \"tacos\" + \"?\"");
}
@Test public void namedAndNoArgFormat() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("text", "tacos");
CodeBlock block = CodeBlock.builder()
.addNamed("$>\n$text:L for $$3.50", map).build();
assertThat(block.toString()).isEqualTo("\n tacos for $3.50");
}
@Test public void missingNamedArgument() {
try {
Map<String, Object> map = new LinkedHashMap<>();
CodeBlock.builder().addNamed("$text:S", map).build();
fail();
} catch(IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("Missing named argument for $text");
}
}
@Test public void lowerCaseNamed() {
try {
Map<String, Object> map = new LinkedHashMap<>();
map.put("Text", "tacos");
CodeBlock block = CodeBlock.builder().addNamed("$Text:S", map).build();
fail();
} catch(IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("argument 'Text' must start with a lowercase character");
}
}
@Test public void multipleNamedArguments() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("pipe", System.class);
map.put("text", "tacos");
CodeBlock block = CodeBlock.builder()
.addNamed("$pipe:T.out.println(\"Let's eat some $text:L\");", map)
.build();
assertThat(block.toString()).isEqualTo(
"java.lang.System.out.println(\"Let's eat some tacos\");");
}
@Test public void namedNewline() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("clazz", Integer.class);
CodeBlock block = CodeBlock.builder().addNamed("$clazz:T\n", map).build();
assertThat(block.toString()).isEqualTo("java.lang.Integer\n");
}
@Test public void danglingNamed() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("clazz", Integer.class);
try {
CodeBlock.builder().addNamed("$clazz:T$", map).build();
fail();
} catch(IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("dangling $ at end");
}
}
@Test public void indexTooHigh() {
try {
CodeBlock.builder().add("$2T", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("index 2 for '$2T' not in range (received 1 arguments)");
}
}
@Test public void indexIsZero() {
try {
CodeBlock.builder().add("$0T", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("index 0 for '$0T' not in range (received 1 arguments)");
}
}
@Test public void indexIsNegative() {
try {
CodeBlock.builder().add("$-1T", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("invalid format string: '$-1T'");
}
}
@Test public void indexWithoutFormatType() {
try {
CodeBlock.builder().add("$1", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("dangling format characters in '$1'");
}
}
@Test public void indexWithoutFormatTypeNotAtStringEnd() {
try {
CodeBlock.builder().add("$1 taco", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("invalid format string: '$1 taco'");
}
}
@Test public void indexButNoArguments() {
try {
CodeBlock.builder().add("$1T").build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("index 1 for '$1T' not in range (received 0 arguments)");
}
}
@Test public void formatIndicatorAlone() {
try {
CodeBlock.builder().add("$", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("dangling format characters in '$'");
}
}
@Test public void formatIndicatorWithoutIndexOrFormatType() {
try {
CodeBlock.builder().add("$ tacoString", String.class).build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("invalid format string: '$ tacoString'");
}
}
@Test public void sameIndexCanBeUsedWithDifferentFormats() {
CodeBlock block = CodeBlock.builder()
.add("$1T.out.println($1S)", ClassName.get(System.class))
.build();
assertThat(block.toString()).isEqualTo("java.lang.System.out.println(\"java.lang.System\")");
}
@Test public void tooManyStatementEnters() {
CodeBlock codeBlock = CodeBlock.builder().add("$[$[").build();
try {
// We can't report this error until rendering type because code blocks might be composed.
codeBlock.toString();
fail();
} catch (IllegalStateException expected) {
assertThat(expected).hasMessageThat().isEqualTo("statement enter $[ followed by statement enter $[");
}
}
@Test public void statementExitWithoutStatementEnter() {
CodeBlock codeBlock = CodeBlock.builder().add("$]").build();
try {
// We can't report this error until rendering type because code blocks might be composed.
codeBlock.toString();
fail();
} catch (IllegalStateException expected) {
assertThat(expected).hasMessageThat().isEqualTo("statement exit $] has no matching statement enter $[");
}
}
@Test public void join() {
List<CodeBlock> codeBlocks = new ArrayList<>();
codeBlocks.add(CodeBlock.of("$S", "hello"));
codeBlocks.add(CodeBlock.of("$T", ClassName.get("world", "World")));
codeBlocks.add(CodeBlock.of("need tacos"));
CodeBlock joined = CodeBlock.join(codeBlocks, " || ");
assertThat(joined.toString()).isEqualTo("\"hello\" || world.World || need tacos");
}
@Test public void joining() {
List<CodeBlock> codeBlocks = new ArrayList<>();
codeBlocks.add(CodeBlock.of("$S", "hello"));
codeBlocks.add(CodeBlock.of("$T", ClassName.get("world", "World")));
codeBlocks.add(CodeBlock.of("need tacos"));
CodeBlock joined = codeBlocks.stream().collect(CodeBlock.joining(" || "));
assertThat(joined.toString()).isEqualTo("\"hello\" || world.World || need tacos");
}
@Test public void joiningSingle() {
List<CodeBlock> codeBlocks = new ArrayList<>();
codeBlocks.add(CodeBlock.of("$S", "hello"));
CodeBlock joined = codeBlocks.stream().collect(CodeBlock.joining(" || "));
assertThat(joined.toString()).isEqualTo("\"hello\"");
}
@Test public void joiningWithPrefixAndSuffix() {
List<CodeBlock> codeBlocks = new ArrayList<>();
codeBlocks.add(CodeBlock.of("$S", "hello"));
codeBlocks.add(CodeBlock.of("$T", ClassName.get("world", "World")));
codeBlocks.add(CodeBlock.of("need tacos"));
CodeBlock joined = codeBlocks.stream().collect(CodeBlock.joining(" || ", "start {", "} end"));
assertThat(joined.toString()).isEqualTo("start {\"hello\" || world.World || need tacos} end");
}
}

View file

@ -0,0 +1,204 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

165
github/codeql-action-v2/node_modules/ts-poet/README.md generated vendored Normal file
View file

@ -0,0 +1,165 @@
![npm](https://img.shields.io/npm/v/ts-poet)
[![CircleCI](https://circleci.com/gh/stephenh/ts-poet.svg?style=svg)](https://circleci.com/gh/stephenh/ts-poet)
Overview
========
ts-poet is a TypeScript code generator that is a fancy wrapper around [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals).
Here's some example `HelloWorld` output generated by ts-poet:
```typescript
import { Observable } from "rxjs/Observable";
export class Greeter {
private name: string;
constructor(private name: string) {}
greet(): Observable<string> {
return Observable.from(`Hello $name`);
}
}
```
And this is the code to generate it with ts-poet:
```typescript
import { code, imp } from "ts-poet";
// Use `imp` to declare an import that will conditionally auto-imported
const Observable = imp("@rxjs/Observable");
// Optionally create helper consts/methods to incrementally create output
const greet = code`
greet(): ${Observable}<string> {
return ${Observable}.from(\`Hello $name\`);
}
`;
// Combine all of the output (note no imports are at the top, they'll be auto-added)
const greeter = code`
export class Greeter {
private name: string;
constructor(private name: string) {
}
${greet}
}
`;
// Generate the full output, with imports
const output = greeter.toStringWithImports("Greeter");
```
I.e. the primary value provided by ts-poet is:
1. "Auto import" only actually-used symbols
I.e. if you use `imp` to define the modules/imports you need in your generated code, ts-poet will create the import stanza at the top of the file.
This can seem fairly minor, but it facilitates decomposition of your code generation code, so that you can have multiple levels of helper methods/etc. that can return `code` template literals that embed both the code itself as well as the import types.
And when the final file is generated, ts-poet will collect and emit the necessary imports.
2. Includes any other conditional output (see later), as/if needed.
3. Formats the output with prettier (using your local `.prettierrc` if it exists)
Import Specs
============
Given the primary goal of ts-poet is to manage imports for you, there are several ways of specifying imports to the `imp` function:
* `imp("Observable@rxjs")` --> `import { Observable } from "rxjs"`
* `imp("Observable:CustomizedObservable@rxjs")` --> `import { Observable as CustomizedObservable } from "rxjs"`
* `imp("t:Observable@rxjs")` --> `import type { Observable } from "rxjs"`
* `imp("t:Observable:CustomizedObservable@rxjs")` --> `import type { Observable as CustomizedObservable } from "rxjs"`
* `imp("Observable@./Api")` --> `import { Observable } from "./Api"`
* `imp("Observable*./Api")` --> `import * as Observable from "./Api"`
* `imp("Observable=./Api")` --> `import Observable from "./Api"`
* `imp("@rxjs/Observable")` --> `import { Observable } from "rxjs/Observable"`
* `imp("*rxjs/Observable")` --> `import * as Observable from "rxjs/Observable"`
* `imp("@Api")` --> `import { Api } from "Api"`
* `imp("describe+mocha")` --> `import "mocha"`
### Avoiding Import Conflicts
Sometimes code generation output may declare a symbol that conflicts with an imported type (usually for generic names like `Error`).
ts-poet will automatically detect and avoid conflicts if you tell it which symbols you're declaring, i.e.:
```typescript
const bar = imp('Bar@./bar');
const output = code`
class ${def("Bar")} extends ${bar} {
...
}
`;
```
Will result in the imported `Bar` symbol being remapped to `Bar1` in the output:
```typescript
import { Bar as Bar1 } from "./bar";
class Bar extends Bar1 {}
```
This is an admittedly contrived example for documentation purposes, but can be really useful when generating code against arbitrary / user-defined input (i.e. a schema that happens to uses a really common term).
# Conditional Output
Sometimes when generating larger, intricate output, you want to conditionally include helper methods. I.e. have a `convertTimestamps` function declared at the top of your module, but only actually include that function if some other part of the output actually uses timestamps (which might depend on the specific input/schema you're generating code against).
ts-poet supports this with a `conditionalOutput` method:
```typescript
const convertTimestamps = conditionalOutput(
// The string to output at the usage site
"convertTimestamps",
// The code to conditionally output if convertTimestamps is used
code`function convertTimestamps() { ...impl... }`,
);
const output = code`
${someSchema.map(f => {
if (f.type === "timestamp") {
// Using the convertTimestamps const marks it as used in our output
return code`${convertTimestamps}(f)`;
}
})}
// The .ifUsed result will be empty unless `convertTimestamps` has been marked has used
${convertTimestamps.ifUsed}
`;
```
And your output will have the `convertTimestamps` declaration only if one of the schema fields had a `timestamp` type.
This helps cut down on unnecessary output in the code, and compiler/IDE warnings like unused functions.
# Literals
If you want to add a literal value, you can use `literalOf` and `arrayOf`:
| code | output |
| --------------------------------- | ------------------------- |
| `let a = ${literalOf('foo')}` | `let a = 'foo';` |
| `let a = ${arrayOf(1, 2, 3)}` | `let a = [1, 2, 3];` |
| `let a = ${{foo: 'bar'}}` | `let a = { foo: 'bar' };` |
| `` let a = ${{foo: code`bar`}} `` | `let a = { foo: bar };` |
History
=======
ts-poet was originally inspired by Square's [JavaPoet](https://github.com/square/javapoet) code generation DSL, which has a very "Java-esque" builder API of `addFunction`/`addProperty`/etc. that ts-poet copied in it's original v1/v2 releases.
JavaPoet's approach worked very well for the Java ecosystem, as it was providing three features:
1. nice formatting (historically code generation output has looked terrible; bad formatting, bad indentation, etc.)
2. nice multi-line string support, via `appendLine(...).appendLine(...)` style methods.
3. "auto organize imports", of collecting imported symbols across the entire compilation unit of output, and organizing/formatting them at the top of the output file.
However, in the JavaScript/TypeScript world we have prettier for formatting, and nice multi-line string support via template literals, so really the only value add that ts-poet needs to provide is the "auto organize imports", which is what the post-v2/3.0 API has been rewritten (and dramatically simplified as a result) to provide.

View file

@ -0,0 +1,61 @@
import { Node } from './Node';
import { Options } from 'prettier';
/** Options for `toStringWithImports`, i.e. for the top-level, per-file output. */
export interface ToStringOpts {
/** The intended file name of this code; used to know whether we can skip import statements that would be from our own file. */
path?: string;
/** Modules to use a CommonJS-in-ESM destructure fix for. */
forceDefaultImport?: string[];
/** Modules to use a CommonJS-in-ESM destructure fix for. */
forceModuleImport?: string[];
/** A top-of-file prefix, i.e. eslint disable. */
prefix?: string;
/** Optional per-file overrides for the prettier config, i.e. to use longer-than-normal line lengths. */
prettierOverrides?: Options;
/** optional importMappings */
importMappings?: {
[key: string]: string;
};
}
export declare class Code extends Node {
private literals;
private placeholders;
trim: boolean;
private oneline;
constructor(literals: TemplateStringsArray, placeholders: any[]);
/**
* Returns the code with any necessary import statements prefixed.
*
* This method will also use any local `.prettierrc` settings, hence needs
* to return a `Promise<String>`.
*/
toStringWithImports(opts?: ToStringOpts): Promise<string>;
/**
* Returns the formatted code, without any imports.
*
* Note that we don't use `.prettierrc` b/c that requires async I/O to resolve.
*/
toString(): string;
asOneline(): Code;
get childNodes(): unknown[];
toCodeString(): string;
private deepFindImports;
private deepFindDefs;
private deepConditionalOutput;
private deepReplaceNamedImports;
private generateCode;
}
export declare function deepGenerate(object: unknown): string;
/**
* Represents a symbol defined in the current file.
*
* We use this to know if a symbol imported from a different file is going to
* have a namespace collision.
*/
export declare class Def extends Node {
symbol: string;
constructor(symbol: string);
toCodeString(): string;
/** Any potentially string/SymbolSpec/Code nested nodes within us. */
get childNodes(): Node[];
}

View file

@ -0,0 +1,305 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Def = exports.deepGenerate = exports.Code = void 0;
const Node_1 = require("./Node");
const Import_1 = require("./Import");
const prettier_1 = __importStar(require("prettier"));
const parser_typescript_1 = __importDefault(require("prettier/parser-typescript"));
const is_plain_object_1 = require("./is-plain-object");
const ConditionalOutput_1 = require("./ConditionalOutput");
const index_1 = require("./index");
// We only have a single top-level Code.toStringWithImports running at a time,
// so use a global var to capture this contextual state.
let usedConditionals = [];
class Code extends Node_1.Node {
constructor(literals, placeholders) {
super();
this.literals = literals;
this.placeholders = placeholders;
// Used by joinCode
this.trim = false;
this.oneline = false;
}
/**
* Returns the code with any necessary import statements prefixed.
*
* This method will also use any local `.prettierrc` settings, hence needs
* to return a `Promise<String>`.
*/
toStringWithImports(opts) {
const { path = '', forceDefaultImport, forceModuleImport, prefix, prettierOverrides = {}, importMappings = {} } = opts || {};
const ourModulePath = path.replace(/\.[tj]sx?/, '');
if (forceDefaultImport || forceModuleImport) {
this.deepReplaceNamedImports(forceDefaultImport || [], forceModuleImport || []);
}
usedConditionals = this.deepConditionalOutput();
const imports = this.deepFindImports();
const defs = this.deepFindDefs();
assignAliasesIfNeeded(defs, imports, ourModulePath);
const importPart = Import_1.emitImports(imports, ourModulePath, importMappings);
const bodyPart = this.generateCode();
const maybePrefix = prefix ? `${prefix}\n` : '';
return maybePrettyWithConfig(maybePrefix + importPart + '\n' + bodyPart, prettierOverrides);
}
/**
* Returns the formatted code, without any imports.
*
* Note that we don't use `.prettierrc` b/c that requires async I/O to resolve.
*/
toString() {
return maybePretty(this.generateCode());
}
asOneline() {
this.oneline = true;
return this;
}
get childNodes() {
return this.placeholders;
}
toCodeString() {
return this.generateCode();
}
deepFindImports() {
const imports = [];
let todo = [this];
while (todo.length > 0) {
const placeholder = todo.shift();
if (placeholder instanceof Import_1.Import) {
imports.push(placeholder);
}
else if (placeholder instanceof Node_1.Node) {
todo = [...todo, ...placeholder.childNodes];
}
else if (placeholder instanceof ConditionalOutput_1.MaybeOutput) {
if (usedConditionals.includes(placeholder.parent)) {
todo = [...todo, placeholder.code];
}
}
else if (Array.isArray(placeholder)) {
todo = [...todo, ...placeholder];
}
}
return imports;
}
deepFindDefs() {
const defs = [];
let todo = [this];
while (todo.length > 0) {
const placeholder = todo.shift();
if (placeholder instanceof Def) {
defs.push(placeholder);
}
else if (placeholder instanceof Node_1.Node) {
todo = [...todo, ...placeholder.childNodes];
}
else if (placeholder instanceof ConditionalOutput_1.MaybeOutput) {
if (usedConditionals.includes(placeholder.parent)) {
todo = [...todo, placeholder.code];
}
}
else if (Array.isArray(placeholder)) {
todo = [...todo, ...placeholder];
}
}
return defs;
}
deepConditionalOutput() {
const used = [];
let todo = [this];
while (todo.length > 0) {
const placeholder = todo.shift();
if (placeholder instanceof ConditionalOutput_1.ConditionalOutput) {
used.push(placeholder);
todo = [...todo, ...placeholder.declarationSiteCode.childNodes];
}
else if (placeholder instanceof Node_1.Node) {
todo = [...todo, ...placeholder.childNodes];
}
else if (Array.isArray(placeholder)) {
todo = [...todo, ...placeholder];
}
}
return used;
}
deepReplaceNamedImports(forceDefaultImport, forceModuleImport) {
// Keep a map of module name --> symbol we're importing, i.e. protobufjs/simple is _m1
const assignedNames = {};
function getName(source) {
let name = assignedNames[source];
if (!name) {
name = `_m${Object.values(assignedNames).length}`;
assignedNames[source] = name;
}
return name;
}
let todo = [this];
while (todo.length > 0) {
const placeholder = todo.shift();
if (placeholder instanceof Node_1.Node) {
const array = placeholder.childNodes;
for (let i = 0; i < array.length; i++) {
const maybeImp = array[i];
if (maybeImp instanceof Import_1.ImportsName && forceDefaultImport.includes(maybeImp.source)) {
const name = getName(maybeImp.source);
array[i] = index_1.code `${new Import_1.ImportsDefault(name, maybeImp.source)}.${maybeImp.sourceSymbol || maybeImp.symbol}`;
}
else if (maybeImp instanceof Import_1.ImportsName && forceModuleImport.includes(maybeImp.source)) {
const name = getName(maybeImp.source);
array[i] = index_1.code `${new Import_1.ImportsAll(name, maybeImp.source)}.${maybeImp.sourceSymbol || maybeImp.symbol}`;
}
}
todo = [...todo, ...placeholder.childNodes];
}
else if (Array.isArray(placeholder)) {
todo = [...todo, ...placeholder];
}
}
}
generateCode() {
const { literals, placeholders } = this;
let result = '';
// interleave the literals with the placeholders
for (let i = 0; i < placeholders.length; i++) {
result += literals[i] + deepGenerate(placeholders[i]);
}
// add the last literal
result += literals[literals.length - 1];
if (this.trim) {
result = result.trim();
}
if (this.oneline) {
result = result.replace(/\n/g, '');
}
return result;
}
}
exports.Code = Code;
function deepGenerate(object) {
let result = '';
let todo = [object];
while (todo.length > 0) {
const current = todo.shift();
if (Array.isArray(current)) {
todo = [...todo, ...current];
}
else if (current instanceof Node_1.Node) {
result += current.toCodeString();
}
else if (current instanceof ConditionalOutput_1.MaybeOutput) {
if (usedConditionals.includes(current.parent)) {
result += current.code.toCodeString();
}
}
else if (current === null) {
result += 'null';
}
else if (current !== undefined) {
if (is_plain_object_1.isPlainObject(current)) {
result += JSON.stringify(current);
}
else {
result += current.toString();
}
}
else {
result += 'undefined';
}
}
return result;
}
exports.deepGenerate = deepGenerate;
// Use an optional call here in case we are using standalone prettier. This can happen when loaded through a CDN from
// a browser (or Deno), because prettier has `"browser": "./standalone.js"` in it's package.json.
const configPromise = prettier_1.resolveConfig === null || prettier_1.resolveConfig === void 0 ? void 0 : prettier_1.resolveConfig('./');
async function maybePrettyWithConfig(input, options) {
try {
const config = await configPromise;
return prettier_1.default.format(input.trim(), { parser: 'typescript', plugins: [parser_typescript_1.default], ...config, ...options });
}
catch (e) {
return input; // assume it's invalid syntax and ignore
}
}
/** Finds any namespace collisions of a named import colliding with def and assigns the import an alias it. */
function assignAliasesIfNeeded(defs, imports, ourModulePath) {
// Keep track of used (whether declared or imported) symbols
const usedSymbols = new Set();
// Mark all locally-defined symbols as used
defs.forEach((def) => usedSymbols.add(def.symbol));
// A mapping of original to assigned alias, i.e. Foo@foo --> Foo2
const assignedAliases = {};
let j = 1;
imports.forEach((i) => {
if (i instanceof Import_1.ImportsName &&
// Don't both aliasing imports from our own module
!(Import_1.sameModule(i.source, ourModulePath) || (i.definedIn && Import_1.sameModule(i.definedIn, ourModulePath)))) {
const key = `${i.symbol}@${i.source}`;
if (usedSymbols.has(i.symbol)) {
let alias = assignedAliases[key];
if (!alias) {
alias = `${i.symbol}${j++}`;
assignedAliases[key] = alias;
}
// Move the original symbol over
if (alias !== i.symbol) {
i.sourceSymbol = i.symbol;
}
i.symbol = alias;
}
else {
usedSymbols.add(i.symbol);
assignedAliases[key] = i.symbol;
}
}
});
}
function maybePretty(input) {
try {
return prettier_1.default.format(input.trim(), { parser: 'typescript', plugins: [parser_typescript_1.default] });
}
catch (e) {
return input; // assume it's invalid syntax and ignore
}
}
/**
* Represents a symbol defined in the current file.
*
* We use this to know if a symbol imported from a different file is going to
* have a namespace collision.
*/
class Def extends Node_1.Node {
constructor(symbol) {
super();
this.symbol = symbol;
}
toCodeString() {
return this.symbol;
}
/** Any potentially string/SymbolSpec/Code nested nodes within us. */
get childNodes() {
return [];
}
}
exports.Def = Def;

View file

@ -0,0 +1,40 @@
import { Node } from './Node';
import { Code } from './Code';
/**
* Helps output conditional helper methods.
*
* The `ConditionalOutput` concept is split into a usage site and a declaration
* site, i.e. declaring a `function someHelper() { ... }`, and calling it
* like `someHelper()`.
*
* While generating code, you can make usage says by using `someHelper` as
* a placeholder, and then output the declaration with `someHelper.ifUsed`
* to output the declaration conditionally only if `someHelper` has been
* seen in the tree.
*
* ```typescript
* const someHelper = conditionalOutput(
* "someHelper",
* code`function someHelper() { return 1 } `
* );
*
* const code = code`
* ${someHelper}
*
* ${someHelper.ifUsed}
* `
* ```
*/
export declare class ConditionalOutput extends Node {
usageSiteName: string;
declarationSiteCode: Code;
constructor(usageSiteName: string, declarationSiteCode: Code);
get childNodes(): unknown[];
toCodeString(): string;
get ifUsed(): MaybeOutput;
}
export declare class MaybeOutput {
parent: ConditionalOutput;
code: Code;
constructor(parent: ConditionalOutput, code: Code);
}

View file

@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MaybeOutput = exports.ConditionalOutput = void 0;
const Node_1 = require("./Node");
/**
* Helps output conditional helper methods.
*
* The `ConditionalOutput` concept is split into a usage site and a declaration
* site, i.e. declaring a `function someHelper() { ... }`, and calling it
* like `someHelper()`.
*
* While generating code, you can make usage says by using `someHelper` as
* a placeholder, and then output the declaration with `someHelper.ifUsed`
* to output the declaration conditionally only if `someHelper` has been
* seen in the tree.
*
* ```typescript
* const someHelper = conditionalOutput(
* "someHelper",
* code`function someHelper() { return 1 } `
* );
*
* const code = code`
* ${someHelper}
*
* ${someHelper.ifUsed}
* `
* ```
*/
class ConditionalOutput extends Node_1.Node {
// A given ConditionalOutput const could be used in multiple code
// parents, and so we don't want to use instance state to store
// "should I be output or not", b/c it depends on the containing tree.
constructor(usageSiteName, declarationSiteCode) {
super();
this.usageSiteName = usageSiteName;
this.declarationSiteCode = declarationSiteCode;
}
get childNodes() {
return [this.declarationSiteCode];
}
toCodeString() {
return this.usageSiteName;
}
get ifUsed() {
return new MaybeOutput(this, this.declarationSiteCode);
}
}
exports.ConditionalOutput = ConditionalOutput;
class MaybeOutput {
constructor(parent, code) {
this.parent = parent;
this.code = code;
}
}
exports.MaybeOutput = MaybeOutput;

View file

@ -0,0 +1,190 @@
import { Node } from './Node';
export declare const importType = "[*@+=]";
/**
* Specifies a symbol and its related origin, either via import or implicit/local declaration.
*/
export declare abstract class Import extends Node {
symbol: string;
/**
* Parses a symbol reference pattern to create a symbol. The pattern
* allows the simple definition of all symbol types including any possible
* import variation. If the spec to parse does not follow the proper format
* an implicit symbol is created from the unparsed spec.
*
* Pattern: `symbolName? importType modulePath (#<augmentedSymbolName>)?`
*
* Where:
*
* - `symbolName` is any legal JS/TS symbol. If none, we use the last part of the module path as a guess.
* - `importType` is one of `@` or `*` or `+`, where:
* - `@` is a named import
* - `Foo@bar` becomes `import { Foo } from 'bar'`
* - `*` is a star import,
* - `*Foo` becomes `import * as Foo from 'Foo'`
* - `Foo*foo` becomes `import * as Foo from 'foo'`
* - `+` is an implicit import
* - E.g. `Foo+foo` becomes `import 'foo'`
* - `modulePath` is a path
* - E.g. `<filename>(/<filename)*`
* - augmentedSymbolName = `[a-zA-Z0-9_]+`
*
* Any valid symbol name that represents the symbol that is being augmented. For example,
* the import `rxjs/add/observable/from` attaches the `from` method to the `Observable` class.
* To import it correctly the spec should be `+rxjs/add/observable/from#Observable`. Adding this
* parameter to augmented imports ensures they are output only when the symbol being augmented
* is actually used.
*
*
* @param spec Symbol spec to parse.
* @return Parsed symbol specification
*/
static from(spec: string): Import;
static fromMaybeString(spec: string | Import): Import;
/**
* Defined if the symbol is typically imported from a barrel/etc. path, but is technically defined in another file.
*
* We need to know this in case the "this comes from the barrel" type ends up being used in the file where
* the symbol itself is defined, i.e. we don't need an import in that case.
*/
definedIn?: string;
protected constructor(symbol: string);
toCodeString(): string;
get childNodes(): unknown[];
abstract source: string | undefined;
/**
* Creates an import of all the modules exported symbols as a single
* local named symbol
*
* e.g. `import * as Engine from 'templates';`
*
* @param localName The local name of the imported symbols
* @param from The module to import the symbols from
*/
static importsAll(localName: string, from: string): Import;
/**
* Creates an import of a single named symbol from the module's exported
* symbols.
*
* e.g. `import { Engine } from 'templates';`
*
* @param exportedName The symbol that is both exported and imported
* @param from The module the symbol is exported from
* @param typeImport whether this is an `import type` import
*/
static importsName(exportedName: string, from: string, typeImport: boolean, sourceExportedName?: string): Import;
/**
* Creates a symbol that is brought in by a whole module import
* that "augments" an existing symbol.
*
* e.g. `import 'rxjs/add/operator/flatMap'`
*
* @param symbolName The augmented symbol to be imported
* @param from The entire import that does the augmentation
* @param target The symbol that is augmented
*/
static augmented(symbolName: string, from: string, target: string): Import;
/**
* Creates a symbol that is brought in as a side effect of
* an import.
*
* e.g. `import 'mocha'`
*
* @param symbolName The symbol to be imported
* @param from The entire import that does the augmentation
*/
static sideEffect(symbolName: string, from: string): Import;
/**
* An implied symbol that does no tracking of imports
*
* @param name The implicit symbol name
*/
static implicit(name: string): Import;
/**
* Creates an import of a single named symbol from the module's exported
* default.
*
* e.g. `import Engine from 'engine';`
*
* @param exportedName The symbol that is both exported and imported
* @param from The module the symbol is exported from
*/
static importsDefault(exportedName: string, from: string): Import;
}
/**
* Non-imported symbol
*/
export declare class Implicit extends Import {
constructor(symbol: string);
source: undefined;
}
/** Common base class for imported symbols. */
export declare abstract class Imported extends Import {
symbol: string;
source: string;
/** The symbol is the imported symbol, i.e. `BarClass`, and source is the path it comes from. */
protected constructor(symbol: string, source: string);
}
/**
* Imports a single named symbol from the module's exported
* symbols.
*
* E.g.:
*
* `import { Engine } from 'templates'` or
* `import { Engine as Engine2 } from 'templates'`
*/
export declare class ImportsName extends Imported {
sourceSymbol?: string | undefined;
typeImport?: boolean | undefined;
/**
* @param symbol
* @param source
* @param sourceSymbol is the optional original symbol, i.e if we're renaming the symbol it is `Engine`
* @param typeImport whether this is an `import type` import
*/
constructor(symbol: string, source: string, sourceSymbol?: string | undefined, typeImport?: boolean | undefined);
toImportPiece(): string;
}
/**
* Imports a single named symbol from the module's exported
* default.
*
* e.g. `import Engine from 'engine';`
*/
export declare class ImportsDefault extends Imported {
constructor(symbol: string, source: string);
}
/**
* Imports all of the modules exported symbols as a single
* named symbol
*
* e.g. `import * as Engine from 'templates';`
*/
export declare class ImportsAll extends Imported {
constructor(symbol: string, source: string);
}
/**
* A symbol that is brought in by a whole module import
* that "augments" an existing symbol.
*
* e.g. `import 'rxjs/add/operator/flatMap'`
*/
export declare class Augmented extends Imported {
augmented: string;
constructor(symbol: string, source: string, augmented: string);
}
/**
* A symbol that is brought in as a side effect of an import.
*
* E.g. `from("Foo+mocha")` will add `import 'mocha'`
*/
export declare class SideEffect extends Imported {
constructor(symbol: string, source: string);
}
/** Generates the `import ...` lines for the given `imports`. */
export declare function emitImports(imports: Import[], ourModulePath: string, importMappings: {
[key: string]: string;
}): string;
export declare function maybeRelativePath(outputPath: string, importPath: string): string;
/** Checks if `path1 === path2` despite minor path differences like `./foo` and `foo`. */
export declare function sameModule(path1: string, path2: string): boolean;

View file

@ -0,0 +1,377 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sameModule = exports.maybeRelativePath = exports.emitImports = exports.SideEffect = exports.Augmented = exports.ImportsAll = exports.ImportsDefault = exports.ImportsName = exports.Imported = exports.Implicit = exports.Import = exports.importType = void 0;
const lodash_1 = __importDefault(require("lodash"));
const path = __importStar(require("path"));
const Node_1 = require("./Node");
const typeImportMarker = '(?:t:)?';
const fileNamePattern = '(?:[a-zA-Z0-9._-]+)';
const modulePattern = `@?(?:(?:${fileNamePattern}(?:/${fileNamePattern})*))`;
const identPattern = `(?:(?:[a-zA-Z][_a-zA-Z0-9.]*)|(?:[_a-zA-Z][_a-zA-Z0-9.]+))`;
exports.importType = '[*@+=]';
const importPattern = `^(${typeImportMarker}${identPattern})?(${exports.importType})(${modulePattern})(?:#(${identPattern}))?`;
const sourceIdentPattern = `(?:(?:${identPattern}:)?)`;
const sourceImportPattern = `^(${typeImportMarker}${sourceIdentPattern}${identPattern})?(@)(${modulePattern})(?:#(${identPattern}))?`;
/**
* Specifies a symbol and its related origin, either via import or implicit/local declaration.
*/
class Import extends Node_1.Node {
constructor(symbol) {
super();
this.symbol = symbol;
}
/**
* Parses a symbol reference pattern to create a symbol. The pattern
* allows the simple definition of all symbol types including any possible
* import variation. If the spec to parse does not follow the proper format
* an implicit symbol is created from the unparsed spec.
*
* Pattern: `symbolName? importType modulePath (#<augmentedSymbolName>)?`
*
* Where:
*
* - `symbolName` is any legal JS/TS symbol. If none, we use the last part of the module path as a guess.
* - `importType` is one of `@` or `*` or `+`, where:
* - `@` is a named import
* - `Foo@bar` becomes `import { Foo } from 'bar'`
* - `*` is a star import,
* - `*Foo` becomes `import * as Foo from 'Foo'`
* - `Foo*foo` becomes `import * as Foo from 'foo'`
* - `+` is an implicit import
* - E.g. `Foo+foo` becomes `import 'foo'`
* - `modulePath` is a path
* - E.g. `<filename>(/<filename)*`
* - augmentedSymbolName = `[a-zA-Z0-9_]+`
*
* Any valid symbol name that represents the symbol that is being augmented. For example,
* the import `rxjs/add/observable/from` attaches the `from` method to the `Observable` class.
* To import it correctly the spec should be `+rxjs/add/observable/from#Observable`. Adding this
* parameter to augmented imports ensures they are output only when the symbol being augmented
* is actually used.
*
*
* @param spec Symbol spec to parse.
* @return Parsed symbol specification
*/
static from(spec) {
let matched = spec.match(importPattern);
if (matched === null) {
matched = spec.match(sourceImportPattern);
}
if (matched != null) {
const modulePath = matched[3];
const kind = matched[2] || '@';
const symbolName = matched[1] || lodash_1.default.last(modulePath.split('/')) || '';
const targetName = matched[4];
switch (kind) {
case '*':
return Import.importsAll(symbolName, modulePath);
case '@':
const isTypeImport = symbolName.startsWith('t:');
let exportedNames;
if (isTypeImport) {
exportedNames = symbolName.substring(2).split(':');
}
else {
exportedNames = symbolName.split(':');
}
const exportedName = exportedNames.pop();
const sourceExportedName = exportedNames[0];
return Import.importsName(exportedName, modulePath, isTypeImport, sourceExportedName);
case '=':
return Import.importsDefault(symbolName, modulePath);
case '+':
return targetName
? Import.augmented(symbolName, modulePath, targetName)
: Import.sideEffect(symbolName, modulePath);
default:
throw new Error('Invalid import kind character');
}
}
return Import.implicit(spec);
}
static fromMaybeString(spec) {
return typeof spec === 'string' ? Import.from(spec) : spec;
}
toCodeString() {
return this.symbol;
}
get childNodes() {
return [];
}
/**
* Creates an import of all the modules exported symbols as a single
* local named symbol
*
* e.g. `import * as Engine from 'templates';`
*
* @param localName The local name of the imported symbols
* @param from The module to import the symbols from
*/
static importsAll(localName, from) {
return new ImportsAll(localName, from);
}
/**
* Creates an import of a single named symbol from the module's exported
* symbols.
*
* e.g. `import { Engine } from 'templates';`
*
* @param exportedName The symbol that is both exported and imported
* @param from The module the symbol is exported from
* @param typeImport whether this is an `import type` import
*/
static importsName(exportedName, from, typeImport, sourceExportedName) {
return new ImportsName(exportedName, from, sourceExportedName, typeImport);
}
/**
* Creates a symbol that is brought in by a whole module import
* that "augments" an existing symbol.
*
* e.g. `import 'rxjs/add/operator/flatMap'`
*
* @param symbolName The augmented symbol to be imported
* @param from The entire import that does the augmentation
* @param target The symbol that is augmented
*/
static augmented(symbolName, from, target) {
return new Augmented(symbolName, from, target);
}
/**
* Creates a symbol that is brought in as a side effect of
* an import.
*
* e.g. `import 'mocha'`
*
* @param symbolName The symbol to be imported
* @param from The entire import that does the augmentation
*/
static sideEffect(symbolName, from) {
return new SideEffect(symbolName, from);
}
/**
* An implied symbol that does no tracking of imports
*
* @param name The implicit symbol name
*/
static implicit(name) {
return new Implicit(name);
}
/**
* Creates an import of a single named symbol from the module's exported
* default.
*
* e.g. `import Engine from 'engine';`
*
* @param exportedName The symbol that is both exported and imported
* @param from The module the symbol is exported from
*/
static importsDefault(exportedName, from) {
return new ImportsDefault(exportedName, from);
}
}
exports.Import = Import;
/**
* Non-imported symbol
*/
class Implicit extends Import {
constructor(symbol) {
super(symbol);
this.source = undefined;
}
}
exports.Implicit = Implicit;
/** Common base class for imported symbols. */
class Imported extends Import {
/** The symbol is the imported symbol, i.e. `BarClass`, and source is the path it comes from. */
constructor(symbol, source) {
super(source);
this.symbol = symbol;
this.source = source;
}
}
exports.Imported = Imported;
/**
* Imports a single named symbol from the module's exported
* symbols.
*
* E.g.:
*
* `import { Engine } from 'templates'` or
* `import { Engine as Engine2 } from 'templates'`
*/
class ImportsName extends Imported {
/**
* @param symbol
* @param source
* @param sourceSymbol is the optional original symbol, i.e if we're renaming the symbol it is `Engine`
* @param typeImport whether this is an `import type` import
*/
constructor(symbol, source, sourceSymbol, typeImport) {
super(symbol, source);
this.sourceSymbol = sourceSymbol;
this.typeImport = typeImport;
}
toImportPiece() {
return this.sourceSymbol ? `${this.sourceSymbol} as ${this.symbol}` : this.symbol;
}
}
exports.ImportsName = ImportsName;
/**
* Imports a single named symbol from the module's exported
* default.
*
* e.g. `import Engine from 'engine';`
*/
class ImportsDefault extends Imported {
constructor(symbol, source) {
super(symbol, source);
}
}
exports.ImportsDefault = ImportsDefault;
/**
* Imports all of the modules exported symbols as a single
* named symbol
*
* e.g. `import * as Engine from 'templates';`
*/
class ImportsAll extends Imported {
constructor(symbol, source) {
super(symbol, source);
}
}
exports.ImportsAll = ImportsAll;
/**
* A symbol that is brought in by a whole module import
* that "augments" an existing symbol.
*
* e.g. `import 'rxjs/add/operator/flatMap'`
*/
class Augmented extends Imported {
constructor(symbol, source, augmented) {
super(symbol, source);
this.augmented = augmented;
}
}
exports.Augmented = Augmented;
/**
* A symbol that is brought in as a side effect of an import.
*
* E.g. `from("Foo+mocha")` will add `import 'mocha'`
*/
class SideEffect extends Imported {
constructor(symbol, source) {
super(symbol, source);
}
}
exports.SideEffect = SideEffect;
/** Generates the `import ...` lines for the given `imports`. */
function emitImports(imports, ourModulePath, importMappings) {
if (imports.length == 0) {
return '';
}
let result = '';
const augmentImports = lodash_1.default.groupBy(filterInstances(imports, Augmented), (a) => a.augmented);
// Group the imports by source module they're imported from
const importsByModule = lodash_1.default.groupBy(imports.filter((it) => it.source !== undefined &&
// Ignore imports that are in our own file
!(it instanceof ImportsName && it.definedIn && sameModule(it.definedIn, ourModulePath))), (it) => it.source);
// Output each source module as one line
Object.entries(importsByModule).forEach(([modulePath, imports]) => {
// Skip imports from the current module
if (sameModule(ourModulePath, modulePath)) {
return;
}
if (modulePath in importMappings) {
modulePath = importMappings[modulePath];
}
const importPath = maybeRelativePath(ourModulePath, modulePath);
// Output star imports individually
unique(filterInstances(imports, ImportsAll).map((i) => i.symbol)).forEach((symbol) => {
result += `import * as ${symbol} from '${importPath}';\n`;
const augments = augmentImports[symbol];
if (augments) {
augments.forEach((augment) => (result += `import '${augment.source}';\n`));
}
});
// Partition named imported into `import type` vs. regular imports
const allNames = filterInstances(imports, ImportsName);
const names = unique(allNames.filter((i) => !i.typeImport).map((it) => it.toImportPiece()));
const def = unique(filterInstances(imports, ImportsDefault).map((it) => it.symbol));
// Output named imports as a group
if (names.length > 0 || def.length > 0) {
const namesPart = names.length > 0 ? [`{ ${names.join(', ')} }`] : [];
const defPart = def.length > 0 ? [def[0]] : [];
result += `import ${[...defPart, ...namesPart].join(', ')} from '${importPath}';\n`;
[...names, ...def].forEach((name) => {
const augments = augmentImports[name];
if (augments) {
augments.forEach((augment) => (result += `import '${augment.source}';\n`));
}
});
}
const typeImports = unique(allNames
.filter((i) => i.typeImport)
.map((it) => it.toImportPiece())
// If the `import type` is already used as a concrete import, just use that
.filter((p) => !names.includes(p)));
if (typeImports.length > 0) {
result += `import type { ${typeImports.join(', ')} } from '${importPath}';\n`;
}
});
const sideEffectImports = lodash_1.default.groupBy(filterInstances(imports, SideEffect), (a) => a.source);
Object.keys(sideEffectImports).forEach((it) => (result += `import '${it}';\n`));
return result;
}
exports.emitImports = emitImports;
function filterInstances(list, t) {
return list.filter((e) => e instanceof t);
}
function unique(list) {
return [...new Set(list)];
}
function maybeRelativePath(outputPath, importPath) {
if (!importPath.startsWith('./')) {
return importPath;
}
importPath = path.normalize(importPath);
outputPath = path.normalize(outputPath);
const outputPathDir = path.dirname(outputPath);
let relativePath = path.relative(outputPathDir, importPath).split(path.sep).join(path.posix.sep);
if (!relativePath.startsWith('.')) {
// ensure the js compiler recognizes this is a relative path.
relativePath = './' + relativePath;
}
return relativePath;
}
exports.maybeRelativePath = maybeRelativePath;
/** Checks if `path1 === path2` despite minor path differences like `./foo` and `foo`. */
function sameModule(path1, path2) {
// TypeScript: import paths ending in .js and .ts are resolved to the .ts file.
// Check the base paths (without the .js or .ts suffix).
const [basePath1, basePath2] = [path1, path2].map((p) => p.replace(/\.[tj]sx?/, ''));
return basePath1 === basePath2 || path.resolve(basePath1) === path.resolve(basePath2);
}
exports.sameModule = sameModule;

View file

@ -0,0 +1,10 @@
import { Node } from './Node';
/**
* A literal source representation of the provided object
*/
export declare class Literal extends Node {
private readonly tokens;
constructor(object: unknown);
get childNodes(): unknown[];
toCodeString(): string;
}

View file

@ -0,0 +1,63 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Literal = void 0;
const Node_1 = require("./Node");
const ConditionalOutput_1 = require("./ConditionalOutput");
const is_plain_object_1 = require("./is-plain-object");
/**
* A literal source representation of the provided object
*/
class Literal extends Node_1.Node {
constructor(object) {
super();
this.tokens = flatten(object);
}
get childNodes() {
return this.tokens;
}
toCodeString() {
return this.tokens
.map((node) => {
if (typeof node === 'string')
return node;
if (node instanceof Node_1.Node)
return node.toCodeString();
return '';
})
.join(' ');
}
}
exports.Literal = Literal;
function flatten(o) {
if (typeof o === 'undefined') {
return ['undefined'];
}
if (typeof o === 'object' && o != null) {
if (o instanceof Node_1.Node || o instanceof ConditionalOutput_1.MaybeOutput) {
return [o];
}
else if (Array.isArray(o)) {
const nodes = ['['];
for (let i = 0; i < o.length; i++) {
if (i !== 0)
nodes.push(',');
nodes.push(...flatten(o[i]));
}
nodes.push(']');
return nodes;
}
else if (is_plain_object_1.isPlainObject(o)) {
const nodes = ['{'];
const entries = Object.entries(o);
for (let i = 0; i < entries.length; i++) {
if (i !== 0)
nodes.push(',');
const [key, value] = entries[i];
nodes.push(JSON.stringify(key), ':', ...flatten(value));
}
nodes.push('}');
return nodes;
}
}
return [JSON.stringify(o)];
}

View file

@ -0,0 +1,6 @@
export declare abstract class Node {
/** Return the unformatted code for this node. */
abstract toCodeString(): string;
/** Any potentially string/SymbolSpec/Code nested nodes within us. */
abstract get childNodes(): unknown[];
}

View file

@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Node = void 0;
class Node {
}
exports.Node = Node;

View file

@ -0,0 +1,190 @@
import { Node } from './Node';
export declare const importType = "[*@+=]";
/**
* Specifies a symbol and its related origin, either via import or implicit/local declaration.
*
* @param value Value of the symbol
*/
export declare abstract class SymbolSpec extends Node {
value: string;
/**
* Parses a symbol reference pattern to create a symbol. The pattern
* allows the simple definition of all symbol types including any possible
* import variation. If the spec to parse does not follow the proper format
* an implicit symbol is created from the unparsed spec.
*
* Pattern: `symbolName? importType modulePath (#<augmentedSymbolName>)?`
*
* Where:
*
* - `symbolName` is any legal JS/TS symbol. If none, we use the last part of the module path as a guess.
* - `importType` is one of `@` or `*` or `+`, where:
* - `@` is a named import
* - `Foo@bar` becomes `import { Foo } from 'bar'`
* - `*` is a star import,
* - `*Foo` becomes `import * as Foo from 'Foo'`
* - `Foo*foo` becomes `import * as Foo from 'foo'`
* - `+` is an implicit import
* - E.g. `Foo+foo` becomes `import 'foo'`
* - `modulePath` is a path
* - E.g. `<filename>(/<filename)*`
* - augmentedSymbolName = `[a-zA-Z0-9_]+`
*
* Any valid symbol name that represents the symbol that is being augmented. For example,
* the import `rxjs/add/observable/from` attaches the `from` method to the `Observable` class.
* To import it correctly the spec should be `+rxjs/add/observable/from#Observable`. Adding this
* parameter to augmented imports ensures they are output only when the symbol being augmented
* is actually used.
*
*
* @param spec Symbol spec to parse.
* @return Parsed symbol specification
*/
static from(spec: string): SymbolSpec;
static fromMaybeString(spec: string | SymbolSpec): SymbolSpec;
/**
* Defined if the symbol is typically imported from a barrel/etc. path, but is technically defined in another file.
*
* We need to know this in case the "this comes from the barrel" type ends up being used in the file where
* the symbol itself is defined, i.e. we don't need an import in that case.
*/
definedIn?: string;
protected constructor(value: string);
toCodeString(): string;
get childNodes(): unknown[];
abstract source: string | undefined;
}
export declare class SymbolSpecs {
/**
* Creates an import of all the modules exported symbols as a single
* local named symbol
*
* e.g. `import * as Engine from 'templates';`
*
* @param localName The local name of the imported symbols
* @param from The module to import the symbols from
*/
static importsAll(localName: string, from: string): SymbolSpec;
/**
* Creates an import of a single named symbol from the module's exported
* symbols.
*
* e.g. `import { Engine } from 'templates';`
*
* @param exportedName The symbol that is both exported and imported
* @param from The module the symbol is exported from
*/
static importsName(exportedName: string, from: string): SymbolSpec;
/**
* Creates a symbol that is brought in by a whole module import
* that "augments" an existing symbol.
*
* e.g. `import 'rxjs/add/operator/flatMap'`
*
* @param symbolName The augmented symbol to be imported
* @param from The entire import that does the augmentation
* @param target The symbol that is augmented
*/
static augmented(symbolName: string, from: string, target: string): SymbolSpec;
/**
* Creates a symbol that is brought in as a side effect of
* an import.
*
* e.g. `import 'mocha'`
*
* @param symbolName The symbol to be imported
* @param from The entire import that does the augmentation
*/
static sideEffect(symbolName: string, from: string): SymbolSpec;
/**
* An implied symbol that does no tracking of imports
*
* @param name The implicit symbol name
*/
static implicit(name: string): SymbolSpec;
/**
* Creates an import of a single named symbol from the module's exported
* default.
*
* e.g. `import Engine from 'engine';`
*
* @param exportedName The symbol that is both exported and imported
* @param from The module the symbol is exported from
*/
static importsDefault(exportedName: string, from: string): SymbolSpec;
}
/**
* Non-imported symbol
*/
export declare class Implicit extends SymbolSpec {
constructor(value: string);
source: undefined;
}
/** Common base class for imported symbols. */
export declare abstract class Imported extends SymbolSpec {
value: string;
source: string;
/** The value is the imported symbol, i.e. `BarClass`, and source is the path it comes from. */
protected constructor(value: string, source: string);
}
/**
* Imports a single named symbol from the module's exported
* symbols.
*
* E.g.:
*
* `import { Engine } from 'templates'` or
* `import { Engine as Engine2 } from 'templates'`
*/
export declare class ImportsName extends Imported {
sourceValue?: string | undefined;
/**
* @param value
* @param source
* @param sourceValue is the optional original value, i.e if we're renaming the symbol it is `Engine`
*/
constructor(value: string, source: string, sourceValue?: string | undefined);
toImportPiece(): string;
}
/**
* Imports a single named symbol from the module's exported
* default.
*
* e.g. `import Engine from 'engine';`
*/
export declare class ImportsDefault extends Imported {
constructor(value: string, source: string);
}
/**
* Imports all of the modules exported symbols as a single
* named symbol
*
* e.g. `import * as Engine from 'templates';`
*/
export declare class ImportsAll extends Imported {
constructor(value: string, source: string);
}
/**
* A symbol that is brought in by a whole module import
* that "augments" an existing symbol.
*
* e.g. `import 'rxjs/add/operator/flatMap'`
*/
export declare class Augmented extends Imported {
augmented: string;
constructor(value: string, source: string, augmented: string);
}
/**
* A symbol that is brought in as a side effect of an
* import.
*
* E.g. `from("Foo+mocha")` will add `import 'mocha'`
*/
export declare class SideEffect extends Imported {
constructor(value: string, source: string);
}
/** Generates the `import ...` lines for the given `imports`. */
export declare function emitImports(imports: SymbolSpec[], ourModulePath: string): string;
export declare function maybeRelativePath(outputPath: string, importPath: string): string;
/** Checks if `path1 === path2` despite minor path differences like `./foo` and `foo`. */
export declare function sameModule(path1: string, path2: string): boolean;

View file

@ -0,0 +1,330 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = __importDefault(require("lodash"));
const path_1 = __importDefault(require("path"));
const Node_1 = require("./Node");
const fileNamePattern = '(?:[a-zA-Z0-9._-]+)';
const modulePattern = `@?(?:(?:${fileNamePattern}(?:/${fileNamePattern})*))`;
const identPattern = `(?:(?:[a-zA-Z][_a-zA-Z0-9.]*)|(?:[_a-zA-Z][_a-zA-Z0-9.]+))`;
exports.importType = '[*@+=]';
const importPattern = `^(${identPattern})?(${exports.importType})(${modulePattern})(?:#(${identPattern}))?`;
/**
* Specifies a symbol and its related origin, either via import or implicit/local declaration.
*
* @param value Value of the symbol
*/
class SymbolSpec extends Node_1.Node {
constructor(value) {
super();
this.value = value;
}
/**
* Parses a symbol reference pattern to create a symbol. The pattern
* allows the simple definition of all symbol types including any possible
* import variation. If the spec to parse does not follow the proper format
* an implicit symbol is created from the unparsed spec.
*
* Pattern: `symbolName? importType modulePath (#<augmentedSymbolName>)?`
*
* Where:
*
* - `symbolName` is any legal JS/TS symbol. If none, we use the last part of the module path as a guess.
* - `importType` is one of `@` or `*` or `+`, where:
* - `@` is a named import
* - `Foo@bar` becomes `import { Foo } from 'bar'`
* - `*` is a star import,
* - `*Foo` becomes `import * as Foo from 'Foo'`
* - `Foo*foo` becomes `import * as Foo from 'foo'`
* - `+` is an implicit import
* - E.g. `Foo+foo` becomes `import 'foo'`
* - `modulePath` is a path
* - E.g. `<filename>(/<filename)*`
* - augmentedSymbolName = `[a-zA-Z0-9_]+`
*
* Any valid symbol name that represents the symbol that is being augmented. For example,
* the import `rxjs/add/observable/from` attaches the `from` method to the `Observable` class.
* To import it correctly the spec should be `+rxjs/add/observable/from#Observable`. Adding this
* parameter to augmented imports ensures they are output only when the symbol being augmented
* is actually used.
*
*
* @param spec Symbol spec to parse.
* @return Parsed symbol specification
*/
static from(spec) {
const matched = spec.match(importPattern);
if (matched != null) {
const modulePath = matched[3];
const type = matched[2] || '@';
const symbolName = matched[1] || lodash_1.default.last(modulePath.split('/')) || '';
const targetName = matched[4];
switch (type) {
case '*':
return SymbolSpecs.importsAll(symbolName, modulePath);
case '@':
return SymbolSpecs.importsName(symbolName, modulePath);
case '=':
return SymbolSpecs.importsDefault(symbolName, modulePath);
case '+':
return targetName
? SymbolSpecs.augmented(symbolName, modulePath, targetName)
: SymbolSpecs.sideEffect(symbolName, modulePath);
default:
throw new Error('Invalid type character');
}
}
return SymbolSpecs.implicit(spec);
}
static fromMaybeString(spec) {
return typeof spec === 'string' ? SymbolSpec.from(spec) : spec;
}
toCodeString() {
return this.value;
}
get childNodes() {
return [];
}
}
exports.SymbolSpec = SymbolSpec;
class SymbolSpecs {
/**
* Creates an import of all the modules exported symbols as a single
* local named symbol
*
* e.g. `import * as Engine from 'templates';`
*
* @param localName The local name of the imported symbols
* @param from The module to import the symbols from
*/
static importsAll(localName, from) {
return new ImportsAll(localName, from);
}
/**
* Creates an import of a single named symbol from the module's exported
* symbols.
*
* e.g. `import { Engine } from 'templates';`
*
* @param exportedName The symbol that is both exported and imported
* @param from The module the symbol is exported from
*/
static importsName(exportedName, from) {
return new ImportsName(exportedName, from);
}
/**
* Creates a symbol that is brought in by a whole module import
* that "augments" an existing symbol.
*
* e.g. `import 'rxjs/add/operator/flatMap'`
*
* @param symbolName The augmented symbol to be imported
* @param from The entire import that does the augmentation
* @param target The symbol that is augmented
*/
static augmented(symbolName, from, target) {
return new Augmented(symbolName, from, target);
}
/**
* Creates a symbol that is brought in as a side effect of
* an import.
*
* e.g. `import 'mocha'`
*
* @param symbolName The symbol to be imported
* @param from The entire import that does the augmentation
*/
static sideEffect(symbolName, from) {
return new SideEffect(symbolName, from);
}
/**
* An implied symbol that does no tracking of imports
*
* @param name The implicit symbol name
*/
static implicit(name) {
return new Implicit(name);
}
/**
* Creates an import of a single named symbol from the module's exported
* default.
*
* e.g. `import Engine from 'engine';`
*
* @param exportedName The symbol that is both exported and imported
* @param from The module the symbol is exported from
*/
static importsDefault(exportedName, from) {
return new ImportsDefault(exportedName, from);
}
}
exports.SymbolSpecs = SymbolSpecs;
/**
* Non-imported symbol
*/
class Implicit extends SymbolSpec {
constructor(value) {
super(value);
this.source = undefined;
}
}
exports.Implicit = Implicit;
/** Common base class for imported symbols. */
class Imported extends SymbolSpec {
/** The value is the imported symbol, i.e. `BarClass`, and source is the path it comes from. */
constructor(value, source) {
super(source);
this.value = value;
this.source = source;
}
}
exports.Imported = Imported;
/**
* Imports a single named symbol from the module's exported
* symbols.
*
* E.g.:
*
* `import { Engine } from 'templates'` or
* `import { Engine as Engine2 } from 'templates'`
*/
class ImportsName extends Imported {
/**
* @param value
* @param source
* @param sourceValue is the optional original value, i.e if we're renaming the symbol it is `Engine`
*/
constructor(value, source, sourceValue) {
super(value, source);
this.sourceValue = sourceValue;
}
toImportPiece() {
return this.sourceValue ? `${this.sourceValue} as ${this.value}` : this.value;
}
}
exports.ImportsName = ImportsName;
/**
* Imports a single named symbol from the module's exported
* default.
*
* e.g. `import Engine from 'engine';`
*/
class ImportsDefault extends Imported {
constructor(value, source) {
super(value, source);
}
}
exports.ImportsDefault = ImportsDefault;
/**
* Imports all of the modules exported symbols as a single
* named symbol
*
* e.g. `import * as Engine from 'templates';`
*/
class ImportsAll extends Imported {
constructor(value, source) {
super(value, source);
}
}
exports.ImportsAll = ImportsAll;
/**
* A symbol that is brought in by a whole module import
* that "augments" an existing symbol.
*
* e.g. `import 'rxjs/add/operator/flatMap'`
*/
class Augmented extends Imported {
constructor(value, source, augmented) {
super(value, source);
this.augmented = augmented;
}
}
exports.Augmented = Augmented;
/**
* A symbol that is brought in as a side effect of an
* import.
*
* E.g. `from("Foo+mocha")` will add `import 'mocha'`
*/
class SideEffect extends Imported {
constructor(value, source) {
super(value, source);
}
}
exports.SideEffect = SideEffect;
/** Generates the `import ...` lines for the given `imports`. */
function emitImports(imports, ourModulePath) {
if (imports.length == 0) {
return '';
}
let result = '';
const augmentImports = lodash_1.default.groupBy(filterInstances(imports, Augmented), (a) => a.augmented);
// Group the imports by source module they're imported from
const importsByModule = lodash_1.default.groupBy(imports.filter((it) => it.source !== undefined &&
!(it instanceof ImportsName && it.definedIn && sameModule(it.definedIn, ourModulePath))), (it) => it.source);
// Output each source module as one line
Object.entries(importsByModule).forEach(([modulePath, imports]) => {
// Skip imports from the current module
if (sameModule(ourModulePath, modulePath)) {
return;
}
const importPath = maybeRelativePath(ourModulePath, modulePath);
// Output star imports individually
filterInstances(imports, ImportsAll).forEach((i) => {
result += `import * as ${i.value} from '${importPath}';\n`;
const augments = augmentImports[i.value];
if (augments) {
augments.forEach((augment) => (result += `import '${augment.source}';\n`));
}
});
// Output named imports as a group
const names = unique(filterInstances(imports, ImportsName).map((it) => it.toImportPiece()));
const def = unique(filterInstances(imports, ImportsDefault).map((it) => it.value));
if (names.length > 0 || def.length > 0) {
const namesPart = names.length > 0 ? [`{ ${names.join(', ')} }`] : [];
const defPart = def.length > 0 ? [def[0]] : [];
const allNames = [...defPart, ...namesPart];
result += `import ${allNames.join(', ')} from '${importPath}';\n`;
[...names, ...def].forEach((name) => {
const augments = augmentImports[name];
if (augments) {
augments.forEach((augment) => (result += `import '${augment.source}';\n`));
}
});
}
});
const sideEffectImports = lodash_1.default.groupBy(filterInstances(imports, SideEffect), (a) => a.source);
Object.keys(sideEffectImports).forEach((it) => (result += `import '${it}';\n`));
return result;
}
exports.emitImports = emitImports;
function filterInstances(list, t) {
return list.filter((e) => e instanceof t);
}
function unique(list) {
return [...new Set(list)];
}
function maybeRelativePath(outputPath, importPath) {
if (!importPath.startsWith('./')) {
return importPath;
}
// Drop the `./` prefix from the outputPath if it exists.
const basePath = outputPath.replace(/^.\//, '');
// Ideally we'd use a path library to do all this.
const numberOfDirs = basePath.split('').filter((l) => l === '/').length;
if (numberOfDirs === 0) {
return importPath;
}
// Make an array of `..` to get our importPath to the root directory.
const a = new Array(numberOfDirs);
const prefix = a.fill('..', 0, numberOfDirs).join('/');
return prefix + importPath.substring(1);
}
exports.maybeRelativePath = maybeRelativePath;
/** Checks if `path1 === path2` despite minor path differences like `./foo` and `foo`. */
function sameModule(path1, path2) {
return path1 === path2 || path_1.default.resolve(path1) === path_1.default.resolve(path2);
}
exports.sameModule = sameModule;

View file

@ -0,0 +1,22 @@
import { Import } from './Import';
import { Code, Def } from './Code';
import { Node } from './Node';
import { ConditionalOutput } from './ConditionalOutput';
export { Code } from './Code';
export { Import } from './Import';
/** A template literal to format code and auto-organize imports. */
export declare function code(literals: TemplateStringsArray, ...placeholders: unknown[]): Code;
export declare function literalOf(object: unknown): Node;
export declare function arrayOf(...elements: unknown[]): Node;
export declare function joinCode(chunks: Code[], opts?: {
on?: string;
trim?: boolean;
}): Code;
/** Creates an import that will be auto-imported at the top of the output file. */
export declare function imp(spec: string, opts?: {
definedIn?: string;
}): Import;
/** Defines `symbol` as being locally defined in the file, to avoid import collisions. */
export declare function def(symbol: string): Def;
/** Creates a conditionally-output code snippet. */
export declare function conditionalOutput(usageSite: string, declarationSite: Code): ConditionalOutput;

View file

@ -0,0 +1,64 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.conditionalOutput = exports.def = exports.imp = exports.joinCode = exports.arrayOf = exports.literalOf = exports.code = exports.Import = exports.Code = void 0;
const Import_1 = require("./Import");
const Code_1 = require("./Code");
const ConditionalOutput_1 = require("./ConditionalOutput");
const is_plain_object_1 = require("./is-plain-object");
const Literal_1 = require("./Literal");
var Code_2 = require("./Code");
Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return Code_2.Code; } });
var Import_2 = require("./Import");
Object.defineProperty(exports, "Import", { enumerable: true, get: function () { return Import_2.Import; } });
/** A template literal to format code and auto-organize imports. */
function code(literals, ...placeholders) {
return new Code_1.Code(literals, placeholders.map((p) => {
if (is_plain_object_1.isPlainObject(p)) {
return literalOf(p);
}
else {
return p;
}
}));
}
exports.code = code;
function literalOf(object) {
return new Literal_1.Literal(object);
}
exports.literalOf = literalOf;
function arrayOf(...elements) {
return literalOf(elements);
}
exports.arrayOf = arrayOf;
function joinCode(chunks, opts = {}) {
const { on = '', trim = true } = opts;
const literals = [''];
for (let i = 0; i < chunks.length - 1; i++) {
literals.push(on);
}
literals.push('');
if (trim) {
chunks.forEach((c) => (c.trim = true));
}
return new Code_1.Code(literals, chunks);
}
exports.joinCode = joinCode;
/** Creates an import that will be auto-imported at the top of the output file. */
function imp(spec, opts = {}) {
const sym = Import_1.Import.from(spec);
if (opts && opts.definedIn) {
sym.definedIn = opts.definedIn;
}
return sym;
}
exports.imp = imp;
/** Defines `symbol` as being locally defined in the file, to avoid import collisions. */
function def(symbol) {
return new Code_1.Def(symbol);
}
exports.def = def;
/** Creates a conditionally-output code snippet. */
function conditionalOutput(usageSite, declarationSite) {
return new ConditionalOutput_1.ConditionalOutput(usageSite, declarationSite);
}
exports.conditionalOutput = conditionalOutput;

View file

@ -0,0 +1,7 @@
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
export declare function isPlainObject(o: unknown): boolean;

View file

@ -0,0 +1,31 @@
"use strict";
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPlainObject = void 0;
function isPlainObject(o) {
if (o === null || o === undefined)
return false;
if (!isObject(o))
return false;
// If has modified constructor
const ctor = o.constructor;
if (ctor === undefined)
return true;
// If has modified prototype
if (!isObject(ctor.prototype))
return false;
// If constructor does not have an Object-specific method
if (!ctor.prototype.hasOwnProperty('isPrototypeOf'))
return false;
// Most likely a plain Object
return true;
}
exports.isPlainObject = isPlainObject;
function isObject(o) {
return Object.prototype.toString.call(o) === '[object Object]';
}

View file

@ -0,0 +1,15 @@
module.exports = {
clearMocks: true,
globals: {
'ts-jest': {
tsconfig: 'tsconfig.json',
},
},
moduleFileExtensions: ['ts', 'tsx', 'js'],
testEnvironment: 'node',
testMatch: ['<rootDir>/src/**/*-tests.+(ts|tsx|js)'],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
},
watchman: true,
};

View file

@ -0,0 +1 @@
../prettier/bin-prettier.js

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,109 @@
![Prettier Banner](https://unpkg.com/prettier-logo@1.0.3/images/prettier-banner-light.svg)
<h2 align="center">Opinionated Code Formatter</h2>
<p align="center">
<em>
JavaScript
· TypeScript
· Flow
· JSX
· JSON
</em>
<br />
<em>
CSS
· SCSS
· Less
</em>
<br />
<em>
HTML
· Vue
· Angular
</em>
<br />
<em>
GraphQL
· Markdown
· YAML
</em>
<br />
<em>
<a href="https://prettier.io/docs/en/plugins.html">
Your favorite language?
</a>
</em>
</p>
<p align="center">
<a href="https://github.com/prettier/prettier/actions?query=workflow%3AProd+branch%3Amain">
<img alt="Github Actions Build Status" src="https://img.shields.io/github/actions/workflow/status/prettier/prettier/prod-test.yml?label=Prod&style=flat-square"></a>
<a href="https://github.com/prettier/prettier/actions?query=workflow%3ADev+branch%3Amain">
<img alt="Github Actions Build Status" src="https://img.shields.io/github/actions/workflow/status/prettier/prettier/dev-test.yml?label=Dev&style=flat-square"></a>
<a href="https://github.com/prettier/prettier/actions?query=workflow%3ALint+branch%3Amain">
<img alt="Github Actions Build Status" src="https://img.shields.io/github/actions/workflow/status/prettier/prettier/lint.yml?label=Lint&style=flat-square"></a>
<a href="https://codecov.io/gh/prettier/prettier">
<img alt="Codecov Coverage Status" src="https://img.shields.io/codecov/c/github/prettier/prettier.svg?style=flat-square"></a>
<a href="https://twitter.com/acdlite/status/974390255393505280">
<img alt="Blazing Fast" src="https://img.shields.io/badge/speed-blazing%20%F0%9F%94%A5-brightgreen.svg?style=flat-square"></a>
<br/>
<a href="https://www.npmjs.com/package/prettier">
<img alt="npm version" src="https://img.shields.io/npm/v/prettier.svg?style=flat-square"></a>
<a href="https://www.npmjs.com/package/prettier">
<img alt="weekly downloads from npm" src="https://img.shields.io/npm/dw/prettier.svg?style=flat-square"></a>
<a href="#badge">
<img alt="code style: prettier" src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square"></a>
<a href="https://twitter.com/PrettierCode">
<img alt="Follow Prettier on Twitter" src="https://img.shields.io/twitter/follow/prettiercode.svg?label=follow+prettier&style=flat-square"></a>
</p>
## Intro
Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.
### Input
<!-- prettier-ignore -->
```js
foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
```
### Output
```js
foo(
reallyLongArg(),
omgSoManyParameters(),
IShouldRefactorThis(),
isThereSeriouslyAnotherOne()
);
```
Prettier can be run [in your editor](https://prettier.io/docs/en/editors.html) on-save, in a [pre-commit hook](https://prettier.io/docs/en/precommit.html), or in [CI environments](https://prettier.io/docs/en/cli.html#list-different) to ensure your codebase has a consistent style without devs ever having to post a nit-picky comment on a code review ever again!
---
**[Documentation](https://prettier.io/docs/en/)**
<!-- prettier-ignore -->
[Install](https://prettier.io/docs/en/install.html) ·
[Options](https://prettier.io/docs/en/options.html) ·
[CLI](https://prettier.io/docs/en/cli.html) ·
[API](https://prettier.io/docs/en/api.html)
**[Playground](https://prettier.io/playground/)**
---
## Badge
Show the world you're using _Prettier_ → [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
```md
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
```
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md).

View file

@ -0,0 +1,64 @@
#!/usr/bin/env node
"use strict";
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = function(cb, mod) {
return function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
};
// node_modules/semver-compare/index.js
var require_semver_compare = __commonJS({
"node_modules/semver-compare/index.js": function(exports2, module2) {
module2.exports = function cmp(a, b) {
var pa = a.split(".");
var pb = b.split(".");
for (var i = 0; i < 3; i++) {
var na = Number(pa[i]);
var nb = Number(pb[i]);
if (na > nb)
return 1;
if (nb > na)
return -1;
if (!isNaN(na) && isNaN(nb))
return 1;
if (isNaN(na) && !isNaN(nb))
return -1;
}
return 0;
};
}
});
// node_modules/please-upgrade-node/index.js
var require_please_upgrade_node = __commonJS({
"node_modules/please-upgrade-node/index.js": function(exports2, module2) {
var semverCompare = require_semver_compare();
module2.exports = function pleaseUpgradeNode2(pkg, opts) {
var opts = opts || {};
var requiredVersion = pkg.engines.node.replace(">=", "");
var currentVersion = process.version.replace("v", "");
if (semverCompare(currentVersion, requiredVersion) === -1) {
if (opts.message) {
console.error(opts.message(requiredVersion));
} else {
console.error(
pkg.name + " requires at least version " + requiredVersion + " of Node, please upgrade"
);
}
if (opts.hasOwnProperty("exitCode")) {
process.exit(opts.exitCode);
} else {
process.exit(1);
}
}
};
}
});
// bin/prettier.js
var pleaseUpgradeNode = require_please_upgrade_node();
var packageJson = require("./package.json");
pleaseUpgradeNode(packageJson);
var cli = require("./cli.js");
module.exports = cli.run(process.argv.slice(2));

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,21 @@
{
"name": "prettier",
"version": "2.8.8",
"description": "Prettier is an opinionated code formatter",
"bin": "./bin-prettier.js",
"repository": "prettier/prettier",
"funding": "https://github.com/prettier/prettier?sponsor=1",
"homepage": "https://prettier.io",
"author": "James Long",
"license": "MIT",
"main": "./index.js",
"browser": "./standalone.js",
"unpkg": "./standalone.js",
"engines": {
"node": ">=10.13.0"
},
"files": [
"*.js",
"esm/*.mjs"
]
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,37 @@
{
"name": "ts-poet",
"version": "4.15.0",
"description": "code generation DSL for TypeScript",
"main": "build/index.js",
"types": "build/index.d.ts",
"scripts": {
"prepare": "yarn build && yarn test",
"test": "yarn jest",
"build": "yarn tsc",
"lint": "yarn tslint --project ."
},
"repository": {
"type": "git",
"url": "https://github.com/stephenh/ts-poet.git"
},
"keywords": [],
"author": "Stephen Haberman",
"license": "Apache-2.0",
"devDependencies": {
"@types/jest": "^26.0.20",
"@types/lodash": "^4.14.137",
"@types/node": "^12.7.2",
"@typescript-eslint/eslint-plugin": "^2.0.0",
"@typescript-eslint/parser": "^2.0.0",
"eslint": "^6.2.2",
"eslint-config-prettier": "^6.1.0",
"eslint-plugin-prettier": "^3.1.0",
"jest": "^26.6.3",
"ts-jest": "^26.5.1",
"typescript": "^4.1.5"
},
"dependencies": {
"lodash": "^4.17.15",
"prettier": "^2.5.1"
}
}

View file

@ -0,0 +1,6 @@
/@Test
qf 4dw i it(" <sec> e a ",<sp> <esc> f)la => <esc> %a ); <esc>n
---- ------ -- --