@pbuilder/sdk 0.3.1 → 0.5.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.
Files changed (54) hide show
  1. package/README.md +57 -17
  2. package/dist/commons/index.d.ts +22 -22
  3. package/dist/commons/index.js +25 -22
  4. package/dist/conformance/index.d.ts +2 -2
  5. package/dist/conformance/index.js +38 -19
  6. package/dist/core/authoring-error.d.ts +3 -3
  7. package/dist/core/authoring-error.js +5 -5
  8. package/dist/core/context.d.ts +6 -6
  9. package/dist/core/context.js +18 -18
  10. package/dist/core/define-dialect.d.ts +1 -1
  11. package/dist/core/define-dialect.js +16 -9
  12. package/dist/core/dialect-handle.js +9 -9
  13. package/dist/core/index.d.ts +1 -1
  14. package/dist/core/json-value.d.ts +14 -0
  15. package/dist/core/json-value.js +43 -0
  16. package/dist/core/session.d.ts +1 -1
  17. package/dist/core/session.js +2 -2
  18. package/dist/dialects/json/ast.d.ts +24 -0
  19. package/dist/dialects/json/ast.js +21 -0
  20. package/dist/dialects/json/index.d.ts +55 -0
  21. package/dist/dialects/json/index.js +54 -0
  22. package/dist/dialects/json/ops.d.ts +46 -0
  23. package/dist/dialects/json/ops.js +561 -0
  24. package/dist/dialects/react/index.d.ts +1 -1
  25. package/dist/dialects/react/index.js +1 -1
  26. package/dist/dialects/typescript/index.d.ts +2 -2
  27. package/dist/dialects/typescript/index.js +2 -2
  28. package/dist/dialects/typescript/ops.js +1 -1
  29. package/dist/dialects/yaml/ast.d.ts +15 -0
  30. package/dist/dialects/yaml/ast.js +154 -0
  31. package/dist/dialects/yaml/documents.d.ts +8 -0
  32. package/dist/dialects/yaml/documents.js +24 -0
  33. package/dist/dialects/yaml/index.d.ts +69 -0
  34. package/dist/dialects/yaml/index.js +70 -0
  35. package/dist/dialects/yaml/paths.d.ts +55 -0
  36. package/dist/dialects/yaml/paths.js +208 -0
  37. package/dist/dialects/yaml/presentation.d.ts +24 -0
  38. package/dist/dialects/yaml/presentation.js +264 -0
  39. package/dist/dialects/yaml/structural.d.ts +39 -0
  40. package/dist/dialects/yaml/structural.js +307 -0
  41. package/dist/pending-directives/index.d.ts +2 -0
  42. package/dist/pending-directives/index.js +1 -0
  43. package/dist/{dry-run/plan.d.ts → pending-directives/render.d.ts} +8 -33
  44. package/dist/{dry-run/plan.js → pending-directives/render.js} +5 -5
  45. package/dist/runner-manifest.json +6 -6
  46. package/dist/scaffold/expander.js +3 -3
  47. package/dist/scaffold/index.d.ts +1 -1
  48. package/dist/scaffold/index.js +1 -1
  49. package/dist/transport/error-text.d.ts +6 -1
  50. package/dist/transport/error-text.js +94 -31
  51. package/package.json +16 -3
  52. package/schemas/project-builder.schema.json +112 -0
  53. package/dist/dry-run/index.d.ts +0 -2
  54. package/dist/dry-run/index.js +0 -1
@@ -8,26 +8,26 @@ export interface DialectRegistry {
8
8
  }): void;
9
9
  drain(): Promise<void>;
10
10
  }
