@autotelic/joggle 0.0.0-stage → 0.1.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.
Files changed (101) hide show
  1. package/JOGGLE.md +634 -0
  2. package/LICENSE +21 -0
  3. package/README.md +88 -2
  4. package/bin/joggle.js +6 -0
  5. package/dist/answer-store.js +305 -0
  6. package/dist/architecture.js +190 -0
  7. package/dist/ask.js +184 -0
  8. package/dist/astro.js +75 -0
  9. package/dist/atoms.js +76 -0
  10. package/dist/bundles.js +156 -0
  11. package/dist/calibration.js +60 -0
  12. package/dist/candidates.js +561 -0
  13. package/dist/canonical.js +24 -0
  14. package/dist/cascade.js +98 -0
  15. package/dist/check.js +854 -0
  16. package/dist/cluster.js +69 -0
  17. package/dist/config.js +195 -0
  18. package/dist/content-mappers.js +83 -0
  19. package/dist/decision.js +203 -0
  20. package/dist/fingerprint.js +61 -0
  21. package/dist/git.js +127 -0
  22. package/dist/gitignore.js +65 -0
  23. package/dist/glob.js +51 -0
  24. package/dist/imports.js +153 -0
  25. package/dist/jsonc.js +95 -0
  26. package/dist/main.js +630 -0
  27. package/dist/manifest.js +42 -0
  28. package/dist/meta.js +170 -0
  29. package/dist/moves.js +47 -0
  30. package/dist/operation.js +133 -0
  31. package/dist/parsecache.js +264 -0
  32. package/dist/plans.js +425 -0
  33. package/dist/plugin.js +71 -0
  34. package/dist/plugins.js +136 -0
  35. package/dist/policy.js +676 -0
  36. package/dist/presets/composition.js +32 -0
  37. package/dist/report.js +474 -0
  38. package/dist/reporting.js +132 -0
  39. package/dist/result.js +28 -0
  40. package/dist/roles.js +303 -0
  41. package/dist/rule.js +194 -0
  42. package/dist/rules/append-only-honoured.js +190 -0
  43. package/dist/rules/bundle-conformance.js +245 -0
  44. package/dist/rules/call-pattern.js +209 -0
  45. package/dist/rules/cluster-verdict.js +700 -0
  46. package/dist/rules/compose-types.js +250 -0
  47. package/dist/rules/data-error-as-outage.js +482 -0
  48. package/dist/rules/declared-staleness.js +242 -0
  49. package/dist/rules/dependency-fit.js +297 -0
  50. package/dist/rules/deviation-has-a-shape.js +225 -0
  51. package/dist/rules/doc-matches-code.js +191 -0
  52. package/dist/rules/duplicate-call-run.js +240 -0
  53. package/dist/rules/duplicate-implementation.js +89 -0
  54. package/dist/rules/duplicate-meaning.js +130 -0
  55. package/dist/rules/fact-or-derivation.js +202 -0
  56. package/dist/rules/field-type-drift.js +373 -0
  57. package/dist/rules/generic-carries-a-caller.js +198 -0
  58. package/dist/rules/hoist-to-domain.js +288 -0
  59. package/dist/rules/import-architecture.js +393 -0
  60. package/dist/rules/index.js +105 -0
  61. package/dist/rules/inferred-over-recorded.js +214 -0
  62. package/dist/rules/intent-drift.js +286 -0
  63. package/dist/rules/invariant-has-a-reconciler.js +190 -0
  64. package/dist/rules/language-drift.js +234 -0
  65. package/dist/rules/meaning-switched-by-flag.js +189 -0
  66. package/dist/rules/module-direction.js +231 -0
  67. package/dist/rules/name-as-address.js +216 -0
  68. package/dist/rules/name-the-primitive.js +203 -0
  69. package/dist/rules/naming-drift.js +218 -0
  70. package/dist/rules/nullability-drift.js +220 -0
  71. package/dist/rules/object-shape.js +280 -0
  72. package/dist/rules/one-concept-one-type.js +243 -0
  73. package/dist/rules/page-needs-composition.js +227 -0
  74. package/dist/rules/reimplemented-primitive.js +283 -0
  75. package/dist/rules/reversal.js +264 -0
  76. package/dist/rules/rule-judgment.js +252 -0
  77. package/dist/rules/schema-excludes-domain-value.js +190 -0
  78. package/dist/rules/shallow-module.js +204 -0
  79. package/dist/rules/single-path.js +237 -0
  80. package/dist/rules/structural-collapse.js +198 -0
  81. package/dist/rules/temporal-coupling.js +205 -0
  82. package/dist/rules/types-over-logic.js +198 -0
  83. package/dist/rules/unaccounted-drop.js +190 -0
  84. package/dist/rules/unbounded-default-read.js +227 -0
  85. package/dist/run-cache.js +132 -0
  86. package/dist/schema.js +285 -0
  87. package/dist/similarity.js +119 -0
  88. package/dist/source.js +30 -0
  89. package/dist/sql.js +34 -0
  90. package/dist/stages.js +39 -0
  91. package/dist/state.js +65 -0
  92. package/dist/testing.js +131 -0
  93. package/dist/tsconfig-scope.js +32 -0
  94. package/dist/tsgo.js +127 -0
  95. package/dist/typefacts.js +455 -0
  96. package/dist/typetrace.js +283 -0
  97. package/dist/verdict.js +65 -0
  98. package/dist/vocabulary.js +365 -0
  99. package/dist/workspace.js +1963 -0
  100. package/extensions/joggle.ts +454 -0
  101. package/package.json +85 -3
