@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.
Files changed (121) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +202 -0
  3. package/dist/bin/pbuilder-codegen.js +506 -0
  4. package/dist/bin/pbuilder-runner.d.ts +1 -0
  5. package/dist/bin/pbuilder-runner.js +47 -0
  6. package/dist/commons/classify-content.d.ts +40 -0
  7. package/dist/commons/classify-content.js +32 -0
  8. package/dist/commons/index.d.ts +271 -0
  9. package/dist/commons/index.js +276 -0
  10. package/dist/conformance/index.d.ts +115 -0
  11. package/dist/conformance/index.js +218 -0
  12. package/dist/conformance/run-vehicle.d.ts +19 -0
  13. package/dist/conformance/run-vehicle.js +104 -0
  14. package/dist/core/authoring-error.d.ts +116 -0
  15. package/dist/core/authoring-error.js +205 -0
  16. package/dist/core/base-handle.d.ts +17 -0
  17. package/dist/core/base-handle.js +4 -0
  18. package/dist/core/context.d.ts +85 -0
  19. package/dist/core/context.js +356 -0
  20. package/dist/core/deep-equal.d.ts +1 -0
  21. package/dist/core/deep-equal.js +29 -0
  22. package/dist/core/define-dialect.d.ts +94 -0
  23. package/dist/core/define-dialect.js +121 -0
  24. package/dist/core/dialect-error.d.ts +8 -0
  25. package/dist/core/dialect-error.js +26 -0
  26. package/dist/core/dialect-handle.d.ts +21 -0
  27. package/dist/core/dialect-handle.js +382 -0
  28. package/dist/core/directive-factory.d.ts +47 -0
  29. package/dist/core/directive-factory.js +154 -0
  30. package/dist/core/emit-rejection.d.ts +19 -0
  31. package/dist/core/emit-rejection.js +31 -0
  32. package/dist/core/engine-client.d.ts +7 -0
  33. package/dist/core/engine-client.js +5 -0
  34. package/dist/core/fs-errors.d.ts +1 -0
  35. package/dist/core/fs-errors.js +5 -0
  36. package/dist/core/handle-state.d.ts +24 -0
  37. package/dist/core/handle-state.js +4 -0
  38. package/dist/core/index.d.ts +10 -0
  39. package/dist/core/index.js +6 -0
  40. package/dist/core/jsx-name-validator.d.ts +19 -0
  41. package/dist/core/jsx-name-validator.js +104 -0
  42. package/dist/core/reject-tail.d.ts +23 -0
  43. package/dist/core/reject-tail.js +63 -0
  44. package/dist/core/schema/input-rejection.d.ts +4 -0
  45. package/dist/core/schema/input-rejection.js +32 -0
  46. package/dist/core/schema/schema-digest.d.ts +1 -0
  47. package/dist/core/schema/schema-digest.js +7 -0
  48. package/dist/core/schema/schema-discovery.d.ts +13 -0
  49. package/dist/core/schema/schema-discovery.js +51 -0
  50. package/dist/core/schema/schema-locate.d.ts +10 -0
  51. package/dist/core/schema/schema-locate.js +192 -0
  52. package/dist/core/schema/schema-model.d.ts +18 -0
  53. package/dist/core/schema/schema-model.js +15 -0
  54. package/dist/core/schema/schema-parse.d.ts +20 -0
  55. package/dist/core/schema/schema-parse.js +80 -0
  56. package/dist/core/schema/schema-sufficiency.d.ts +17 -0
  57. package/dist/core/schema/schema-sufficiency.js +54 -0
  58. package/dist/core/schema/schema-validate.d.ts +14 -0
  59. package/dist/core/schema/schema-validate.js +64 -0
  60. package/dist/core/session.d.ts +13 -0
  61. package/dist/core/session.js +72 -0
  62. package/dist/core/wire.d.ts +87 -0
  63. package/dist/core/wire.js +49 -0
  64. package/dist/dialects/react/ast.d.ts +25 -0
  65. package/dist/dialects/react/ast.js +80 -0
  66. package/dist/dialects/react/index.d.ts +39 -0
  67. package/dist/dialects/react/index.js +71 -0
  68. package/dist/dialects/react/ops.d.ts +56 -0
  69. package/dist/dialects/react/ops.js +186 -0
  70. package/dist/dialects/typescript/ast.d.ts +42 -0
  71. package/dist/dialects/typescript/ast.js +93 -0
  72. package/dist/dialects/typescript/index.d.ts +32 -0
  73. package/dist/dialects/typescript/index.js +40 -0
  74. package/dist/dialects/typescript/ops.d.ts +123 -0
  75. package/dist/dialects/typescript/ops.js +365 -0
  76. package/dist/dry-run/index.d.ts +2 -0
  77. package/dist/dry-run/index.js +1 -0
  78. package/dist/dry-run/plan.d.ts +69 -0
  79. package/dist/dry-run/plan.js +44 -0
  80. package/dist/index.d.ts +1 -0
  81. package/dist/index.js +3 -0
  82. package/dist/runner-manifest.json +104 -0
  83. package/dist/scaffold/classify-transport.d.ts +57 -0
  84. package/dist/scaffold/classify-transport.js +123 -0
  85. package/dist/scaffold/containment.d.ts +54 -0
  86. package/dist/scaffold/containment.js +242 -0
  87. package/dist/scaffold/expander.d.ts +30 -0
  88. package/dist/scaffold/expander.js +161 -0
  89. package/dist/scaffold/filename-pipeline.d.ts +39 -0
  90. package/dist/scaffold/filename-pipeline.js +125 -0
  91. package/dist/scaffold/index.d.ts +45 -0
  92. package/dist/scaffold/index.js +99 -0
  93. package/dist/scaffold/walk.d.ts +25 -0
  94. package/dist/scaffold/walk.js +124 -0
  95. package/dist/testing/contract-fake.d.ts +17 -0
  96. package/dist/testing/contract-fake.js +221 -0
  97. package/dist/testing/index.d.ts +84 -0
  98. package/dist/testing/index.js +82 -0
  99. package/dist/testing/rejection-messages.d.ts +7 -0
  100. package/dist/testing/rejection-messages.js +12 -0
  101. package/dist/transport/bootstrap-bridge.d.ts +33 -0
  102. package/dist/transport/bootstrap-bridge.js +65 -0
  103. package/dist/transport/error-text.d.ts +8 -0
  104. package/dist/transport/error-text.js +44 -0
  105. package/dist/transport/exit-codes.d.ts +2 -0
  106. package/dist/transport/exit-codes.js +35 -0
  107. package/dist/transport/factory-pointer.d.ts +32 -0
  108. package/dist/transport/factory-pointer.js +63 -0
  109. package/dist/transport/frame-reader.d.ts +10 -0
  110. package/dist/transport/frame-reader.js +81 -0
  111. package/dist/transport/framing.d.ts +20 -0
  112. package/dist/transport/framing.js +98 -0
  113. package/dist/transport/runner.d.ts +25 -0
  114. package/dist/transport/runner.js +308 -0
  115. package/dist/transport/single-instance-probe.d.ts +23 -0
  116. package/dist/transport/single-instance-probe.js +119 -0
  117. package/dist/transport/stdio-engine-client.d.ts +27 -0
  118. package/dist/transport/stdio-engine-client.js +243 -0
  119. package/dist/transport/wire-protocol.d.ts +33 -0
  120. package/dist/transport/wire-protocol.js +22 -0
  121. package/package.json +93 -0
