@openrewrite/rewrite 8.97.1 → 8.97.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -0
- package/dist/javascript/comparator.d.ts +16 -10
- package/dist/javascript/comparator.d.ts.map +1 -1
- package/dist/javascript/comparator.js +10 -8
- package/dist/javascript/comparator.js.map +1 -1
- package/dist/javascript/package-json-parser.d.ts +2 -0
- package/dist/javascript/package-json-parser.d.ts.map +1 -1
- package/dist/javascript/package-json-parser.js +27 -15
- package/dist/javascript/package-json-parser.js.map +1 -1
- package/dist/javascript/package-manager.d.ts +13 -4
- package/dist/javascript/package-manager.d.ts.map +1 -1
- package/dist/javascript/package-manager.js +134 -17
- package/dist/javascript/package-manager.js.map +1 -1
- package/dist/javascript/print.d.ts.map +1 -1
- package/dist/javascript/print.js +1 -1
- package/dist/javascript/print.js.map +1 -1
- package/dist/javascript/recipes/dependencies.d.ts +17 -0
- package/dist/javascript/recipes/dependencies.d.ts.map +1 -1
- package/dist/javascript/recipes/dependencies.js +8 -0
- package/dist/javascript/recipes/dependencies.js.map +1 -1
- package/dist/javascript/templating/comparator.d.ts +32 -79
- package/dist/javascript/templating/comparator.d.ts.map +1 -1
- package/dist/javascript/templating/comparator.js +35 -628
- package/dist/javascript/templating/comparator.js.map +1 -1
- package/dist/javascript/templating/debug.d.ts +143 -0
- package/dist/javascript/templating/debug.d.ts.map +1 -0
- package/dist/javascript/templating/debug.js +769 -0
- package/dist/javascript/templating/debug.js.map +1 -0
- package/dist/javascript/templating/index.d.ts +1 -1
- package/dist/javascript/templating/index.d.ts.map +1 -1
- package/dist/javascript/templating/index.js.map +1 -1
- package/dist/javascript/templating/pattern.d.ts +44 -35
- package/dist/javascript/templating/pattern.d.ts.map +1 -1
- package/dist/javascript/templating/pattern.js +224 -238
- package/dist/javascript/templating/pattern.js.map +1 -1
- package/dist/javascript/templating/rewrite.d.ts +4 -0
- package/dist/javascript/templating/rewrite.d.ts.map +1 -1
- package/dist/javascript/templating/rewrite.js +5 -1
- package/dist/javascript/templating/rewrite.js.map +1 -1
- package/dist/javascript/templating/types.d.ts +38 -35
- package/dist/javascript/templating/types.d.ts.map +1 -1
- package/dist/javascript/templating/utils.d.ts.map +1 -1
- package/dist/javascript/templating/utils.js +15 -0
- package/dist/javascript/templating/utils.js.map +1 -1
- package/dist/rewrite-javascript-version.txt +1 -1
- package/dist/rpc/request/install-recipes.d.ts +10 -0
- package/dist/rpc/request/install-recipes.d.ts.map +1 -1
- package/dist/rpc/request/install-recipes.js +51 -0
- package/dist/rpc/request/install-recipes.js.map +1 -1
- package/dist/rpc/request/prepare-recipe.d.ts +1 -0
- package/dist/rpc/request/prepare-recipe.d.ts.map +1 -1
- package/dist/rpc/request/prepare-recipe.js +13 -6
- package/dist/rpc/request/prepare-recipe.js.map +1 -1
- package/dist/test/rewrite-test.d.ts +1 -16
- package/dist/test/rewrite-test.d.ts.map +1 -1
- package/dist/test/rewrite-test.js +7 -58
- package/dist/test/rewrite-test.js.map +1 -1
- package/dist/util.d.ts +16 -0
- package/dist/util.d.ts.map +1 -1
- package/dist/util.js +53 -0
- package/dist/util.js.map +1 -1
- package/dist/yaml/parser.js +8 -5
- package/dist/yaml/parser.js.map +1 -1
- package/dist/yaml/print.js +9 -3
- package/dist/yaml/print.js.map +1 -1
- package/package.json +1 -1
- package/src/javascript/comparator.ts +66 -53
- package/src/javascript/package-json-parser.ts +25 -16
- package/src/javascript/package-manager.ts +121 -15
- package/src/javascript/print.ts +1 -2
- package/src/javascript/recipes/dependencies.ts +21 -0
- package/src/javascript/templating/comparator.ts +76 -766
- package/src/javascript/templating/debug.ts +806 -0
- package/src/javascript/templating/index.ts +1 -0
- package/src/javascript/templating/pattern.ts +267 -270
- package/src/javascript/templating/rewrite.ts +5 -1
- package/src/javascript/templating/types.ts +40 -37
- package/src/javascript/templating/utils.ts +0 -1
- package/src/rpc/request/install-recipes.ts +54 -0
- package/src/rpc/request/prepare-recipe.ts +18 -15
- package/src/test/rewrite-test.ts +2 -59
- package/src/util.ts +58 -0
- package/src/yaml/parser.ts +9 -5
- package/src/yaml/print.ts +9 -3
|
@@ -44,7 +44,7 @@ class RewriteRuleImpl implements RewriteRule {
|
|
|
44
44
|
|
|
45
45
|
for (const pattern of this.before) {
|
|
46
46
|
// Pass cursor to pattern.match() for context-aware capture constraints
|
|
47
|
-
const match = await pattern.match(node, cursor);
|
|
47
|
+
const match = await pattern.match(node, cursor, {debug: options?.debug});
|
|
48
48
|
if (match) {
|
|
49
49
|
// Evaluate postMatch after structural match succeeds
|
|
50
50
|
if (this.postMatch) {
|
|
@@ -123,6 +123,10 @@ class RewriteRuleImpl implements RewriteRule {
|
|
|
123
123
|
/**
|
|
124
124
|
* Creates a replacement rule using a capture context and configuration.
|
|
125
125
|
*
|
|
126
|
+
* To see why a rule does not apply where you expected it to, call `tryOn(cursor, node, {debug: true})`,
|
|
127
|
+
* or set PATTERN_DEBUG=true for every pattern. Each match attempt then prints why it matched or not,
|
|
128
|
+
* as `PatternOptions.debug` describes.
|
|
129
|
+
*
|
|
126
130
|
* @param builderFn Function that takes a capture context and returns before/after configuration
|
|
127
131
|
* @returns A replacement rule that can be applied to AST nodes
|
|
128
132
|
*
|
|
@@ -366,47 +366,51 @@ export interface PatternOptions {
|
|
|
366
366
|
lenientTypeMatching?: boolean;
|
|
367
367
|
|
|
368
368
|
/**
|
|
369
|
-
*
|
|
370
|
-
*
|
|
371
|
-
* including the AST path traversed, mismatches encountered, and captured values.
|
|
372
|
-
*
|
|
373
|
-
* Can be overridden at the match() call level.
|
|
374
|
-
* Global debug can be enabled via PATTERN_DEBUG=true environment variable.
|
|
375
|
-
*
|
|
376
|
-
* Precedence: match() call > pattern configure() > PATTERN_DEBUG env var
|
|
377
|
-
*
|
|
378
|
-
* @default undefined (inherits from environment or match() call)
|
|
369
|
+
* Prints to stderr why each match attempt of this pattern matched or not, as {@link DebugSetting} describes.
|
|
370
|
+
* A match() call's own `debug` overrides it, and it overrides the PATTERN_DEBUG=true environment variable.
|
|
379
371
|
*
|
|
380
372
|
* @example
|
|
381
373
|
* ```typescript
|
|
382
|
-
* //
|
|
383
|
-
* const pat = pattern({
|
|
374
|
+
* // Every attempt
|
|
375
|
+
* const pat = pattern({debug: true})`console.log(${value})`;
|
|
384
376
|
*
|
|
385
|
-
* //
|
|
386
|
-
* const
|
|
377
|
+
* // Only attempts on calls named `log`, where a visitor matches the pattern against every call
|
|
378
|
+
* const onLog = (tree: J) => isMethodInvocation(tree) && tree.name.simpleName === 'log';
|
|
379
|
+
* const logs = pattern({debug: onLog})`console.log(${value})`;
|
|
380
|
+
*
|
|
381
|
+
* // No attempt, even with PATTERN_DEBUG=true
|
|
382
|
+
* const quiet = pattern({debug: false})`import ${x} from ${y}`;
|
|
387
383
|
* ```
|
|
388
384
|
*/
|
|
389
|
-
debug?:
|
|
385
|
+
debug?: DebugSetting;
|
|
390
386
|
}
|
|
391
387
|
|
|
388
|
+
/**
|
|
389
|
+
* Whether a match attempt prints debug output. `true` prints every attempt and `false` none, and a
|
|
390
|
+
* predicate decides per attempt from the node, its cursor and how the attempt ended. A failed attempt
|
|
391
|
+
* prints the pattern and the code with the mismatch marked and says why they differ. A successful one
|
|
392
|
+
* marks the captured code. Both name where the code is and where match() was called.
|
|
393
|
+
*/
|
|
394
|
+
export type DebugSetting = boolean | ((tree: J, cursor: Cursor, attempt: MatchAttemptResult) => boolean);
|
|
395
|
+
|
|
392
396
|
/**
|
|
393
397
|
* Options for individual match() calls.
|
|
394
398
|
*/
|
|
395
399
|
export interface MatchOptions {
|
|
396
400
|
/**
|
|
397
|
-
*
|
|
398
|
-
* Overrides pattern
|
|
401
|
+
* Prints to stderr why this call matched or not, as {@link DebugSetting} describes.
|
|
402
|
+
* Overrides the pattern's own `debug` and the PATTERN_DEBUG=true environment variable.
|
|
399
403
|
*
|
|
400
404
|
* @example
|
|
401
405
|
* ```typescript
|
|
402
406
|
* // Debug just this call
|
|
403
|
-
* const match = await pattern.match(node, cursor, {
|
|
407
|
+
* const match = await pattern.match(node, cursor, {debug: true});
|
|
404
408
|
*
|
|
405
409
|
* // Disable debug for this call even if pattern or global debug is on
|
|
406
|
-
* const match = await pattern.match(node, cursor, {
|
|
410
|
+
* const match = await pattern.match(node, cursor, {debug: false});
|
|
407
411
|
* ```
|
|
408
412
|
*/
|
|
409
|
-
debug?:
|
|
413
|
+
debug?: DebugSetting;
|
|
410
414
|
}
|
|
411
415
|
|
|
412
416
|
/**
|
|
@@ -560,6 +564,9 @@ export interface TryOnOptions {
|
|
|
560
564
|
|
|
561
565
|
/** As {@link ApplyOptions.bindings}, for a caller that resolves the modules some other way. */
|
|
562
566
|
bindings?: Record<string, string>;
|
|
567
|
+
|
|
568
|
+
/** Prints why each of the rule's patterns matched or not, as {@link PatternOptions.debug} describes. */
|
|
569
|
+
debug?: DebugSetting;
|
|
563
570
|
}
|
|
564
571
|
|
|
565
572
|
/**
|
|
@@ -729,7 +736,6 @@ export interface RewriteConfig {
|
|
|
729
736
|
|
|
730
737
|
/**
|
|
731
738
|
* Options for debugging pattern matching.
|
|
732
|
-
* Used in Layer 1 (Core Instrumentation) to control debug output.
|
|
733
739
|
*/
|
|
734
740
|
export interface DebugOptions {
|
|
735
741
|
/**
|
|
@@ -750,7 +756,6 @@ export interface DebugOptions {
|
|
|
750
756
|
|
|
751
757
|
/**
|
|
752
758
|
* A single debug log entry collected during pattern matching.
|
|
753
|
-
* Part of Layer 1 (Core Instrumentation).
|
|
754
759
|
*/
|
|
755
760
|
export interface DebugLogEntry {
|
|
756
761
|
/**
|
|
@@ -763,11 +768,6 @@ export interface DebugLogEntry {
|
|
|
763
768
|
*/
|
|
764
769
|
scope: 'matching' | 'comparison' | 'constraint';
|
|
765
770
|
|
|
766
|
-
/**
|
|
767
|
-
* Path in the AST where this log entry was generated.
|
|
768
|
-
*/
|
|
769
|
-
path: string[];
|
|
770
|
-
|
|
771
771
|
/**
|
|
772
772
|
* Human-readable message.
|
|
773
773
|
*/
|
|
@@ -781,7 +781,6 @@ export interface DebugLogEntry {
|
|
|
781
781
|
|
|
782
782
|
/**
|
|
783
783
|
* Detailed explanation of why a pattern failed to match.
|
|
784
|
-
* Built by Layer 1 (Core Instrumentation) and exposed by Layer 2 (API).
|
|
785
784
|
*/
|
|
786
785
|
export interface MatchExplanation {
|
|
787
786
|
/**
|
|
@@ -789,11 +788,6 @@ export interface MatchExplanation {
|
|
|
789
788
|
*/
|
|
790
789
|
reason: 'structural-mismatch' | 'constraint-failed' | 'type-mismatch' | 'kind-mismatch' | 'value-mismatch' | 'array-length-mismatch';
|
|
791
790
|
|
|
792
|
-
/**
|
|
793
|
-
* Path in the AST where the failure occurred (e.g., ['select', 'name']).
|
|
794
|
-
*/
|
|
795
|
-
path: string[];
|
|
796
|
-
|
|
797
791
|
/**
|
|
798
792
|
* Human-readable description of what was expected.
|
|
799
793
|
*/
|
|
@@ -804,6 +798,12 @@ export interface MatchExplanation {
|
|
|
804
798
|
*/
|
|
805
799
|
actual: string;
|
|
806
800
|
|
|
801
|
+
/** The pattern node where the pattern and the source differ, which debug output marks. */
|
|
802
|
+
patternElement?: J | J.Container<J>;
|
|
803
|
+
|
|
804
|
+
/** The source node where the pattern and the source differ, which debug output marks. */
|
|
805
|
+
targetElement?: J | J.Container<J>;
|
|
806
|
+
|
|
807
807
|
/**
|
|
808
808
|
* For constraint failures, details about which constraints failed.
|
|
809
809
|
*/
|
|
@@ -845,7 +845,6 @@ export interface MatchResult {
|
|
|
845
845
|
|
|
846
846
|
/**
|
|
847
847
|
* Result of a pattern match attempt with debug information.
|
|
848
|
-
* Part of Layer 2 (Public API).
|
|
849
848
|
*/
|
|
850
849
|
export interface MatchAttemptResult {
|
|
851
850
|
/**
|
|
@@ -864,8 +863,12 @@ export interface MatchAttemptResult {
|
|
|
864
863
|
*/
|
|
865
864
|
explanation?: MatchExplanation;
|
|
866
865
|
|
|
867
|
-
/**
|
|
868
|
-
* Debug log entries collected during matching (if debug was enabled).
|
|
869
|
-
*/
|
|
866
|
+
/** An entry for each capture constraint evaluated during matching, which `DebugOptions` can turn off. */
|
|
870
867
|
debugLog?: DebugLogEntry[];
|
|
868
|
+
|
|
869
|
+
/** Where the matched code starts in its source file, where the cursor leads to one. */
|
|
870
|
+
location?: { sourcePath: string, line?: number, column?: number };
|
|
871
|
+
|
|
872
|
+
/** What debug output prints for this attempt, without colours. Set by {@link Pattern.matchWithExplanation}. */
|
|
873
|
+
report?: string;
|
|
871
874
|
}
|
|
@@ -21,6 +21,7 @@ import * as nodeModule from "module";
|
|
|
21
21
|
import {createRequire} from "module";
|
|
22
22
|
import {pathToFileURL} from "url";
|
|
23
23
|
import {spawn} from "child_process";
|
|
24
|
+
import * as semver from "semver";
|
|
24
25
|
import {withMetrics} from "./metrics";
|
|
25
26
|
import {RecipeMarketplace} from "../../marketplace";
|
|
26
27
|
import {getPlatformCommand} from "../../shell-utils";
|
|
@@ -130,6 +131,11 @@ export class InstallRecipes {
|
|
|
130
131
|
resolvedPath = request.recipes;
|
|
131
132
|
}
|
|
132
133
|
|
|
134
|
+
const manifest = packageManifest(resolvedPath);
|
|
135
|
+
if (manifest) {
|
|
136
|
+
checkHostVersion(manifest, hostVersion(), logger);
|
|
137
|
+
}
|
|
138
|
+
|
|
133
139
|
let recipeModule;
|
|
134
140
|
try {
|
|
135
141
|
if (!resolveSharedDependenciesFromHost()) {
|
|
@@ -173,6 +179,54 @@ export class InstallRecipes {
|
|
|
173
179
|
}
|
|
174
180
|
}
|
|
175
181
|
|
|
182
|
+
const INCOMPATIBLE_RECIPE_BUNDLE = 1001;
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Throws when this host's version is outside the package's peer range for @openrewrite/rewrite.
|
|
186
|
+
* A development build of the host (0.0.0, or a prerelease snapshot) only warns.
|
|
187
|
+
* A plain dependency's range only records the version the package was built against, so it is not checked.
|
|
188
|
+
*/
|
|
189
|
+
export function checkHostVersion(manifest: { name?: string, version?: string, peerDependencies?: Record<string, string> },
|
|
190
|
+
hostVersion: string, logger?: rpc.Logger): void {
|
|
191
|
+
const range = manifest.peerDependencies?.['@openrewrite/rewrite'];
|
|
192
|
+
if (!range || !semver.validRange(range) || semver.satisfies(hostVersion, range, {includePrerelease: true})) {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const message = `${manifest.name}@${manifest.version} requires @openrewrite/rewrite ${range}, but this host runs ${hostVersion}`;
|
|
196
|
+
if (hostVersion === '0.0.0' || semver.prerelease(hostVersion)) {
|
|
197
|
+
logger?.warn(message);
|
|
198
|
+
} else {
|
|
199
|
+
// RewriteRpc on the Java side turns this code and data into an IncompatibleRecipeBundleException.
|
|
200
|
+
// data is a string because that side's JSON-RPC library cannot decode an object there.
|
|
201
|
+
throw new rpc.ResponseError(INCOMPATIBLE_RECIPE_BUNDLE, message, JSON.stringify(
|
|
202
|
+
{packageName: manifest.name, packageVersion: manifest.version, requiredRange: range, hostVersion}));
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function hostVersion(): string {
|
|
207
|
+
const root = findPackageRoot(__filename, '@openrewrite/rewrite');
|
|
208
|
+
return root ? JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version : '0.0.0';
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* The package.json of the package a module belongs to, the nearest one above its entry file.
|
|
213
|
+
*/
|
|
214
|
+
function packageManifest(modulePath: string): any {
|
|
215
|
+
let dir: string;
|
|
216
|
+
try {
|
|
217
|
+
dir = path.dirname(require.resolve(modulePath));
|
|
218
|
+
} catch {
|
|
219
|
+
return undefined; // Loading the module reports why it does not resolve
|
|
220
|
+
}
|
|
221
|
+
for (; dir !== path.dirname(dir); dir = path.dirname(dir)) {
|
|
222
|
+
const file = path.join(dir, 'package.json');
|
|
223
|
+
if (fs.existsSync(file)) {
|
|
224
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
|
|
176
230
|
const SHARED_DEPENDENCIES = ['@openrewrite/rewrite', 'vscode-jsonrpc', 'mutative'];
|
|
177
231
|
let sharedDependencyHook: boolean | undefined;
|
|
178
232
|
|
|
@@ -174,22 +174,21 @@ export class PrepareRecipe {
|
|
|
174
174
|
const wireEntry = this.conditionWireEntry(visitor.check, phase);
|
|
175
175
|
if (wireEntry) {
|
|
176
176
|
preconditions.push(wireEntry);
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
{
|
|
182
|
-
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
183
|
-
return visitor.v;
|
|
184
|
-
}
|
|
185
|
-
} :
|
|
186
|
-
{
|
|
187
|
-
async scanner(acc: any): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
188
|
-
const checkVisitor = await (recipe as ScanningRecipe<any>).scanner(acc);
|
|
189
|
-
return (checkVisitor as Check<any>).v;
|
|
190
|
-
}
|
|
177
|
+
if (phase === "edit") {
|
|
178
|
+
recipe = PrepareRecipe.withOverrides(recipe, {
|
|
179
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
180
|
+
return visitor.v;
|
|
191
181
|
}
|
|
192
|
-
|
|
182
|
+
});
|
|
183
|
+
} else {
|
|
184
|
+
const scanner = (recipe as ScanningRecipe<any>).scanner;
|
|
185
|
+
recipe = PrepareRecipe.withOverrides(recipe, {
|
|
186
|
+
async scanner(this: ScanningRecipe<any>, acc: any): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
187
|
+
const scanVisitor = await scanner.call(this, acc);
|
|
188
|
+
return scanVisitor instanceof Check ? scanVisitor.v : scanVisitor;
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
193
192
|
}
|
|
194
193
|
await this.visitorTypePrecondition(preconditions, visitor.v);
|
|
195
194
|
} else {
|
|
@@ -198,6 +197,10 @@ export class PrepareRecipe {
|
|
|
198
197
|
return recipe;
|
|
199
198
|
}
|
|
200
199
|
|
|
200
|
+
private static withOverrides(recipe: Recipe, overrides: object): Recipe {
|
|
201
|
+
return Object.assign(Object.create(Object.getPrototypeOf(recipe)), recipe, overrides);
|
|
202
|
+
}
|
|
203
|
+
|
|
201
204
|
/**
|
|
202
205
|
* Translate a precondition condition (operand) to a wire entry.
|
|
203
206
|
*
|
package/src/test/rewrite-test.ts
CHANGED
|
@@ -20,7 +20,8 @@ import {Parser} from "../parser";
|
|
|
20
20
|
import {MarkerPrinter, PrintOutputCapture, TreePrinters} from "../print";
|
|
21
21
|
import {Cursor, isTree, rootCursor, SourceFile} from "../tree";
|
|
22
22
|
import {ACCUMULATOR_LISTENER, Result, scheduleRun} from "../run";
|
|
23
|
-
import {mapAsync, trimIndent} from "../util";
|
|
23
|
+
import {dedent, mapAsync, trimIndent} from "../util";
|
|
24
|
+
export {dedent} from "../util";
|
|
24
25
|
import {isParseError, ParseErrorKind} from "../parse-error";
|
|
25
26
|
import {Marker, Markers, MarkersKind, ParseExceptionResult} from "../markers";
|
|
26
27
|
import {isNamedStyles} from "../style";
|
|
@@ -854,64 +855,6 @@ class NoopRecipe extends Recipe {
|
|
|
854
855
|
|
|
855
856
|
export type AfterRecipeText = string | ((actual: string) => string | undefined) | undefined | null;
|
|
856
857
|
|
|
857
|
-
/**
|
|
858
|
-
* Simple dedent implementation that removes common leading whitespace from each line.
|
|
859
|
-
*
|
|
860
|
-
* Behavior:
|
|
861
|
-
* - Removes ONE leading newline if present (for template string ergonomics)
|
|
862
|
-
* - Preserves trailing newlines (important for testing formatters like Prettier)
|
|
863
|
-
* - For lines with content: removes common indentation
|
|
864
|
-
* - For lines with only whitespace: removes common indentation, preserving remaining spaces
|
|
865
|
-
*
|
|
866
|
-
* Examples:
|
|
867
|
-
* - `\n code` → `code` (single leading newline removed)
|
|
868
|
-
* - `\n\n code` → `\ncode` (first newline removed, second preserved)
|
|
869
|
-
* - ` code\n` → `code\n` (trailing newline preserved)
|
|
870
|
-
* - ` code\n\n` → `code\n\n` (trailing newlines preserved)
|
|
871
|
-
*/
|
|
872
|
-
export function dedent(s: string): string {
|
|
873
|
-
if (!s) return s;
|
|
874
|
-
|
|
875
|
-
// Remove single leading newline for ergonomics
|
|
876
|
-
const start = s.charCodeAt(0) === 10 ? 1 : 0; // 10 = '\n'
|
|
877
|
-
|
|
878
|
-
if (start >= s.length) return '';
|
|
879
|
-
|
|
880
|
-
const str = start > 0 ? s.slice(start) : s;
|
|
881
|
-
const lines = str.split('\n');
|
|
882
|
-
|
|
883
|
-
// Always consider all lines for minIndent calculation
|
|
884
|
-
// If first line has content at column 0, minIndent will be 0 and no dedenting happens
|
|
885
|
-
const startLine = 0;
|
|
886
|
-
|
|
887
|
-
// Find minimum indentation
|
|
888
|
-
let minIndent = Infinity;
|
|
889
|
-
for (let i = startLine; i < lines.length; i++) {
|
|
890
|
-
const line = lines[i];
|
|
891
|
-
let indent = 0;
|
|
892
|
-
for (let j = 0; j < line.length; j++) {
|
|
893
|
-
const ch = line.charCodeAt(j);
|
|
894
|
-
if (ch === 32 || ch === 9) { // ' ' or '\t'
|
|
895
|
-
indent++;
|
|
896
|
-
} else {
|
|
897
|
-
// Found non-whitespace, update minIndent
|
|
898
|
-
if (indent < minIndent) minIndent = indent;
|
|
899
|
-
break;
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
|
|
904
|
-
// If all lines are empty or no indentation
|
|
905
|
-
if (minIndent === Infinity || minIndent === 0) {
|
|
906
|
-
return lines.join('\n');
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
// Remove common indentation from all lines
|
|
910
|
-
return lines.map(line =>
|
|
911
|
-
line.length >= minIndent ? line.slice(minIndent) : ''
|
|
912
|
-
).join('\n');
|
|
913
|
-
}
|
|
914
|
-
|
|
915
858
|
export function dedentAfter(s?: AfterRecipeText): AfterRecipeText {
|
|
916
859
|
if (s !== null) {
|
|
917
860
|
if (s === undefined) {
|
package/src/util.ts
CHANGED
|
@@ -50,6 +50,64 @@ export function trimIndent(str: string | null | undefined): string {
|
|
|
50
50
|
.trim();
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
/**
|
|
54
|
+
* Removes common leading whitespace from each line, optimized for template strings.
|
|
55
|
+
*
|
|
56
|
+
* Behavior:
|
|
57
|
+
* - Removes ONE leading newline if present (for template string ergonomics)
|
|
58
|
+
* - Preserves trailing newlines (important for testing formatters like Prettier)
|
|
59
|
+
* - For lines with content: removes common indentation
|
|
60
|
+
* - For lines with only whitespace: removes common indentation, preserving remaining spaces
|
|
61
|
+
*
|
|
62
|
+
* Examples:
|
|
63
|
+
* - `\n code` → `code` (single leading newline removed)
|
|
64
|
+
* - `\n\n code` → `\ncode` (first newline removed, second preserved)
|
|
65
|
+
* - ` code\n` → `code\n` (trailing newline preserved)
|
|
66
|
+
* - ` code\n\n` → `code\n\n` (trailing newlines preserved)
|
|
67
|
+
*/
|
|
68
|
+
export function dedent(s: string): string {
|
|
69
|
+
if (!s) return s;
|
|
70
|
+
|
|
71
|
+
// Remove single leading newline for ergonomics
|
|
72
|
+
const start = s.charCodeAt(0) === 10 ? 1 : 0; // 10 = '\n'
|
|
73
|
+
|
|
74
|
+
if (start >= s.length) return '';
|
|
75
|
+
|
|
76
|
+
const str = start > 0 ? s.slice(start) : s;
|
|
77
|
+
const lines = str.split('\n');
|
|
78
|
+
|
|
79
|
+
// Always consider all lines for minIndent calculation
|
|
80
|
+
// If first line has content at column 0, minIndent will be 0 and no dedenting happens
|
|
81
|
+
const startLine = 0;
|
|
82
|
+
|
|
83
|
+
// Find minimum indentation
|
|
84
|
+
let minIndent = Infinity;
|
|
85
|
+
for (let i = startLine; i < lines.length; i++) {
|
|
86
|
+
const line = lines[i];
|
|
87
|
+
let indent = 0;
|
|
88
|
+
for (let j = 0; j < line.length; j++) {
|
|
89
|
+
const ch = line.charCodeAt(j);
|
|
90
|
+
if (ch === 32 || ch === 9) { // ' ' or '\t'
|
|
91
|
+
indent++;
|
|
92
|
+
} else {
|
|
93
|
+
// Found non-whitespace, update minIndent
|
|
94
|
+
if (indent < minIndent) minIndent = indent;
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// If all lines are empty or no indentation
|
|
101
|
+
if (minIndent === Infinity || minIndent === 0) {
|
|
102
|
+
return lines.join('\n');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Remove common indentation from all lines
|
|
106
|
+
return lines.map(line =>
|
|
107
|
+
line.length >= minIndent ? line.slice(minIndent) : ''
|
|
108
|
+
).join('\n');
|
|
109
|
+
}
|
|
110
|
+
|
|
53
111
|
/**
|
|
54
112
|
* A compiled `(original, updates) => merged` builder that names every resulting property in an
|
|
55
113
|
* object literal. V8 sizes a literal's in-object storage to the properties it names, so the merged
|
package/src/yaml/parser.ts
CHANGED
|
@@ -129,7 +129,7 @@ class YamlCstReader {
|
|
|
129
129
|
prefix: "",
|
|
130
130
|
markers: emptyMarkers,
|
|
131
131
|
documents,
|
|
132
|
-
suffix: undefined
|
|
132
|
+
suffix: pendingPrefix || undefined
|
|
133
133
|
};
|
|
134
134
|
}
|
|
135
135
|
|
|
@@ -749,20 +749,20 @@ class YamlCstReader {
|
|
|
749
749
|
}
|
|
750
750
|
|
|
751
751
|
private convertFlowScalarWithTrailing(cst: CstFlowScalar): {node: Yaml.Scalar, trailing: string} {
|
|
752
|
-
const resolved = CST.resolveAsScalar(cst);
|
|
753
|
-
const value = resolved?.value ?? "";
|
|
754
|
-
|
|
755
|
-
// Determine scalar style
|
|
756
752
|
let style: Yaml.ScalarStyle;
|
|
753
|
+
let value: string;
|
|
757
754
|
switch (cst.type) {
|
|
758
755
|
case 'single-quoted-scalar':
|
|
759
756
|
style = Yaml.ScalarStyle.SINGLE_QUOTED;
|
|
757
|
+
value = this.unwrapQuotes(cst.source);
|
|
760
758
|
break;
|
|
761
759
|
case 'double-quoted-scalar':
|
|
762
760
|
style = Yaml.ScalarStyle.DOUBLE_QUOTED;
|
|
761
|
+
value = this.unwrapQuotes(cst.source);
|
|
763
762
|
break;
|
|
764
763
|
default:
|
|
765
764
|
style = Yaml.ScalarStyle.PLAIN;
|
|
765
|
+
value = cst.source;
|
|
766
766
|
}
|
|
767
767
|
|
|
768
768
|
// End tokens contain trailing whitespace/newlines
|
|
@@ -962,6 +962,10 @@ class YamlCstReader {
|
|
|
962
962
|
private concatenateSources(tokens: CstSourceToken[]): string {
|
|
963
963
|
return tokens.map(t => t.source).join('');
|
|
964
964
|
}
|
|
965
|
+
|
|
966
|
+
private unwrapQuotes(source: string): string {
|
|
967
|
+
return source.substring(1, source.length - 1);
|
|
968
|
+
}
|
|
965
969
|
}
|
|
966
970
|
|
|
967
971
|
Parsers.registerParser("yaml", YamlParser);
|
package/src/yaml/print.ts
CHANGED
|
@@ -70,6 +70,9 @@ class YamlPrinter extends YamlVisitor<PrintOutputCapture> {
|
|
|
70
70
|
if (mapping.anchor) {
|
|
71
71
|
await this.visit(mapping.anchor, p);
|
|
72
72
|
}
|
|
73
|
+
if (mapping.tag) {
|
|
74
|
+
await this.visit(mapping.tag, p);
|
|
75
|
+
}
|
|
73
76
|
if (mapping.openingBracePrefix !== undefined) {
|
|
74
77
|
p.append(mapping.openingBracePrefix);
|
|
75
78
|
p.append('{');
|
|
@@ -99,12 +102,12 @@ class YamlPrinter extends YamlVisitor<PrintOutputCapture> {
|
|
|
99
102
|
|
|
100
103
|
protected async visitScalar(scalar: Yaml.Scalar, p: PrintOutputCapture): Promise<Yaml | undefined> {
|
|
101
104
|
await this.beforeSyntax(scalar, p);
|
|
102
|
-
if (scalar.tag) {
|
|
103
|
-
await this.visit(scalar.tag, p);
|
|
104
|
-
}
|
|
105
105
|
if (scalar.anchor) {
|
|
106
106
|
await this.visit(scalar.anchor, p);
|
|
107
107
|
}
|
|
108
|
+
if (scalar.tag) {
|
|
109
|
+
await this.visit(scalar.tag, p);
|
|
110
|
+
}
|
|
108
111
|
switch (scalar.style) {
|
|
109
112
|
case Yaml.ScalarStyle.DOUBLE_QUOTED:
|
|
110
113
|
p.append('"');
|
|
@@ -138,6 +141,9 @@ class YamlPrinter extends YamlVisitor<PrintOutputCapture> {
|
|
|
138
141
|
if (sequence.anchor) {
|
|
139
142
|
await this.visit(sequence.anchor, p);
|
|
140
143
|
}
|
|
144
|
+
if (sequence.tag) {
|
|
145
|
+
await this.visit(sequence.tag, p);
|
|
146
|
+
}
|
|
141
147
|
if (sequence.openingBracketPrefix !== undefined) {
|
|
142
148
|
p.append(sequence.openingBracketPrefix);
|
|
143
149
|
p.append('[');
|