package/dist/git.js ADDED
@@ -0,0 +1,127 @@
1
+ import { Context, Effect, Layer, Schema, Stream } from "effect";
2
+ import { ChildProcess } from "effect/process";
3
+ import { GitError } from "./schema.js";
4
+ export class Service extends Context.Service()("@joggle/Git") {
5
+ }
6
+ /* -------------------------------------------------------------------------- */
7
+ /* Implementation */
8
+ /* -------------------------------------------------------------------------- */
9
+ const lines = (text) => text
10
+ .split(/\r?\n/)
11
+ .map((line) => line.trim())
12
+ .filter((line) => line.length > 0);
13
+ /**
14
+ * One subprocess, stdout or a typed failure.
15
+ *
16
+ * A non-zero exit is the failure the caller cares about, and its own stderr is
17
+ * the message -- "fatal: not a git repository" is more useful than anything this
18
+ * could invent. The binary being absent is the same shape of failure.
19
+ */
20
+ const command = ({ binary, args, cwd, }) => Effect.scoped(Effect.gen(function* () {
21
+ const handle = yield* ChildProcess.make(binary, [...args], { cwd });
22
+ const [stdout, stderr, exitCode] = yield* Effect.all([
23
+ handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
24
+ handle.stderr.pipe(Stream.decodeText(), Stream.mkString),
25
+ handle.exitCode,
26
+ ], { concurrency: "unbounded" });
27
+ if (Number(exitCode) !== 0) {
28
+ return yield* GitError.make({
29
+ operation: `${binary} ${args.join(" ")}`,
30
+ detail: stderr.trim() === "" ? `exited with code ${Number(exitCode)}` : stderr.trim(),
31
+ });
32
+ }
33
+ return stdout;
34
+ })).pipe(Effect.mapError((cause) => Schema.is(GitError)(cause)
35
+ ? cause
36
+ : GitError.make({
37
+ operation: `${binary} ${args.join(" ")}`,
38
+ detail: cause instanceof Error ? cause.message : String(cause),
39
+ })));
40
+ /** Whether a ref exists, without the failure of a missing one. */
41
+ const resolves = (input) => command({
42
+ binary: "git",
43
+ args: ["rev-parse", "--verify", "--quiet", input.ref],
44
+ cwd: input.cwd,
45
+ }).pipe(Effect.map(() => true), Effect.orElseSucceed(() => false));
46
+ /**
47
+ * The ref a pull request forked from.
48
+ *
49
+ * `gh` answers which branch the PR targets; git answers whether that branch is
50
+ * already a local remote-tracking ref. Fetching is the last resort, so a PR run
51
+ * on an up-to-date checkout costs no network.
52
+ */
53
+ const prRef = (cwd, pr) => Effect.gen(function* () {
54
+ const args = pr === undefined
55
+ ? ["pr", "view", "--json", "baseRefName", "--jq", ".baseRefName"]
56
+ : ["pr", "view", pr, "--json", "baseRefName", "--jq", ".baseRefName"];
57
+ const base = (yield* command({ binary: "gh", args, cwd })).trim();
58
+ if (base === "") {
59
+ return yield* GitError.make({
60
+ operation: "gh pr view",
61
+ detail: "the pull request has no base branch",
62
+ });
63
+ }
64
+ const origin = `origin/${base}`;
65
+ if (yield* resolves({ cwd, ref: origin }))
66
+ return origin;
67
+ if (yield* resolves({ cwd, ref: base }))
68
+ return base;
69
+ yield* command({ binary: "git", args: ["fetch", "origin", base], cwd });
70
+ return "FETCH_HEAD";
71
+ });
72
+ const changedFiles = Effect.fn("Git.changedFiles")(function* (cwd, options) {
73
+ const base = options.pr !== undefined
74
+ ? yield* prRef(cwd, options.pr === "" ? undefined : options.pr)
75
+ : options.since;
76
+ if (base === undefined)
77
+ return { changed: [], renamed: [] };
78
+ // Three dots by hand: the merge base is where the branch forked, so the diff
79
+ // is the PR's own work rather than every commit main has gained since. A ref
80
+ // with no common history (a fresh shallow clone, a squashed import) falls back
81
+ // to itself, which is the best answer git can give.
82
+ const mergeBase = yield* command({
83
+ binary: "git",
84
+ args: ["merge-base", base, "HEAD"],
85
+ cwd,
86
+ }).pipe(Effect.map((output) => lines(output)[0] ?? base), Effect.orElseSucceed(() => base));
87
+ // `-M` turns rename detection on and `--name-status` reports it as `R<score>`.
88
+ // `R100` is a rename git is certain kept every byte; anything below it changed
89
+ // content on the way, so it is a normal change.
90
+ const status = yield* command({
91
+ binary: "git",
92
+ args: ["diff", "--name-status", "-M", "--diff-filter=ACMR", "--relative", mergeBase],
93
+ cwd,
94
+ });
95
+ const changed = new Set();
96
+ const moved = new Set();
97
+ for (const line of status.split(/\r?\n/)) {
98
+ if (line.trim() === "")
99
+ continue;
100
+ const [code = "", second, third] = line.split("\t");
101
+ if (code.startsWith("R")) {
102
+ // A rename's path is the third column; the second is where it came from.
103
+ if (third === undefined)
104
+ continue;
105
+ if (code === "R100")
106
+ moved.add(third);
107
+ else
108
+ changed.add(third);
109
+ continue;
110
+ }
111
+ if (second !== undefined)
112
+ changed.add(second);
113
+ }
114
+ // A file the work just created is untracked, and a new duplicate most often
115
+ // arrives in one. `--exclude-standard` keeps .gitignore's word.
116
+ const untracked = yield* command({
117
+ binary: "git",
118
+ args: ["ls-files", "--others", "--exclude-standard"],
119
+ cwd,
120
+ });
121
+ for (const file of lines(untracked))
122
+ changed.add(file);
123
+ const order = (left, right) => left.localeCompare(right);
124
+ return { changed: [...changed].sort(order), renamed: [...moved].sort(order) };
125
+ });
126
+ const make = () => ({ changedFiles });
127
+ export const layer = Layer.succeed(Service, make());
@@ -0,0 +1,65 @@
1
+ import { Effect, FileSystem, Path } from "effect";
2
+ import { globSource } from "./glob.js";
3
+ /**
4
+ * One pattern to one regex, over a path relative to the pattern's directory.
5
+ *
6
+ * Returns undefined for the forms this deliberately does not handle, so the
7
+ * caller skips them instead of guessing: a rule nobody can predict is worse than
8
+ * a rule that is not there.
9
+ */
10
+ const toRegExp = (pattern) => {
11
+ let body = pattern;
12
+ if (body.startsWith("/"))
13
+ body = body.slice(1);
14
+ const directoryOnly = body.endsWith("/");
15
+ if (directoryOnly)
16
+ body = body.slice(0, -1);
17
+ if (body === "")
18
+ return undefined;
19
+ const hasSlash = body.includes("/");
20
+ // A pattern with no slash matches at any depth; one with a slash is anchored
21
+ // to the .gitignore's own directory. Git ignores a matched directory and
22
+ // everything below it, which is what the trailing group does.
23
+ const prefix = hasSlash || pattern.startsWith("/") ? "^" : "(?:^|.*/)";
24
+ return new RegExp(prefix + globSource(body, { question: true, doubleStarSkipsSlash: true }) + "(?:/.*)?$");
25
+ };
26
+ /** Parse gitignore lines into rules, relative to the file's directory. */
27
+ export const parseGitignore = ({ text, base, depth }) => {
28
+ const rules = [];
29
+ for (const raw of text.split("\n")) {
30
+ const line = raw.replace(/\s+$/, "");
31
+ if (line === "" || line.startsWith("#"))
32
+ continue;
33
+ const negated = line.startsWith("!");
34
+ const regex = toRegExp(negated ? line.slice(1) : line);
35
+ if (regex !== undefined)
36
+ rules.push({ base, depth, regex, negated });
37
+ }
38
+ return rules;
39
+ };
40
+ /** Shallowest first, so a deeper .gitignore overrides a higher one. */
41
+ export const orderRules = (rules) => [...rules].sort((left, right) => left.depth - right.depth);
42
+ /** Whether a path is ignored: the last matching rule wins, as git decides it. */
43
+ export const isIgnored = (rules, absolute, path) => {
44
+ let ignored = false;
45
+ for (const rule of rules) {
46
+ const relative = path.relative(rule.base, absolute);
47
+ // A rule only speaks for its own directory and below it.
48
+ if (relative === "" || relative.startsWith(".."))
49
+ continue;
50
+ if (rule.regex.test(relative))
51
+ ignored = !rule.negated;
52
+ }
53
+ return ignored;
54
+ };
55
+ /** The .gitignore in one directory, if it has one. */
56
+ export const rulesAt = (directory, depth) => Effect.gen(function* () {
57
+ const fs = yield* FileSystem.FileSystem;
58
+ const path = yield* Path.Path;
59
+ const file = path.join(directory, ".gitignore");
60
+ const exists = yield* Effect.orElseSucceed(fs.exists(file), () => false);
61
+ if (!exists)
62
+ return [];
63
+ const text = yield* Effect.orElseSucceed(fs.readFileString(file), () => "");
64
+ return parseGitignore({ text, base: directory, depth });
65
+ });
package/dist/glob.js ADDED
@@ -0,0 +1,51 @@
1
+ const SPECIAL = new Set([".", "+", "^", "$", "{", "}", "(", ")", "|", "[", "]", "?", "\\"]);
2
+ const escape = (text) => text
3
+ .split("")
4
+ .map((character) => (SPECIAL.has(character) ? "\\" + character : character))
5
+ .join("");
6
+ /**
7
+ * The regular-expression source for a glob pattern.
8
+ *
9
+ * @param pattern - The glob, without a leading or trailing delimiter.
10
+ * @param syntax - Which of the two behaviours to apply.
11
+ * @returns A regex source the caller anchors and compiles.
12
+ */
13
+ export const globSource = (pattern, syntax) => {
14
+ let source = "";
15
+ for (let index = 0; index < pattern.length; index += 1) {
16
+ const character = pattern[index];
17
+ if (character === "*") {
18
+ if (pattern[index + 1] === "*") {
19
+ source += ".*";
20
+ index += 1;
21
+ if (syntax.doubleStarSkipsSlash && pattern[index + 1] === "/")
22
+ index += 1;
23
+ }
24
+ else {
25
+ source += "[^/]*";
26
+ }
27
+ }
28
+ else if (character === "?" && syntax.question) {
29
+ source += "[^/]";
30
+ }
31
+ else {
32
+ source += escape(character ?? "");
33
+ }
34
+ }
35
+ return source;
36
+ };
37
+ const WILDCARD = /[*?]/;
38
+ /**
39
+ * A tsconfig `include` or `exclude` entry as a predicate over root-relative paths.
40
+ *
41
+ * An entry with no wildcard names a file or a directory, and a directory covers
42
+ * everything under it, as the compiler reads it. A wildcard entry follows
43
+ * gitignore's syntax: `src/**\/*` matches `src/a.astro` as well as deeper files.
44
+ */
45
+ export const tsconfigEntry = (entry) => {
46
+ const pattern = entry.replace(/^\.\//, "").replace(/\/$/, "");
47
+ if (!WILDCARD.test(pattern))
48
+ return (file) => file === pattern || file.startsWith(pattern + "/");
49
+ const regex = new RegExp("^" + globSource(pattern, { question: true, doubleStarSkipsSlash: true }) + "$");
50
+ return (file) => regex.test(file);
51
+ };
@@ -0,0 +1,153 @@
1
+ import { Schema } from "effect";
2
+ /**
3
+ * One import or re-export statement, before resolution.
4
+ *
5
+ * Declared as a Schema first and derived from it, because a parsed import is
6
+ * written to the parse cache and read back from disk. That makes it an external
7
+ * payload -- a file that can be truncated, stale or edited by hand -- so it is
8
+ * worth decoding rather than casting, and the type comes from the decoder so the
9
+ * two cannot drift.
10
+ */
11
+ export const ParsedImport = Schema.Struct({
12
+ specifier: Schema.String,
13
+ /** Names taken from the target. Empty for a side-effect import. */
14
+ names: Schema.Array(Schema.String),
15
+ /**
16
+ * `import type` and `export type` are erased at build time.
17
+ *
18
+ * Worth recording because it is the difference between a cycle that cannot
19
+ * exist at runtime and one that can: a type-only edge leaves no module
20
+ * initialisation behind, so a loop through it has no load-order consequence.
21
+ * Reporting both at the same volume is how a linter trains people to ignore it.
22
+ */
23
+ typeOnly: Schema.Boolean,
24
+ });
25
+ const EXTENSIONS = ["", ".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", "/index.ts", "/index.tsx"];
26
+ /**
27
+ * Resolve a specifier against the files we actually analysed.
28
+ *
29
+ * Relative specifiers resolve exactly. Anything else is treated as a bundler
30
+ * root alias and resolved by walking up from the importing file, which is how
31
+ * `~/utils` behaves in this codebase and needs no tsconfig, no plugin config and
32
+ * no extra filesystem calls. A package specifier fails to resolve, which is
33
+ * correct: we cannot fix a file we did not analyse.
34
+ */
35
+ export const resolveSpecifier = ({ from, specifier, known, path }) => {
36
+ const bases = [];
37
+ if (specifier.startsWith(".")) {
38
+ bases.push(path.join(path.dirname(from), specifier));
39
+ }
40
+ else if (!specifier.startsWith("/")) {
41
+ // `~/x` and `@/x` mean "from the project root"; strip the sigil and let the
42
+ // walk-up find which ancestor directory it is rooted at.
43
+ const trimmed = specifier.startsWith("~/") || specifier.startsWith("@/")
44
+ ? specifier.slice(2)
45
+ : specifier;
46
+ let directory = path.dirname(from);
47
+ for (let depth = 0; depth < 8; depth += 1) {
48
+ bases.push(path.join(directory, trimmed));
49
+ const parent = path.dirname(directory);
50
+ if (parent === directory)
51
+ break;
52
+ directory = parent;
53
+ }
54
+ }
55
+ for (const base of bases) {
56
+ for (const extension of EXTENSIONS) {
57
+ const candidate = base + extension;
58
+ if (known.has(candidate))
59
+ return candidate;
60
+ }
61
+ }
62
+ return undefined;
63
+ };
64
+ /** Resolve every file's imports against the known set, and return the graph. */
65
+ export const buildImportGraph = (files, path) => {
66
+ const known = new Set(files.map((file) => file.path));
67
+ const edges = [];
68
+ let unresolved = 0;
69
+ for (const file of files) {
70
+ for (const statement of file.importStatements) {
71
+ const target = resolveSpecifier({ from: file.path, specifier: statement.specifier, known, path });
72
+ if (target === undefined)
73
+ unresolved += 1;
74
+ edges.push({
75
+ importer: file.path,
76
+ specifier: statement.specifier,
77
+ to: target ?? statement.specifier,
78
+ resolution: target !== undefined ? "resolved" : "unresolved",
79
+ names: statement.names,
80
+ typeOnly: statement.typeOnly,
81
+ });
82
+ }
83
+ }
84
+ const importersOf = new Map();
85
+ for (const edge of edges) {
86
+ if (edge.resolution === "unresolved")
87
+ continue;
88
+ const existing = importersOf.get(edge.to);
89
+ if (existing === undefined)
90
+ importersOf.set(edge.to, [edge]);
91
+ else
92
+ existing.push(edge);
93
+ }
94
+ return {
95
+ edges,
96
+ importersOf,
97
+ importersOfName: (file, name) => (importersOf.get(file) ?? []).filter((edge) => edge.names.includes(name)),
98
+ unresolved,
99
+ };
100
+ };
101
+ /** Statements that introduce or forward a module binding. */
102
+ export const importsIn = (program) => {
103
+ const body = program["body"];
104
+ if (!Array.isArray(body))
105
+ return [];
106
+ const found = [];
107
+ for (const statement of body) {
108
+ if (typeof statement !== "object" || statement === null)
109
+ continue;
110
+ const node = statement;
111
+ const kind = node["type"];
112
+ if (kind !== "ImportDeclaration" && kind !== "ExportNamedDeclaration" && kind !== "ExportAllDeclaration") {
113
+ continue;
114
+ }
115
+ const source = node["source"];
116
+ if (typeof source !== "object" || source === null)
117
+ continue;
118
+ const value = source["value"];
119
+ if (typeof value !== "string")
120
+ continue;
121
+ const names = [];
122
+ const specifiers = node["specifiers"];
123
+ if (Array.isArray(specifiers)) {
124
+ for (const specifier of specifiers) {
125
+ if (typeof specifier !== "object" || specifier === null)
126
+ continue;
127
+ const record = specifier;
128
+ const imported = record["imported"];
129
+ const exported = record["exported"];
130
+ const name = typeof imported === "object" && imported !== null && typeof imported["name"] === "string"
131
+ ? imported["name"]
132
+ : typeof exported === "object" && exported !== null && typeof exported["name"] === "string"
133
+ ? exported["name"]
134
+ : undefined;
135
+ if (name !== undefined)
136
+ names.push(name);
137
+ }
138
+ }
139
+ // A statement is erased when it says so at the declaration, or when every
140
+ // name it takes is taken as a type. Mixed imports (`import { type A, b }`) are
141
+ // NOT erased: the runtime edge is real and so is any cycle through it.
142
+ let typeOnly = node["importKind"] === "type" || node["exportKind"] === "type";
143
+ if (!typeOnly && Array.isArray(specifiers) && specifiers.length > 0) {
144
+ typeOnly = specifiers.every((specifier) => {
145
+ if (typeof specifier !== "object" || specifier === null)
146
+ return false;
147
+ return specifier["importKind"] === "type";
148
+ });
149
+ }
150
+ found.push({ specifier: value, names, typeOnly });
151
+ }
152
+ return found;
153
+ };
package/dist/jsonc.js ADDED
@@ -0,0 +1,95 @@
1
+ /*
2
+ * JSON with comments and trailing commas, as tsconfig is written.
3
+ *
4
+ * `tsconfig.json` is JSONC by specification, and a strict `JSON.parse` turns a
5
+ * commented config into "no configuration" -- which is indistinguishable from a
6
+ * config that declares nothing. That is the wrong direction for a tool whose
7
+ * job is to notice what it did not look at.
8
+ *
9
+ * This is a scanner, not a regex: `//` inside a string is a string, and a
10
+ * trailing comma is only trailing if the next structural character is `}` or
11
+ * `]`. It does not validate; the schema decoder does that after.
12
+ */
13
+ /** Copy one string literal, including its quotes and escapes. */
14
+ const stringAt = (text, start) => {
15
+ let index = start + 1;
16
+ while (index < text.length) {
17
+ const character = text[index];
18
+ if (character === "\\") {
19
+ index += 2;
20
+ continue;
21
+ }
22
+ if (character === '"')
23
+ return { text: text.slice(start, index + 1), end: index + 1 };
24
+ index += 1;
25
+ }
26
+ return { text: text.slice(start), end: text.length };
27
+ };
28
+ /** Remove comments, preserving newlines so a diagnostic still points at a line. */
29
+ const withoutComments = (text) => {
30
+ let out = "";
31
+ let index = 0;
32
+ while (index < text.length) {
33
+ const character = text[index];
34
+ const next = text[index + 1];
35
+ if (character === '"') {
36
+ const literal = stringAt(text, index);
37
+ out += literal.text;
38
+ index = literal.end;
39
+ continue;
40
+ }
41
+ if (character === "/" && next === "/") {
42
+ while (index < text.length && text[index] !== "\n")
43
+ index += 1;
44
+ continue;
45
+ }
46
+ if (character === "/" && next === "*") {
47
+ index += 2;
48
+ while (index < text.length && !(text[index] === "*" && text[index + 1] === "/")) {
49
+ if (text[index] === "\n")
50
+ out += "\n";
51
+ index += 1;
52
+ }
53
+ index += 2;
54
+ continue;
55
+ }
56
+ out += character;
57
+ index += 1;
58
+ }
59
+ return out;
60
+ };
61
+ /** Remove a comma whose next structural character closes an object or array. */
62
+ const withoutTrailingCommas = (text) => {
63
+ let out = "";
64
+ let index = 0;
65
+ while (index < text.length) {
66
+ const character = text[index];
67
+ if (character === '"') {
68
+ const literal = stringAt(text, index);
69
+ out += literal.text;
70
+ index = literal.end;
71
+ continue;
72
+ }
73
+ if (character === ",") {
74
+ let look = index + 1;
75
+ while (look < text.length && /\s/u.test(text[look] ?? ""))
76
+ look += 1;
77
+ const next = text[look];
78
+ if (next === "}" || next === "]") {
79
+ index += 1;
80
+ continue;
81
+ }
82
+ }
83
+ out += character;
84
+ index += 1;
85
+ }
86
+ return out;
87
+ };
88
+ /**
89
+ * Strip the parts of JSONC that `JSON.parse` rejects.
90
+ *
91
+ * @param text - The file's text, as written.
92
+ * @returns Text a strict JSON parser accepts, or the original when it cannot be
93
+ * scanned (the decoder will reject it either way).
94
+ */
95
+ export const stripJsonc = (text) => withoutTrailingCommas(withoutComments(text));