@@ -0,0 +1,30 @@
1
+ import type { JsonValue } from "../core/wire.ts";
2
+ /**
3
+ * Argument shape for the `scaffold` author verb (REQ-FSC-01). `from`/`to` are mandatory;
4
+ * every other field defaults per REQ-FSC-01: `options` → `{}`, `include` → match
5
+ * everything, `exclude` → match nothing, `rename` → no remap, `force` → `false`.
6
+ */
7
+ export interface ScaffoldArgs {
8
+ from: string;
9
+ to: string;
10
+ options?: JsonValue;
11
+ include?: string[];
12
+ exclude?: string[];
13
+ rename?: Record<string, string>;
14
+ force?: boolean;
15
+ }
16
+ /**
17
+ * Walks a package-local folder and mirrors it into the target tree (REQ-FSC-01..09):
18
+ * every source-relative path enumerates (REQ-FSC-09), passes include/exclude filtering
19
+ * (REQ-FSC-03), runs the rename→token→`.template`-strip pipeline (REQ-FSC-05), and is
20
+ * checked for intra-scaffold destination collisions (REQ-FSC-08) BEFORE any file is
21
+ * classified. Each surviving source classifies by-value or by-reference
22
+ * (`content-classification`); by-value sources emit a `create` directive through the
23
+ * existing IR. A truly-empty `from` folder no-ops (REQ-FSC-04.1); filters eliminating
24
+ * every entry fail loud, naming them (REQ-FSC-04.2). `force` passes through unchanged to
25
+ * every emitted directive (REQ-FSC-06). The destination lexical guard (REQ-PRC-09) applies
26
+ * to the FINAL computed destination, immediately pre-emit. Aggregate size never blocks the
27
+ * scaffold outright (REQ-04) — the expander chunks via mid-run `session.flush()` calls
28
+ * (see the module header for the sync/async bridge); run-level atomicity (REQ-05) is free.
29
+ */
30
+ export declare function runScaffold(args: ScaffoldArgs): void;
@@ -0,0 +1,161 @@
1
+ // src/scaffold/expander.ts (ADR-0044): the SINGLE owner of the scaffold fan-out — drives
2
+ // `walk.ts` → `filename-pipeline.ts` → `classify-transport.ts` → emits `factory.create(...)`/
3
+ // `factory.copyIn(...)` directives via the run's session (Executor Context §18).
4
+ // `classify-transport.ts` stays a PURE per-file decision; a by-reference VERDICT is handled
5
+ // HERE, not there. S-003: the by-reference verdict now emits a real `copyIn` directive
6
+ // (`from` package-relative, REQ-BRC-07) instead of S-001/S-002's fail-loud placeholder throw.
7
+ //
8
+ // S-004 (batch-cap chunked flush, REQ-04/05): the expander maintains a serialized-size
9
+ // accumulator over the CURRENT `session` pending buffer and calls `session.flush()`
10
+ // BETWEEN groups when the next directive would push the pending batch's serialized form
11
+ // over `BATCH_CAP_BYTES` — the SDK never rejects on aggregate size (ADR-0018 amendment);
12
+ // an over-cap SINGLE group still rejects at the fake's `emit` unchanged (REQ-04.2).
13
+ //
14
+ // `scaffold(): void` is a PINNED synchronous author surface (design §Data Model, T2), yet
15
+ // `Session.flush()` is `async` and `session.ts` is READ-ONLY for this change (design §A4)
16
+ // — no synchronous flush variant may be added. The bridge is the EXISTING `DialectRegistry`
17
+ // (`context.ts`, ADR-0037), documented as generic over "anything with a `settle()`": a
18
+ // mid-run `session.flush()` call is fired here WITHOUT awaiting (its synchronous prefix —
19
+ // draining `#pending`, building the batch, and the fake's entirely-synchronous `#apply`
20
+ // loop — still runs to completion before `flush()`'s own `await` suspends it, so the
21
+ // `#tree` mutation for this group happens in-order, synchronously, before the next group
22
+ // starts buffering) and REGISTERED as a dialect handle. `defineFactory` already awaits
23
+ // `ctx.dialects.drain()` BEFORE its own run-end `session.flush()` (which covers the final,
24
+ // still-pending group) and BEFORE `commit()` — so a later-chunk rejection surfaces through
25
+ // `drain()`, routes to `defineFactory`'s existing catch, and `discard()` clears the SAME
26
+ // underlying `#tree` every chunk staged into: run-level all-or-nothing (REQ-05) holds with
27
+ // NO new atomicity mechanism, exactly as the design promises.
28
+ import { posix, join } from "node:path";
29
+ import { currentContext, requirePackageAnchors } from "../core/context.js";
30
+ import { invalidInput } from "../core/authoring-error.js";
31
+ import { forceEntry } from "../core/directive-factory.js";
32
+ import { EMIT_BATCH_BUDGET_BYTES, serializedBatchSize } from "../core/wire.js";
33
+ import { walkFolder } from "./walk.js";
34
+ import { runFilenamePipeline, isIncluded, detectDestinationCollisions, translateTokens } from "./filename-pipeline.js";
35
+ import { classifyTransport } from "./classify-transport.js";
36
+ import { validateDestinationLexical, validateSourceRootContainment, resolveRealCeiling } from "./containment.js";
37
+ function noResolutionAnchorMessage() {
38
+ return ("invalid input: scaffold has no package directory to resolve package-local files against — " +
39
+ "pass `packageDir` to the call that runs this factory");
40
+ }
41
+ function missingArgMessage(field) {
42
+ return `invalid input: scaffold requires "${field}"`;
43
+ }
44
+ function filtersEliminatedEverythingMessage(include, exclude) {
45
+ return (`invalid input: scaffold filters eliminated every entry — ` +
46
+ `include: ${JSON.stringify(include ?? [])}, exclude: ${JSON.stringify(exclude ?? [])}`);
47
+ }
48
+ // REQ-04's serialized-size heuristic (S-004): tracks what the PENDING batch would
49
+ // serialize to via `serializedBatchSize`'s envelope shape — the EXACT same measurement the
50
+ // fake applies at emit time — a lowering heuristic, not a second size authority (ADR-0018
51
+ // amendment); the fake's own `emit` cap check remains the sole judge (ADR-0019).
52
+ const EMPTY_BATCH_SIZE = serializedBatchSize([]);
53
+ /**
54
+ * Walks a package-local folder and mirrors it into the target tree (REQ-FSC-01..09):
55
+ * every source-relative path enumerates (REQ-FSC-09), passes include/exclude filtering
56
+ * (REQ-FSC-03), runs the rename→token→`.template`-strip pipeline (REQ-FSC-05), and is
57
+ * checked for intra-scaffold destination collisions (REQ-FSC-08) BEFORE any file is
58
+ * classified. Each surviving source classifies by-value or by-reference
59
+ * (`content-classification`); by-value sources emit a `create` directive through the
60
+ * existing IR. A truly-empty `from` folder no-ops (REQ-FSC-04.1); filters eliminating
61
+ * every entry fail loud, naming them (REQ-FSC-04.2). `force` passes through unchanged to
62
+ * every emitted directive (REQ-FSC-06). The destination lexical guard (REQ-PRC-09) applies
63
+ * to the FINAL computed destination, immediately pre-emit. Aggregate size never blocks the
64
+ * scaffold outright (REQ-04) — the expander chunks via mid-run `session.flush()` calls
65
+ * (see the module header for the sync/async bridge); run-level atomicity (REQ-05) is free.
66
+ */
67
+ export function runScaffold(args) {
68
+ if (args.from === undefined) {
69
+ throw invalidInput(missingArgMessage("from"));
70
+ }
71
+ if (args.to === undefined) {
72
+ throw invalidInput(missingArgMessage("to"));
73
+ }
74
+ const ctx = currentContext();
75
+ const { session, factory } = ctx;
76
+ const { packageDir, packageRoot } = requirePackageAnchors(noResolutionAnchorMessage());
77
+ // The ceiling's realpath is a RUN invariant (not one of the pinned per-candidate
78
+ // validation steps) — resolve it once for both the root check below and the whole
79
+ // entry loop.
80
+ const realCeiling = resolveRealCeiling(packageRoot);
81
+ // SEC (owner-ratified final-verify remediation): the walk ROOT itself must be
82
+ // containment-checked BEFORE `walkFolder` ever enumerates it — otherwise an escaping
83
+ // `from` (e.g. `../secrets`) would readdirSync/lstatSync the whole out-of-ceiling
84
+ // subtree (bounded by `walk.ts`'s 10k-entry cap) before any per-entry containment
85
+ // check had a chance to fire. Reuses the SAME lexical + realpath ceiling machinery the
86
+ // per-entry loop below already uses via `classifyTransport` → `validateSourceContainment`
87
+ // — no parallel check forked for this directory case.
88
+ validateSourceRootContainment({ packageDir, packageRoot, relPath: args.from, realCeiling });
89
+ const fromAbs = join(packageDir, args.from);
90
+ const walked = walkFolder(fromAbs, undefined, args.from);
91
+ if (walked.length === 0) {
92
+ return; // REQ-FSC-04.1: a truly-empty source folder is a silent no-op.
93
+ }
94
+ const filtered = walked.filter((entry) => isIncluded(entry.relPath, args.include, args.exclude));
95
+ if (filtered.length === 0) {
96
+ throw invalidInput(filtersEliminatedEverythingMessage(args.include, args.exclude));
97
+ }
98
+ const pipelineResults = filtered.map((entry) => runFilenamePipeline(entry.relPath, args.rename));
99
+ detectDestinationCollisions(pipelineResults);
100
+ const toPrefix = translateTokens(args.to);
101
+ // Running serialized-size counter over the CURRENT pending buffer — seeded from the real
102
+ // snapshot (directives buffered BEFORE this scaffold call count toward the first group)
103
+ // and maintained incrementally. Byte-identical to re-serializing the whole batch per
104
+ // append: JSON array bytes are additive — each extra element contributes exactly its own
105
+ // `JSON.stringify` bytes plus one comma when it is not the first.
106
+ const seedPending = session.pendingSnapshot();
107
+ let pendingCount = seedPending.length;
108
+ let pendingSize = serializedBatchSize(seedPending);
109
+ for (const result of pipelineResults) {
110
+ const sourceRelPath = posix.join(args.from, result.sourceRelPath);
111
+ // destPath computed BEFORE classify (reordered from the source-only call this
112
+ // replaces): REQ-CCL-02's budget is evaluated against the PROSPECTIVE `create`
113
+ // directive this source would emit, so classifyTransport needs the same
114
+ // pathTemplate/options/force this loop will put on that directive below.
115
+ const destPath = posix.join(toPrefix, result.destRelPath);
116
+ const verdict = classifyTransport({
117
+ packageDir,
118
+ packageRoot,
119
+ relPath: sourceRelPath,
120
+ isTemplateMarked: result.isTemplateMarked,
121
+ realCeiling,
122
+ destPath,
123
+ options: args.options ?? {},
124
+ force: args.force,
125
+ });
126
+ validateDestinationLexical(destPath);
127
+ // S-003: a by-reference verdict emits a real `copyIn` directive — `from` is the
128
+ // package-relative source path (REQ-BRC-07), never the resolved absolute path;
129
+ // containment already validated this source inside `classifyTransport`
130
+ // (`validateSourceContainment` runs BEFORE the stat/sniff/budget gates, REQ-PRC-08),
131
+ // so no second containment check is needed here.
132
+ const directive = verdict.verdict === "by-value"
133
+ ? factory.create({
134
+ pathTemplate: destPath,
135
+ template: verdict.content,
136
+ options: args.options ?? {},
137
+ ...forceEntry(args.force),
138
+ })
139
+ : factory.copyIn({
140
+ from: sourceRelPath,
141
+ to: destPath,
142
+ ...forceEntry(args.force),
143
+ });
144
+ // REQ-04: if adding this directive to the CURRENTLY pending (not-yet-flushed) group
145
+ // would push its serialized batch over the emit budget (`EMIT_BATCH_BUDGET_BYTES` —
146
+ // the SAME boundary the emit authority enforces, spec V4 REQ-WPS-04.1), flush the
147
+ // existing group first — never preemptively when the pending buffer is empty (an
148
+ // over-budget SINGLE directive still flushes as its own group and rejects at the
149
+ // fake's `emit`, unchanged REQ-04.2).
150
+ const directiveSize = Buffer.byteLength(JSON.stringify(directive), "utf8");
151
+ if (pendingCount > 0 && pendingSize + directiveSize + 1 > EMIT_BATCH_BUDGET_BYTES) {
152
+ const flushPromise = session.flush();
153
+ ctx.dialects.register({ settle: () => flushPromise });
154
+ pendingCount = 0;
155
+ pendingSize = EMPTY_BATCH_SIZE;
156
+ }
157
+ session.buffer(directive);
158
+ pendingCount += 1;
159
+ pendingSize += directiveSize + (pendingCount > 1 ? 1 : 0);
160
+ }
161
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Translates on-disk filename tokens to the wire `pathTemplate` syntax the ENGINE
3
+ * substitutes (obs #915 ruling 4) — the SDK never renders these itself, only rewrites the
4
+ * marker syntax. `__name@dasherize__` → `{= name | dasherize =}`; a bare `__name__`
5
+ * (no `@pipe`) → `{= name =}`.
6
+ */
7
+ export declare function translateTokens(path: string): string;
8
+ /** REQ-FSC-05 step (3): strips a `.template` suffix from the (post-translation) path. */
9
+ export declare function stripTemplateSuffix(path: string): {
10
+ stripped: string;
11
+ wasTemplate: boolean;
12
+ };
13
+ export interface PipelineResult {
14
+ /** The original, unmodified source-relative path (used for classification + naming). */
15
+ sourceRelPath: string;
16
+ /** The final destination-relative path, post rename/token/strip — NOT prefixed by `to`. */
17
+ destRelPath: string;
18
+ /** Whether the (post-translation) path carried the `.template` render-request marker. */
19
+ isTemplateMarked: boolean;
20
+ }
21
+ /**
22
+ * Applies the PINNED REQ-FSC-05 order to one source-relative path: (1) `rename` — matched
23
+ * against the ORIGINAL path (so authors never predict token-translated names); (2) filename
24
+ * token translation on the (possibly renamed) path; (3) `.template` suffix strip, last
25
+ * (the marker must survive translation to be recognized).
26
+ */
27
+ export declare function runFilenamePipeline(relPath: string, rename: Record<string, string> | undefined): PipelineResult;
28
+ /**
29
+ * REQ-FSC-03: include/exclude filtering — `exclude` WINS on overlap with `include`.
30
+ * Default `include` matches everything (`["**"]`); default `exclude` matches nothing.
31
+ */
32
+ export declare function isIncluded(relPath: string, include: readonly string[] | undefined, exclude: readonly string[] | undefined): boolean;
33
+ /**
34
+ * REQ-FSC-08: when two or more sources in the same `scaffold` call map to the SAME
35
+ * destination (after the filename pipeline collapses their names), reject fail-loud,
36
+ * deterministically, naming ALL offending source paths — never last-writer-wins, never
37
+ * dependent on walk order.
38
+ */
39
+ export declare function detectDestinationCollisions(results: readonly PipelineResult[]): void;
@@ -0,0 +1,125 @@
1
+ // src/scaffold/filename-pipeline.ts (ADR-0044): the pure per-source-path pipeline —
2
+ // rename (matches the ORIGINAL source-relative path) → filename token translation
3
+ // (`__x__` → `{= x =}` in the wire pathTemplate) → `.template` suffix strip, in that PINNED
4
+ // order (REQ-FSC-05). Also owns include/exclude glob filtering (REQ-FSC-03, hand-rolled —
5
+ // the repo carries no glob library and none may be added) and intra-scaffold
6
+ // destination-collision detection (REQ-FSC-08). Zero I/O — pure string transforms over
7
+ // already-enumerated `walk.ts` entries.
8
+ import { invalidInput } from "../core/authoring-error.js";
9
+ const TEMPLATE_SUFFIX = ".template";
10
+ const TOKEN_PATTERN = /__([A-Za-z_][A-Za-z0-9_]*(?:@[A-Za-z_][A-Za-z0-9_]*)*)__/g;
11
+ /**
12
+ * Translates on-disk filename tokens to the wire `pathTemplate` syntax the ENGINE
13
+ * substitutes (obs #915 ruling 4) — the SDK never renders these itself, only rewrites the
14
+ * marker syntax. `__name@dasherize__` → `{= name | dasherize =}`; a bare `__name__`
15
+ * (no `@pipe`) → `{= name =}`.
16
+ */
17
+ export function translateTokens(path) {
18
+ return path.replace(TOKEN_PATTERN, (_match, inner) => {
19
+ const [field, ...pipes] = inner.split("@");
20
+ return pipes.length > 0 ? `{= ${field} | ${pipes.join(" | ")} =}` : `{= ${field} =}`;
21
+ });
22
+ }
23
+ /** REQ-FSC-05 step (3): strips a `.template` suffix from the (post-translation) path. */
24
+ export function stripTemplateSuffix(path) {
25
+ if (path.endsWith(TEMPLATE_SUFFIX)) {
26
+ return { stripped: path.slice(0, -TEMPLATE_SUFFIX.length), wasTemplate: true };
27
+ }
28
+ return { stripped: path, wasTemplate: false };
29
+ }
30
+ /**
31
+ * Applies the PINNED REQ-FSC-05 order to one source-relative path: (1) `rename` — matched
32
+ * against the ORIGINAL path (so authors never predict token-translated names); (2) filename
33
+ * token translation on the (possibly renamed) path; (3) `.template` suffix strip, last
34
+ * (the marker must survive translation to be recognized).
35
+ */
36
+ export function runFilenamePipeline(relPath, rename) {
37
+ const renamed = rename?.[relPath] ?? relPath;
38
+ const translated = translateTokens(renamed);
39
+ const { stripped, wasTemplate } = stripTemplateSuffix(translated);
40
+ return { sourceRelPath: relPath, destRelPath: stripped, isTemplateMarked: wasTemplate };
41
+ }
42
+ function escapeRegexChar(ch) {
43
+ return /[.+^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
44
+ }
45
+ /**
46
+ * Compiles ONE glob pattern (REQ-FSC-03's hand-rolled MVP dialect) into a regex matched
47
+ * against a source-relative path: `*` = any run of characters WITHIN a segment (never
48
+ * crosses `/`); `**` = any run of segments (zero or more), consuming its trailing `/` when
49
+ * one follows — so a leading `**` combined with a following segment pattern also matches a
50
+ * ROOT-level file (zero segments consumed), not only nested ones.
51
+ */
52
+ // Compiled-pattern memo: `isIncluded` runs per walked entry with the SAME include/exclude
53
+ // pattern strings — no flags on the compiled regex, so a cached instance is stateless.
54
+ const globRegexCache = new Map();
55
+ function globToRegex(pattern) {
56
+ const cached = globRegexCache.get(pattern);
57
+ if (cached !== undefined) {
58
+ return cached;
59
+ }
60
+ let out = "";
61
+ let i = 0;
62
+ while (i < pattern.length) {
63
+ if (pattern.startsWith("**", i)) {
64
+ if (pattern[i + 2] === "/") {
65
+ out += "(?:.*/)?";
66
+ i += 3;
67
+ }
68
+ else {
69
+ out += ".*";
70
+ i += 2;
71
+ }
72
+ }
73
+ else if (pattern[i] === "*") {
74
+ out += "[^/]*";
75
+ i += 1;
76
+ }
77
+ else {
78
+ out += escapeRegexChar(pattern[i]);
79
+ i += 1;
80
+ }
81
+ }
82
+ const compiled = new RegExp(`^${out}$`);
83
+ globRegexCache.set(pattern, compiled);
84
+ return compiled;
85
+ }
86
+ /**
87
+ * REQ-FSC-03: include/exclude filtering — `exclude` WINS on overlap with `include`.
88
+ * Default `include` matches everything (`["**"]`); default `exclude` matches nothing.
89
+ */
90
+ export function isIncluded(relPath, include, exclude) {
91
+ const includePatterns = include ?? ["**"];
92
+ const excludePatterns = exclude ?? [];
93
+ if (excludePatterns.some((p) => globToRegex(p).test(relPath)))
94
+ return false;
95
+ return includePatterns.some((p) => globToRegex(p).test(relPath));
96
+ }
97
+ function collisionMessage(collisions) {
98
+ const parts = collisions.map(([dest, srcs]) => `"${dest}" ← ${srcs.join(", ")}`);
99
+ return `invalid input: scaffold destination collision — ${parts.join("; ")}`;
100
+ }
101
+ /**
102
+ * REQ-FSC-08: when two or more sources in the same `scaffold` call map to the SAME
103
+ * destination (after the filename pipeline collapses their names), reject fail-loud,
104
+ * deterministically, naming ALL offending source paths — never last-writer-wins, never
105
+ * dependent on walk order.
106
+ */
107
+ export function detectDestinationCollisions(results) {
108
+ const byDest = new Map();
109
+ for (const r of results) {
110
+ const existing = byDest.get(r.destRelPath);
111
+ if (existing) {
112
+ existing.push(r.sourceRelPath);
113
+ }
114
+ else {
115
+ byDest.set(r.destRelPath, [r.sourceRelPath]);
116
+ }
117
+ }
118
+ const collisions = [...byDest.entries()]
119
+ .filter(([, srcs]) => srcs.length > 1)
120
+ .map((entry) => [entry[0], entry[1].slice().sort()])
121
+ .sort((a, b) => a[0].localeCompare(b[0]));
122
+ if (collisions.length > 0) {
123
+ throw invalidInput(collisionMessage(collisions));
124
+ }
125
+ }
@@ -0,0 +1,45 @@
1
+ import type { JsonValue } from "../core/wire.ts";
2
+ export { runScaffold } from "./expander.ts";
3
+ export type { ScaffoldArgs } from "./expander.ts";
4
+ export { isSniffableText } from "./classify-transport.ts";
5
+ /**
6
+ * Reads a package-local file (relative to the active run's `packageDir`) and returns its
7
+ * content as the string to use for a `create({ templateFile })` render request.
8
+ *
9
+ * Containment (S-005, verify-in-loop-4 Deviation #1 ruling): the path is validated through
10
+ * the SAME `validateSourceContainment` machinery `scaffold`/`copyIn` already use
11
+ * (`package-root-containment` REQ-PRC-01..08) BEFORE any content read — a missing/
12
+ * outside-package/non-regular/unreadable source surfaces the matching neutral `source-*`
13
+ * `AuthoringReason` (REQ-AEC-10/11), never a parallel templateFile-only check. The whole
14
+ * containment → stat-size (REQ-CCL-06 posture) → read → sniff (REQ-CCL-01/03) → budget
15
+ * (REQ-CCL-02) chain is `classifyTransport`'s — ONE gate engine for both callers. A
16
+ * `templateFile` REQUESTS a render — unlike `scaffold`'s by-value/by-reference
17
+ * classification of unmarked files, there is no silent by-reference fallback here
18
+ * (REQ-FEH-02): invalid UTF-8, a null byte, or an over-budget file all fail loud with
19
+ * reason `invalid-input` via the pinned templateFile message pair (these are
20
+ * RENDER-REQUEST failures, distinct from the source-* containment/existence failures).
21
+ *
22
+ * `destPath`/`options`/`force` are the SAME `pathTemplate`/`options`/`force` the caller
23
+ * (`commons/index.ts`'s `create({templateFile})` handler) will put on the `create`
24
+ * directive it builds from this call's return value — threaded through so the CCL-02
25
+ * budget gate below measures the PROSPECTIVE DIRECTIVE, matching the emit authority,
26
+ * never the template content alone.
27
+ */
28
+ export declare function readTemplateFile(relPath: string, destPath: string, options: JsonValue, force?: boolean): string;
29
+ /**
30
+ * Emits a by-reference copy of ONE package-local file (`from`, resolved against the active
31
+ * run's `packageDir`) to `to` (REQ-FEH-03/04) — ALWAYS by-reference, never classified or
32
+ * rendered: a text asset containing `{= =}`-like sequences travels verbatim, the documented
33
+ * escape from `scaffold`'s by-value classification (`content-classification` REQ-CCL-04).
34
+ * `from`/`to` are mandatory; a missing one rejects fail-loud before any emission
35
+ * (REQ-FEH-04.1/.2). Source containment (existence, in-ceiling, regular-file) is validated
36
+ * SDK-side against real disk BEFORE any directive is emitted — a missing/outside-package/
37
+ * non-regular source surfaces the matching `source-*` reason
38
+ * (`package-root-containment` REQ-PRC-04, `by-reference-copy-wire` REQ-BRC-06); content is
39
+ * never read (`copyIn` never classifies, REQ-FEH-03).
40
+ */
41
+ export declare function runCopyIn(args: {
42
+ from: string | undefined;
43
+ to: string | undefined;
44
+ force?: boolean;
45
+ }): void;
@@ -0,0 +1,99 @@
1
+ // src/scaffold/ (ADR-0044): the isolated leaf that reads package-local disk content and
2
+ // hands rendered strings back to `commons`. `commons` never touches `node:fs` itself — this
3
+ // leaf folder is the ONE place that does (FIT-01: `commons -> ../scaffold -> node:fs` is
4
+ // compliant by the fitness rule's own terms — it bans bare external PACKAGES, not `node:`
5
+ // builtins).
6
+ import { currentContext, requirePackageAnchors } from "../core/context.js";
7
+ import { invalidInput } from "../core/authoring-error.js";
8
+ import { forceEntry } from "../core/directive-factory.js";
9
+ import { validateSourceContainment, validateDestinationLexical } from "./containment.js";
10
+ import { classifyTransport } from "./classify-transport.js";
11
+ // S-001: the folder-scaffold orchestrator lives in expander.ts (the single owner of the
12
+ // walk → filename-pipeline → classify → emit fan-out, ADR-0044); re-exported here so
13
+ // `commons` reaches every scaffold-family orchestrator through this one leaf entrypoint.
14
+ export { runScaffold } from "./expander.js";
15
+ function noResolutionAnchorMessage(relPath) {
16
+ return (`invalid input: templateFile "${relPath}" has no package directory to resolve it against — ` +
17
+ "pass `packageDir` to the call that runs this factory");
18
+ }
19
+ function templateFileBinaryMessage(relPath) {
20
+ return `invalid input: templateFile "${relPath}" is not valid text (binary content) — render requests never silently fall back to a copy`;
21
+ }
22
+ function templateFileOversizedMessage(relPath) {
23
+ return `invalid input: templateFile "${relPath}" is too large to render inline (over the 4 MiB limit)`;
24
+ }
25
+ // REQ-CCL-01's whole-file sniff — moved into `classify-transport.ts` (the classify leaf)
26
+ // to break the `index → expander → classify-transport → index` import cycle; re-exported
27
+ // so this module's surface is unchanged.
28
+ export { isSniffableText } from "./classify-transport.js";
29
+ /**
30
+ * Reads a package-local file (relative to the active run's `packageDir`) and returns its
31
+ * content as the string to use for a `create({ templateFile })` render request.
32
+ *
33
+ * Containment (S-005, verify-in-loop-4 Deviation #1 ruling): the path is validated through
34
+ * the SAME `validateSourceContainment` machinery `scaffold`/`copyIn` already use
35
+ * (`package-root-containment` REQ-PRC-01..08) BEFORE any content read — a missing/
36
+ * outside-package/non-regular/unreadable source surfaces the matching neutral `source-*`
37
+ * `AuthoringReason` (REQ-AEC-10/11), never a parallel templateFile-only check. The whole
38
+ * containment → stat-size (REQ-CCL-06 posture) → read → sniff (REQ-CCL-01/03) → budget
39
+ * (REQ-CCL-02) chain is `classifyTransport`'s — ONE gate engine for both callers. A
40
+ * `templateFile` REQUESTS a render — unlike `scaffold`'s by-value/by-reference
41
+ * classification of unmarked files, there is no silent by-reference fallback here
42
+ * (REQ-FEH-02): invalid UTF-8, a null byte, or an over-budget file all fail loud with
43
+ * reason `invalid-input` via the pinned templateFile message pair (these are
44
+ * RENDER-REQUEST failures, distinct from the source-* containment/existence failures).
45
+ *
46
+ * `destPath`/`options`/`force` are the SAME `pathTemplate`/`options`/`force` the caller
47
+ * (`commons/index.ts`'s `create({templateFile})` handler) will put on the `create`
48
+ * directive it builds from this call's return value — threaded through so the CCL-02
49
+ * budget gate below measures the PROSPECTIVE DIRECTIVE, matching the emit authority,
50
+ * never the template content alone.
51
+ */
52
+ export function readTemplateFile(relPath, destPath, options, force) {
53
+ const { packageDir, packageRoot } = requirePackageAnchors(noResolutionAnchorMessage(relPath));
54
+ return classifyTransport({
55
+ packageDir,
56
+ packageRoot,
57
+ relPath,
58
+ isTemplateMarked: false,
59
+ destPath,
60
+ options,
61
+ force,
62
+ failMessages: {
63
+ binary: templateFileBinaryMessage(relPath),
64
+ oversized: templateFileOversizedMessage(relPath),
65
+ },
66
+ }).content;
67
+ }
68
+ function missingCopyInArgMessage(field) {
69
+ return `invalid input: copyIn requires "${field}"`;
70
+ }
71
+ function noResolutionAnchorForCopyInMessage() {
72
+ return ("invalid input: copyIn has no package directory to resolve its source against — " +
73
+ "pass `packageDir` to the call that runs this factory");
74
+ }
75
+ /**
76
+ * Emits a by-reference copy of ONE package-local file (`from`, resolved against the active
77
+ * run's `packageDir`) to `to` (REQ-FEH-03/04) — ALWAYS by-reference, never classified or
78
+ * rendered: a text asset containing `{= =}`-like sequences travels verbatim, the documented
79
+ * escape from `scaffold`'s by-value classification (`content-classification` REQ-CCL-04).
80
+ * `from`/`to` are mandatory; a missing one rejects fail-loud before any emission
81
+ * (REQ-FEH-04.1/.2). Source containment (existence, in-ceiling, regular-file) is validated
82
+ * SDK-side against real disk BEFORE any directive is emitted — a missing/outside-package/
83
+ * non-regular source surfaces the matching `source-*` reason
84
+ * (`package-root-containment` REQ-PRC-04, `by-reference-copy-wire` REQ-BRC-06); content is
85
+ * never read (`copyIn` never classifies, REQ-FEH-03).
86
+ */
87
+ export function runCopyIn(args) {
88
+ if (args.from === undefined) {
89
+ throw invalidInput(missingCopyInArgMessage("from"));
90
+ }
91
+ if (args.to === undefined) {
92
+ throw invalidInput(missingCopyInArgMessage("to"));
93
+ }
94
+ const { session, factory } = currentContext();
95
+ const { packageDir, packageRoot } = requirePackageAnchors(noResolutionAnchorForCopyInMessage());
96
+ validateSourceContainment({ packageDir, packageRoot, relPath: args.from });
97
+ validateDestinationLexical(args.to);
98
+ session.buffer(factory.copyIn({ from: args.from, to: args.to, ...forceEntry(args.force) }));
99
+ }
@@ -0,0 +1,25 @@
1
+ export declare const DEFAULT_WALK_ENTRY_BOUND = 10000;
2
+ export interface WalkEntry {
3
+ /** Source-relative path, posix-separated, relative to the walked `from` root. */
4
+ relPath: string;
5
+ /** Absolute filesystem path — `join(fromAbs, relPath)`. */
6
+ absPath: string;
7
+ }
8
+ /**
9
+ * Enumerates every file under `fromAbs`, mirroring nested directory structure into
10
+ * posix-separated `relPath`s (sorted for deterministic output). Symlinked directories are
11
+ * NEVER descended — even when their target resolves inside the containment ceiling
12
+ * (REQ-FSC-09.1) — skipped silently, no error. Fails loud, naming the bound, once the
13
+ * enumerated entry count exceeds `bound` (REQ-FSC-09.2); `bound` is injectable so a test
14
+ * can drive the branch without materializing 10,001 real files.
15
+ *
16
+ * `rootRelPath` (judgment-day iteration 2 fix, package-root-containment REQ-PRC-10.3
17
+ * amendment): the author-facing, package-relative `from` — threaded through SOLELY to name
18
+ * the ROOT in an `AuthoringError` message if the root itself is not a readable directory (a
19
+ * regular file, or missing — `runScaffold`'s `validateSourceRootContainment` proves the root
20
+ * is in-ceiling but deliberately leaves existence/type to this function, see its own
21
+ * doc-comment). Recursive sub-directory reads below are NOT re-guarded — every one of them
22
+ * enumerates a directory this walk already lstat'd as a directory, so their behavior for a
23
+ * valid tree is unchanged.
24
+ */
25
+ export declare function walkFolder(fromAbs: string, bound?: number, rootRelPath?: string): WalkEntry[];
@@ -0,0 +1,124 @@
1
+ // src/scaffold/walk.ts (ADR-0044): folder enumeration for `scaffold` — lstat-based
2
+ // symlinked-directory non-descent (REQ-FSC-09.1) and a 10 000-entry bound (REQ-FSC-09.2).
3
+ // Pure enumeration only: source/destination eligibility, containment, and the by-value/
4
+ // by-reference verdict are NOT this module's concern (classify-transport.ts + containment.ts,
5
+ // the latter landing in S-002).
6
+ import { lstatSync, readdirSync, statSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { invalidInput } from "../core/authoring-error.js";
9
+ import { isErrnoException } from "../core/fs-errors.js";
10
+ export const DEFAULT_WALK_ENTRY_BOUND = 10_000;
11
+ function boundExceededMessage(bound) {
12
+ return `invalid input: scaffold walk exceeded the ${bound}-entry bound`;
13
+ }
14
+ // judgment-day iteration 2 fix: the ROOT `readdirSync` (below) has no per-entry containment
15
+ // guard ahead of it the way every recursive sub-directory read does (those enumerate
16
+ // directories `validateSourceRootContainment` + this function's own walk already proved
17
+ // in-ceiling) — `runScaffold` only proves the root is IN-CEILING, never that it exists or is
18
+ // a directory (`validateSourceRootContainment`'s own contract: a legitimately absent root is
19
+ // deliberately left for `walkFolder` to answer, package-root-containment REQ-PRC-10.3). A
20
+ // `from` that resolves to a regular FILE or does not exist at all therefore used to reach
21
+ // `readdirSync` unguarded and throw a raw Node `Error` — never an `AuthoringError` — whose
22
+ // message echoes the ABSOLUTE filesystem path (no-echo violation). `rootRelPath` is the
23
+ // author-facing, package-relative `from` the caller already has in hand (never re-derived
24
+ // from `fromAbs`); a caller that omits it (only the direct-unit-test callers in walk.test.ts
25
+ // do) falls back to a locator-free phrasing rather than ever risking an absolute-path leak.
26
+ function rootNotDirectoryMessage(rootRelPath) {
27
+ return rootRelPath === undefined
28
+ ? "invalid input: scaffold \"from\" must be a folder — it resolves to a regular file"
29
+ : `invalid input: scaffold "from" (${rootRelPath}) must be a folder — it resolves to a regular file`;
30
+ }
31
+ function rootNotFoundMessage(rootRelPath) {
32
+ return rootRelPath === undefined
33
+ ? "invalid input: scaffold \"from\" folder does not exist"
34
+ : `invalid input: scaffold "from" folder (${rootRelPath}) does not exist`;
35
+ }
36
+ function rootUnreadableMessage(rootRelPath) {
37
+ return rootRelPath === undefined
38
+ ? "invalid input: scaffold \"from\" folder could not be read"
39
+ : `invalid input: scaffold "from" folder (${rootRelPath}) could not be read`;
40
+ }
41
+ // Never re-throws the raw Node error (no-echo, REQ-AEC-05/FIT-11 posture already held by
42
+ // every other scaffold-family rejection): ENOTDIR (the root resolves to a non-directory —
43
+ // most commonly a regular file) and ENOENT (the root doesn't exist) each mint their own
44
+ // `AuthoringError` naming ONLY the package-relative `rootRelPath`; any other errno (e.g.
45
+ // EACCES) still fails closed the same way — a generic "could not be read" — rather than ever
46
+ // leaking `err.message`'s absolute path.
47
+ function rootReadFailure(err, rootRelPath) {
48
+ if (isErrnoException(err) && err.code === "ENOTDIR") {
49
+ return invalidInput(rootNotDirectoryMessage(rootRelPath));
50
+ }
51
+ if (isErrnoException(err) && err.code === "ENOENT") {
52
+ return invalidInput(rootNotFoundMessage(rootRelPath));
53
+ }
54
+ return invalidInput(rootUnreadableMessage(rootRelPath));
55
+ }
56
+ // A symlink's OWN type (lstat) is always "symbolic link" — this asks what the link's
57
+ // TARGET is, via `statSync` (follows the link), ONLY to decide non-descent (REQ-FSC-09.1).
58
+ // NOT a containment check: a broken symlink (target absent) is treated as a
59
+ // (later-failing) file candidate rather than silently vanishing from the walk.
60
+ function symlinkTargetIsDirectory(absPath) {
61
+ try {
62
+ return statSync(absPath).isDirectory();
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ }
68
+ /**
69
+ * Enumerates every file under `fromAbs`, mirroring nested directory structure into
70
+ * posix-separated `relPath`s (sorted for deterministic output). Symlinked directories are
71
+ * NEVER descended — even when their target resolves inside the containment ceiling
72
+ * (REQ-FSC-09.1) — skipped silently, no error. Fails loud, naming the bound, once the
73
+ * enumerated entry count exceeds `bound` (REQ-FSC-09.2); `bound` is injectable so a test
74
+ * can drive the branch without materializing 10,001 real files.
75
+ *
76
+ * `rootRelPath` (judgment-day iteration 2 fix, package-root-containment REQ-PRC-10.3
77
+ * amendment): the author-facing, package-relative `from` — threaded through SOLELY to name
78
+ * the ROOT in an `AuthoringError` message if the root itself is not a readable directory (a
79
+ * regular file, or missing — `runScaffold`'s `validateSourceRootContainment` proves the root
80
+ * is in-ceiling but deliberately leaves existence/type to this function, see its own
81
+ * doc-comment). Recursive sub-directory reads below are NOT re-guarded — every one of them
82
+ * enumerates a directory this walk already lstat'd as a directory, so their behavior for a
83
+ * valid tree is unchanged.
84
+ */
85
+ export function walkFolder(fromAbs, bound = DEFAULT_WALK_ENTRY_BOUND, rootRelPath) {
86
+ const entries = [];
87
+ const dirStack = [""];
88
+ while (dirStack.length > 0) {
89
+ const relDir = dirStack.pop();
90
+ const absDir = relDir === "" ? fromAbs : join(fromAbs, relDir);
91
+ let names;
92
+ if (relDir === "") {
93
+ try {
94
+ names = readdirSync(absDir).sort();
95
+ }
96
+ catch (err) {
97
+ throw rootReadFailure(err, rootRelPath);
98
+ }
99
+ }
100
+ else {
101
+ names = readdirSync(absDir).sort();
102
+ }
103
+ for (const name of names) {
104
+ const relPath = relDir === "" ? name : `${relDir}/${name}`;
105
+ const absPath = join(absDir, name);
106
+ const lst = lstatSync(absPath);
107
+ if (lst.isSymbolicLink()) {
108
+ if (symlinkTargetIsDirectory(absPath)) {
109
+ continue; // REQ-FSC-09.1: never descended, no error for the skip
110
+ }
111
+ // symlinked file (or broken symlink): walkable entry, eligibility deferred.
112
+ }
113
+ else if (lst.isDirectory()) {
114
+ dirStack.push(relPath);
115
+ continue;
116
+ }
117
+ entries.push({ relPath, absPath });
118
+ if (entries.length > bound) {
119
+ throw invalidInput(boundExceededMessage(bound));
120
+ }
121
+ }
122
+ }
123
+ return entries;
124
+ }