@pbuilder/sdk 0.1.0
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/LICENSE +21 -0
- package/README.md +202 -0
- package/dist/bin/pbuilder-codegen.js +506 -0
- package/dist/bin/pbuilder-runner.d.ts +1 -0
- package/dist/bin/pbuilder-runner.js +47 -0
- package/dist/commons/classify-content.d.ts +40 -0
- package/dist/commons/classify-content.js +32 -0
- package/dist/commons/index.d.ts +271 -0
- package/dist/commons/index.js +276 -0
- package/dist/conformance/index.d.ts +115 -0
- package/dist/conformance/index.js +218 -0
- package/dist/conformance/run-vehicle.d.ts +19 -0
- package/dist/conformance/run-vehicle.js +104 -0
- package/dist/core/authoring-error.d.ts +116 -0
- package/dist/core/authoring-error.js +205 -0
- package/dist/core/base-handle.d.ts +17 -0
- package/dist/core/base-handle.js +4 -0
- package/dist/core/context.d.ts +85 -0
- package/dist/core/context.js +356 -0
- package/dist/core/deep-equal.d.ts +1 -0
- package/dist/core/deep-equal.js +29 -0
- package/dist/core/define-dialect.d.ts +94 -0
- package/dist/core/define-dialect.js +121 -0
- package/dist/core/dialect-error.d.ts +8 -0
- package/dist/core/dialect-error.js +26 -0
- package/dist/core/dialect-handle.d.ts +21 -0
- package/dist/core/dialect-handle.js +382 -0
- package/dist/core/directive-factory.d.ts +47 -0
- package/dist/core/directive-factory.js +154 -0
- package/dist/core/emit-rejection.d.ts +19 -0
- package/dist/core/emit-rejection.js +31 -0
- package/dist/core/engine-client.d.ts +7 -0
- package/dist/core/engine-client.js +5 -0
- package/dist/core/fs-errors.d.ts +1 -0
- package/dist/core/fs-errors.js +5 -0
- package/dist/core/handle-state.d.ts +24 -0
- package/dist/core/handle-state.js +4 -0
- package/dist/core/index.d.ts +10 -0
- package/dist/core/index.js +6 -0
- package/dist/core/jsx-name-validator.d.ts +19 -0
- package/dist/core/jsx-name-validator.js +104 -0
- package/dist/core/reject-tail.d.ts +23 -0
- package/dist/core/reject-tail.js +63 -0
- package/dist/core/schema/input-rejection.d.ts +4 -0
- package/dist/core/schema/input-rejection.js +32 -0
- package/dist/core/schema/schema-digest.d.ts +1 -0
- package/dist/core/schema/schema-digest.js +7 -0
- package/dist/core/schema/schema-discovery.d.ts +13 -0
- package/dist/core/schema/schema-discovery.js +51 -0
- package/dist/core/schema/schema-locate.d.ts +10 -0
- package/dist/core/schema/schema-locate.js +192 -0
- package/dist/core/schema/schema-model.d.ts +18 -0
- package/dist/core/schema/schema-model.js +15 -0
- package/dist/core/schema/schema-parse.d.ts +20 -0
- package/dist/core/schema/schema-parse.js +80 -0
- package/dist/core/schema/schema-sufficiency.d.ts +17 -0
- package/dist/core/schema/schema-sufficiency.js +54 -0
- package/dist/core/schema/schema-validate.d.ts +14 -0
- package/dist/core/schema/schema-validate.js +64 -0
- package/dist/core/session.d.ts +13 -0
- package/dist/core/session.js +72 -0
- package/dist/core/wire.d.ts +87 -0
- package/dist/core/wire.js +49 -0
- package/dist/dialects/react/ast.d.ts +25 -0
- package/dist/dialects/react/ast.js +80 -0
- package/dist/dialects/react/index.d.ts +39 -0
- package/dist/dialects/react/index.js +71 -0
- package/dist/dialects/react/ops.d.ts +56 -0
- package/dist/dialects/react/ops.js +186 -0
- package/dist/dialects/typescript/ast.d.ts +42 -0
- package/dist/dialects/typescript/ast.js +93 -0
- package/dist/dialects/typescript/index.d.ts +32 -0
- package/dist/dialects/typescript/index.js +40 -0
- package/dist/dialects/typescript/ops.d.ts +123 -0
- package/dist/dialects/typescript/ops.js +365 -0
- package/dist/dry-run/index.d.ts +2 -0
- package/dist/dry-run/index.js +1 -0
- package/dist/dry-run/plan.d.ts +69 -0
- package/dist/dry-run/plan.js +44 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -0
- package/dist/runner-manifest.json +104 -0
- package/dist/scaffold/classify-transport.d.ts +57 -0
- package/dist/scaffold/classify-transport.js +123 -0
- package/dist/scaffold/containment.d.ts +54 -0
- package/dist/scaffold/containment.js +242 -0
- package/dist/scaffold/expander.d.ts +30 -0
- package/dist/scaffold/expander.js +161 -0
- package/dist/scaffold/filename-pipeline.d.ts +39 -0
- package/dist/scaffold/filename-pipeline.js +125 -0
- package/dist/scaffold/index.d.ts +45 -0
- package/dist/scaffold/index.js +99 -0
- package/dist/scaffold/walk.d.ts +25 -0
- package/dist/scaffold/walk.js +124 -0
- package/dist/testing/contract-fake.d.ts +17 -0
- package/dist/testing/contract-fake.js +221 -0
- package/dist/testing/index.d.ts +84 -0
- package/dist/testing/index.js +82 -0
- package/dist/testing/rejection-messages.d.ts +7 -0
- package/dist/testing/rejection-messages.js +12 -0
- package/dist/transport/bootstrap-bridge.d.ts +33 -0
- package/dist/transport/bootstrap-bridge.js +65 -0
- package/dist/transport/error-text.d.ts +8 -0
- package/dist/transport/error-text.js +44 -0
- package/dist/transport/exit-codes.d.ts +2 -0
- package/dist/transport/exit-codes.js +35 -0
- package/dist/transport/factory-pointer.d.ts +32 -0
- package/dist/transport/factory-pointer.js +63 -0
- package/dist/transport/frame-reader.d.ts +10 -0
- package/dist/transport/frame-reader.js +81 -0
- package/dist/transport/framing.d.ts +20 -0
- package/dist/transport/framing.js +98 -0
- package/dist/transport/runner.d.ts +25 -0
- package/dist/transport/runner.js +308 -0
- package/dist/transport/single-instance-probe.d.ts +23 -0
- package/dist/transport/single-instance-probe.js +119 -0
- package/dist/transport/stdio-engine-client.d.ts +27 -0
- package/dist/transport/stdio-engine-client.js +243 -0
- package/dist/transport/wire-protocol.d.ts +33 -0
- package/dist/transport/wire-protocol.js +22 -0
- package/package.json +93 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// ADR-0001 / ADR-0013: SDK↔engine wire contract (adopts engine ADR-0028 directive shapes).
|
|
2
|
+
// The SDK emits these shapes over JSON; the engine deserialises them. Types are opaque to
|
|
3
|
+
// the template DSL — SDK treats template/pathTemplate as uninterpreted strings.
|
|
4
|
+
// ADR-0019: 4 MiB cap on Buffer.byteLength(JSON.stringify(batch), 'utf8') — the fake
|
|
5
|
+
// (engine stand-in) enforces this at emit, never the SDK (ADR-0018). Provenance: an
|
|
6
|
+
// SDK-chosen placeholder, not engine-confirmed; cheap to change until the Stage 6
|
|
7
|
+
// semver freeze.
|
|
8
|
+
export const BATCH_CAP_BYTES = 4 * 1024 * 1024;
|
|
9
|
+
// REQ-WPS-04 / fit-32 (cap-single-source, stdio-engine-client change): the UTF-8 serialized
|
|
10
|
+
// byte length of a full Batch envelope — the one measurer both `serializedBatchSize` (below)
|
|
11
|
+
// and `exceedsBatchCap`'s outbound leg consume, so the envelope shape can never drift.
|
|
12
|
+
export function serializedBatchBytes(batch) {
|
|
13
|
+
return Buffer.byteLength(JSON.stringify(batch), "utf8");
|
|
14
|
+
}
|
|
15
|
+
// The one shared measurer of what `instructions` serialize to inside the wire envelope —
|
|
16
|
+
// the SAME shape `Session.flush` emits and the fake's `emit` cap check measures
|
|
17
|
+
// (ADR-0018/0019). The expander's chunk heuristic and the batch-cap tests both consume
|
|
18
|
+
// this so the envelope shape can never drift between them.
|
|
19
|
+
export function serializedBatchSize(instructions) {
|
|
20
|
+
const batch = { protocolVersion: 1, force: false, instructions: [...instructions] };
|
|
21
|
+
return serializedBatchBytes(batch);
|
|
22
|
+
}
|
|
23
|
+
export function exceedsBatchCap(subject) {
|
|
24
|
+
const bytes = typeof subject === "number" ? subject : serializedBatchBytes(subject);
|
|
25
|
+
return bytes > BATCH_CAP_BYTES;
|
|
26
|
+
}
|
|
27
|
+
// REQ-WPS-04.1 (spec V4, judgment-day R2): the outbound cap is enforced on the ENCODED
|
|
28
|
+
// ir.emit FRAME BODY — `{type,id,method,params:{batch}}` — but the enforcement must be
|
|
29
|
+
// DETERMINISTIC (independent of the request id's length, which varies with the call
|
|
30
|
+
// ordinal) and IDENTICAL between `StdioEngineClient` and `ContractFake` (FEH-01 parity).
|
|
31
|
+
// So the budget reserves a FIXED allowance: the envelope's serialized overhead with the
|
|
32
|
+
// LONGEST id the client can ever mint. Request ids are `s${n}` with `n` a monotonically
|
|
33
|
+
// incremented non-negative integer, so `s${Number.MAX_SAFE_INTEGER}` (17 chars) bounds the
|
|
34
|
+
// id and the allowance bounds every real envelope's overhead — an accepted batch's actual
|
|
35
|
+
// encoded frame body can NEVER exceed BATCH_CAP_BYTES. Derived by measuring the envelope
|
|
36
|
+
// shape itself (the `0` placeholder stands where the batch JSON goes; its own 1 serialized
|
|
37
|
+
// byte is subtracted back out) — never a hand-waved literal; the derivation is asserted
|
|
38
|
+
// against the client's real written bytes in test.
|
|
39
|
+
export const EMIT_FRAME_ENVELOPE_ALLOWANCE_BYTES = Buffer.byteLength(JSON.stringify({ type: "request", id: `s${Number.MAX_SAFE_INTEGER}`, method: "ir.emit", params: { batch: 0 } }), "utf8") - Buffer.byteLength(JSON.stringify(0), "utf8");
|
|
40
|
+
// The author-visible outbound batch budget: the largest serialized Batch that is
|
|
41
|
+
// GUARANTEED to fit an ir.emit frame body within BATCH_CAP_BYTES for any request id.
|
|
42
|
+
export const EMIT_BATCH_BUDGET_BYTES = BATCH_CAP_BYTES - EMIT_FRAME_ENVELOPE_ALLOWANCE_BYTES;
|
|
43
|
+
// The ONE outbound-leg measurer (fit-32 cap-single-source): both `ContractFake.emit` (the
|
|
44
|
+
// engine stand-in) and `StdioEngineClient.emit` (the real transport) route through this,
|
|
45
|
+
// so the two can never diverge on an accept/reject verdict for the same batch. `>` via
|
|
46
|
+
// `exceedsBatchCap`, never a re-derived comparison: exactly-at-budget is WITHIN the budget.
|
|
47
|
+
export function exceedsEmitBatchBudget(batch) {
|
|
48
|
+
return exceedsBatchCap(serializedBatchBytes(batch) + EMIT_FRAME_ENVELOPE_ALLOWANCE_BYTES);
|
|
49
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type SourceFile } from "ts-morph";
|
|
2
|
+
/**
|
|
3
|
+
* Parses TSX source into a live ts-morph `SourceFile` — the React dialect's `Ast` (design
|
|
4
|
+
* §4.4). Constructs a FRESH `Project` per call (never a module-level singleton) whose
|
|
5
|
+
* `manipulationSettings.newLineKind` is derived from THIS source's own content
|
|
6
|
+
* (`detectNewLineKind`). Indentation and quote style are frozen constants.
|
|
7
|
+
*
|
|
8
|
+
* Failure posture (REQ-RXD-03.5 / REQ-DG-05.2): ts-morph's parser is fault-tolerant — it
|
|
9
|
+
* records diagnostics rather than throwing natively. This function surfaces a genuine parse
|
|
10
|
+
* failure by throwing whenever the freshly-parsed file carries at least one SYNTACTIC
|
|
11
|
+
* diagnostic. `const x = <string>y;` is the canonical proof: a legal angle-bracket cast under
|
|
12
|
+
* `.ts` semantics, but an unclosed JSX element under `ScriptKind.Tsx` (2 syntactic
|
|
13
|
+
* diagnostics, spike-confirmed) — the SAME source parses cleanly through the TypeScript
|
|
14
|
+
* dialect's `parse`, and that divergence is what proves `ScriptKind.Tsx` is actually engaged,
|
|
15
|
+
* not silently defaulted. The caller (`src/core/dialect-handle.ts`) wraps any throw from this
|
|
16
|
+
* function with the frozen contained-error prefix; this function's own thrown message is
|
|
17
|
+
* never surfaced directly to the author.
|
|
18
|
+
*/
|
|
19
|
+
export declare function parse(source: string): SourceFile;
|
|
20
|
+
/**
|
|
21
|
+
* Prints the live AST back to a string — the ONLY serialization point for a React handle's
|
|
22
|
+
* flush. Re-prepends a BOM if the original parse observed one (see `hadBom` above) — ts-morph's
|
|
23
|
+
* own `getFullText()` does not carry it.
|
|
24
|
+
*/
|
|
25
|
+
export declare function print(ast: SourceFile): string;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// S-000: ts-morph parse/print pair for the React dialect (REQ-RXD-03, design §4.4, ADR-01).
|
|
2
|
+
// DUPLICATES (does not import) typescript/ast.ts's four fidelity primitives — BOM
|
|
3
|
+
// re-prepend, content-derived newline detection, a frozen per-parse ManipulationSettings,
|
|
4
|
+
// and the syntactic-diagnostic throw — so `typescript/ast.ts` stays untouched and ts-morph
|
|
5
|
+
// stays leaf-isolated to one importer per dialect (fit-38 guards this repo-wide). A fresh
|
|
6
|
+
// `Project` per parse, never a module-level singleton, so the newLineKind setting can vary
|
|
7
|
+
// per source.
|
|
8
|
+
import { Project, NewLineKind, QuoteKind, IndentationText } from "ts-morph";
|
|
9
|
+
// In-memory-only path fed to ts-morph's virtual file system — never a real disk path. The
|
|
10
|
+
// `.tsx` extension is what engages `ScriptKind.Tsx` (ts-morph infers script kind from the
|
|
11
|
+
// extension, verified empirically against ts-morph@28.0.0 — no explicit scriptKind option
|
|
12
|
+
// needed, mirroring typescript/ast.ts's "the extension drives it" shape).
|
|
13
|
+
const VIRTUAL_PATH = "dialect-source.tsx";
|
|
14
|
+
const BOM = "";
|
|
15
|
+
// ts-morph@28's `getFullText()` does not round-trip a leading UTF-8 BOM (same finding as
|
|
16
|
+
// typescript/ast.ts, same pinned ts-morph version) — a private per-SourceFile flag remembers
|
|
17
|
+
// whether the ORIGINAL source started with a BOM, and `print` re-prepends it. Invisible to
|
|
18
|
+
// the frozen `Ast = SourceFile` type; implementation-internal to this module only.
|
|
19
|
+
const hadBom = new WeakMap();
|
|
20
|
+
/**
|
|
21
|
+
* Detects the dominant newline convention IN the source content itself — never the host OS.
|
|
22
|
+
* Identical algorithm to typescript/ast.ts's `detectNewLineKind` (duplicated per ADR-01, not
|
|
23
|
+
* exported here — the React dialect's frozen signatures are `parse`/`print` only).
|
|
24
|
+
*/
|
|
25
|
+
function detectNewLineKind(source) {
|
|
26
|
+
const crlf = countOccurrences(source, "\r\n");
|
|
27
|
+
const totalLf = countOccurrences(source, "\n");
|
|
28
|
+
const bareLf = totalLf - crlf;
|
|
29
|
+
return crlf > bareLf ? NewLineKind.CarriageReturnLineFeed : NewLineKind.LineFeed;
|
|
30
|
+
}
|
|
31
|
+
function countOccurrences(source, needle) {
|
|
32
|
+
return source.split(needle).length - 1;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Parses TSX source into a live ts-morph `SourceFile` — the React dialect's `Ast` (design
|
|
36
|
+
* §4.4). Constructs a FRESH `Project` per call (never a module-level singleton) whose
|
|
37
|
+
* `manipulationSettings.newLineKind` is derived from THIS source's own content
|
|
38
|
+
* (`detectNewLineKind`). Indentation and quote style are frozen constants.
|
|
39
|
+
*
|
|
40
|
+
* Failure posture (REQ-RXD-03.5 / REQ-DG-05.2): ts-morph's parser is fault-tolerant — it
|
|
41
|
+
* records diagnostics rather than throwing natively. This function surfaces a genuine parse
|
|
42
|
+
* failure by throwing whenever the freshly-parsed file carries at least one SYNTACTIC
|
|
43
|
+
* diagnostic. `const x = <string>y;` is the canonical proof: a legal angle-bracket cast under
|
|
44
|
+
* `.ts` semantics, but an unclosed JSX element under `ScriptKind.Tsx` (2 syntactic
|
|
45
|
+
* diagnostics, spike-confirmed) — the SAME source parses cleanly through the TypeScript
|
|
46
|
+
* dialect's `parse`, and that divergence is what proves `ScriptKind.Tsx` is actually engaged,
|
|
47
|
+
* not silently defaulted. The caller (`src/core/dialect-handle.ts`) wraps any throw from this
|
|
48
|
+
* function with the frozen contained-error prefix; this function's own thrown message is
|
|
49
|
+
* never surfaced directly to the author.
|
|
50
|
+
*/
|
|
51
|
+
export function parse(source) {
|
|
52
|
+
const startsWithBom = source.startsWith(BOM);
|
|
53
|
+
const body = startsWithBom ? source.slice(BOM.length) : source;
|
|
54
|
+
const project = new Project({
|
|
55
|
+
useInMemoryFileSystem: true,
|
|
56
|
+
manipulationSettings: {
|
|
57
|
+
indentationText: IndentationText.TwoSpaces,
|
|
58
|
+
quoteKind: QuoteKind.Double,
|
|
59
|
+
newLineKind: detectNewLineKind(body),
|
|
60
|
+
usePrefixAndSuffixTextForRename: false,
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
const sourceFile = project.createSourceFile(VIRTUAL_PATH, body);
|
|
64
|
+
if (startsWithBom)
|
|
65
|
+
hadBom.set(sourceFile, true);
|
|
66
|
+
const syntacticErrors = project.getProgram().getSyntacticDiagnostics(sourceFile);
|
|
67
|
+
if (syntacticErrors.length > 0) {
|
|
68
|
+
throw new Error("syntactically invalid TSX source");
|
|
69
|
+
}
|
|
70
|
+
return sourceFile;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Prints the live AST back to a string — the ONLY serialization point for a React handle's
|
|
74
|
+
* flush. Re-prepends a BOM if the original parse observed one (see `hadBom` above) — ts-morph's
|
|
75
|
+
* own `getFullText()` does not carry it.
|
|
76
|
+
*/
|
|
77
|
+
export function print(ast) {
|
|
78
|
+
const text = ast.getFullText();
|
|
79
|
+
return hadBom.get(ast) === true ? BOM + text : text;
|
|
80
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { SourceFile } from "ts-morph";
|
|
2
|
+
import { type Handle } from "../../core/define-dialect.ts";
|
|
3
|
+
type ReactOps = {
|
|
4
|
+
setJsxProp: (ast: SourceFile, elementName: string, propName: string, value?: string) => void;
|
|
5
|
+
addImport: (ast: SourceFile, name: string, from: string) => void;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Opens a `.tsx` file for React-dialect-aware editing — the dialect's entry verb into a run
|
|
9
|
+
* (REQ-DG-01.2). `path` MUST end in `.tsx`: the gate below runs SYNCHRONOUSLY, before any op
|
|
10
|
+
* is chained and before any run flush, so a rejected path throws on the bare `find()` call
|
|
11
|
+
* itself. `.ts` files are TypeScript, not this dialect — use `@pbuilder/sdk/typescript`.
|
|
12
|
+
* `.jsx` is not supported in v1: the extension must stay explicit so a future `.jsx` dialect
|
|
13
|
+
* addition never has to disambiguate an assumed `.tsx` default (tracked as a React op-catalog
|
|
14
|
+
* follow-up). Every other extension, dotfile basename, trailing-dot basename, and
|
|
15
|
+
* extensionless path is rejected the same way — no normalization, always an explicit `.tsx`.
|
|
16
|
+
* Every gate rejection throws via `dialectError`, so its message carries the standard
|
|
17
|
+
* `dialect operation failed: ` prefix.
|
|
18
|
+
*
|
|
19
|
+
* Trust boundary: a value handed to a structured mutation (e.g. `setJsxProp`'s `value`
|
|
20
|
+
* argument) is emitted verbatim into the output and becomes executable code — the SDK
|
|
21
|
+
* performs no validation, escaping, or sanitisation on it; the author is solely responsible
|
|
22
|
+
* for any untrusted input reaching that channel.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* import * as react from "@pbuilder/sdk/react";
|
|
26
|
+
*
|
|
27
|
+
* // src/Button.tsx before: const el = <Button />;
|
|
28
|
+
* export const run = async () => {
|
|
29
|
+
* await react
|
|
30
|
+
* .find("src/Button.tsx")
|
|
31
|
+
* .addImport("handleClick", "./handlers")
|
|
32
|
+
* .setJsxProp("Button", "onClick", "{handleClick}");
|
|
33
|
+
* };
|
|
34
|
+
* // -> import { handleClick } from "./handlers";
|
|
35
|
+
* // ->
|
|
36
|
+
* // -> const el = <Button onClick={handleClick} />;
|
|
37
|
+
*/
|
|
38
|
+
export declare function find(path: string): Handle<"found", SourceFile, ReactOps>;
|
|
39
|
+
export {};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// S-000: the React dialect module — `@pbuilder/sdk/react` (REQ-RXD-01, walking skeleton).
|
|
2
|
+
// Composes the sanctioned kit surface ONLY (`defineDialect`/`defineOpPack`/`withOps` from
|
|
3
|
+
// ../../core/define-dialect.ts) — mirrors src/dialects/typescript/index.ts's shape exactly,
|
|
4
|
+
// no port-internal machinery imported anywhere in this tree (REQ-DG-04.1, fit-08/fit-10).
|
|
5
|
+
// S-002 closes the op-pack at its final, exact two-op shape: `setJsxProp` (S-001) +
|
|
6
|
+
// `addImport` (S-002) — no third op ships in v1 (REQ-RXD-01.1).
|
|
7
|
+
import { basename } from "node:path";
|
|
8
|
+
import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.js";
|
|
9
|
+
import { dialectError } from "../../core/dialect-error.js";
|
|
10
|
+
import { parse, print } from "./ast.js";
|
|
11
|
+
import { addImport, setJsxProp } from "./ops.js";
|
|
12
|
+
const opsPack = defineOpPack({ setJsxProp, addImport });
|
|
13
|
+
const baseDialect = defineDialect({
|
|
14
|
+
extensions: [".tsx"],
|
|
15
|
+
ast: { parse, print },
|
|
16
|
+
ops: {},
|
|
17
|
+
});
|
|
18
|
+
const reactDialect = withOps(baseDialect, opsPack);
|
|
19
|
+
/**
|
|
20
|
+
* Opens a `.tsx` file for React-dialect-aware editing — the dialect's entry verb into a run
|
|
21
|
+
* (REQ-DG-01.2). `path` MUST end in `.tsx`: the gate below runs SYNCHRONOUSLY, before any op
|
|
22
|
+
* is chained and before any run flush, so a rejected path throws on the bare `find()` call
|
|
23
|
+
* itself. `.ts` files are TypeScript, not this dialect — use `@pbuilder/sdk/typescript`.
|
|
24
|
+
* `.jsx` is not supported in v1: the extension must stay explicit so a future `.jsx` dialect
|
|
25
|
+
* addition never has to disambiguate an assumed `.tsx` default (tracked as a React op-catalog
|
|
26
|
+
* follow-up). Every other extension, dotfile basename, trailing-dot basename, and
|
|
27
|
+
* extensionless path is rejected the same way — no normalization, always an explicit `.tsx`.
|
|
28
|
+
* Every gate rejection throws via `dialectError`, so its message carries the standard
|
|
29
|
+
* `dialect operation failed: ` prefix.
|
|
30
|
+
*
|
|
31
|
+
* Trust boundary: a value handed to a structured mutation (e.g. `setJsxProp`'s `value`
|
|
32
|
+
* argument) is emitted verbatim into the output and becomes executable code — the SDK
|
|
33
|
+
* performs no validation, escaping, or sanitisation on it; the author is solely responsible
|
|
34
|
+
* for any untrusted input reaching that channel.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* import * as react from "@pbuilder/sdk/react";
|
|
38
|
+
*
|
|
39
|
+
* // src/Button.tsx before: const el = <Button />;
|
|
40
|
+
* export const run = async () => {
|
|
41
|
+
* await react
|
|
42
|
+
* .find("src/Button.tsx")
|
|
43
|
+
* .addImport("handleClick", "./handlers")
|
|
44
|
+
* .setJsxProp("Button", "onClick", "{handleClick}");
|
|
45
|
+
* };
|
|
46
|
+
* // -> import { handleClick } from "./handlers";
|
|
47
|
+
* // ->
|
|
48
|
+
* // -> const el = <Button onClick={handleClick} />;
|
|
49
|
+
*/
|
|
50
|
+
export function find(path) {
|
|
51
|
+
const base = basename(path);
|
|
52
|
+
// A non-empty STEM before `.tsx` is required — `base.endsWith(".tsx")` alone is true for
|
|
53
|
+
// `base === ".tsx"` itself (and for a degenerate `..tsx`, whose stem is a lone dot), which
|
|
54
|
+
// would pass a basename with no real name before the extension. That is the SAME "dotfile
|
|
55
|
+
// with no usable name" shape as `.babelrc` (suffix `babelrc`, not `.tsx`) — by the suffix
|
|
56
|
+
// rule REQ-RXD-02 already applies to dotfiles, `.tsx`'s suffix is `tsx`, not `.tsx`.
|
|
57
|
+
const stem = base.substring(0, base.length - ".tsx".length);
|
|
58
|
+
if (base.endsWith(".tsx") && stem.length > 0 && !stem.endsWith(".")) {
|
|
59
|
+
return reactDialect.find(path);
|
|
60
|
+
}
|
|
61
|
+
if (!base.includes(".")) {
|
|
62
|
+
throw dialectError("find(path) — the React dialect requires an explicit .tsx extension; received a path with no extension. Append .tsx to the path.");
|
|
63
|
+
}
|
|
64
|
+
if (base.endsWith(".ts")) {
|
|
65
|
+
throw dialectError("find(path) — .ts is not a React file; use @pbuilder/sdk/typescript for TypeScript sources.");
|
|
66
|
+
}
|
|
67
|
+
if (base.endsWith(".jsx")) {
|
|
68
|
+
throw dialectError("find(path) — .jsx is not supported in v1; tracked as a follow-up in the React dialect's op catalog.");
|
|
69
|
+
}
|
|
70
|
+
throw dialectError("find(path) — .tsx is the only extension the React dialect supports.");
|
|
71
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type SourceFile } from "ts-morph";
|
|
2
|
+
/**
|
|
3
|
+
* Sets (inserts or updates) a JSX attribute on the ONE element whose tag-name text equals
|
|
4
|
+
* `elementName` (REQ-RXD-04). Zero matches or more than one match both reject — never a
|
|
5
|
+
* silent first-match. `value`'s three forms (REQ-RXD-11): a quoted string (`'"hi"'`), an
|
|
6
|
+
* expression container (`'{count}'`), or omitted (boolean shorthand, no `=`). An insert lands
|
|
7
|
+
* immediately after the element's last existing attribute — including after a trailing
|
|
8
|
+
* `{...spread}`, which is deliberate: the explicit prop wins at React runtime (REQ-RXD-10). An
|
|
9
|
+
* update replaces the initializer IN PLACE, preserving attribute position.
|
|
10
|
+
*
|
|
11
|
+
* Trust boundary (REQ-RXD-12): `value` is emitted VERBATIM and becomes executable code — the
|
|
12
|
+
* SDK performs no validation, escaping, or sanitisation on it; the author is solely
|
|
13
|
+
* responsible for any untrusted input reaching this channel. `elementName`/`propName` ARE
|
|
14
|
+
* validated and are not a trusted-code channel.
|
|
15
|
+
*/
|
|
16
|
+
export declare const setJsxProp: (ast: SourceFile, elementName: string, propName: string, value?: string | undefined) => void;
|
|
17
|
+
/**
|
|
18
|
+
* Adds `import { name } from "from";`, or merges `name` into an EXISTING NAMED-import clause
|
|
19
|
+
* from the SAME module `from` if one already exists (REQ-RXD-05, V8 unified algorithm):
|
|
20
|
+
*
|
|
21
|
+
* 1. Already-bound (idempotency, SAME module only): if an EXISTING declaration for `from` has
|
|
22
|
+
* a VALUE-BOUND specifier whose local name equals `name`, AND that specifier is a default
|
|
23
|
+
* specifier, a namespace specifier, or an UNALIASED named specifier — this is a no-op. An
|
|
24
|
+
* aliased named specifier's local name identifies a DIFFERENT export, so it does NOT satisfy
|
|
25
|
+
* idempotency (Defect 3); neither does a type-only specifier at either granularity (Defect
|
|
26
|
+
* 1), because it does not satisfy the value-binding promise.
|
|
27
|
+
* 2. Collision (file-wide, V7; widened V8): otherwise, if `name` is CLAIMED anywhere in the
|
|
28
|
+
* file — EITHER the local name of ANY import specifier, in ANY module, value-bound or
|
|
29
|
+
* type-only alike (V7 half), OR a top-level VALUE-NAMESPACE declaration (`function`/`const`/
|
|
30
|
+
* `let`/`var`/`class`/`enum`/`namespace`) sharing `name` (V8 half, `isValueNamespaceClaimed`
|
|
31
|
+
* above, adopting ADR-0039's `assertNoCollision` predicate verbatim) — REJECT via
|
|
32
|
+
* `dialectError`. TypeScript treats a same-name type-only/value collision as the identical
|
|
33
|
+
* `TS2300: Duplicate identifier` error as two value bindings, so a type-only specifier claims
|
|
34
|
+
* its name exactly as a value specifier does (Defect 1); the claiming declaration may be FROM
|
|
35
|
+
* `from` (a same-module alias or type-only collision, Defect 1/3), from a DIFFERENT module
|
|
36
|
+
* entirely (a cross-module collision, Defect 2), or a same-file value-namespace declaration
|
|
37
|
+
* (V8) — all reject. `type`/`interface` declarations are exempt (legal TS coexistence).
|
|
38
|
+
* 3. Merge: otherwise, if an EXISTING declaration for `from` has a non-type-only named-import
|
|
39
|
+
* clause, add a NEW, UNALIASED named specifier to it. (Reaching this step guarantees `name`
|
|
40
|
+
* is claimed nowhere in the file, so the merge is always safe.)
|
|
41
|
+
* 4. Create: otherwise (no declaration for `from`; every one is type-only, default-only, or
|
|
42
|
+
* namespace-only), INSERT a FRESH, SEPARATE `import { name } from "from";` — a type-only,
|
|
43
|
+
* default-only, or namespace-only declaration's clause structure is NEVER mutated to graft
|
|
44
|
+
* a named binding onto it. (Reaching this step also guarantees `name` is claimed nowhere in
|
|
45
|
+
* the file, so the fresh declaration never collides.)
|
|
46
|
+
*
|
|
47
|
+
* NAMED-ONLY, pinned as contract: always the `import { name } from "from"` form — v1 never
|
|
48
|
+
* synthesizes default or namespace imports (REQ-RXD-05.4).
|
|
49
|
+
*
|
|
50
|
+
* `name` is validated (`assertValidImportBinding`, REQ-RXD-06) — a plain JS identifier, not a
|
|
51
|
+
* reserved word, checked against the reserved-name denylist — BEFORE any AST mutation. `from`
|
|
52
|
+
* has NO allow-list: legitimate module specifiers contain `@ / . :` and more; its safety rests
|
|
53
|
+
* on ts-morph escaping `moduleSpecifier` as a single string literal (REQ-RXD-06.4 pins this
|
|
54
|
+
* assumption as a regression test, never assumes it silently).
|
|
55
|
+
*/
|
|
56
|
+
export declare const addImport: (ast: SourceFile, name: string, from: string) => void;
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// S-001: `setJsxProp` (REQ-RXD-04 targeting/upsert, REQ-RXD-10 placement, REQ-RXD-11 value
|
|
2
|
+
// forms, REQ-RXD-12 trust boundary, design §4.4/ADR-02/ADR-03). Wrapped in `validatedOp` —
|
|
3
|
+
// `elementName`/`propName` validate BEFORE `body` runs; `value` is NOT validated (trust
|
|
4
|
+
// contract, REQ-RXD-11/12 verbatim: it is emitted AS-IS, malformed or not, and becomes
|
|
5
|
+
// executable code the author is solely responsible for).
|
|
6
|
+
//
|
|
7
|
+
// S-002: `addImport` (REQ-RXD-05 merge/create/idempotent/named-only, REQ-RXD-06 `name`
|
|
8
|
+
// validation + `from`'s pinned-escaping trust, design §4.4/ADR-05). Written FRESH — NOT
|
|
9
|
+
// copied from the TypeScript dialect's `addImport` (src/dialects/typescript/ops.ts), which
|
|
10
|
+
// validates nothing; that laxity is a confirmed vulnerability class this op does not repeat.
|
|
11
|
+
import { SyntaxKind, } from "ts-morph";
|
|
12
|
+
import { dialectError } from "../../core/dialect-error.js";
|
|
13
|
+
import { assertValidAttributeName, assertValidElementName, assertValidImportBinding, validatedOp, } from "../../core/jsx-name-validator.js";
|
|
14
|
+
import { claimedNameTail, multiMatchTail, zeroMatchTail } from "../../core/reject-tail.js";
|
|
15
|
+
// Text-equality targeting against each element's tag-name text (design §4.4) — Set-key-safety
|
|
16
|
+
// clause: `elementName` is compared with `===`, NEVER used as an object/array index.
|
|
17
|
+
function matchingElements(ast, elementName) {
|
|
18
|
+
const openings = ast.getDescendantsOfKind(SyntaxKind.JsxOpeningElement);
|
|
19
|
+
const selfClosing = ast.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement);
|
|
20
|
+
const all = [...openings, ...selfClosing];
|
|
21
|
+
return all.filter((element) => element.getTagNameNode().getText() === elementName);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Sets (inserts or updates) a JSX attribute on the ONE element whose tag-name text equals
|
|
25
|
+
* `elementName` (REQ-RXD-04). Zero matches or more than one match both reject — never a
|
|
26
|
+
* silent first-match. `value`'s three forms (REQ-RXD-11): a quoted string (`'"hi"'`), an
|
|
27
|
+
* expression container (`'{count}'`), or omitted (boolean shorthand, no `=`). An insert lands
|
|
28
|
+
* immediately after the element's last existing attribute — including after a trailing
|
|
29
|
+
* `{...spread}`, which is deliberate: the explicit prop wins at React runtime (REQ-RXD-10). An
|
|
30
|
+
* update replaces the initializer IN PLACE, preserving attribute position.
|
|
31
|
+
*
|
|
32
|
+
* Trust boundary (REQ-RXD-12): `value` is emitted VERBATIM and becomes executable code — the
|
|
33
|
+
* SDK performs no validation, escaping, or sanitisation on it; the author is solely
|
|
34
|
+
* responsible for any untrusted input reaching this channel. `elementName`/`propName` ARE
|
|
35
|
+
* validated and are not a trusted-code channel.
|
|
36
|
+
*/
|
|
37
|
+
export const setJsxProp = validatedOp(([elementName, propName]) => {
|
|
38
|
+
assertValidElementName(elementName);
|
|
39
|
+
assertValidAttributeName(propName);
|
|
40
|
+
}, (ast, elementName, propName, value) => {
|
|
41
|
+
const matches = matchingElements(ast, elementName);
|
|
42
|
+
if (matches.length === 0) {
|
|
43
|
+
throw dialectError(zeroMatchTail(elementName));
|
|
44
|
+
}
|
|
45
|
+
if (matches.length > 1) {
|
|
46
|
+
throw dialectError(multiMatchTail(elementName, matches.length));
|
|
47
|
+
}
|
|
48
|
+
const element = matches[0];
|
|
49
|
+
const existingAttr = element.getAttribute(propName);
|
|
50
|
+
if (existingAttr !== undefined && existingAttr.getKind() === SyntaxKind.JsxAttribute) {
|
|
51
|
+
const attr = existingAttr.asKindOrThrow(SyntaxKind.JsxAttribute);
|
|
52
|
+
if (value === undefined) {
|
|
53
|
+
attr.removeInitializer();
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
attr.setInitializer(value);
|
|
57
|
+
}
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
element.addAttribute({ name: propName, initializer: value });
|
|
61
|
+
});
|
|
62
|
+
// Collects every local name a single declaration binds, across all three clause shapes at once
|
|
63
|
+
// (a declaration can carry a default AND a named clause simultaneously, e.g. `import React, {
|
|
64
|
+
// useState } from "react"`). Set-key-safety clause: names are compared via `.includes()`/`===`
|
|
65
|
+
// on plain arrays, NEVER used as an object/Map key.
|
|
66
|
+
function boundNamesIn(decl) {
|
|
67
|
+
const declTypeOnly = decl.isTypeOnly();
|
|
68
|
+
const names = [];
|
|
69
|
+
const defaultImport = decl.getDefaultImport();
|
|
70
|
+
if (defaultImport !== undefined) {
|
|
71
|
+
names.push({ localName: defaultImport.getText(), kind: "default", aliased: false, valueBound: !declTypeOnly });
|
|
72
|
+
}
|
|
73
|
+
const namespaceImport = decl.getNamespaceImport();
|
|
74
|
+
if (namespaceImport !== undefined) {
|
|
75
|
+
names.push({
|
|
76
|
+
localName: namespaceImport.getText(),
|
|
77
|
+
kind: "namespace",
|
|
78
|
+
aliased: false,
|
|
79
|
+
valueBound: !declTypeOnly,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
for (const specifier of decl.getNamedImports()) {
|
|
83
|
+
const alias = specifier.getAliasNode();
|
|
84
|
+
names.push({
|
|
85
|
+
localName: alias !== undefined ? alias.getText() : specifier.getName(),
|
|
86
|
+
kind: "named",
|
|
87
|
+
aliased: alias !== undefined,
|
|
88
|
+
valueBound: !declTypeOnly && !specifier.isTypeOnly(),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return names;
|
|
92
|
+
}
|
|
93
|
+
// Step 1's idempotency-satisfying shape (REQ-RXD-05, V7-narrowed): a value-bound default
|
|
94
|
+
// specifier, a value-bound namespace specifier, or a value-bound UNALIASED named specifier.
|
|
95
|
+
// An aliased named specifier's local name identifies a DIFFERENT export (Defect 3) and a
|
|
96
|
+
// type-only binding at either granularity does not satisfy the value-binding promise (Defect
|
|
97
|
+
// 1) — neither counts here, even though both still CLAIM the name for Step 2's purposes.
|
|
98
|
+
function satisfiesIdempotency(bound) {
|
|
99
|
+
if (!bound.valueBound)
|
|
100
|
+
return false;
|
|
101
|
+
return bound.kind !== "named" || !bound.aliased;
|
|
102
|
+
}
|
|
103
|
+
// V5 (REQ-RXD-05, step 2): a valid MERGE target is a declaration that (a) is NOT type-only and
|
|
104
|
+
// (b) has a `NamedImports` clause node — whether or not it already carries specifiers. A
|
|
105
|
+
// default-only or namespace-only declaration has no `NamedImports` node at all: TS/JS syntax
|
|
106
|
+
// forbids grafting a named clause onto a namespace import, and grafting one onto a default-only
|
|
107
|
+
// declaration would silently widen an existing statement the author did not ask this op to
|
|
108
|
+
// touch — so neither is a merge target, matching a FRESH separate declaration instead.
|
|
109
|
+
function isNonTypeOnlyNamedImportClause(decl) {
|
|
110
|
+
if (decl.isTypeOnly())
|
|
111
|
+
return false;
|
|
112
|
+
const namedBindings = decl.getImportClause()?.getNamedBindings();
|
|
113
|
+
return namedBindings !== undefined && namedBindings.getKind() === SyntaxKind.NamedImports;
|
|
114
|
+
}
|
|
115
|
+
// V8 (judgment-day Round 2, REQ-RXD-05 step 2, second half of CLAIMED): a top-level
|
|
116
|
+
// VALUE-NAMESPACE declaration under `name` collides the same way a same-name import specifier
|
|
117
|
+
// does — ADOPTED verbatim from ADR-0039's ratified `assertNoCollision` predicate
|
|
118
|
+
// (typescript/ops.ts:54-75), not reinvented. `type`/`interface` are exempt (legal TS
|
|
119
|
+
// coexistence, the same ADR-0039 carve-out).
|
|
120
|
+
function isValueNamespaceClaimed(ast, name) {
|
|
121
|
+
return (ast.getFunction(name) !== undefined ||
|
|
122
|
+
ast.getVariableDeclaration(name) !== undefined ||
|
|
123
|
+
ast.getClass(name) !== undefined ||
|
|
124
|
+
ast.getEnum(name) !== undefined ||
|
|
125
|
+
ast.getModule(name) !== undefined);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Adds `import { name } from "from";`, or merges `name` into an EXISTING NAMED-import clause
|
|
129
|
+
* from the SAME module `from` if one already exists (REQ-RXD-05, V8 unified algorithm):
|
|
130
|
+
*
|
|
131
|
+
* 1. Already-bound (idempotency, SAME module only): if an EXISTING declaration for `from` has
|
|
132
|
+
* a VALUE-BOUND specifier whose local name equals `name`, AND that specifier is a default
|
|
133
|
+
* specifier, a namespace specifier, or an UNALIASED named specifier — this is a no-op. An
|
|
134
|
+
* aliased named specifier's local name identifies a DIFFERENT export, so it does NOT satisfy
|
|
135
|
+
* idempotency (Defect 3); neither does a type-only specifier at either granularity (Defect
|
|
136
|
+
* 1), because it does not satisfy the value-binding promise.
|
|
137
|
+
* 2. Collision (file-wide, V7; widened V8): otherwise, if `name` is CLAIMED anywhere in the
|
|
138
|
+
* file — EITHER the local name of ANY import specifier, in ANY module, value-bound or
|
|
139
|
+
* type-only alike (V7 half), OR a top-level VALUE-NAMESPACE declaration (`function`/`const`/
|
|
140
|
+
* `let`/`var`/`class`/`enum`/`namespace`) sharing `name` (V8 half, `isValueNamespaceClaimed`
|
|
141
|
+
* above, adopting ADR-0039's `assertNoCollision` predicate verbatim) — REJECT via
|
|
142
|
+
* `dialectError`. TypeScript treats a same-name type-only/value collision as the identical
|
|
143
|
+
* `TS2300: Duplicate identifier` error as two value bindings, so a type-only specifier claims
|
|
144
|
+
* its name exactly as a value specifier does (Defect 1); the claiming declaration may be FROM
|
|
145
|
+
* `from` (a same-module alias or type-only collision, Defect 1/3), from a DIFFERENT module
|
|
146
|
+
* entirely (a cross-module collision, Defect 2), or a same-file value-namespace declaration
|
|
147
|
+
* (V8) — all reject. `type`/`interface` declarations are exempt (legal TS coexistence).
|
|
148
|
+
* 3. Merge: otherwise, if an EXISTING declaration for `from` has a non-type-only named-import
|
|
149
|
+
* clause, add a NEW, UNALIASED named specifier to it. (Reaching this step guarantees `name`
|
|
150
|
+
* is claimed nowhere in the file, so the merge is always safe.)
|
|
151
|
+
* 4. Create: otherwise (no declaration for `from`; every one is type-only, default-only, or
|
|
152
|
+
* namespace-only), INSERT a FRESH, SEPARATE `import { name } from "from";` — a type-only,
|
|
153
|
+
* default-only, or namespace-only declaration's clause structure is NEVER mutated to graft
|
|
154
|
+
* a named binding onto it. (Reaching this step also guarantees `name` is claimed nowhere in
|
|
155
|
+
* the file, so the fresh declaration never collides.)
|
|
156
|
+
*
|
|
157
|
+
* NAMED-ONLY, pinned as contract: always the `import { name } from "from"` form — v1 never
|
|
158
|
+
* synthesizes default or namespace imports (REQ-RXD-05.4).
|
|
159
|
+
*
|
|
160
|
+
* `name` is validated (`assertValidImportBinding`, REQ-RXD-06) — a plain JS identifier, not a
|
|
161
|
+
* reserved word, checked against the reserved-name denylist — BEFORE any AST mutation. `from`
|
|
162
|
+
* has NO allow-list: legitimate module specifiers contain `@ / . :` and more; its safety rests
|
|
163
|
+
* on ts-morph escaping `moduleSpecifier` as a single string literal (REQ-RXD-06.4 pins this
|
|
164
|
+
* assumption as a regression test, never assumes it silently).
|
|
165
|
+
*/
|
|
166
|
+
export const addImport = validatedOp(([name]) => {
|
|
167
|
+
assertValidImportBinding(name);
|
|
168
|
+
}, (ast, name, from) => {
|
|
169
|
+
const declarationsForModule = ast
|
|
170
|
+
.getImportDeclarations()
|
|
171
|
+
.filter((decl) => decl.getModuleSpecifierValue() === from);
|
|
172
|
+
const alreadyBound = declarationsForModule.some((decl) => boundNamesIn(decl).some((bound) => bound.localName === name && satisfiesIdempotency(bound)));
|
|
173
|
+
if (alreadyBound)
|
|
174
|
+
return;
|
|
175
|
+
const claimed = ast.getImportDeclarations().some((decl) => boundNamesIn(decl).some((bound) => bound.localName === name)) ||
|
|
176
|
+
isValueNamespaceClaimed(ast, name);
|
|
177
|
+
if (claimed) {
|
|
178
|
+
throw dialectError(claimedNameTail(name));
|
|
179
|
+
}
|
|
180
|
+
const mergeTarget = declarationsForModule.find(isNonTypeOnlyNamedImportClause);
|
|
181
|
+
if (mergeTarget !== undefined) {
|
|
182
|
+
mergeTarget.addNamedImport(name);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
ast.addImportDeclaration({ moduleSpecifier: from, namedImports: [name] });
|
|
186
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { NewLineKind, type SourceFile } from "ts-morph";
|
|
2
|
+
/**
|
|
3
|
+
* Detects the dominant newline convention IN the source content itself — never the host OS
|
|
4
|
+
* (REQ-TSD-02.2). `crlf` = count of `"\r\n"` pairs; `lf` = count of bare `"\n"` (every `\n`
|
|
5
|
+
* minus the ones already counted inside a `\r\n` pair). CRLF wins strictly on `crlf > lf`;
|
|
6
|
+
* a tie (including the empty/no-newline case, `0 > 0` = false) falls back to LF — the
|
|
7
|
+
* deterministic default for indeterminate content.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* detectNewLineKind("a\r\nb\r\n"); // NewLineKind.CarriageReturnLineFeed
|
|
11
|
+
* detectNewLineKind("a\nb\n"); // NewLineKind.LineFeed
|
|
12
|
+
*/
|
|
13
|
+
export declare function detectNewLineKind(source: string): NewLineKind;
|
|
14
|
+
/**
|
|
15
|
+
* Parses TypeScript source into a live ts-morph `SourceFile` — the dialect's `Ast` (design
|
|
16
|
+
* §4.4). Constructs a FRESH `Project` per call (never a module-level singleton) whose
|
|
17
|
+
* `manipulationSettings.newLineKind` is derived from THIS source's own content
|
|
18
|
+
* (`detectNewLineKind`) — the frozen determinism pin (REQ-TSD-02). Indentation and quote
|
|
19
|
+
* style are likewise frozen constants, never inferred from the source or the host.
|
|
20
|
+
*
|
|
21
|
+
* Failure posture (REQ-TSD-04.1 / REQ-DG-05.2): ts-morph's parser is deliberately
|
|
22
|
+
* FAULT-TOLERANT — it does not natively throw on malformed syntax, it records diagnostics.
|
|
23
|
+
* This function surfaces that as a genuine parse failure by throwing when the freshly-parsed
|
|
24
|
+
* file carries at least one SYNTACTIC diagnostic (a real syntax error) — a file with only
|
|
25
|
+
* semantic/type diagnostics (e.g. a type mismatch) is syntactically valid and does NOT throw.
|
|
26
|
+
* The caller (`src/core/dialect-handle.ts`) wraps any throw from this function with the
|
|
27
|
+
* frozen contained-error prefix; this function's own thrown message is never surfaced
|
|
28
|
+
* directly to the author.
|
|
29
|
+
*
|
|
30
|
+
* Row-139 (stage-5b, executor-latitude, no REQ of its own): classification below reads off
|
|
31
|
+
* `getSyntacticDiagnostics()`'s own diagnostic objects — never an assumption about a caught
|
|
32
|
+
* error's own-enumerable-properties or call-stack shape. Verified already in this shape; no
|
|
33
|
+
* heuristic-based classification exists in this function to sweep out.
|
|
34
|
+
*/
|
|
35
|
+
export declare function parse(source: string): SourceFile;
|
|
36
|
+
/**
|
|
37
|
+
* Prints the live AST back to a string — the ONLY serialization point (ADR-0006's "serialize
|
|
38
|
+
* once at flush", realised by the dialect handle's memoized lazy getter). Re-prepends a BOM
|
|
39
|
+
* if the original parse observed one (see `hadBom` above) — ts-morph's own `getFullText()`
|
|
40
|
+
* does not carry it.
|
|
41
|
+
*/
|
|
42
|
+
export declare function print(ast: SourceFile): string;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// S-002: ts-morph parse/print pair for the TypeScript dialect (REQ-TSD-02, design §4.4).
|
|
2
|
+
// FROZEN ManipulationSettings + an explicit, CONTENT-DERIVED newLineKind (never host-OS) —
|
|
3
|
+
// a fresh `Project` per parse so the setting can vary per source, never a module-level
|
|
4
|
+
// singleton. No language-service formatter is ever invoked (REQ-TSD-02.3): this module calls
|
|
5
|
+
// no `.formatText()`/language-service API anywhere.
|
|
6
|
+
import { Project, NewLineKind, QuoteKind, IndentationText } from "ts-morph";
|
|
7
|
+
// In-memory-only path fed to ts-morph's virtual file system — never a real disk path; the
|
|
8
|
+
// dialect handle (src/core/dialect-handle.ts) owns the AUTHOR-FACING path, this is purely an
|
|
9
|
+
// internal identifier ts-morph's Project API requires.
|
|
10
|
+
const VIRTUAL_PATH = "dialect-source.ts";
|
|
11
|
+
const BOM = "";
|
|
12
|
+
// ts-morph's `SourceFile#getFullText()` does NOT round-trip a leading UTF-8 BOM (verified
|
|
13
|
+
// empirically against the pinned ts-morph@28.0.0 — the design's "preserved by ts-morph
|
|
14
|
+
// independently" prose assumption does not hold for this version): a BOM survives ts-morph's
|
|
15
|
+
// OWN internal text but is stripped from every printed string. REQ-TSD-03.6 requires
|
|
16
|
+
// byte-exact BOM preservation across a round-trip, so this module owns that: a private
|
|
17
|
+
// per-SourceFile flag (WeakMap, invisible to the frozen `Ast = SourceFile` type) remembers
|
|
18
|
+
// whether the ORIGINAL source started with a BOM, and `print` re-prepends it. This is
|
|
19
|
+
// implementation-internal to this module only — it does not touch the frozen
|
|
20
|
+
// `ast.parse(source): Ast` / `ast.print(ast): string` signatures.
|
|
21
|
+
const hadBom = new WeakMap();
|
|
22
|
+
/**
|
|
23
|
+
* Detects the dominant newline convention IN the source content itself — never the host OS
|
|
24
|
+
* (REQ-TSD-02.2). `crlf` = count of `"\r\n"` pairs; `lf` = count of bare `"\n"` (every `\n`
|
|
25
|
+
* minus the ones already counted inside a `\r\n` pair). CRLF wins strictly on `crlf > lf`;
|
|
26
|
+
* a tie (including the empty/no-newline case, `0 > 0` = false) falls back to LF — the
|
|
27
|
+
* deterministic default for indeterminate content.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* detectNewLineKind("a\r\nb\r\n"); // NewLineKind.CarriageReturnLineFeed
|
|
31
|
+
* detectNewLineKind("a\nb\n"); // NewLineKind.LineFeed
|
|
32
|
+
*/
|
|
33
|
+
export function detectNewLineKind(source) {
|
|
34
|
+
const crlf = countOccurrences(source, "\r\n");
|
|
35
|
+
const totalLf = countOccurrences(source, "\n");
|
|
36
|
+
const bareLf = totalLf - crlf;
|
|
37
|
+
return crlf > bareLf ? NewLineKind.CarriageReturnLineFeed : NewLineKind.LineFeed;
|
|
38
|
+
}
|
|
39
|
+
function countOccurrences(source, needle) {
|
|
40
|
+
return source.split(needle).length - 1;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Parses TypeScript source into a live ts-morph `SourceFile` — the dialect's `Ast` (design
|
|
44
|
+
* §4.4). Constructs a FRESH `Project` per call (never a module-level singleton) whose
|
|
45
|
+
* `manipulationSettings.newLineKind` is derived from THIS source's own content
|
|
46
|
+
* (`detectNewLineKind`) — the frozen determinism pin (REQ-TSD-02). Indentation and quote
|
|
47
|
+
* style are likewise frozen constants, never inferred from the source or the host.
|
|
48
|
+
*
|
|
49
|
+
* Failure posture (REQ-TSD-04.1 / REQ-DG-05.2): ts-morph's parser is deliberately
|
|
50
|
+
* FAULT-TOLERANT — it does not natively throw on malformed syntax, it records diagnostics.
|
|
51
|
+
* This function surfaces that as a genuine parse failure by throwing when the freshly-parsed
|
|
52
|
+
* file carries at least one SYNTACTIC diagnostic (a real syntax error) — a file with only
|
|
53
|
+
* semantic/type diagnostics (e.g. a type mismatch) is syntactically valid and does NOT throw.
|
|
54
|
+
* The caller (`src/core/dialect-handle.ts`) wraps any throw from this function with the
|
|
55
|
+
* frozen contained-error prefix; this function's own thrown message is never surfaced
|
|
56
|
+
* directly to the author.
|
|
57
|
+
*
|
|
58
|
+
* Row-139 (stage-5b, executor-latitude, no REQ of its own): classification below reads off
|
|
59
|
+
* `getSyntacticDiagnostics()`'s own diagnostic objects — never an assumption about a caught
|
|
60
|
+
* error's own-enumerable-properties or call-stack shape. Verified already in this shape; no
|
|
61
|
+
* heuristic-based classification exists in this function to sweep out.
|
|
62
|
+
*/
|
|
63
|
+
export function parse(source) {
|
|
64
|
+
const startsWithBom = source.startsWith(BOM);
|
|
65
|
+
const body = startsWithBom ? source.slice(BOM.length) : source;
|
|
66
|
+
const project = new Project({
|
|
67
|
+
useInMemoryFileSystem: true,
|
|
68
|
+
manipulationSettings: {
|
|
69
|
+
indentationText: IndentationText.TwoSpaces,
|
|
70
|
+
quoteKind: QuoteKind.Double,
|
|
71
|
+
newLineKind: detectNewLineKind(body),
|
|
72
|
+
usePrefixAndSuffixTextForRename: false,
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
const sourceFile = project.createSourceFile(VIRTUAL_PATH, body);
|
|
76
|
+
if (startsWithBom)
|
|
77
|
+
hadBom.set(sourceFile, true);
|
|
78
|
+
const syntacticErrors = project.getProgram().getSyntacticDiagnostics(sourceFile);
|
|
79
|
+
if (syntacticErrors.length > 0) {
|
|
80
|
+
throw new Error("syntactically invalid TypeScript source");
|
|
81
|
+
}
|
|
82
|
+
return sourceFile;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Prints the live AST back to a string — the ONLY serialization point (ADR-0006's "serialize
|
|
86
|
+
* once at flush", realised by the dialect handle's memoized lazy getter). Re-prepends a BOM
|
|
87
|
+
* if the original parse observed one (see `hadBom` above) — ts-morph's own `getFullText()`
|
|
88
|
+
* does not carry it.
|
|
89
|
+
*/
|
|
90
|
+
export function print(ast) {
|
|
91
|
+
const text = ast.getFullText();
|
|
92
|
+
return hadBom.get(ast) === true ? BOM + text : text;
|
|
93
|
+
}
|