11
- export interface RunContext {
11
+ export interface SessionContext {
12
12
  session: Session;
13
13
  factory: DirectiveFactory;
14
14
  dialects: DialectRegistry;
15
- runFailure?: {
15
+ sessionFailure?: {
16
16
  reason: unknown;
17
17
  };
18
18
  packageAnchors?: {
19
19
  packageDir: string;
20
20
  };
21
21
  }
22
- export declare const RUN_ALS_REGISTRY_KEY = "@pbuilder/sdk:core/context#run-als";
23
- export declare function resolveRunAls(slotValue: unknown): AsyncLocalStorage<RunContext>;
22
+ export declare const SESSION_ALS_REGISTRY_KEY = "@pbuilder/sdk:core/context#session-als";
23
+ export declare function resolveSessionAls(slotValue: unknown): AsyncLocalStorage<SessionContext>;
24
24
  export declare function isDefineFactoryWrapped(value: unknown): boolean;
25
- export declare function currentContext(): RunContext;
25
+ export declare function currentContext(): SessionContext;
26
26
  export declare function requirePackageAnchors(missingAnchorMessage: string): {
27
27
  packageDir: string;
28
28
  };
29
29
  /**
30
- * Builds a run-context and runs the factory inside it, flushing buffered
30
+ * Builds a SessionContext and runs the factory inside it, flushing buffered
31
31
  * directives at run end (REQ-KIT-05) — a write-only factory still emits.
32
32
  *
33
33
  * All-or-nothing contract (ADR-01): on success the full directive batch is committed;
@@ -1,4 +1,4 @@
1
- // KIT-05: Ambient RunContext via AsyncLocalStorage.
1
+ // KIT-05: Ambient SessionContext via AsyncLocalStorage.
2
2
  // defineFactory returns a runner that builds the context and runs fn inside the ALS.
3
3
  // The EngineClient is injected by the caller (test passes the fake) — no module global.
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -33,11 +33,11 @@ class DialectRegistryImpl {
33
33
  }
34
34
  // context-singleton-fix (REQ-MIS-01/02, design §4.3): a module-scope `als` is realm-local —
35
35
  // when `dist/bin/pbuilder-runner.js` and a src-relative `.ts` factory co-execute in one Bun
36
- // process, each resolves its OWN copy of this module and its OWN `als`, so a run entered in
36
+ // process, each resolves its OWN copy of this module and its OWN `als`, so a Session entered in
37
37
  // one realm is invisible to `currentContext()` in the other. The store is therefore parked at
38
- // `globalThis[Symbol.for(RUN_ALS_REGISTRY_KEY)]` — a process-singleton every realm resolving
38
+ // `globalThis[Symbol.for(SESSION_ALS_REGISTRY_KEY)]` — a process-singleton every realm resolving
39
39
  // this file reaches via the SAME well-known key — lazily installed on first access.
40
- export const RUN_ALS_REGISTRY_KEY = "@pbuilder/sdk:core/context#run-als";
40
+ export const SESSION_ALS_REGISTRY_KEY = "@pbuilder/sdk:core/context#session-als";
41
41
  function isAsyncLocalStorageLike(value) {
42
42
  return (typeof value === "object" &&
43
43
  value !== null &&
@@ -51,25 +51,25 @@ function isAsyncLocalStorageLike(value) {
51
51
  // trusted or silently clobbered. Plain `Error` (NOT AuthoringError) — this is
52
52
  // environment/integration corruption, not author-input misuse; the closed reason enum has no
53
53
  // member for it (mirrors `validateAtRunBoundary`'s read-path posture).
54
- export function resolveRunAls(slotValue) {
54
+ export function resolveSessionAls(slotValue) {
55
55
  if (slotValue === undefined) {
56
56
  return new AsyncLocalStorage();
57
57
  }
58
58
  if (isAsyncLocalStorageLike(slotValue)) {
59
59
  return slotValue;
60
60
  }
61
- throw new Error(`[pbuilder] run-context registry slot Symbol.for("${RUN_ALS_REGISTRY_KEY}") is occupied by an ` +
61
+ throw new Error(`[pbuilder] run-context registry slot Symbol.for("${SESSION_ALS_REGISTRY_KEY}") is occupied by an ` +
62
62
  `incompatible value (expected an AsyncLocalStorage, got ${typeof slotValue}) — another module ` +
63
63
  "may have polluted globalThis");
64
64
  }
65
65
  // IMPURE thin shell: reads the shared slot, delegates the 3-state decision to the pure
66
- // `resolveRunAls`, and installs the resolved ALS ONLY when the slot was absent — a frozen
66
+ // `resolveSessionAls`, and installs the resolved ALS ONLY when the slot was absent — a frozen
67
67
  // descriptor (non-enumerable, non-configurable, non-writable) so REQ-MIS-01.2's no-pollution
68
68
  // guarantee holds and the slot can never be silently reassigned after first install.
69
- function getRunAls() {
70
- const registryKey = Symbol.for(RUN_ALS_REGISTRY_KEY);
69
+ function getSessionAls() {
70
+ const registryKey = Symbol.for(SESSION_ALS_REGISTRY_KEY);
71
71
  const slot = globalThis[registryKey];
72
- const resolved = resolveRunAls(slot);
72
+ const resolved = resolveSessionAls(slot);
73
73
  if (slot === undefined) {
74
74
  Object.defineProperty(globalThis, registryKey, {
75
75
  value: resolved,
@@ -90,17 +90,17 @@ const DEFINE_FACTORY_BRAND = Symbol("pbuilder.defineFactory.wrapped");
90
90
  export function isDefineFactoryWrapped(value) {
91
91
  return typeof value === "function" && Reflect.get(value, DEFINE_FACTORY_BRAND) === true;
92
92
  }
93
- // REQ-AEC-02.1 (2.4): a verb called outside any defineFactory run is SDK-side misuse,
94
- // independent of any engine round-trip — an AuthoringError{authoring-rejected,outside-run},
95
- // not a plain Error. The prose lives in authoring-error.ts's outside-run message template
93
+ // REQ-AEC-02.1 (2.4): a verb called outside any defineFactory Session is SDK-side misuse,
94
+ // independent of any engine round-trip — an AuthoringError{authoring-rejected,outside-session},
95
+ // not a plain Error. The prose lives in authoring-error.ts's outside-session message template
96
96
  // (the third template, REQ-AEC-06); this is the one call site that reaches it.
97
97
  export function currentContext() {
98
- const ctx = getRunAls().getStore();
98
+ const ctx = getSessionAls().getStore();
99
99
  if (ctx === undefined) {
100
100
  throw new AuthoringError({
101
101
  verb: undefined,
102
102
  path: undefined,
103
- reason: "outside-run",
103
+ reason: "outside-session",
104
104
  appliedCount: 0,
105
105
  });
106
106
  }
@@ -153,7 +153,7 @@ function emptySchemaWarning(packageDir) {
153
153
  return `[pbuilder] factory at ${relativeDir(packageDir)}: schema.json declares zero properties — no input validation performed`;
154
154
  }
155
155
  // Pre-`als.run` schema-conformance check (ADR-0029, REQ-RBV-01/03/05): validates BEFORE
156
- // RunContext is built, so a rejection throws with nothing buffered — all-or-nothing holds
156
+ // SessionContext is built, so a rejection throws with nothing buffered — all-or-nothing holds
157
157
  // trivially and the rejection never reaches the emit seam. Bare `defineFactory(fn)` (no
158
158
  // `options`) skips this entirely — the untyped opt-out (REQ-TFO-02) stays byte-for-byte
159
159
  // unchanged. Read-path posture (SEC-3, constraint 4): ONLY ENOENT maps to the opt-out;
@@ -213,7 +213,7 @@ function checkReservedNames(packageDir) {
213
213
  }
214
214
  }
215
215
  /**
216
- * Builds a run-context and runs the factory inside it, flushing buffered
216
+ * Builds a SessionContext and runs the factory inside it, flushing buffered
217
217
  * directives at run end (REQ-KIT-05) — a write-only factory still emits.
218
218
  *
219
219
  * All-or-nothing contract (ADR-01): on success the full directive batch is committed;
@@ -288,7 +288,7 @@ export function defineFactory(fn, options) {
288
288
  // rejection (an unawaited chain that threw) routes through the SAME catch below as a
289
289
  // flush rejection already does.
290
290
  try {
291
- await getRunAls().run(ctx, () => fn(o));
291
+ await getSessionAls().run(ctx, () => fn(o));
292
292
  await ctx.dialects.drain();
293
293
  await ctx.session.flush();
294
294
  await ctx.session.commit();
@@ -53,7 +53,7 @@ export interface Dialect<Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> {
53
53
  export declare function defineOpPack<Ast, Ops extends OpPack<Ast>>(ops: Ops): Ops;
54
54
  /**
55
55
  * Assembles a `Dialect` from its frozen descriptor (extensions, an AST parse/print pair,
56
- * and an op-pack). `find` is the dialect's ONLY entry verb into a run (REQ-DG-01.2) — it
56
+ * and an op-pack). `find` is the dialect's ONLY entry verb into a Session (REQ-DG-01.2) — it
57
57
  * returns an open, coalescing `Handle`.
58
58
  *
59
59
  * @example
@@ -11,7 +11,9 @@
11
11
  // (target's param `unknown` must be assignable to source's param `ToyAst`, which it is not),
12
12
  // but `any` short-circuits variance checking in both directions, which is exactly the
13
13
  // "don't care about the concrete Ast" erasure this bare form needs.
14
+ import { basename } from "node:path";
14
15
  import { createDialectHandle } from "./dialect-handle.js";
16
+ import { dialectError } from "./dialect-error.js";
15
17
  /**
16
18
  * Declares a named collection of ops over one AST type — usable standalone (REQ-DG-02.3),
17
19
  * e.g. shareable across two dialects targeting the same AST type, before any `withOps`
@@ -25,9 +27,18 @@ import { createDialectHandle } from "./dialect-handle.js";
25
27
  export function defineOpPack(ops) {
26
28
  return ops;
27
29
  }
30
+ // A basename that is only the extension (`.ts`) or whose stem ends in a dot (`a..ts`) names no
31
+ // file of that type, the same as a dotfile such as `.babelrc`.
32
+ function hasDeclaredExtension(path, extensions) {
33
+ const base = basename(path);
34
+ return extensions.some((extension) => {
35
+ const stem = base.slice(0, base.length - extension.length);
36
+ return base.endsWith(extension) && stem.length > 0 && !stem.endsWith(".");
37
+ });
38
+ }
28
39
  /**
29
40
  * Assembles a `Dialect` from its frozen descriptor (extensions, an AST parse/print pair,
30
- * and an op-pack). `find` is the dialect's ONLY entry verb into a run (REQ-DG-01.2) — it
41
+ * and an op-pack). `find` is the dialect's ONLY entry verb into a Session (REQ-DG-01.2) — it
31
42
  * returns an open, coalescing `Handle`.
32
43
  *
33
44
  * @example
@@ -43,6 +54,9 @@ export function defineDialect(d) {
43
54
  ast: d.ast,
44
55
  ops: d.ops,
45
56
  find(path) {
57
+ if (!hasDeclaredExtension(path, d.extensions)) {
58
+ throw dialectError(`find(${JSON.stringify(path)}) — the file's extension is not one this dialect declares (${d.extensions.join(", ")}).`);
59
+ }
46
60
  return createDialectHandle(d.ast, d.ops, path);
47
61
  },
48
62
  };
@@ -110,12 +124,5 @@ function assertNoCompositionCollision(baseOpNames, packs) {
110
124
  export function withOps(base, ...packs) {
111
125
  assertNoCompositionCollision(Object.keys(base.ops), packs);
112
126
  const merged = Object.assign({}, base.ops, ...packs);
113
- return {
114
- extensions: base.extensions,
115
- ast: base.ast,
116
- ops: merged,
117
- find(path) {
118
- return createDialectHandle(base.ast, merged, path);
119
- },
120
- };
127
+ return defineDialect({ extensions: [...base.extensions], ast: base.ast, ops: merged });
121
128
  }
@@ -38,7 +38,7 @@ export function handlePathFor(ast) {
38
38
  }
39
39
  // A getter-backed modify directive: `content` resolves lazily, exactly once, memoized — at
40
40
  // whichever flush first `JSON.stringify`s the batch (ADR-0006's "serialize once at flush").
41
- // `dryRun()` never triggers this: `dryRunPlan` reads only `verb`/`path` (REQ-MC-05).
41
+ // `pendingDirectives()` never triggers this: `renderPendingDirectives` reads only `verb`/`path` (REQ-MC-05).
42
42
  //
43
43
  // Row-145: `resolve` is nulled out immediately after its one use (rather than a separate
44
44
  // `resolved` boolean) — the memoized getter's closure retained the ts-morph `Project` (via
@@ -101,23 +101,23 @@ class DialectHandleController {
101
101
  // `#tail` already skips `guardedStep` via ordinary promise-chain semantics, no flag
102
102
  // needed. The flag exists for the CROSS-handle case: a different handle's `#tail` is
103
103
  // independent, so without this check its step WOULD run (mutate/buffer) even though
104
- // nothing ever commits. `ctx.runFailure` is consulted at step entry (never attempted as a
105
- // fresh operation) and set FIRST-WINS on catch (the earliest rejection in the run is the
104
+ // nothing ever commits. `ctx.sessionFailure` is consulted at step entry (never attempted as a
105
+ // fresh operation) and set FIRST-WINS on catch (the earliest rejection in the Session is the
106
106
  // one every later op/read surfaces, unchanged).
107
107
  #chain(step) {
108
108
  const guardedStep = async () => {
109
109
  const ctx = currentContext();
110
- if (ctx.runFailure !== undefined) {
111
- throw ctx.runFailure.reason;
110
+ if (ctx.sessionFailure !== undefined) {
111
+ throw ctx.sessionFailure.reason;
112
112
  }
113
113
  try {
114
114
  return await step();
115
115
  }
116
116
  catch (err) {
117
- if (ctx.runFailure === undefined) {
118
- ctx.runFailure = { reason: err };
117
+ if (ctx.sessionFailure === undefined) {
118
+ ctx.sessionFailure = { reason: err };
119
119
  }
120
- throw ctx.runFailure.reason;
120
+ throw ctx.sessionFailure.reason;
121
121
  }
122
122
  };
123
123
  const result = this.#tail.then(guardedStep);
@@ -155,7 +155,7 @@ class DialectHandleController {
155
155
  this.#live = this.#dialectAst.parse(content);
156
156
  }
157
157
  catch {
158
- throw dialectError(`could not parse "${this.#path}" as TypeScript`);
158
+ throw dialectError(`could not parse "${this.#path}"`);
159
159
  }
160
160
  astHandlePaths.set(this.#live, this.#path);
161
161
  this.#lastEmittedText = content;
@@ -2,7 +2,7 @@ export type { EngineClient } from "./engine-client.ts";
2
2
  export type { Batch, Directive, JsonValue } from "./wire.ts";
3
3
  export { Session } from "./session.ts";
4
4
  export { DirectiveFactory } from "./directive-factory.ts";
5
- export type { RunContext } from "./context.ts";
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";
@@ -0,0 +1,14 @@
1
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
2
+ [key: string]: JsonValue;
3
+ };
4
+ export type JsonPath = readonly (string | number)[];
5
+ /**
6
+ * Renders a path for a rejection tail, e.g. `["scripts","build"]`. JSON encoding keeps a key
7
+ * containing quotes or newlines on one unambiguous line.
8
+ */
9
+ export declare function formatPath(path: JsonPath): string;
10
+ /**
11
+ * Rejects anything a JSON document cannot hold, before an op touches the document. Types alone
12
+ * do not suffice: `as never`, `any`, and untyped JavaScript factories reach ops unchecked.
13
+ */
14
+ export declare function assertJsonValue(value: unknown, where?: JsonPath, seen?: Set<object>): asserts value is JsonValue;
@@ -0,0 +1,43 @@
1
+ import { dialectError } from "./dialect-error.js";
2
+ /**
3
+ * Renders a path for a rejection tail, e.g. `["scripts","build"]`. JSON encoding keeps a key
4
+ * containing quotes or newlines on one unambiguous line.
5
+ */
6
+ export function formatPath(path) {
7
+ return JSON.stringify(path);
8
+ }
9
+ function isPlainObject(value) {
10
+ const proto = Object.getPrototypeOf(value);
11
+ return proto === Object.prototype || proto === null;
12
+ }
13
+ /**
14
+ * Rejects anything a JSON document cannot hold, before an op touches the document. Types alone
15
+ * do not suffice: `as never`, `any`, and untyped JavaScript factories reach ops unchecked.
16
+ */
17
+ export function assertJsonValue(value, where = [], seen = new Set()) {
18
+ const fail = (what) => {
19
+ throw dialectError(`value at ${formatPath(where)} is ${what}, which JSON cannot represent.`);
20
+ };
21
+ if (value === null || typeof value === "boolean" || typeof value === "string")
22
+ return;
23
+ if (typeof value === "number") {
24
+ if (!Number.isFinite(value))
25
+ fail(String(value));
26
+ return;
27
+ }
28
+ if (typeof value !== "object")
29
+ return fail(typeof value);
30
+ if (seen.has(value))
31
+ fail("a cyclic reference");
32
+ if (!Array.isArray(value) && !isPlainObject(value))
33
+ fail(`a ${value.constructor?.name ?? "non-plain"} instance`);
34
+ seen.add(value);
35
+ if (Array.isArray(value)) {
36
+ value.forEach((item, index) => assertJsonValue(item, [...where, index], seen));
37
+ }
38
+ else {
39
+ for (const [key, item] of Object.entries(value))
40
+ assertJsonValue(item, [...where, key], seen);
41
+ }
42
+ seen.delete(value);
43
+ }
@@ -4,7 +4,7 @@ export declare class Session {
4
4
  #private;
5
5
  constructor(client: EngineClient);
6
6
  buffer(directive: Directive): void;
7
- pendingSnapshot(): readonly Directive[];
7
+ pendingDirectives(): readonly Directive[];
8
8
  isPending(directive: Directive): boolean;
9
9
  read(path: string): Promise<string | undefined>;
10
10
  commit(): Promise<void>;
@@ -17,9 +17,9 @@ export class Session {
17
17
  buffer(directive) {
18
18
  this.#pending.push(directive);
19
19
  }
20
- // SEAM-02 (REQ-03): a defensive copy of the pending buffer for the dry-run renderer.
20
+ // SEAM-02 (REQ-03): a defensive copy of the pending buffer for the pending Directives renderer.
21
21
  // Later mutations to #pending must NOT affect a snapshot taken earlier.
22
- pendingSnapshot() {
22
+ pendingDirectives() {
23
23
  return this.#pending.slice();
24
24
  }
25
25
  // Row-141 kept-half: an identity membership check against the LIVE buffer (no defensive
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The live document a JSON handle edits. `text` is the current source without its UTF-8 BOM
3
+ * (re-added on print). `jsonc-parser` edits text rather than a mutable tree, so named ops
4
+ * replace `text` with format-preserving edits; a `.modify(fn)` callback may do the same with
5
+ * any `jsonc-parser` edit.
6
+ *
7
+ * @example
8
+ * import * as json from "@pbuilder/sdk/json";
9
+ *
10
+ * await json.find("package.json").modify((doc) => {
11
+ * const edits = json.astLibrary.modify(doc.text, ["private"], true, {});
12
+ * doc.text = json.astLibrary.applyEdits(doc.text, edits);
13
+ * });
14
+ */
15
+ export interface JsonDocument {
16
+ text: string;
17
+ }
18
+ /**
19
+ * Wraps `source` in a `JsonDocument`, throwing on any syntax error. Comments and trailing
20
+ * commas are JSONC and allowed; an empty or whitespace/comment-only source is a document with
21
+ * no value, which `setValue` fills.
22
+ */
23
+ export declare function parse(source: string): JsonDocument;
24
+ export declare function print(doc: JsonDocument): string;
@@ -0,0 +1,21 @@
1
+ import { parseTree } from "jsonc-parser";
2
+ const BOM = "";
3
+ const hadBom = new WeakSet();
4
+ /**
5
+ * Wraps `source` in a `JsonDocument`, throwing on any syntax error. Comments and trailing
6
+ * commas are JSONC and allowed; an empty or whitespace/comment-only source is a document with
7
+ * no value, which `setValue` fills.
8
+ */
9
+ export function parse(source) {
10
+ const doc = { text: source.startsWith(BOM) ? source.slice(BOM.length) : source };
11
+ const errors = [];
12
+ parseTree(doc.text, errors, { allowTrailingComma: true, disallowComments: false, allowEmptyContent: true });
13
+ if (errors.length > 0)
14
+ throw new Error("invalid JSON");
15
+ if (source.startsWith(BOM))
16
+ hadBom.add(doc);
17
+ return doc;
18
+ }
19
+ export function print(doc) {
20
+ return hadBom.has(doc) ? BOM + doc.text : doc.text;
21
+ }
@@ -0,0 +1,55 @@
1
+ import { type Handle } from "../../core/define-dialect.ts";
2
+ import type { JsonPath, JsonValue } from "../../core/json-value.ts";
3
+ import { type JsonDocument } from "./ast.ts";
4
+ import { type AppendOptions, type KeyPosition, type SortOptions } from "./ops.ts";
5
+ export * as astLibrary from "jsonc-parser";
6
+ export type { JsonDocument, JsonPath, JsonValue, KeyPosition, AppendOptions, SortOptions };
7
+ type JsonOps = {
8
+ setValue: (ast: JsonDocument, path: JsonPath, value: JsonValue, options?: KeyPosition) => void;
9
+ addKey: (ast: JsonDocument, path: JsonPath, value: JsonValue, options?: KeyPosition) => void;
10
+ removeKey: (ast: JsonDocument, path: JsonPath) => void;
11
+ renameKey: (ast: JsonDocument, path: JsonPath, newKey: string) => void;
12
+ insertItem: (ast: JsonDocument, path: JsonPath, index: number, value: JsonValue) => void;
13
+ appendItem: (ast: JsonDocument, path: JsonPath, value: JsonValue, options?: AppendOptions) => void;
14
+ removeItem: (ast: JsonDocument, path: JsonPath, index: number) => void;
15
+ removeValue: (ast: JsonDocument, path: JsonPath, value: JsonValue) => void;
16
+ replaceItem: (ast: JsonDocument, path: JsonPath, index: number, value: JsonValue) => void;
17
+ moveItem: (ast: JsonDocument, path: JsonPath, from: number, to: number) => void;
18
+ merge: (ast: JsonDocument, path: JsonPath, value: {
19
+ [key: string]: JsonValue;
20
+ }) => void;
21
+ updateValue: <T extends JsonValue>(ast: JsonDocument, path: JsonPath, fn: (current: JsonValue | undefined) => T) => void;
22
+ moveValue: (ast: JsonDocument, from: JsonPath, to: JsonPath) => void;
23
+ copyValue: (ast: JsonDocument, from: JsonPath, to: JsonPath) => void;
24
+ sortKeys: (ast: JsonDocument, path: JsonPath, options?: SortOptions) => void;
25
+ };
26
+ /**
27
+ * Opens a `.json` or `.jsonc` file for structural editing. Every op addresses a value by a
28
+ * path array (`["scripts", "build"]`, `["files", 0]`) and edits only the bytes it must:
29
+ * comments, key order, indentation, line endings, a BOM, and the trailing newline survive.
30
+ * Any other extension, a basename with no stem (`.json`), or an extensionless path throws
31
+ * synchronously with the `dialect operation failed: ` prefix. `.modify(fn)` hands `fn` the
32
+ * live `JsonDocument`; edit its `text` with `astLibrary` (`jsonc-parser`) for anything the
33
+ * ops do not cover, such as comments.
34
+ *
35
+ * @example
36
+ * import * as json from "@pbuilder/sdk/json";
37
+ *
38
+ * // package.json before: {\n "name": "app"\n}\n
39
+ * export const run = async () => {
40
+ * await json
41
+ * .find("package.json")
42
+ * .setValue(["scripts", "build"], "tsc")
43
+ * .appendItem(["files"], "dist", { unique: true });
44
+ * };
45
+ * // -> {
46
+ * // -> "name": "app",
47
+ * // -> "scripts": {
48
+ * // -> "build": "tsc"
49
+ * // -> },
50
+ * // -> "files": [
51
+ * // -> "dist"
52
+ * // -> ]
53
+ * // -> }
54
+ */
55
+ export declare function find(path: string): Handle<"found", JsonDocument, JsonOps>;
@@ -0,0 +1,54 @@
1
+ import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.js";
2
+ import { parse, print } from "./ast.js";
3
+ import { addKey, appendItem, copyValue, insertItem, merge, moveItem, moveValue, removeItem, removeKey, removeValue, renameKey, replaceItem, setValue, sortKeys, updateValue, } from "./ops.js";
4
+ export * as astLibrary from "jsonc-parser";
5
+ const opsPack = defineOpPack({
6
+ setValue,
7
+ addKey,
8
+ removeKey,
9
+ renameKey,
10
+ insertItem,
11
+ appendItem,
12
+ removeItem,
13
+ removeValue,
14
+ replaceItem,
15
+ moveItem,
16
+ merge,
17
+ updateValue,
18
+ moveValue,
19
+ copyValue,
20
+ sortKeys,
21
+ });
22
+ const jsonDialect = withOps(defineDialect({ extensions: [".json", ".jsonc"], ast: { parse, print }, ops: {} }), opsPack);
23
+ /**
24
+ * Opens a `.json` or `.jsonc` file for structural editing. Every op addresses a value by a
25
+ * path array (`["scripts", "build"]`, `["files", 0]`) and edits only the bytes it must:
26
+ * comments, key order, indentation, line endings, a BOM, and the trailing newline survive.
27
+ * Any other extension, a basename with no stem (`.json`), or an extensionless path throws
28
+ * synchronously with the `dialect operation failed: ` prefix. `.modify(fn)` hands `fn` the
29
+ * live `JsonDocument`; edit its `text` with `astLibrary` (`jsonc-parser`) for anything the
30
+ * ops do not cover, such as comments.
31
+ *
32
+ * @example
33
+ * import * as json from "@pbuilder/sdk/json";
34
+ *
35
+ * // package.json before: {\n "name": "app"\n}\n
36
+ * export const run = async () => {
37
+ * await json
38
+ * .find("package.json")
39
+ * .setValue(["scripts", "build"], "tsc")
40
+ * .appendItem(["files"], "dist", { unique: true });
41
+ * };
42
+ * // -> {
43
+ * // -> "name": "app",
44
+ * // -> "scripts": {
45
+ * // -> "build": "tsc"
46
+ * // -> },
47
+ * // -> "files": [
48
+ * // -> "dist"
49
+ * // -> ]
50
+ * // -> }
51
+ */
52
+ export function find(path) {
53
+ return jsonDialect.find(path);
54
+ }
@@ -0,0 +1,46 @@
1
+ import { type JsonPath, type JsonValue } from "../../core/json-value.ts";
2
+ import type { JsonDocument } from "./ast.ts";
3
+ export interface KeyPosition {
4
+ before?: string;
5
+ after?: string;
6
+ }
7
+ export interface AppendOptions {
8
+ unique?: boolean;
9
+ }
10
+ export interface SortOptions {
11
+ recursive?: boolean;
12
+ }
13
+ type JsonObject = {
14
+ [key: string]: JsonValue;
15
+ };
16
+ /** Sets the value at `path`, creating missing parent objects (upsert). */
17
+ export declare function setValue(doc: JsonDocument, path: JsonPath, value: JsonValue, options?: KeyPosition): void;
18
+ /** Adds an absent object key; a deep-equal existing value is a no-op, a different one rejects. */
19
+ export declare function addKey(doc: JsonDocument, path: JsonPath, value: JsonValue, options?: KeyPosition): void;
20
+ /** Removes an object key and its separator; an absent key is a no-op. */
21
+ export declare function removeKey(doc: JsonDocument, path: JsonPath): void;
22
+ /** Renames an object key in place, keeping its value, position, and comments. */
23
+ export declare function renameKey(doc: JsonDocument, path: JsonPath, newKey: string): void;
24
+ /** Inserts `value` before the item at `index`; `index === length` appends. */
25
+ export declare function insertItem(doc: JsonDocument, path: JsonPath, index: number, value: JsonValue): void;
26
+ /** Appends `value`, creating the array when absent; `{ unique: true }` skips a deep-equal duplicate. */
27
+ export declare function appendItem(doc: JsonDocument, path: JsonPath, value: JsonValue, options?: AppendOptions): void;
28
+ /** Removes the item at `index` and its separator. */
29
+ export declare function removeItem(doc: JsonDocument, path: JsonPath, index: number): void;
30
+ /** Removes every item deep-equal to `value`; no match (or no array) is a no-op. */
31
+ export declare function removeValue(doc: JsonDocument, path: JsonPath, value: JsonValue): void;
32
+ /** Replaces the item at `index` in place. */
33
+ export declare function replaceItem(doc: JsonDocument, path: JsonPath, index: number, value: JsonValue): void;
34
+ /** Moves the item at `from` so it ends up at `to`; the other items keep their relative order. */
35
+ export declare function moveItem(doc: JsonDocument, path: JsonPath, from: number, to: number): void;
36
+ /** Deep-merges a plain object into the object at `path`; arrays and scalars are replaced. */
37
+ export declare function merge(doc: JsonDocument, path: JsonPath, value: JsonObject): void;
38
+ /** Replaces the value at `path` with `fn(current)`; `current` is `undefined` when absent. */
39
+ export declare function updateValue<T extends JsonValue>(doc: JsonDocument, path: JsonPath, fn: (current: JsonValue | undefined) => T): void;
40
+ /** Moves the value at `from` to `to` (RFC 6902 `move`); a `number` last segment in `to` inserts. */
41
+ export declare function moveValue(doc: JsonDocument, from: JsonPath, to: JsonPath): void;
42
+ /** Copies the value at `from` to `to` with `setValue`'s rules (RFC 6902 `copy`). */
43
+ export declare function copyValue(doc: JsonDocument, from: JsonPath, to: JsonPath): void;
44
+ /** Orders the object's members by key (code-point order); `{ recursive: true }` sorts nested objects too. */
45
+ export declare function sortKeys(doc: JsonDocument, path: JsonPath, options?: SortOptions): void;
46
+ export {};