@pbuilder/sdk 0.7.0 → 0.10.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/README.md +26 -5
- package/dist/core/define-dialect.d.ts +6 -2
- package/dist/core/define-dialect.js +1 -0
- package/dist/core/dialect-handle.d.ts +14 -1
- package/dist/core/dialect-handle.js +47 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +1 -1
- package/dist/dialects/angular/index.d.ts +5 -0
- package/dist/dialects/angular/index.js +6 -1
- package/dist/dialects/angular/ops.d.ts +13 -0
- package/dist/dialects/angular/ops.js +53 -13
- package/dist/dialects/css/ast.d.ts +7 -0
- package/dist/dialects/css/ast.js +16 -0
- package/dist/dialects/css/index.d.ts +40 -0
- package/dist/dialects/css/index.js +38 -0
- package/dist/dialects/css/ops.d.ts +44 -0
- package/dist/dialects/css/ops.js +216 -0
- package/dist/runner-manifest.json +2 -2
- package/package.json +7 -1
package/README.md
CHANGED
|
@@ -559,9 +559,9 @@ conformance-tests a *dialect or op-pack* implementation — not the same audienc
|
|
|
559
559
|
|
|
560
560
|
When string-level mutation isn't enough — "add an import to this module", "set a prop on
|
|
561
561
|
this JSX element" — **dialects** provide structured, AST-aware operations for one file
|
|
562
|
-
type: see [authoring a dialect](./docs/authoring-a-dialect.md) for the full story.
|
|
562
|
+
type: see [authoring a dialect](./docs/authoring-a-dialect.md) for the full story. Seven
|
|
563
563
|
ship today: `@pbuilder/sdk/typescript`, `@pbuilder/sdk/react`, `@pbuilder/sdk/nestjs`,
|
|
564
|
-
`@pbuilder/sdk/angular`, `@pbuilder/sdk/json`, and `@pbuilder/sdk/
|
|
564
|
+
`@pbuilder/sdk/angular`, `@pbuilder/sdk/json`, `@pbuilder/sdk/yaml`, and `@pbuilder/sdk/css`.
|
|
565
565
|
|
|
566
566
|
A dialect's entry point is its own `find(path)`: it opens a **coalescing, awaitable
|
|
567
567
|
handle**. Every op you chain mutates the same live AST, and the handle serializes to
|
|
@@ -670,6 +670,26 @@ Extra named ops: `setComment`, `removeComment`, `setAnchor`, `removeAnchor`, `se
|
|
|
670
670
|
`addMergeKey`, `setStyle`, `setTag`, `addDocument`, `removeDocument`. `.modify(fn)` exposes
|
|
671
671
|
[yaml](https://eemeli.org/yaml/). See [the YAML dialect guide](./docs/yaml-dialect.md).
|
|
672
672
|
|
|
673
|
+
### `@pbuilder/sdk/css`
|
|
674
|
+
|
|
675
|
+
Sets and removes declarations in `.css` files, such as design tokens synced into a file that
|
|
676
|
+
also holds hand-written rules. A target names one block (`{ selector }`, `{ atRule }`, or
|
|
677
|
+
both); a missing block is created at the end of the file, and everything else keeps its bytes.
|
|
678
|
+
|
|
679
|
+
```ts
|
|
680
|
+
import * as css from "@pbuilder/sdk/css";
|
|
681
|
+
|
|
682
|
+
await css
|
|
683
|
+
.find("tokens.css")
|
|
684
|
+
.setDeclaration({ atRule: "theme" }, "--color-primary", "#1974f9")
|
|
685
|
+
.removeDeclaration({ selector: ":root" }, "--legacy-blue");
|
|
686
|
+
```
|
|
687
|
+
|
|
688
|
+
Named ops: `setDeclaration`, `removeDeclaration`, and the query `getDeclaration(target, property)`,
|
|
689
|
+
which ends the chain and resolves to `{ value, important }` (also exported as
|
|
690
|
+
`getDeclaration(root, target, property)` for use inside `.modify(fn)`). `.modify(fn)` exposes
|
|
691
|
+
[postcss](https://postcss.org/). See [the CSS dialect guide](./docs/css-dialect.md).
|
|
692
|
+
|
|
673
693
|
### `@pbuilder/sdk/nestjs`
|
|
674
694
|
|
|
675
695
|
Every `@pbuilder/sdk/typescript` op, plus ops that import a class and register it in the
|
|
@@ -690,8 +710,8 @@ exposes ts-morph. See [the NestJS dialect guide](./docs/nestjs-dialect.md).
|
|
|
690
710
|
### `@pbuilder/sdk/angular`
|
|
691
711
|
|
|
692
712
|
Every `@pbuilder/sdk/typescript` op, plus ops for standalone components, the application's root
|
|
693
|
-
providers, routes, signal inputs, outputs and state,
|
|
694
|
-
Each op adds the imports its code needs.
|
|
713
|
+
providers, routes, signal inputs, outputs and state, injected dependencies, and `@NgModule`
|
|
714
|
+
metadata. Each op adds the imports its code needs.
|
|
695
715
|
|
|
696
716
|
```ts
|
|
697
717
|
import * as angular from "@pbuilder/sdk/angular";
|
|
@@ -704,7 +724,8 @@ await angular.find("src/app/app.routes.ts").addLazyRoute({ path: "admin", loadCh
|
|
|
704
724
|
```
|
|
705
725
|
|
|
706
726
|
Extra named ops: `addComponentImport`, `addComponentProvider`, `addRootProvider`, `addRoute`,
|
|
707
|
-
`addLazyRoute`, `addInjection`, `addInput`, `addModel`, `addOutput`, `addSignal`, `addComputed
|
|
727
|
+
`addLazyRoute`, `addInjection`, `addInput`, `addModel`, `addOutput`, `addSignal`, `addComputed`,
|
|
728
|
+
`addNgModuleImport`, `addDeclaration`, `addNgModuleProvider`, `addNgModuleExport`, `addBootstrap`.
|
|
708
729
|
`.modify(fn)` exposes ts-morph. See
|
|
709
730
|
[the Angular dialect guide](./docs/angular-dialect.md).
|
|
710
731
|
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import type { ReadOps } from "./base-handle.ts";
|
|
2
|
+
export { query } from "./dialect-handle.ts";
|
|
2
3
|
export type Op<Ast = any> = (ast: Ast, ...args: never[]) => void;
|
|
4
|
+
declare const QUERY: unique symbol;
|
|
5
|
+
export type Query<Ast = any, A extends unknown[] = any[], R = unknown> = ((ast: Ast, ...args: A) => R) & {
|
|
6
|
+
readonly [QUERY]: true;
|
|
7
|
+
};
|
|
3
8
|
export type OpPack<Ast = any> = Record<string, Op<Ast>>;
|
|
4
9
|
export interface DialectDescriptor<Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> {
|
|
5
10
|
extensions: string[];
|
|
@@ -12,7 +17,7 @@ export interface DialectDescriptor<Ast = any, Ops extends OpPack<Ast> = OpPack<A
|
|
|
12
17
|
type Bound<Ast, F> = F extends (ast: Ast, ...rest: infer R) => void ? (...rest: R) => void : never;
|
|
13
18
|
type Edited<Ast, Ops extends OpPack<Ast>> = Handle<"writable", Ast, Ops>;
|
|
14
19
|
type OpMethods<Ast, Ops extends OpPack<Ast>> = {
|
|
15
|
-
[K in keyof Ops]: (...a: Parameters<Bound<Ast, Ops[K]>>) => Edited<Ast, Ops>;
|
|
20
|
+
[K in keyof Ops]: Ops[K] extends Query<any, infer A, infer R> ? (...a: A) => Promise<Awaited<R>> : (...a: Parameters<Bound<Ast, Ops[K]>>) => Edited<Ast, Ops>;
|
|
16
21
|
};
|
|
17
22
|
type DialectWriteOps<Ast, Ops extends OpPack<Ast>> = {
|
|
18
23
|
replaceContent(content: string): Edited<Ast, Ops>;
|
|
@@ -91,4 +96,3 @@ export declare const RESERVED_HANDLE_NAMES: readonly ["then", "read", "raw", "mo
|
|
|
91
96
|
* const tsDialect = withOps(baseTsDialect, addImportPack);
|
|
92
97
|
*/
|
|
93
98
|
export declare function withOps<Ast, B extends OpPack<Ast>, P extends OpPack<Ast>[]>(base: Dialect<Ast, B>, ...packs: P): Dialect<Ast, B & UnionToIntersection<P[number]>>;
|
|
94
|
-
export {};
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
import { basename } from "node:path";
|
|
15
15
|
import { createDialectHandle } from "./dialect-handle.js";
|
|
16
16
|
import { dialectError } from "./dialect-error.js";
|
|
17
|
+
export { query } from "./dialect-handle.js";
|
|
17
18
|
/**
|
|
18
19
|
* Declares a named collection of ops over one AST type — usable standalone (REQ-DG-02.3),
|
|
19
20
|
* e.g. shareable across two dialects targeting the same AST type, before any `withOps`
|
|
@@ -1,8 +1,21 @@
|
|
|
1
|
-
import type { OpPack, Handle } from "./define-dialect.ts";
|
|
1
|
+
import type { OpPack, Handle, Query } from "./define-dialect.ts";
|
|
2
2
|
interface DialectAst<Ast> {
|
|
3
3
|
parse(source: string): Ast;
|
|
4
4
|
print(ast: Ast): string;
|
|
5
5
|
}
|
|
6
|
+
/**
|
|
7
|
+
* Marks an op-pack entry as a query: on the handle it ends the chain and resolves to `fn`'s
|
|
8
|
+
* result instead of returning the handle. It runs in chain order on the live AST, so it sees
|
|
9
|
+
* every op chained before it; it emits nothing, and it rejects if it changes the AST.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* const pack = defineOpPack({
|
|
13
|
+
* push(ast: string[], line: string) { ast.push(line); },
|
|
14
|
+
* count: query((ast: string[]) => ast.length),
|
|
15
|
+
* });
|
|
16
|
+
* // await dialect.find("a.lines").push("x").count() -> number of lines, "x" included
|
|
17
|
+
*/
|
|
18
|
+
export declare function query<Ast, A extends unknown[], R>(fn: (ast: Ast, ...args: A) => R): Query<Ast, A, R>;
|
|
6
19
|
/**
|
|
7
20
|
* Recovers the author-facing handle path for a live AST instance previously registered by
|
|
8
21
|
* `#ensureLive` — the ONLY channel through which an op function can reach the path for its
|
|
@@ -21,6 +21,29 @@ function isThenable(value) {
|
|
|
21
21
|
// WeakMap entry lives exactly as long as the AST instance it's keyed on (set once in
|
|
22
22
|
// #ensureLive, alongside `#live` itself) — no separate cleanup needed.
|
|
23
23
|
const astHandlePaths = new WeakMap();
|
|
24
|
+
// The dispatcher must decide synchronously whether a method returns the handle or a promise,
|
|
25
|
+
// and a function's return type is invisible at runtime — so `query()` brands the function.
|
|
26
|
+
// It lives here, not in define-dialect.ts, because define-dialect.ts already imports this
|
|
27
|
+
// module: the reverse runtime import would be circular.
|
|
28
|
+
const queries = new WeakSet();
|
|
29
|
+
/**
|
|
30
|
+
* Marks an op-pack entry as a query: on the handle it ends the chain and resolves to `fn`'s
|
|
31
|
+
* result instead of returning the handle. It runs in chain order on the live AST, so it sees
|
|
32
|
+
* every op chained before it; it emits nothing, and it rejects if it changes the AST.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* const pack = defineOpPack({
|
|
36
|
+
* push(ast: string[], line: string) { ast.push(line); },
|
|
37
|
+
* count: query((ast: string[]) => ast.length),
|
|
38
|
+
* });
|
|
39
|
+
* // await dialect.find("a.lines").push("x").count() -> number of lines, "x" included
|
|
40
|
+
*/
|
|
41
|
+
export function query(fn) {
|
|
42
|
+
// A fresh wrapper, so `fn` itself stays a plain op wherever it is reused unwrapped.
|
|
43
|
+
const branded = (ast, ...args) => fn(ast, ...args);
|
|
44
|
+
queries.add(branded);
|
|
45
|
+
return branded;
|
|
46
|
+
}
|
|
24
47
|
/**
|
|
25
48
|
* Recovers the author-facing handle path for a live AST instance previously registered by
|
|
26
49
|
* `#ensureLive` — the ONLY channel through which an op function can reach the path for its
|
|
@@ -257,6 +280,24 @@ class DialectHandleController {
|
|
|
257
280
|
this.#ensureOpen();
|
|
258
281
|
});
|
|
259
282
|
}
|
|
283
|
+
// Sequenced on #tail like an op, but it never calls #ensureOpen: a query only reads the live
|
|
284
|
+
// AST, so it registers no directive (#ensureLive's first read still drains, as for an op).
|
|
285
|
+
// The print comparison is what keeps it read-only: a query that edits the AST would
|
|
286
|
+
// otherwise smuggle its edit into the next op's directive.
|
|
287
|
+
runQuery(fn, args, name) {
|
|
288
|
+
return this.#chain(async () => {
|
|
289
|
+
await this.#ensureLive();
|
|
290
|
+
const before = this.#printContained();
|
|
291
|
+
let result;
|
|
292
|
+
await this.#invokeContained(async () => {
|
|
293
|
+
result = await fn(this.#live, ...args);
|
|
294
|
+
}, `${name}() on "${this.#path}" threw`);
|
|
295
|
+
if (this.#printContained() !== before) {
|
|
296
|
+
throw dialectError(`${name}() is a query and must not change "${this.#path}"`);
|
|
297
|
+
}
|
|
298
|
+
return result;
|
|
299
|
+
});
|
|
300
|
+
}
|
|
260
301
|
// Council fix pass (security note 1, ADR-0037): an ASYNC `fn` is awaited INSIDE the SAME
|
|
261
302
|
// shared containment `runOp` uses (`#invokeContained`) — the enqueued step already runs
|
|
262
303
|
// in the async `#tail` chain, so awaiting is natural. Without this, `fn`'s returned
|
|
@@ -369,11 +410,15 @@ export function createDialectHandle(dialectAst, ops, path) {
|
|
|
369
410
|
then: (onfulfilled, onrejected) => controller.then(onfulfilled, onrejected),
|
|
370
411
|
};
|
|
371
412
|
// The op-derived members — one bound dispatcher per key in `ops` (exactly what
|
|
372
|
-
// `OpMethods<Ast, Ops>` describes at the type level)
|
|
413
|
+
// `OpMethods<Ast, Ops>` describes at the type level): a query resolves to its value, any
|
|
414
|
+
// other op chains.
|
|
373
415
|
const opMethods = Object.fromEntries(Object.keys(ops).map((opName) => [
|
|
374
416
|
opName,
|
|
375
417
|
(...args) => {
|
|
376
|
-
|
|
418
|
+
const op = ops[opName];
|
|
419
|
+
if (queries.has(op))
|
|
420
|
+
return controller.runQuery(op, args, opName);
|
|
421
|
+
controller.runOp(op, args, opName);
|
|
377
422
|
return handle;
|
|
378
423
|
},
|
|
379
424
|
]));
|
package/dist/core/index.d.ts
CHANGED
|
@@ -6,5 +6,5 @@ export type { SessionContext } from "./context.ts";
|
|
|
6
6
|
export { defineFactory, currentContext } from "./context.ts";
|
|
7
7
|
export type { ReadOps, WriteOps, WritableHandleRef } from "./base-handle.ts";
|
|
8
8
|
export type { FoundHandle, WritableHandle } from "./handle-state.ts";
|
|
9
|
-
export { defineDialect, defineOpPack, withOps } from "./define-dialect.ts";
|
|
10
|
-
export type { Dialect, OpPack } from "./define-dialect.ts";
|
|
9
|
+
export { defineDialect, defineOpPack, query, withOps } from "./define-dialect.ts";
|
|
10
|
+
export type { Dialect, OpPack, Query } from "./define-dialect.ts";
|
package/dist/core/index.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
export { Session } from "./session.js";
|
|
4
4
|
export { DirectiveFactory } from "./directive-factory.js";
|
|
5
5
|
export { defineFactory, currentContext } from "./context.js";
|
|
6
|
-
export { defineDialect, defineOpPack, withOps } from "./define-dialect.js";
|
|
6
|
+
export { defineDialect, defineOpPack, query, withOps } from "./define-dialect.js";
|
|
@@ -18,6 +18,11 @@ type AngularOps = {
|
|
|
18
18
|
addOutput: (ast: SourceFile, name: string, options?: OutputOptions) => void;
|
|
19
19
|
addSignal: (ast: SourceFile, name: string, initial: string, options?: StateOptions) => void;
|
|
20
20
|
addComputed: (ast: SourceFile, name: string, expression: string, options?: StateOptions) => void;
|
|
21
|
+
addNgModuleImport: InsertOp;
|
|
22
|
+
addDeclaration: InsertOp;
|
|
23
|
+
addNgModuleProvider: InsertOp;
|
|
24
|
+
addNgModuleExport: InsertOp;
|
|
25
|
+
addBootstrap: InsertOp;
|
|
21
26
|
};
|
|
22
27
|
/**
|
|
23
28
|
* Opens a `.ts` file of an Angular project for editing. The handle carries every
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.js";
|
|
2
2
|
import { parse, print } from "../typescript/ast.js";
|
|
3
3
|
import { typescriptOps } from "../typescript/pack.js";
|
|
4
|
-
import { addComponentImport, addComponentProvider, addComputed, addInjection, addInput, addLazyRoute, addModel, addOutput, addRootProvider, addRoute, addSignal, } from "./ops.js";
|
|
4
|
+
import { addBootstrap, addComponentImport, addComponentProvider, addComputed, addDeclaration, addInjection, addInput, addLazyRoute, addModel, addNgModuleExport, addNgModuleImport, addNgModuleProvider, addOutput, addRootProvider, addRoute, addSignal, } from "./ops.js";
|
|
5
5
|
export * as astLibrary from "ts-morph";
|
|
6
6
|
const angularOps = defineOpPack({
|
|
7
7
|
addComponentImport,
|
|
@@ -15,6 +15,11 @@ const angularOps = defineOpPack({
|
|
|
15
15
|
addOutput,
|
|
16
16
|
addSignal,
|
|
17
17
|
addComputed,
|
|
18
|
+
addNgModuleImport,
|
|
19
|
+
addDeclaration,
|
|
20
|
+
addNgModuleProvider,
|
|
21
|
+
addNgModuleExport,
|
|
22
|
+
addBootstrap,
|
|
18
23
|
});
|
|
19
24
|
const baseDialect = defineDialect({
|
|
20
25
|
extensions: [".ts"],
|
|
@@ -19,6 +19,19 @@ export declare const addComponentProvider: (ast: SourceFile, element: ArrayEleme
|
|
|
19
19
|
* config object, created when missing. A config passed by name rejects with the module to edit.
|
|
20
20
|
*/
|
|
21
21
|
export declare const addRootProvider: (ast: SourceFile, element: ArrayElement, imports?: readonly NamedImport[]) => void;
|
|
22
|
+
/**
|
|
23
|
+
* Appends `element` to `imports` of the file's only `@NgModule`, creating the metadata object
|
|
24
|
+
* or the array when missing, then adds each of `imports`. An equal element is a no-op.
|
|
25
|
+
*/
|
|
26
|
+
export declare const addNgModuleImport: (ast: SourceFile, element: ArrayElement, imports?: readonly NamedImport[]) => void;
|
|
27
|
+
/** Same as `addNgModuleImport`, for `declarations`: components, directives and pipes declared `standalone: false`. */
|
|
28
|
+
export declare const addDeclaration: (ast: SourceFile, element: ArrayElement, imports?: readonly NamedImport[]) => void;
|
|
29
|
+
/** Same as `addNgModuleImport`, for `providers`. */
|
|
30
|
+
export declare const addNgModuleProvider: (ast: SourceFile, element: ArrayElement, imports?: readonly NamedImport[]) => void;
|
|
31
|
+
/** Same as `addNgModuleImport`, for `exports`. */
|
|
32
|
+
export declare const addNgModuleExport: (ast: SourceFile, element: ArrayElement, imports?: readonly NamedImport[]) => void;
|
|
33
|
+
/** Same as `addNgModuleImport`, for `bootstrap`. */
|
|
34
|
+
export declare const addBootstrap: (ast: SourceFile, element: ArrayElement, imports?: readonly NamedImport[]) => void;
|
|
22
35
|
/** An eager route: `{ path, component }`, with `component` imported from `from`. */
|
|
23
36
|
export type RouteSpec = {
|
|
24
37
|
path: string;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { Node, SyntaxKind } from "ts-morph";
|
|
1
|
+
import { Node, SyntaxKind, } from "ts-morph";
|
|
2
2
|
import { dialectError } from "../../core/dialect-error.js";
|
|
3
3
|
import { handlePathFor } from "../../core/dialect-handle.js";
|
|
4
4
|
import { assertValidImportBinding } from "../../core/jsx-name-validator.js";
|
|
5
5
|
import { elementNameEcho } from "../../core/reject-tail.js";
|
|
6
|
-
import { appendArrayElement, elementText, isSameElement, unwrap, } from "../typescript/array-element.js";
|
|
6
|
+
import { appendArrayElement, appendEntry, elementText, isSameElement, unwrap, } from "../typescript/array-element.js";
|
|
7
7
|
import { parse } from "../typescript/ast.js";
|
|
8
8
|
import { insertClassProperty } from "../typescript/class-property.js";
|
|
9
9
|
import { addImport } from "../typescript/ops.js";
|
|
@@ -81,6 +81,20 @@ export const addComponentProvider = insertOp("addComponentProvider", () => ({ de
|
|
|
81
81
|
* config object, created when missing. A config passed by name rejects with the module to edit.
|
|
82
82
|
*/
|
|
83
83
|
export const addRootProvider = insertOp("addRootProvider", rootProviders);
|
|
84
|
+
const ngModuleOp = (opName, property) => insertOp(opName, () => ({ decorator: "NgModule", path: [property] }));
|
|
85
|
+
/**
|
|
86
|
+
* Appends `element` to `imports` of the file's only `@NgModule`, creating the metadata object
|
|
87
|
+
* or the array when missing, then adds each of `imports`. An equal element is a no-op.
|
|
88
|
+
*/
|
|
89
|
+
export const addNgModuleImport = ngModuleOp("addNgModuleImport", "imports");
|
|
90
|
+
/** Same as `addNgModuleImport`, for `declarations`: components, directives and pipes declared `standalone: false`. */
|
|
91
|
+
export const addDeclaration = ngModuleOp("addDeclaration", "declarations");
|
|
92
|
+
/** Same as `addNgModuleImport`, for `providers`. */
|
|
93
|
+
export const addNgModuleProvider = ngModuleOp("addNgModuleProvider", "providers");
|
|
94
|
+
/** Same as `addNgModuleImport`, for `exports`. */
|
|
95
|
+
export const addNgModuleExport = ngModuleOp("addNgModuleExport", "exports");
|
|
96
|
+
/** Same as `addNgModuleImport`, for `bootstrap`. */
|
|
97
|
+
export const addBootstrap = ngModuleOp("addBootstrap", "bootstrap");
|
|
84
98
|
const ROUTE_SHAPE = "`route` must be { path, component, from } strings — fix the route, or use `.modify()` to make this edit directly.";
|
|
85
99
|
const LAZY_ROUTE_SHAPE = "`route` must be { path, loadComponent | loadChildren, export? } strings — fix the route, or use `.modify()` to make this edit " +
|
|
86
100
|
"directly.";
|
|
@@ -99,7 +113,40 @@ function pathOf(element) {
|
|
|
99
113
|
const value = route.getProperty("path")?.asKind(SyntaxKind.PropertyAssignment)?.getInitializer();
|
|
100
114
|
return Node.isStringLiteral(value) || Node.isNoSubstitutionTemplateLiteral(value) ? value.getLiteralValue() : undefined;
|
|
101
115
|
}
|
|
102
|
-
//
|
|
116
|
+
// The file's routes: the only variable typed `Routes`/`Route[]`, else the routes of the only
|
|
117
|
+
// `RouterModule.forRoot`/`forChild` call — inline, or a same-file variable it names.
|
|
118
|
+
function routesList(ast, fail) {
|
|
119
|
+
const declarations = typedVariables(ast, ["Routes", "Route[]"]);
|
|
120
|
+
if (declarations.length > 1)
|
|
121
|
+
fail(`${declarations.length} top-level variables are typed Routes or Route[]; exactly one is required`);
|
|
122
|
+
if (declarations.length === 1) {
|
|
123
|
+
const list = unwrap(declarations[0].getInitializerOrThrow());
|
|
124
|
+
if (!Node.isArrayLiteralExpression(list))
|
|
125
|
+
fail(`"${elementNameEcho(declarations[0].getName())}" is not an array literal`);
|
|
126
|
+
return list;
|
|
127
|
+
}
|
|
128
|
+
const calls = ast.getDescendantsOfKind(SyntaxKind.CallExpression).filter((call) => {
|
|
129
|
+
const callee = call.getExpression();
|
|
130
|
+
return (Node.isPropertyAccessExpression(callee) &&
|
|
131
|
+
callee.getExpression().getText() === "RouterModule" &&
|
|
132
|
+
["forRoot", "forChild"].includes(callee.getName()));
|
|
133
|
+
});
|
|
134
|
+
if (calls.length === 0)
|
|
135
|
+
fail("no top-level variable typed Routes or Route[] and no RouterModule.forRoot or forChild call was found");
|
|
136
|
+
if (calls.length > 1)
|
|
137
|
+
fail(`${calls.length} RouterModule.forRoot or forChild calls were found; exactly one is required`);
|
|
138
|
+
let routes = calls[0].getArguments()[0];
|
|
139
|
+
if (Node.isIdentifier(routes)) {
|
|
140
|
+
const named = routes.getText();
|
|
141
|
+
const declaration = ast.getVariableDeclarations().filter((decl) => decl.getName() === named);
|
|
142
|
+
routes = declaration.length === 1 ? declaration[0].getInitializer() : undefined;
|
|
143
|
+
}
|
|
144
|
+
const list = routes === undefined ? undefined : unwrap(routes);
|
|
145
|
+
if (!Node.isArrayLiteralExpression(list))
|
|
146
|
+
fail("the RouterModule routes are not an array literal in this file");
|
|
147
|
+
return list;
|
|
148
|
+
}
|
|
149
|
+
// Adds `text` to the file's routes. Angular matches routes in order and the first
|
|
103
150
|
// match wins, so a new route goes before a top-level `**` route instead of after it.
|
|
104
151
|
function insertRoute(ast, opName, path, text) {
|
|
105
152
|
const label = `${opName}("${elementNameEcho(path)}")`;
|
|
@@ -108,16 +155,9 @@ function insertRoute(ast, opName, path, text) {
|
|
|
108
155
|
};
|
|
109
156
|
if (path.startsWith("/"))
|
|
110
157
|
fail('a route path cannot start with "/"');
|
|
111
|
-
const declarations = typedVariables(ast, ["Routes", "Route[]"]);
|
|
112
|
-
if (declarations.length === 0)
|
|
113
|
-
fail("no top-level variable typed Routes or Route[] was found");
|
|
114
|
-
if (declarations.length > 1)
|
|
115
|
-
fail(`${declarations.length} top-level variables are typed Routes or Route[]; exactly one is required`);
|
|
116
|
-
const name = declarations[0].getName();
|
|
117
|
-
const list = unwrap(declarations[0].getInitializerOrThrow());
|
|
118
|
-
if (!Node.isArrayLiteralExpression(list))
|
|
119
|
-
fail(`"${elementNameEcho(name)}" is not an array literal`);
|
|
120
158
|
const element = { expression: text };
|
|
159
|
+
elementText(element);
|
|
160
|
+
const list = routesList(ast, fail);
|
|
121
161
|
const elements = list.getElements();
|
|
122
162
|
const samePath = elements.find((candidate) => pathOf(candidate) === path);
|
|
123
163
|
if (samePath !== undefined) {
|
|
@@ -127,7 +167,7 @@ function insertRoute(ast, opName, path, text) {
|
|
|
127
167
|
}
|
|
128
168
|
const wildcard = elements.find((candidate) => pathOf(candidate) === "**");
|
|
129
169
|
if (wildcard === undefined) {
|
|
130
|
-
|
|
170
|
+
appendEntry(ast, list, elements, text, `[${text}]`);
|
|
131
171
|
return;
|
|
132
172
|
}
|
|
133
173
|
const source = ast.getFullText();
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Root } from "postcss";
|
|
2
|
+
/**
|
|
3
|
+
* Parses `source` into a PostCSS `Root`, throwing on a CSS syntax error. PostCSS keeps every
|
|
4
|
+
* whitespace, comment, and BOM byte in node `raws`, so `print` returns an unedited source as is.
|
|
5
|
+
*/
|
|
6
|
+
export declare function parse(source: string): Root;
|
|
7
|
+
export declare function print(root: Root): string;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { parse as parseCss } from "postcss";
|
|
2
|
+
/**
|
|
3
|
+
* Parses `source` into a PostCSS `Root`, throwing on a CSS syntax error. PostCSS keeps every
|
|
4
|
+
* whitespace, comment, and BOM byte in node `raws`, so `print` returns an unedited source as is.
|
|
5
|
+
*/
|
|
6
|
+
export function parse(source) {
|
|
7
|
+
try {
|
|
8
|
+
return parseCss(source);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
throw new Error("invalid CSS");
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function print(root) {
|
|
15
|
+
return root.toString();
|
|
16
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Root } from "postcss";
|
|
2
|
+
import { type Handle, type Query } from "../../core/define-dialect.ts";
|
|
3
|
+
import { getDeclaration, type CssTarget, type DeclarationOptions } from "./ops.ts";
|
|
4
|
+
export * as astLibrary from "postcss";
|
|
5
|
+
export { getDeclaration };
|
|
6
|
+
export type { CssTarget, DeclarationOptions };
|
|
7
|
+
type CssOps = {
|
|
8
|
+
setDeclaration: (ast: Root, target: CssTarget, property: string, value: string, options?: DeclarationOptions) => void;
|
|
9
|
+
removeDeclaration: (ast: Root, target: CssTarget, property: string) => void;
|
|
10
|
+
getDeclaration: Query<Root, [target: CssTarget, property: string], ReturnType<typeof getDeclaration>>;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Opens a `.css` file to set and remove declarations. A target names one top-level block —
|
|
14
|
+
* `{ selector: ":root" }`, `{ atRule: "theme" }`, or `{ atRule: "media", params, selector }` —
|
|
15
|
+
* and every op edits only the declaration it addresses: comments, `@import`s, other rules,
|
|
16
|
+
* indentation, line endings, and a BOM survive. Any other extension throws synchronously with
|
|
17
|
+
* the `dialect operation failed: ` prefix. `.modify(fn)` hands `fn` the live PostCSS `Root`;
|
|
18
|
+
* use `astLibrary` (`postcss`) for anything the ops do not cover.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* import * as css from "@pbuilder/sdk/css";
|
|
22
|
+
*
|
|
23
|
+
* // tokens.css before: @import "tailwindcss";\n\n@theme {\n --color-primary: #0b254d;\n}\n
|
|
24
|
+
* export const run = async () => {
|
|
25
|
+
* await css
|
|
26
|
+
* .find("tokens.css")
|
|
27
|
+
* .setDeclaration({ atRule: "theme" }, "--color-primary", "#1974f9")
|
|
28
|
+
* .setDeclaration({ selector: "html[data-theme='nylon']" }, "--color-primary", "#0b254d");
|
|
29
|
+
* };
|
|
30
|
+
* // -> @import "tailwindcss";
|
|
31
|
+
* // ->
|
|
32
|
+
* // -> @theme {
|
|
33
|
+
* // -> --color-primary: #1974f9;
|
|
34
|
+
* // -> }
|
|
35
|
+
* // ->
|
|
36
|
+
* // -> html[data-theme='nylon'] {
|
|
37
|
+
* // -> --color-primary: #0b254d;
|
|
38
|
+
* // -> }
|
|
39
|
+
*/
|
|
40
|
+
export declare function find(path: string): Handle<"found", Root, CssOps>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { defineDialect, defineOpPack, query, withOps } from "../../core/define-dialect.js";
|
|
2
|
+
import { parse, print } from "./ast.js";
|
|
3
|
+
import { getDeclaration, removeDeclaration, setDeclaration } from "./ops.js";
|
|
4
|
+
export * as astLibrary from "postcss";
|
|
5
|
+
export { getDeclaration };
|
|
6
|
+
const opsPack = defineOpPack({ setDeclaration, removeDeclaration, getDeclaration: query(getDeclaration) });
|
|
7
|
+
const cssDialect = withOps(defineDialect({ extensions: [".css"], ast: { parse, print }, ops: {} }), opsPack);
|
|
8
|
+
/**
|
|
9
|
+
* Opens a `.css` file to set and remove declarations. A target names one top-level block —
|
|
10
|
+
* `{ selector: ":root" }`, `{ atRule: "theme" }`, or `{ atRule: "media", params, selector }` —
|
|
11
|
+
* and every op edits only the declaration it addresses: comments, `@import`s, other rules,
|
|
12
|
+
* indentation, line endings, and a BOM survive. Any other extension throws synchronously with
|
|
13
|
+
* the `dialect operation failed: ` prefix. `.modify(fn)` hands `fn` the live PostCSS `Root`;
|
|
14
|
+
* use `astLibrary` (`postcss`) for anything the ops do not cover.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* import * as css from "@pbuilder/sdk/css";
|
|
18
|
+
*
|
|
19
|
+
* // tokens.css before: @import "tailwindcss";\n\n@theme {\n --color-primary: #0b254d;\n}\n
|
|
20
|
+
* export const run = async () => {
|
|
21
|
+
* await css
|
|
22
|
+
* .find("tokens.css")
|
|
23
|
+
* .setDeclaration({ atRule: "theme" }, "--color-primary", "#1974f9")
|
|
24
|
+
* .setDeclaration({ selector: "html[data-theme='nylon']" }, "--color-primary", "#0b254d");
|
|
25
|
+
* };
|
|
26
|
+
* // -> @import "tailwindcss";
|
|
27
|
+
* // ->
|
|
28
|
+
* // -> @theme {
|
|
29
|
+
* // -> --color-primary: #1974f9;
|
|
30
|
+
* // -> }
|
|
31
|
+
* // ->
|
|
32
|
+
* // -> html[data-theme='nylon'] {
|
|
33
|
+
* // -> --color-primary: #0b254d;
|
|
34
|
+
* // -> }
|
|
35
|
+
*/
|
|
36
|
+
export function find(path) {
|
|
37
|
+
return cssDialect.find(path);
|
|
38
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type Root } from "postcss";
|
|
2
|
+
/**
|
|
3
|
+
* Addresses one top-level block: `{ selector }` is a rule, `{ atRule, params? }` is an at-rule's
|
|
4
|
+
* own body (`@theme`), and both together are a rule inside that at-rule. The selector and params
|
|
5
|
+
* match after trimming; the at-rule name, written without `@`, matches case-insensitively.
|
|
6
|
+
*/
|
|
7
|
+
export interface CssTarget {
|
|
8
|
+
selector?: string;
|
|
9
|
+
atRule?: string;
|
|
10
|
+
params?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface DeclarationOptions {
|
|
13
|
+
before?: string;
|
|
14
|
+
after?: string;
|
|
15
|
+
important?: boolean;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Sets `property` to `value` in the `target` block: an existing declaration is updated in place,
|
|
19
|
+
* a new one goes last in the block or next to the `before` / `after` anchor, and a missing block
|
|
20
|
+
* is created at the end of the file. Setting the value a declaration already has changes nothing.
|
|
21
|
+
*/
|
|
22
|
+
export declare const setDeclaration: (ast: Root, args_0: CssTarget, args_1: string, args_2: string, args_3?: DeclarationOptions | undefined) => void;
|
|
23
|
+
/**
|
|
24
|
+
* Reads `property` from the `target` block of a parsed `Root`, such as the one `.modify(fn)`
|
|
25
|
+
* receives: `{ value, important }`, or `undefined` when the block or declaration is missing.
|
|
26
|
+
* Not an op — it returns a value — so it is called directly, never chained on a handle.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* import * as css from "@pbuilder/sdk/css";
|
|
30
|
+
*
|
|
31
|
+
* // tokens.css: @theme {\n --radius: 4px;\n}\n
|
|
32
|
+
* export const run = async () => {
|
|
33
|
+
* await css.find("tokens.css").modify((root) => {
|
|
34
|
+
* const radius = css.getDeclaration(root, { atRule: "theme" }, "--radius");
|
|
35
|
+
* // -> { value: "4px", important: false }
|
|
36
|
+
* });
|
|
37
|
+
* };
|
|
38
|
+
*/
|
|
39
|
+
export declare function getDeclaration(root: Root, target: CssTarget, property: string): {
|
|
40
|
+
value: string;
|
|
41
|
+
important: boolean;
|
|
42
|
+
} | undefined;
|
|
43
|
+
/** Removes `property` from the `target` block; a missing block or declaration is a no-op. */
|
|
44
|
+
export declare const removeDeclaration: (ast: Root, args_0: CssTarget, args_1: string) => void;
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { atRule, decl, parse, rule } from "postcss";
|
|
2
|
+
import { dialectError } from "../../core/dialect-error.js";
|
|
3
|
+
import { validatedOp } from "../../core/jsx-name-validator.js";
|
|
4
|
+
const REGULAR_PROPERTY = /^-?[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
5
|
+
// `*` admits Tailwind's namespace resets (`--color-*: initial`).
|
|
6
|
+
const CUSTOM_PROPERTY = /^--[A-Za-z0-9_*\u0080-\uFFFF-]+$/;
|
|
7
|
+
const AT_RULE_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;
|
|
8
|
+
function label(target) {
|
|
9
|
+
const at = target.atRule === undefined ? [] : [`@${target.atRule} ${target.params?.trim() ?? ""}`.trim()];
|
|
10
|
+
return [...at, ...(target.selector === undefined ? [] : [target.selector.trim()])].join(" ");
|
|
11
|
+
}
|
|
12
|
+
function fail(op, target, why) {
|
|
13
|
+
throw dialectError(`${op}(${label(target)}) — ${why}`);
|
|
14
|
+
}
|
|
15
|
+
function tryParse(css) {
|
|
16
|
+
try {
|
|
17
|
+
return parse(css);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
// The selector, params, and value checks re-parse the argument alone and require PostCSS to
|
|
24
|
+
// read back exactly one node with the same text: anything that would close the node or add
|
|
25
|
+
// another one (`;`, `}`, `{`) is rejected before it can reach the printed file.
|
|
26
|
+
function assertTarget(op, target) {
|
|
27
|
+
const t = target;
|
|
28
|
+
const shaped = typeof target === "object" && target !== null && [t.selector, t.atRule, t.params].every((v) => v === undefined || typeof v === "string");
|
|
29
|
+
if (!shaped)
|
|
30
|
+
throw dialectError(`${op} — a target is an object of string \`selector\`, \`atRule\`, and \`params\`.`);
|
|
31
|
+
if (t.params !== undefined && t.atRule === undefined)
|
|
32
|
+
throw dialectError(`${op} — \`params\` needs an \`atRule\`.`);
|
|
33
|
+
if (t.selector === undefined && t.atRule === undefined) {
|
|
34
|
+
throw dialectError(`${op} — a target needs a \`selector\`, an \`atRule\`, or both.`);
|
|
35
|
+
}
|
|
36
|
+
if (t.atRule !== undefined && !AT_RULE_NAME.test(t.atRule)) {
|
|
37
|
+
fail(op, t, `\`${t.atRule}\` is not an at-rule name; write it without \`@\`.`);
|
|
38
|
+
}
|
|
39
|
+
if (t.params !== undefined) {
|
|
40
|
+
const nodes = tryParse(`@${t.atRule} ${t.params}{}`)?.nodes;
|
|
41
|
+
if (nodes?.length !== 1 || nodes[0].type !== "atrule" || nodes[0].params !== t.params.trim()) {
|
|
42
|
+
fail(op, t, `\`${t.params}\` is not at-rule params.`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (t.selector !== undefined) {
|
|
46
|
+
const nodes = tryParse(`${t.selector}{}`)?.nodes;
|
|
47
|
+
if (t.selector.trim() === "" || nodes?.length !== 1 || nodes[0].type !== "rule" || nodes[0].selector !== t.selector.trim()) {
|
|
48
|
+
fail(op, t, `\`${t.selector}\` is not a single selector.`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const isCustom = (property) => property.startsWith("--");
|
|
53
|
+
function assertProperty(op, target, property) {
|
|
54
|
+
if (typeof property !== "string" || !(isCustom(property) ? CUSTOM_PROPERTY : REGULAR_PROPERTY).test(property)) {
|
|
55
|
+
fail(op, target, `\`${String(property)}\` is not a CSS property name.`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function assertValue(op, target, property, value) {
|
|
59
|
+
const parsed = typeof value === "string" ? tryParse(`a{${property}:${value}}`) : undefined;
|
|
60
|
+
const block = parsed?.nodes.length === 1 && parsed.first?.type === "rule" ? parsed.first.nodes : [];
|
|
61
|
+
const node = block.length === 1 && block[0].type === "decl" ? block[0] : undefined;
|
|
62
|
+
if (node?.important)
|
|
63
|
+
fail(op, target, "put `!important` in the `important` option, not in the value.");
|
|
64
|
+
// PostCSS keeps the surrounding whitespace of a custom property's value, so compare trimmed.
|
|
65
|
+
if (node === undefined || node.prop !== property || node.value.trim() === "" || node.value.trim() !== value.trim()) {
|
|
66
|
+
fail(op, target, `\`${String(value)}\` is not a single declaration value.`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function assertOptions(op, target, options) {
|
|
70
|
+
if (options === undefined)
|
|
71
|
+
return;
|
|
72
|
+
if (typeof options !== "object" || options === null)
|
|
73
|
+
fail(op, target, "options must be an object.");
|
|
74
|
+
const { before, after, important } = options;
|
|
75
|
+
if (before !== undefined && after !== undefined)
|
|
76
|
+
fail(op, target, "pass `before` or `after`, not both.");
|
|
77
|
+
for (const anchor of [before, after])
|
|
78
|
+
if (anchor !== undefined)
|
|
79
|
+
assertProperty(op, target, anchor);
|
|
80
|
+
if (important !== undefined && typeof important !== "boolean")
|
|
81
|
+
fail(op, target, "`important` must be a boolean.");
|
|
82
|
+
}
|
|
83
|
+
function only(op, target, nodes, match) {
|
|
84
|
+
const found = nodes.filter(match);
|
|
85
|
+
if (found.length > 1)
|
|
86
|
+
fail(op, target, `\`${label(target)}\` matches ${found.length} blocks; the target is ambiguous.`);
|
|
87
|
+
return found[0];
|
|
88
|
+
}
|
|
89
|
+
function findBlock(op, root, target) {
|
|
90
|
+
let scope = root;
|
|
91
|
+
if (target.atRule !== undefined) {
|
|
92
|
+
const name = target.atRule.toLowerCase();
|
|
93
|
+
const params = target.params?.trim() ?? "";
|
|
94
|
+
scope = only(op, target, root.nodes, (node) => node.type === "atrule" && node.nodes !== undefined && node.name.toLowerCase() === name && node.params === params);
|
|
95
|
+
}
|
|
96
|
+
if (scope === undefined || target.selector === undefined)
|
|
97
|
+
return scope;
|
|
98
|
+
const selector = target.selector.trim();
|
|
99
|
+
return only(op, target, scope.nodes ?? [], (node) => node.type === "rule" && node.selector === selector);
|
|
100
|
+
}
|
|
101
|
+
function findDeclaration(op, target, block, property) {
|
|
102
|
+
const same = (prop) => (isCustom(property) ? prop === property : prop.toLowerCase() === property.toLowerCase());
|
|
103
|
+
const found = (block.nodes ?? []).filter((node) => node.type === "decl" && same(node.prop));
|
|
104
|
+
if (found.length > 1)
|
|
105
|
+
fail(op, target, `\`${property}\` is declared ${found.length} times in the block.`);
|
|
106
|
+
return found[0];
|
|
107
|
+
}
|
|
108
|
+
// The file's own newline and the indentation of its first top-level declaration, so a block the
|
|
109
|
+
// ops create reads like the blocks around it. PostCSS's own inference writes `selector{` here.
|
|
110
|
+
function styleOf(root) {
|
|
111
|
+
let indent = " ";
|
|
112
|
+
root.walkDecls((node) => {
|
|
113
|
+
if (node.parent?.parent?.type !== "root")
|
|
114
|
+
return;
|
|
115
|
+
// A declaration on its brace's line (`:root { --a: 1; }`) carries no indentation.
|
|
116
|
+
if (node.raws.before?.includes("\n"))
|
|
117
|
+
indent = /[ \t]*$/.exec(node.raws.before)[0] || indent;
|
|
118
|
+
return false;
|
|
119
|
+
});
|
|
120
|
+
return { newline: root.source?.input.css.includes("\r\n") ? "\r\n" : "\n", indent };
|
|
121
|
+
}
|
|
122
|
+
function place(parent, child, style) {
|
|
123
|
+
const level = parent.type === "root" ? 0 : parent.parent?.type === "root" ? 1 : 2;
|
|
124
|
+
const indent = style.indent.repeat(level);
|
|
125
|
+
if ((parent.nodes ?? []).length === 0) {
|
|
126
|
+
child.raws.before = parent.type === "root" ? "" : style.newline + indent;
|
|
127
|
+
parent.raws.after = style.newline + style.indent.repeat(Math.max(level - 1, 0));
|
|
128
|
+
if (parent.type !== "root")
|
|
129
|
+
parent.raws.semicolon = true;
|
|
130
|
+
}
|
|
131
|
+
else if (child.type !== "decl") {
|
|
132
|
+
child.raws.before = style.newline + style.newline + indent;
|
|
133
|
+
}
|
|
134
|
+
parent.append(child);
|
|
135
|
+
return child;
|
|
136
|
+
}
|
|
137
|
+
function createBlock(op, root, target) {
|
|
138
|
+
const style = styleOf(root);
|
|
139
|
+
let parent = root;
|
|
140
|
+
if (target.atRule !== undefined) {
|
|
141
|
+
const params = target.params?.trim() ?? "";
|
|
142
|
+
parent =
|
|
143
|
+
findBlock(op, root, { atRule: target.atRule, params }) ??
|
|
144
|
+
place(root, atRule({ name: target.atRule, params, raws: { afterName: params === "" ? "" : " ", between: " " } }), style);
|
|
145
|
+
}
|
|
146
|
+
if (target.selector === undefined)
|
|
147
|
+
return parent;
|
|
148
|
+
return place(parent, rule({ selector: target.selector.trim(), raws: { between: " " } }), style);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Sets `property` to `value` in the `target` block: an existing declaration is updated in place,
|
|
152
|
+
* a new one goes last in the block or next to the `before` / `after` anchor, and a missing block
|
|
153
|
+
* is created at the end of the file. Setting the value a declaration already has changes nothing.
|
|
154
|
+
*/
|
|
155
|
+
export const setDeclaration = validatedOp(([target, property, value, options]) => {
|
|
156
|
+
assertTarget("setDeclaration", target);
|
|
157
|
+
assertProperty("setDeclaration", target, property);
|
|
158
|
+
assertValue("setDeclaration", target, property, value);
|
|
159
|
+
assertOptions("setDeclaration", target, options);
|
|
160
|
+
}, (root, target, property, value, options = {}) => {
|
|
161
|
+
const op = "setDeclaration";
|
|
162
|
+
const text = value.trim();
|
|
163
|
+
const important = options.important === true;
|
|
164
|
+
const block = findBlock(op, root, target);
|
|
165
|
+
const existing = block === undefined ? undefined : findDeclaration(op, target, block, property);
|
|
166
|
+
if (existing !== undefined) {
|
|
167
|
+
if (existing.value.trim() !== text)
|
|
168
|
+
existing.value = text;
|
|
169
|
+
if (existing.important !== important)
|
|
170
|
+
existing.important = important;
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const anchorName = options.before ?? options.after;
|
|
174
|
+
const anchor = anchorName === undefined || block === undefined ? undefined : findDeclaration(op, target, block, anchorName);
|
|
175
|
+
if (anchorName !== undefined && anchor === undefined)
|
|
176
|
+
fail(op, target, `the anchor \`${anchorName}\` is not declared in the block.`);
|
|
177
|
+
const created = decl({ prop: property, value: text, important });
|
|
178
|
+
if (anchor === undefined)
|
|
179
|
+
place(block ?? createBlock(op, root, target), created, styleOf(root));
|
|
180
|
+
else if (options.before !== undefined)
|
|
181
|
+
anchor.before(created);
|
|
182
|
+
else
|
|
183
|
+
anchor.after(created);
|
|
184
|
+
});
|
|
185
|
+
/**
|
|
186
|
+
* Reads `property` from the `target` block of a parsed `Root`, such as the one `.modify(fn)`
|
|
187
|
+
* receives: `{ value, important }`, or `undefined` when the block or declaration is missing.
|
|
188
|
+
* Not an op — it returns a value — so it is called directly, never chained on a handle.
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* import * as css from "@pbuilder/sdk/css";
|
|
192
|
+
*
|
|
193
|
+
* // tokens.css: @theme {\n --radius: 4px;\n}\n
|
|
194
|
+
* export const run = async () => {
|
|
195
|
+
* await css.find("tokens.css").modify((root) => {
|
|
196
|
+
* const radius = css.getDeclaration(root, { atRule: "theme" }, "--radius");
|
|
197
|
+
* // -> { value: "4px", important: false }
|
|
198
|
+
* });
|
|
199
|
+
* };
|
|
200
|
+
*/
|
|
201
|
+
export function getDeclaration(root, target, property) {
|
|
202
|
+
assertTarget("getDeclaration", target);
|
|
203
|
+
assertProperty("getDeclaration", target, property);
|
|
204
|
+
const block = findBlock("getDeclaration", root, target);
|
|
205
|
+
const found = block === undefined ? undefined : findDeclaration("getDeclaration", target, block, property);
|
|
206
|
+
return found === undefined ? undefined : { value: found.value.trim(), important: found.important === true };
|
|
207
|
+
}
|
|
208
|
+
/** Removes `property` from the `target` block; a missing block or declaration is a no-op. */
|
|
209
|
+
export const removeDeclaration = validatedOp(([target, property]) => {
|
|
210
|
+
assertTarget("removeDeclaration", target);
|
|
211
|
+
assertProperty("removeDeclaration", target, property);
|
|
212
|
+
}, (root, target, property) => {
|
|
213
|
+
const block = findBlock("removeDeclaration", root, target);
|
|
214
|
+
if (block !== undefined)
|
|
215
|
+
findDeclaration("removeDeclaration", target, block, property)?.remove();
|
|
216
|
+
});
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"manifestVersion": 1,
|
|
3
3
|
"algorithm": "sha256",
|
|
4
4
|
"entry": "dist/bin/pbuilder-runner.js",
|
|
5
|
-
"packageVersion": "0.
|
|
5
|
+
"packageVersion": "0.10.0",
|
|
6
6
|
"files": [
|
|
7
7
|
{
|
|
8
8
|
"path": "dist/bin/pbuilder-runner.js",
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
},
|
|
99
99
|
{
|
|
100
100
|
"path": "package.json",
|
|
101
|
-
"sha256": "
|
|
101
|
+
"sha256": "ef9f722cff4d538c25daad7eedc26b2df66a2784bba63a8e97f4eef339af33f8"
|
|
102
102
|
}
|
|
103
103
|
]
|
|
104
104
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pbuilder/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "The public TypeScript/Bun authoring layer for Project Builder schematics. Authors file mutations (create, replaceContent, remove, rename, move, copy, copyIn), lowers them to IR, and talks to the Project Builder engine over framed stdio (see docs/engine-sdk-wire-spec.md).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -87,6 +87,11 @@
|
|
|
87
87
|
"types": "./dist/dialects/yaml/index.d.ts",
|
|
88
88
|
"import": "./dist/dialects/yaml/index.js",
|
|
89
89
|
"default": "./dist/dialects/yaml/index.js"
|
|
90
|
+
},
|
|
91
|
+
"./css": {
|
|
92
|
+
"types": "./dist/dialects/css/index.d.ts",
|
|
93
|
+
"import": "./dist/dialects/css/index.js",
|
|
94
|
+
"default": "./dist/dialects/css/index.js"
|
|
90
95
|
}
|
|
91
96
|
},
|
|
92
97
|
"scripts": {
|
|
@@ -112,6 +117,7 @@
|
|
|
112
117
|
},
|
|
113
118
|
"dependencies": {
|
|
114
119
|
"jsonc-parser": "3.3.1",
|
|
120
|
+
"postcss": "8.5.30",
|
|
115
121
|
"ts-morph": "28.0.0",
|
|
116
122
|
"yaml": "2.9.1"
|
|
117
123
|
}
|