@mgamadeus/ddd-web 0.17.1 → 0.19.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/.claude/skills/ddd-web-specialist/SKILL.md +13 -2
- package/.claude/skills/ddd-web-specialist/references/consumer.md +41 -0
- package/CHANGELOG.md +41 -0
- package/README.md +44 -0
- package/dist/{chunk-3V22MYDI.js → chunk-HZ4VYIHY.js} +1160 -594
- package/dist/chunk-HZ4VYIHY.js.map +1 -0
- package/dist/codegen/cli.js +9 -2
- package/dist/codegen/cli.js.map +1 -1
- package/dist/codegen/index.d.ts +121 -14
- package/dist/codegen/index.js +3 -1
- package/package.json +2 -1
- package/dist/chunk-3V22MYDI.js.map +0 -1
|
@@ -99,17 +99,17 @@ var SdkGenerationError = class extends Error {
|
|
|
99
99
|
var HTTP_METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
|
|
100
100
|
function listOperations(doc) {
|
|
101
101
|
const result = [];
|
|
102
|
-
for (const [
|
|
102
|
+
for (const [path13, item] of Object.entries(doc.paths ?? {})) {
|
|
103
103
|
if (!item) continue;
|
|
104
104
|
for (const method of HTTP_METHODS) {
|
|
105
105
|
const operation = item[method];
|
|
106
|
-
if (operation) result.push({ method, path:
|
|
106
|
+
if (operation) result.push({ method, path: path13, operation });
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
109
|
return result;
|
|
110
110
|
}
|
|
111
|
-
function operationKey(method,
|
|
112
|
-
return `${method.toUpperCase()} ${
|
|
111
|
+
function operationKey(method, path13) {
|
|
112
|
+
return `${method.toUpperCase()} ${path13}`;
|
|
113
113
|
}
|
|
114
114
|
|
|
115
115
|
// src/codegen/tags.ts
|
|
@@ -166,9 +166,9 @@ function segmentToPascal(segment) {
|
|
|
166
166
|
if (/[A-Z]/.test(segment)) return segment;
|
|
167
167
|
return segment.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
168
168
|
}
|
|
169
|
-
function tagFromPath(
|
|
169
|
+
function tagFromPath(path13, lookup) {
|
|
170
170
|
let matched = null;
|
|
171
|
-
for (const segment of
|
|
171
|
+
for (const segment of path13.replace(/\{[^}]+\}/g, "").split("/").filter(Boolean)) {
|
|
172
172
|
matched = lookup.get(segmentToPascal(segment).toLowerCase()) ?? matched;
|
|
173
173
|
}
|
|
174
174
|
return matched;
|
|
@@ -180,11 +180,11 @@ function tagFromOperation(info, audience, lookup) {
|
|
|
180
180
|
}
|
|
181
181
|
return null;
|
|
182
182
|
}
|
|
183
|
-
function trailingPlaceholder(
|
|
184
|
-
return
|
|
183
|
+
function trailingPlaceholder(path13) {
|
|
184
|
+
return path13.match(/\{([^}]+)\}\/?$/)?.[1] ?? null;
|
|
185
185
|
}
|
|
186
|
-
function isPrimaryEntityPath(
|
|
187
|
-
const segments =
|
|
186
|
+
function isPrimaryEntityPath(path13, tag) {
|
|
187
|
+
const segments = path13.replace(/\{[^}]+\}\/?$/, "").split("/").filter(Boolean);
|
|
188
188
|
const last = segments[segments.length - 1];
|
|
189
189
|
return last !== void 0 && segmentToPascal(last).toLowerCase() === tag.toLowerCase();
|
|
190
190
|
}
|
|
@@ -223,9 +223,9 @@ function singularForms(tag) {
|
|
|
223
223
|
if (lower.endsWith("s")) forms.add(lower.slice(0, -1));
|
|
224
224
|
return [...forms];
|
|
225
225
|
}
|
|
226
|
-
function identityPathParameter(
|
|
226
|
+
function identityPathParameter(path13, tag) {
|
|
227
227
|
const singulars = singularForms(tag);
|
|
228
|
-
const segments =
|
|
228
|
+
const segments = path13.split("/").filter(Boolean);
|
|
229
229
|
let found = null;
|
|
230
230
|
segments.forEach((segment, index) => {
|
|
231
231
|
const name = segment.match(/^\{([^}]+)\}$/)?.[1];
|
|
@@ -292,8 +292,8 @@ function entityInvalidation(endpoint, info, tag) {
|
|
|
292
292
|
if (action === "upsert" || action === "delete") {
|
|
293
293
|
if (identity.startsWith("path:")) {
|
|
294
294
|
const accessor = endpoint.pathArgs[identity.slice("path:".length)];
|
|
295
|
-
const
|
|
296
|
-
if (
|
|
295
|
+
const relative7 = accessor !== void 0 ? relativeAccessor(accessor) : null;
|
|
296
|
+
if (relative7 !== null) return [argTag(tag, relative7), listTag(tag)];
|
|
297
297
|
}
|
|
298
298
|
if (identity.startsWith("body:") && endpoint.bodyArg !== void 0) {
|
|
299
299
|
const body = relativeAccessor(endpoint.bodyArg);
|
|
@@ -306,8 +306,8 @@ function entityInvalidation(endpoint, info, tag) {
|
|
|
306
306
|
function heuristicInvalidation(endpoint, info, tag, doc, lookup) {
|
|
307
307
|
const parameter = identityPathParameter(endpoint.path, tag);
|
|
308
308
|
const accessor = parameter ? endpoint.pathArgs[parameter] : void 0;
|
|
309
|
-
const
|
|
310
|
-
if (
|
|
309
|
+
const relative7 = accessor !== void 0 ? relativeAccessor(accessor) : null;
|
|
310
|
+
if (relative7 !== null) return [argTag(tag, relative7), listTag(tag)];
|
|
311
311
|
if (info && endpoint.bodyArg !== void 0) {
|
|
312
312
|
const body = relativeAccessor(endpoint.bodyArg);
|
|
313
313
|
const inner = identityBodyPath(doc, info.operation, tag, lookup);
|
|
@@ -418,8 +418,8 @@ function buildEnhancedEndpoints(input) {
|
|
|
418
418
|
sideEffects: info?.sideEffects ?? true,
|
|
419
419
|
pathArgs: Object.fromEntries(
|
|
420
420
|
Object.entries(endpoint.pathArgs).flatMap(([name, accessor]) => {
|
|
421
|
-
const
|
|
422
|
-
return
|
|
421
|
+
const relative7 = relativeAccessor(accessor);
|
|
422
|
+
return relative7 === null ? [] : [[name, relative7]];
|
|
423
423
|
})
|
|
424
424
|
),
|
|
425
425
|
...endpoint.bodyArg !== void 0 && relativeAccessor(endpoint.bodyArg) !== null ? { bodyArg: relativeAccessor(endpoint.bodyArg) } : {},
|
|
@@ -476,12 +476,674 @@ function buildEnhancedEndpoints(input) {
|
|
|
476
476
|
return { source, tagTypes: [...allTags].sort() };
|
|
477
477
|
}
|
|
478
478
|
|
|
479
|
+
// src/codegen/spec.ts
|
|
480
|
+
import * as fs2 from "fs";
|
|
481
|
+
var SUPPORTED_CONTRACT = { min: 1, max: 1 };
|
|
482
|
+
var SCHEMA_DEFINITION_MARKUP = "<SchemaDefinition schemaRef=";
|
|
483
|
+
async function loadSpec(source, timeoutMs = 6e4) {
|
|
484
|
+
let text;
|
|
485
|
+
if (isUrl(source)) {
|
|
486
|
+
let response;
|
|
487
|
+
try {
|
|
488
|
+
response = await fetch(source, { signal: AbortSignal.timeout(timeoutMs) });
|
|
489
|
+
} catch (error) {
|
|
490
|
+
throw new SdkGenerationError(`Could not fetch spec ${source}: ${error.message}`);
|
|
491
|
+
}
|
|
492
|
+
if (!response.ok) {
|
|
493
|
+
throw new SdkGenerationError(`Could not fetch spec ${source}: HTTP ${response.status} ${response.statusText}`);
|
|
494
|
+
}
|
|
495
|
+
text = await response.text();
|
|
496
|
+
} else {
|
|
497
|
+
if (!fs2.existsSync(source)) throw new SdkGenerationError(`Spec file not found: ${source}`);
|
|
498
|
+
text = fs2.readFileSync(source, "utf-8");
|
|
499
|
+
}
|
|
500
|
+
let parsed;
|
|
501
|
+
try {
|
|
502
|
+
parsed = JSON.parse(text);
|
|
503
|
+
} catch (error) {
|
|
504
|
+
throw new SdkGenerationError(`Spec ${source} is not valid JSON: ${error.message}`);
|
|
505
|
+
}
|
|
506
|
+
if (!parsed || typeof parsed !== "object" || !("paths" in parsed)) {
|
|
507
|
+
throw new SdkGenerationError(`Spec ${source} is not an OpenAPI document (no "paths").`);
|
|
508
|
+
}
|
|
509
|
+
return parsed;
|
|
510
|
+
}
|
|
511
|
+
function validateSpec(doc, source, logger) {
|
|
512
|
+
const contract = doc.info?.["x-ddd-contract"];
|
|
513
|
+
if (contract === void 0) {
|
|
514
|
+
logger.warn(`${source}: no info.x-ddd-contract \u2014 assuming a pre-contract DDD spec.`);
|
|
515
|
+
} else {
|
|
516
|
+
const number = typeof contract === "object" && contract ? contract.contract : void 0;
|
|
517
|
+
if (typeof number !== "number" || number < SUPPORTED_CONTRACT.min || number > SUPPORTED_CONTRACT.max) {
|
|
518
|
+
throw new SdkGenerationError(
|
|
519
|
+
`${source}: DDD contract ${JSON.stringify(number ?? contract)} is not supported by this @mgamadeus/ddd-web (supported: ${SUPPORTED_CONTRACT.min}\u2013${SUPPORTED_CONTRACT.max}). Update @mgamadeus/ddd-web or the backend.`
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
const hasSchemaTags = (doc.tags ?? []).some((tag) => tag.description?.includes(SCHEMA_DEFINITION_MARKUP));
|
|
524
|
+
if (!hasSchemaTags) {
|
|
525
|
+
throw new SdkGenerationError(
|
|
526
|
+
`${source}: no <SchemaDefinition schemaRef="\u2026"/> markup in tags[].description. The codegen needs it to place models into namespace folders \u2014 fetch the spec without removeSchemaTags=1.`
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// src/codegen/delegated-sdk.ts
|
|
532
|
+
import * as fs6 from "fs";
|
|
533
|
+
import { createRequire as createRequire2 } from "module";
|
|
534
|
+
import * as os from "os";
|
|
535
|
+
import * as path5 from "path";
|
|
536
|
+
|
|
537
|
+
// src/codegen/files.ts
|
|
538
|
+
import * as fs3 from "fs";
|
|
539
|
+
import * as path2 from "path";
|
|
540
|
+
var OutputFiles = class {
|
|
541
|
+
files = /* @__PURE__ */ new Map();
|
|
542
|
+
lowerCaseIndex = /* @__PURE__ */ new Map();
|
|
543
|
+
set(filePath, content) {
|
|
544
|
+
const absolute = path2.resolve(filePath);
|
|
545
|
+
this.files.set(absolute, { content, generatedThisRun: true });
|
|
546
|
+
this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);
|
|
547
|
+
}
|
|
548
|
+
get(filePath) {
|
|
549
|
+
return this.files.get(path2.resolve(filePath))?.content;
|
|
550
|
+
}
|
|
551
|
+
isGeneratedThisRun(filePath) {
|
|
552
|
+
return this.files.get(path2.resolve(filePath))?.generatedThisRun ?? false;
|
|
553
|
+
}
|
|
554
|
+
/** Case-insensitive lookup; returns the stored path spelling. */
|
|
555
|
+
findPath(filePath) {
|
|
556
|
+
return this.lowerCaseIndex.get(path2.resolve(filePath).toLowerCase());
|
|
557
|
+
}
|
|
558
|
+
paths() {
|
|
559
|
+
return [...this.files.keys()];
|
|
560
|
+
}
|
|
561
|
+
/** Seeds the store with existing `.ts` files below `dir` (for runs that regenerate only some apis). */
|
|
562
|
+
seedFromDisk(dir) {
|
|
563
|
+
for (const absolute of listTsFiles(dir)) {
|
|
564
|
+
this.files.set(absolute, { content: fs3.readFileSync(absolute, "utf-8"), generatedThisRun: false });
|
|
565
|
+
this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
function listTsFiles(dir) {
|
|
570
|
+
if (!fs3.existsSync(dir)) return [];
|
|
571
|
+
const result = [];
|
|
572
|
+
for (const entry of fs3.readdirSync(dir, { withFileTypes: true })) {
|
|
573
|
+
const absolute = path2.join(dir, entry.name);
|
|
574
|
+
if (entry.isDirectory()) result.push(...listTsFiles(absolute));
|
|
575
|
+
else if (entry.isFile() && entry.name.endsWith(".ts")) result.push(absolute);
|
|
576
|
+
}
|
|
577
|
+
return result;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// src/codegen/format.ts
|
|
581
|
+
import { execFileSync } from "child_process";
|
|
582
|
+
import * as fs4 from "fs";
|
|
583
|
+
import { createRequire } from "module";
|
|
584
|
+
import * as path3 from "path";
|
|
585
|
+
import prettier from "prettier";
|
|
586
|
+
async function formatFiles(files) {
|
|
587
|
+
for (const filePath of files.paths()) {
|
|
588
|
+
const options = await prettier.resolveConfig(filePath, { editorconfig: true }) ?? {};
|
|
589
|
+
files.set(filePath, await prettier.format(files.get(filePath), { ...options, filepath: filePath }));
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
function resolveTscOfInstallation(base) {
|
|
593
|
+
let packageJsonPath;
|
|
594
|
+
try {
|
|
595
|
+
packageJsonPath = createRequire(base).resolve("typescript/package.json");
|
|
596
|
+
} catch {
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
const packageJson = JSON.parse(fs4.readFileSync(packageJsonPath, "utf-8"));
|
|
600
|
+
const binEntry = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin?.tsc;
|
|
601
|
+
if (!binEntry) return null;
|
|
602
|
+
const executable = path3.resolve(path3.dirname(packageJsonPath), binEntry);
|
|
603
|
+
return fs4.existsSync(executable) ? { executable, version: packageJson.version ?? "unknown" } : null;
|
|
604
|
+
}
|
|
605
|
+
function resolveTypeScriptCompiler(rootDir) {
|
|
606
|
+
const projectCompiler = resolveTscOfInstallation(path3.join(rootDir, "package.json"));
|
|
607
|
+
if (projectCompiler) return { ...projectCompiler, origin: "project" };
|
|
608
|
+
const ownRequire = createRequire(import.meta.url);
|
|
609
|
+
for (const base of [import.meta.url, ownRequire.resolve("@rtk-query/codegen-openapi")]) {
|
|
610
|
+
const generatorCompiler = resolveTscOfInstallation(base);
|
|
611
|
+
if (generatorCompiler) return { ...generatorCompiler, origin: "generator" };
|
|
612
|
+
}
|
|
613
|
+
throw new SdkGenerationError("No TypeScript compiler found for the type check (install typescript in the project, or pass --skip-tsc).");
|
|
614
|
+
}
|
|
615
|
+
function buildCompilerCommand(executable, args) {
|
|
616
|
+
if (/\.(c|m)?js$/.test(executable)) return [process.execPath, [executable, ...args]];
|
|
617
|
+
const head = fs4.readFileSync(executable).subarray(0, 100).toString("latin1");
|
|
618
|
+
return head.startsWith("#!") && head.split("\n", 1)[0].includes("node") ? [process.execPath, [executable, ...args]] : [executable, args];
|
|
619
|
+
}
|
|
620
|
+
function typecheck(rootDir, tsconfig, logger) {
|
|
621
|
+
if (!fs4.existsSync(tsconfig)) {
|
|
622
|
+
logger.warn(`No ${path3.relative(rootDir, tsconfig) || tsconfig} \u2014 skipping the type check.`);
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
const compiler = resolveTypeScriptCompiler(rootDir);
|
|
626
|
+
logger.info(
|
|
627
|
+
`Type check with TypeScript ${compiler.version} (${compiler.origin === "project" ? "the project's compiler" : "the generator's own compiler \u2014 the project has no typescript"}).`
|
|
628
|
+
);
|
|
629
|
+
const [command, args] = buildCompilerCommand(compiler.executable, ["--noEmit", "-p", tsconfig]);
|
|
630
|
+
try {
|
|
631
|
+
execFileSync(command, args, {
|
|
632
|
+
cwd: rootDir,
|
|
633
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
634
|
+
encoding: "utf-8"
|
|
635
|
+
});
|
|
636
|
+
} catch (error) {
|
|
637
|
+
const output = error.stdout ?? "";
|
|
638
|
+
throw new SdkGenerationError(`Type check failed:
|
|
639
|
+
${output.split("\n").slice(0, 40).join("\n")}`);
|
|
640
|
+
}
|
|
641
|
+
return true;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// src/contract/extensions.ts
|
|
645
|
+
function hasSideEffects(method, operation) {
|
|
646
|
+
const explicit = operation?.["x-ddd-side-effects"];
|
|
647
|
+
if (typeof explicit === "boolean") {
|
|
648
|
+
return explicit;
|
|
649
|
+
}
|
|
650
|
+
return !["get", "head", "options", "trace"].includes(method.toLowerCase());
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// src/codegen/operations.ts
|
|
654
|
+
function testPattern(pattern, value) {
|
|
655
|
+
pattern.lastIndex = 0;
|
|
656
|
+
const result = pattern.test(value);
|
|
657
|
+
pattern.lastIndex = 0;
|
|
658
|
+
return result;
|
|
659
|
+
}
|
|
660
|
+
function matchesOperation(override, method, path13) {
|
|
661
|
+
if (override.method && override.method.toLowerCase() !== method) return false;
|
|
662
|
+
return typeof override.path === "string" ? override.path === path13 : testPattern(override.path, path13);
|
|
663
|
+
}
|
|
664
|
+
function canonical(value) {
|
|
665
|
+
return JSON.stringify(
|
|
666
|
+
value,
|
|
667
|
+
(_key, inner) => inner && typeof inner === "object" && !Array.isArray(inner) ? Object.fromEntries(Object.keys(inner).sort().map((key) => [key, inner[key]])) : inner
|
|
668
|
+
) ?? "undefined";
|
|
669
|
+
}
|
|
670
|
+
function isUpsertTwin(post, patch) {
|
|
671
|
+
if (post["x-ddd-side-effects"] !== patch["x-ddd-side-effects"]) return false;
|
|
672
|
+
const postEntity = isEntityExtension(post["x-ddd-entity"]) ? post["x-ddd-entity"] : void 0;
|
|
673
|
+
const patchEntity = isEntityExtension(patch["x-ddd-entity"]) ? patch["x-ddd-entity"] : void 0;
|
|
674
|
+
if (postEntity && patchEntity) {
|
|
675
|
+
return postEntity.action === "upsert" && patchEntity.action === "upsert" && postEntity.schema === patchEntity.schema;
|
|
676
|
+
}
|
|
677
|
+
if (postEntity && postEntity.action !== "upsert" || patchEntity && patchEntity.action !== "upsert") return false;
|
|
678
|
+
if (post.summary === void 0 || post.summary !== patch.summary) return false;
|
|
679
|
+
return ["parameters", "requestBody", "responses"].every((key) => canonical(post[key]) === canonical(patch[key]));
|
|
680
|
+
}
|
|
681
|
+
function isEntityExtension(value) {
|
|
682
|
+
return !!value && typeof value === "object" && typeof value.schema === "string" && typeof value.action === "string";
|
|
683
|
+
}
|
|
684
|
+
function indexOperations(doc, overrides, skipUpdatePostTwins) {
|
|
685
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
686
|
+
for (const { method, path: path13, operation } of listOperations(doc)) {
|
|
687
|
+
const extension = operation["x-ddd-side-effects"];
|
|
688
|
+
const override = overrides.find((candidate) => matchesOperation(candidate, method, path13));
|
|
689
|
+
let sideEffects = hasSideEffects(method, operation);
|
|
690
|
+
let explicit = false;
|
|
691
|
+
if (typeof extension === "boolean") {
|
|
692
|
+
sideEffects = extension;
|
|
693
|
+
explicit = true;
|
|
694
|
+
} else if (override) {
|
|
695
|
+
sideEffects = override.sideEffects;
|
|
696
|
+
explicit = true;
|
|
697
|
+
}
|
|
698
|
+
const naturalType = method === "get" ? "query" : "mutation";
|
|
699
|
+
const classifiedType = explicit ? sideEffects ? "mutation" : "query" : naturalType;
|
|
700
|
+
const endpointType = typeof extension !== "boolean" && override?.endpointType || classifiedType;
|
|
701
|
+
const entity = isEntityExtension(operation["x-ddd-entity"]) ? operation["x-ddd-entity"] : void 0;
|
|
702
|
+
byKey.set(operationKey(method, path13), {
|
|
703
|
+
method,
|
|
704
|
+
path: path13,
|
|
705
|
+
operation,
|
|
706
|
+
sideEffects,
|
|
707
|
+
sideEffectsExplicit: explicit,
|
|
708
|
+
endpointType,
|
|
709
|
+
...entity ? { entity } : {}
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
const skippedTwins = /* @__PURE__ */ new Set();
|
|
713
|
+
if (skipUpdatePostTwins) {
|
|
714
|
+
for (const [path13, item] of Object.entries(doc.paths ?? {})) {
|
|
715
|
+
const post = item?.post;
|
|
716
|
+
const patch = item?.patch;
|
|
717
|
+
if (post && patch && isUpsertTwin(post, patch)) {
|
|
718
|
+
skippedTwins.add(operationKey("post", path13));
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
return { byKey, skippedTwins };
|
|
723
|
+
}
|
|
724
|
+
function endpointTypeOverrides(index) {
|
|
725
|
+
const result = [];
|
|
726
|
+
for (const info of index.byKey.values()) {
|
|
727
|
+
const rtkDefault = info.method === "get" ? "query" : "mutation";
|
|
728
|
+
if (info.endpointType !== rtkDefault) result.push({ method: info.method, path: info.path, type: info.endpointType });
|
|
729
|
+
}
|
|
730
|
+
return result;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// src/codegen/output.ts
|
|
734
|
+
import * as fs5 from "fs";
|
|
735
|
+
import * as path4 from "path";
|
|
736
|
+
function defaultMove(from, to) {
|
|
737
|
+
fs5.mkdirSync(path4.dirname(to), { recursive: true });
|
|
738
|
+
try {
|
|
739
|
+
fs5.renameSync(from, to);
|
|
740
|
+
} catch (error) {
|
|
741
|
+
if (error.code !== "EXDEV") throw error;
|
|
742
|
+
fs5.cpSync(from, to, { recursive: true });
|
|
743
|
+
fs5.rmSync(from, { recursive: true, force: true });
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
function commitOutput(files, modelsDir, stagingParent, options = {}) {
|
|
747
|
+
const move = options.move ?? defaultMove;
|
|
748
|
+
fs5.mkdirSync(stagingParent, { recursive: true });
|
|
749
|
+
const staging = fs5.mkdtempSync(path4.join(stagingParent, ".ddd-web-sdk-"));
|
|
750
|
+
const stagedModels = path4.join(staging, "models");
|
|
751
|
+
const backupModels = path4.join(staging, "models.previous");
|
|
752
|
+
const singles = [];
|
|
753
|
+
try {
|
|
754
|
+
fs5.mkdirSync(stagedModels, { recursive: true });
|
|
755
|
+
for (const filePath of files.paths()) {
|
|
756
|
+
const content = files.get(filePath);
|
|
757
|
+
const relative7 = modelsDir === void 0 ? void 0 : path4.relative(modelsDir, filePath);
|
|
758
|
+
if (relative7 !== void 0 && !relative7.startsWith("..") && !path4.isAbsolute(relative7)) {
|
|
759
|
+
const staged = path4.join(stagedModels, relative7);
|
|
760
|
+
fs5.mkdirSync(path4.dirname(staged), { recursive: true });
|
|
761
|
+
fs5.writeFileSync(staged, content);
|
|
762
|
+
} else {
|
|
763
|
+
const staged = path4.join(staging, "files", String(singles.length));
|
|
764
|
+
fs5.mkdirSync(path4.dirname(staged), { recursive: true });
|
|
765
|
+
fs5.writeFileSync(staged, content);
|
|
766
|
+
singles.push({ target: filePath, staged, backup: path4.join(staging, "files.previous", String(singles.length)) });
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
} catch (error) {
|
|
770
|
+
fs5.rmSync(staging, { recursive: true, force: true });
|
|
771
|
+
throw error;
|
|
772
|
+
}
|
|
773
|
+
const undo = [];
|
|
774
|
+
const rollback = () => {
|
|
775
|
+
const failures = [];
|
|
776
|
+
for (const step of undo.reverse()) {
|
|
777
|
+
try {
|
|
778
|
+
step();
|
|
779
|
+
} catch (error) {
|
|
780
|
+
failures.push(error);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
undo.length = 0;
|
|
784
|
+
if (failures.length > 0) {
|
|
785
|
+
throw new SdkGenerationError(
|
|
786
|
+
`Could not restore the previous output; the previous output is kept in ${staging} (models.previous/, files.previous/): ${failures.map((failure) => failure.message).join("; ")}`
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
fs5.rmSync(staging, { recursive: true, force: true });
|
|
790
|
+
};
|
|
791
|
+
const swap = (target, staged, backup, removeTarget) => {
|
|
792
|
+
const state = { backedUp: false, movedIn: false };
|
|
793
|
+
undo.push(() => {
|
|
794
|
+
if (state.movedIn) removeTarget();
|
|
795
|
+
if (state.backedUp) move(backup, target);
|
|
796
|
+
});
|
|
797
|
+
if (fs5.existsSync(target)) {
|
|
798
|
+
move(target, backup);
|
|
799
|
+
state.backedUp = true;
|
|
800
|
+
}
|
|
801
|
+
move(staged, target);
|
|
802
|
+
state.movedIn = true;
|
|
803
|
+
};
|
|
804
|
+
try {
|
|
805
|
+
if (modelsDir !== void 0) {
|
|
806
|
+
swap(modelsDir, stagedModels, backupModels, () => fs5.rmSync(modelsDir, { recursive: true, force: true }));
|
|
807
|
+
}
|
|
808
|
+
for (const single of singles) {
|
|
809
|
+
swap(single.target, single.staged, single.backup, () => fs5.rmSync(single.target, { force: true }));
|
|
810
|
+
}
|
|
811
|
+
} catch (error) {
|
|
812
|
+
rollback();
|
|
813
|
+
throw error;
|
|
814
|
+
}
|
|
815
|
+
return {
|
|
816
|
+
rollback,
|
|
817
|
+
finalize: () => fs5.rmSync(staging, { recursive: true, force: true })
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// src/codegen/repair.ts
|
|
822
|
+
function resolveParameter(doc, parameter) {
|
|
823
|
+
let current = parameter;
|
|
824
|
+
for (let hops = 0; current?.$ref !== void 0 && hops < 10; hops++) {
|
|
825
|
+
const match = /^#\/components\/parameters\/(.+)$/.exec(current.$ref);
|
|
826
|
+
if (!match) return null;
|
|
827
|
+
const name = match[1].replace(/~1/g, "/").replace(/~0/g, "~");
|
|
828
|
+
current = doc.components?.parameters?.[name];
|
|
829
|
+
}
|
|
830
|
+
return current && current.$ref === void 0 ? current : null;
|
|
831
|
+
}
|
|
832
|
+
function repairMissingPathParameters(doc, logger) {
|
|
833
|
+
const repairs = [];
|
|
834
|
+
for (const { method, path: path13, operation } of listOperations(doc)) {
|
|
835
|
+
const placeholders = [...path13.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
836
|
+
if (placeholders.length === 0) continue;
|
|
837
|
+
const pathLevel = doc.paths?.[path13]?.parameters ?? [];
|
|
838
|
+
const declared = new Set(
|
|
839
|
+
[...pathLevel, ...operation.parameters ?? []].map((parameter) => resolveParameter(doc, parameter)).filter((parameter) => parameter !== null && parameter.in === "path").map((parameter) => parameter.name)
|
|
840
|
+
);
|
|
841
|
+
const missing = placeholders.filter((name) => !declared.has(name));
|
|
842
|
+
if (missing.length > 0) repairs.push({ path: path13, method, names: missing });
|
|
843
|
+
}
|
|
844
|
+
if (repairs.length === 0) return doc;
|
|
845
|
+
const copy = structuredClone(doc);
|
|
846
|
+
for (const { path: path13, method, names } of repairs) {
|
|
847
|
+
const operation = copy.paths[path13][method];
|
|
848
|
+
operation.parameters = [
|
|
849
|
+
...names.map((name) => ({ name, in: "path", required: true, schema: { type: "string" } })),
|
|
850
|
+
...operation.parameters ?? []
|
|
851
|
+
];
|
|
852
|
+
logger.warn(`${method.toUpperCase()} ${path13}: path parameter(s) ${names.join(", ")} not declared in the spec \u2014 added as string.`);
|
|
853
|
+
}
|
|
854
|
+
return copy;
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
// src/codegen/delegated-sdk.ts
|
|
858
|
+
var packageName = "swagger-sdk-generator";
|
|
859
|
+
var ownershipMarker = ".ddd-web-sdk.json";
|
|
860
|
+
function loadGenerator(rootDir, mode) {
|
|
861
|
+
const require2 = createRequire2(path5.join(rootDir, "package.json"));
|
|
862
|
+
const dependency = packageName + (mode === "legacy" ? "@^3.1" : "@^3");
|
|
863
|
+
let entry;
|
|
864
|
+
try {
|
|
865
|
+
entry = require2.resolve(packageName);
|
|
866
|
+
if (mode === "legacy") {
|
|
867
|
+
require2.resolve(packageName + "/runtime/stores");
|
|
868
|
+
require2.resolve(packageName + "/runtime/mocks");
|
|
869
|
+
}
|
|
870
|
+
} catch {
|
|
871
|
+
throw new SdkGenerationError("Install " + dependency + " in the consuming project to use SDK mode " + mode + ".");
|
|
872
|
+
}
|
|
873
|
+
const engine = require2(entry);
|
|
874
|
+
if (typeof engine.generate !== "function") {
|
|
875
|
+
throw new SdkGenerationError(packageName + " must export generate() to use SDK mode " + mode + ".");
|
|
876
|
+
}
|
|
877
|
+
return { generate: engine.generate };
|
|
878
|
+
}
|
|
879
|
+
async function generateLegacySdk(options) {
|
|
880
|
+
const cwd = path5.resolve(options.cwd ?? process.cwd());
|
|
881
|
+
const engine = loadGenerator(cwd, "legacy");
|
|
882
|
+
const logger = options.logger ?? consoleLogger;
|
|
883
|
+
const results = await engine.generate({
|
|
884
|
+
version: 4,
|
|
885
|
+
mode: "legacy",
|
|
886
|
+
targetOptions: options.targetOptions ?? {},
|
|
887
|
+
sources: options.sources,
|
|
888
|
+
prune: false
|
|
889
|
+
}, { cwd, dryRun: true, log: { ...logger, debug() {
|
|
890
|
+
} } });
|
|
891
|
+
const files = new OutputFiles();
|
|
892
|
+
for (const source of options.sources) {
|
|
893
|
+
const result = results.find((candidate) => candidate.source === source.name);
|
|
894
|
+
if (!result?.ok) throw new SdkGenerationError(source.name + ": " + (result?.error?.message ?? "SDK generator returned no result."));
|
|
895
|
+
if (result.skipped) continue;
|
|
896
|
+
if (!result.planned) throw new SdkGenerationError(source.name + ": SDK generator returned no output plan.");
|
|
897
|
+
const roots = Object.values(source.outputs).map(({ dir }) => path5.resolve(cwd, String(dir)));
|
|
898
|
+
for (const output of result.planned) {
|
|
899
|
+
if (!roots.includes(output.dir)) {
|
|
900
|
+
throw new SdkGenerationError(source.name + ": SDK generator returned an unexpected output directory.");
|
|
901
|
+
}
|
|
902
|
+
for (const file of output.files) {
|
|
903
|
+
const target = path5.resolve(output.dir, file.path);
|
|
904
|
+
if (path5.isAbsolute(file.path) || target === output.dir || !contains(output.dir, target)) {
|
|
905
|
+
throw new SdkGenerationError(source.name + ": SDK generator returned an invalid file path: " + file.path);
|
|
906
|
+
}
|
|
907
|
+
files.set(target, file.content);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
const prune = options.prune ? planLegacyPrune(options.sources, results, cwd, options.manifestFile) : void 0;
|
|
912
|
+
if (!options.dryRun && files.paths().length) commitOutput(files, void 0, cwd).finalize();
|
|
913
|
+
if (prune) {
|
|
914
|
+
const count = prune.deletions.reduce((total, { files: deleted }) => total + deleted.length, 0);
|
|
915
|
+
for (const { result, files: deleted } of prune.deletions) result.pruned.push(...deleted);
|
|
916
|
+
if (options.dryRun) {
|
|
917
|
+
logger.info("prune: would delete " + count + " file(s) no longer generated");
|
|
918
|
+
} else {
|
|
919
|
+
for (const { root, files: deleted } of prune.deletions) {
|
|
920
|
+
for (const file of deleted) {
|
|
921
|
+
fs6.rmSync(file, { force: true });
|
|
922
|
+
removeEmptyParents(path5.dirname(file), root);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
fs6.mkdirSync(path5.dirname(prune.manifestPath), { recursive: true });
|
|
926
|
+
fs6.writeFileSync(prune.manifestPath, JSON.stringify(prune.manifest, null, 2) + "\n");
|
|
927
|
+
logger.info("prune: deleted " + count + " file(s) no longer generated");
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
return results;
|
|
931
|
+
}
|
|
932
|
+
function readLegacyManifest(file) {
|
|
933
|
+
if (!fs6.existsSync(file)) return { version: 1, sources: {} };
|
|
934
|
+
let parsed;
|
|
935
|
+
try {
|
|
936
|
+
parsed = JSON.parse(fs6.readFileSync(file, "utf8"));
|
|
937
|
+
} catch (error) {
|
|
938
|
+
throw new SdkGenerationError("Cannot read the legacy SDK manifest " + file + ": " + error.message);
|
|
939
|
+
}
|
|
940
|
+
const sources = parsed?.sources;
|
|
941
|
+
if (parsed?.version !== 1 || !sources || typeof sources !== "object") {
|
|
942
|
+
throw new SdkGenerationError("Unsupported legacy SDK manifest " + file + ". Delete it to start a new one.");
|
|
943
|
+
}
|
|
944
|
+
return parsed;
|
|
945
|
+
}
|
|
946
|
+
function manifestPath(cwd, file) {
|
|
947
|
+
return contains(cwd, file) ? path5.relative(cwd, file).split(path5.sep).join("/") : file;
|
|
948
|
+
}
|
|
949
|
+
function planLegacyPrune(sources, results, cwd, manifestFile) {
|
|
950
|
+
const file = path5.resolve(cwd, manifestFile ?? ".ddd-web-legacy-sdk.json");
|
|
951
|
+
const previous = readLegacyManifest(file);
|
|
952
|
+
const planned = /* @__PURE__ */ new Set();
|
|
953
|
+
const next = { version: 1, sources: {} };
|
|
954
|
+
const ran = /* @__PURE__ */ new Map();
|
|
955
|
+
for (const source of sources) {
|
|
956
|
+
const result = results.find((candidate) => candidate.source === source.name);
|
|
957
|
+
if (!result?.ok || result.skipped) continue;
|
|
958
|
+
ran.set(source.name, { source, result });
|
|
959
|
+
const entries = {};
|
|
960
|
+
for (const [name, options] of Object.entries(source.outputs)) {
|
|
961
|
+
const dir = path5.resolve(cwd, String(options.dir));
|
|
962
|
+
const written = (result.planned ?? []).filter((output) => output.dir === dir).flatMap((output) => output.files.map((planFile) => path5.resolve(output.dir, planFile.path)));
|
|
963
|
+
written.forEach((target) => planned.add(target));
|
|
964
|
+
entries[name] = { dir: manifestPath(cwd, dir), files: [...new Set(written.map((target) => manifestPath(cwd, target)))].sort() };
|
|
965
|
+
}
|
|
966
|
+
next.sources[source.name] = entries;
|
|
967
|
+
}
|
|
968
|
+
const ranOutputs = new Set(Object.entries(next.sources).flatMap(([sourceName, outputs]) => Object.keys(outputs).map((output) => sourceName + "\0" + output)));
|
|
969
|
+
const ranOutput = (sourceName, output) => ranOutputs.has(sourceName + "\0" + output);
|
|
970
|
+
const kept = /* @__PURE__ */ new Set();
|
|
971
|
+
for (const [sourceName, outputs] of Object.entries(previous.sources)) {
|
|
972
|
+
for (const [output, entry] of Object.entries(outputs ?? {})) {
|
|
973
|
+
if (ranOutput(sourceName, output)) continue;
|
|
974
|
+
(entry?.files ?? []).forEach((listed) => kept.add(path5.resolve(cwd, listed)));
|
|
975
|
+
(next.sources[sourceName] ??= {})[output] = entry;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
979
|
+
const deletions = [];
|
|
980
|
+
for (const [sourceName, outputs] of Object.entries(previous.sources)) {
|
|
981
|
+
const current = ran.get(sourceName);
|
|
982
|
+
if (!current) continue;
|
|
983
|
+
for (const [output, entry] of Object.entries(outputs ?? {})) {
|
|
984
|
+
if (!ranOutput(sourceName, output) || !entry || typeof entry.dir !== "string" || !Array.isArray(entry.files)) continue;
|
|
985
|
+
const root = path5.resolve(cwd, entry.dir);
|
|
986
|
+
const stale = entry.files.map((listed) => path5.resolve(cwd, listed)).filter((target) => contains(root, target) && target !== root && !planned.has(target) && !kept.has(target) && !claimed.has(target) && fs6.lstatSync(target, { throwIfNoEntry: false })?.isFile() === true);
|
|
987
|
+
stale.forEach((target) => claimed.add(target));
|
|
988
|
+
if (stale.length) deletions.push({ result: current.result, root, files: stale.sort() });
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
for (const { result } of ran.values()) result.pruned = [];
|
|
992
|
+
return { manifestPath: file, manifest: next, deletions };
|
|
993
|
+
}
|
|
994
|
+
function removeEmptyParents(directory, root) {
|
|
995
|
+
let current = directory;
|
|
996
|
+
while (current !== root && contains(root, current)) {
|
|
997
|
+
if (!fs6.existsSync(current) || fs6.readdirSync(current).length > 0) return;
|
|
998
|
+
fs6.rmdirSync(current);
|
|
999
|
+
current = path5.dirname(current);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
function contains(parent, child) {
|
|
1003
|
+
const relative7 = path5.relative(parent, child);
|
|
1004
|
+
return relative7 !== ".." && !relative7.startsWith(".." + path5.sep) && !path5.isAbsolute(relative7);
|
|
1005
|
+
}
|
|
1006
|
+
function assertGeneratedDirectory(directory) {
|
|
1007
|
+
const entry = fs6.lstatSync(directory, { throwIfNoEntry: false });
|
|
1008
|
+
if (entry && (!entry.isDirectory() || fs6.readdirSync(directory).length > 0 && !fs6.existsSync(path5.join(directory, ownershipMarker)))) {
|
|
1009
|
+
throw new SdkGenerationError("Choose an empty generated SDK directory. DDD Web does not own " + directory + ".");
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
function prepareSpec(document, api, logger) {
|
|
1013
|
+
const repaired = repairMissingPathParameters(document, logger);
|
|
1014
|
+
if (!api.skipUpdatePostTwins) return repaired;
|
|
1015
|
+
const { skippedTwins } = indexOperations(repaired, api.sideEffects, true);
|
|
1016
|
+
return {
|
|
1017
|
+
...repaired,
|
|
1018
|
+
paths: Object.fromEntries(Object.entries(repaired.paths ?? {}).map(([url, item]) => {
|
|
1019
|
+
if (!item || !skippedTwins.has(operationKey("post", url))) return [url, item];
|
|
1020
|
+
const { post: _post, ...remaining } = item;
|
|
1021
|
+
return [url, remaining];
|
|
1022
|
+
}))
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
async function generateDelegatedSdk(mode, loaded, allApis, apis, options, logger) {
|
|
1026
|
+
const { rootDir, config } = loaded;
|
|
1027
|
+
const generator = config.generator?.mode === mode ? config.generator : void 0;
|
|
1028
|
+
const modeDir = path5.resolve(rootDir, generator?.outputDir ?? "./src/generated-sdk", mode);
|
|
1029
|
+
const outputOptions = generator?.outputs ?? {};
|
|
1030
|
+
const outputNames = mode === "legacy" ? ["models", "stores", "mocks"] : ["models", "client"];
|
|
1031
|
+
if (mode === "future" && outputOptions.mocks) outputNames.push("mocks");
|
|
1032
|
+
const unsupported = Object.keys(outputOptions).filter((name) => !outputNames.includes(name));
|
|
1033
|
+
if (unsupported.length) throw new SdkGenerationError("Unsupported " + mode + " SDK outputs: " + unsupported.join(", ") + ".");
|
|
1034
|
+
const stems = /* @__PURE__ */ new Set();
|
|
1035
|
+
const defaultModels = config.modelsDir ? [path5.resolve(rootDir, config.modelsDir)] : allApis.map((api) => path5.resolve(api.outputDir, "..", "models"));
|
|
1036
|
+
const defaultPaths = [...defaultModels, ...allApis.flatMap((api) => [
|
|
1037
|
+
api.outputFile,
|
|
1038
|
+
...["Enhanced", "Tags", "Requests"].map((suffix) => path5.join(api.outputDir, api.stem + suffix + ".ts"))
|
|
1039
|
+
])].map((file) => file.toLowerCase());
|
|
1040
|
+
for (const api of allApis) {
|
|
1041
|
+
const key = api.stem.toLowerCase();
|
|
1042
|
+
if (!/^[a-z\d][a-z\d._-]*$/i.test(api.stem) || stems.has(key)) {
|
|
1043
|
+
throw new SdkGenerationError("Opt-in SDKs need unique API output file stems made of letters, digits, dots, dashes or underscores.");
|
|
1044
|
+
}
|
|
1045
|
+
stems.add(key);
|
|
1046
|
+
const directory = path5.join(modeDir, api.stem);
|
|
1047
|
+
if (defaultPaths.some((file) => contains(directory.toLowerCase(), file) || contains(file, directory.toLowerCase()))) {
|
|
1048
|
+
throw new SdkGenerationError("Opt-in SDK output overlaps the default SDK at " + directory + ". Choose another generator.outputDir.");
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
const engine = loadGenerator(rootDir, mode);
|
|
1052
|
+
const plans = new Map(apis.map((api) => {
|
|
1053
|
+
const directory = path5.join(modeDir, api.stem);
|
|
1054
|
+
assertGeneratedDirectory(directory);
|
|
1055
|
+
const outputDirs = outputNames.map((name) => [name, path5.join(directory, name)]);
|
|
1056
|
+
return [api.stem, { directory, outputDirs, files: new OutputFiles() }];
|
|
1057
|
+
}));
|
|
1058
|
+
const specDir = fs6.mkdtempSync(path5.join(os.tmpdir(), "ddd-web-spec-"));
|
|
1059
|
+
try {
|
|
1060
|
+
const specs = /* @__PURE__ */ new Map();
|
|
1061
|
+
const sources = await Promise.all(apis.map(async (api) => {
|
|
1062
|
+
if (!specs.has(api.schemaSource)) {
|
|
1063
|
+
logger.info("loading " + api.schemaSource);
|
|
1064
|
+
specs.set(api.schemaSource, loadSpec(api.schemaSource));
|
|
1065
|
+
}
|
|
1066
|
+
const document = await specs.get(api.schemaSource);
|
|
1067
|
+
validateSpec(document, api.schemaSource, logger);
|
|
1068
|
+
const file = path5.join(specDir, api.stem + ".json");
|
|
1069
|
+
fs6.writeFileSync(file, JSON.stringify(prepareSpec(document, api, logger)));
|
|
1070
|
+
const outputs = Object.fromEntries(plans.get(api.stem).outputDirs.map(([name, dir]) => [
|
|
1071
|
+
name,
|
|
1072
|
+
{ ...outputOptions[name], dir }
|
|
1073
|
+
]));
|
|
1074
|
+
return { name: api.stem, file, outputs };
|
|
1075
|
+
}));
|
|
1076
|
+
const results = await engine.generate({
|
|
1077
|
+
version: 4,
|
|
1078
|
+
mode,
|
|
1079
|
+
sources,
|
|
1080
|
+
targetOptions: { prettier: options.skipPrettier ? false : { resolveFrom: rootDir } }
|
|
1081
|
+
}, { cwd: rootDir, dryRun: true, log: { ...logger, debug() {
|
|
1082
|
+
} } });
|
|
1083
|
+
for (const source of sources) {
|
|
1084
|
+
const result = results.find((candidate) => candidate.source === source.name);
|
|
1085
|
+
if (!result?.ok || !result.planned?.length) {
|
|
1086
|
+
throw new SdkGenerationError(source.name + ": " + (result?.error?.message ?? "SDK generator returned no output plan."));
|
|
1087
|
+
}
|
|
1088
|
+
const plan = plans.get(source.name);
|
|
1089
|
+
for (const run of result.planned) {
|
|
1090
|
+
if (!plan.outputDirs.some(([, dir]) => dir === run.dir)) {
|
|
1091
|
+
throw new SdkGenerationError(source.name + ": SDK generator returned an unexpected output directory.");
|
|
1092
|
+
}
|
|
1093
|
+
for (const file of run.files) {
|
|
1094
|
+
const target = path5.resolve(run.dir, file.path);
|
|
1095
|
+
if (path5.isAbsolute(file.path) || target === run.dir || !contains(run.dir, target) || plan.files.findPath(target)) {
|
|
1096
|
+
throw new SdkGenerationError(source.name + ": SDK generator returned an invalid or duplicate file path: " + file.path);
|
|
1097
|
+
}
|
|
1098
|
+
plan.files.set(target, file.content);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
} finally {
|
|
1103
|
+
fs6.rmSync(specDir, { recursive: true, force: true });
|
|
1104
|
+
}
|
|
1105
|
+
const writtenFiles = [...plans.values()].flatMap((plan) => plan.files.paths());
|
|
1106
|
+
const committed = [];
|
|
1107
|
+
let typechecked = false;
|
|
1108
|
+
try {
|
|
1109
|
+
for (const { directory, files } of plans.values()) {
|
|
1110
|
+
assertGeneratedDirectory(directory);
|
|
1111
|
+
files.set(path5.join(directory, ownershipMarker), '{"version":1}\n');
|
|
1112
|
+
committed.push(commitOutput(files, directory, rootDir));
|
|
1113
|
+
}
|
|
1114
|
+
if (!options.skipTsc) {
|
|
1115
|
+
typechecked = typecheck(rootDir, path5.resolve(rootDir, config.tsconfig ?? "tsconfig.json"), logger);
|
|
1116
|
+
}
|
|
1117
|
+
} catch (error) {
|
|
1118
|
+
const failures = [];
|
|
1119
|
+
for (const output of committed.reverse()) {
|
|
1120
|
+
try {
|
|
1121
|
+
output.rollback();
|
|
1122
|
+
} catch (failure) {
|
|
1123
|
+
failures.push(failure);
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
if (failures.length) throw new AggregateError([error, ...failures], "SDK generation failed and some output could not be restored.");
|
|
1127
|
+
throw error;
|
|
1128
|
+
}
|
|
1129
|
+
committed.forEach((output) => output.finalize());
|
|
1130
|
+
logger.info("done: " + writtenFiles.length + " files (" + mode + " mode)");
|
|
1131
|
+
const modelsByApi = Object.fromEntries(apis.map((api) => [api.exportName, path5.join(modeDir, api.stem, "models")]));
|
|
1132
|
+
return {
|
|
1133
|
+
apis: apis.map((api) => api.exportName),
|
|
1134
|
+
files: writtenFiles,
|
|
1135
|
+
modelsDir: apis.length === 1 ? Object.values(modelsByApi)[0] : modeDir,
|
|
1136
|
+
modelsByApi,
|
|
1137
|
+
typechecked
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
1140
|
+
|
|
479
1141
|
// src/codegen/document-endpoints.ts
|
|
480
1142
|
var REQUEST_BODY_ARG = "requestBody";
|
|
481
1143
|
var DEFAULT_STRIP_PATH_PREFIX = /^\/(?:app\/)?api(?=\/)/;
|
|
482
1144
|
var upperFirst = (value) => value.charAt(0).toUpperCase() + value.slice(1);
|
|
483
|
-
function buildEndpointNameFromPath(method,
|
|
484
|
-
const stripped = typeof stripPathPrefix === "string" ?
|
|
1145
|
+
function buildEndpointNameFromPath(method, path13, stripPathPrefix = DEFAULT_STRIP_PATH_PREFIX) {
|
|
1146
|
+
const stripped = typeof stripPathPrefix === "string" ? path13.startsWith(stripPathPrefix) ? path13.slice(stripPathPrefix.length) : path13 : path13.replace(stripPathPrefix, "");
|
|
485
1147
|
let lastInnerParameter = null;
|
|
486
1148
|
const withoutInnerParameters = stripped.replace(/\{([^}]+)\}\//g, (_, parameter) => {
|
|
487
1149
|
lastInnerParameter = parameter;
|
|
@@ -502,21 +1164,21 @@ function prepareDocumentForEndpoints(doc, options) {
|
|
|
502
1164
|
const prepared = structuredClone(doc);
|
|
503
1165
|
if (dropsCookieParameters) dropCookieParameters(prepared);
|
|
504
1166
|
const pathByName = /* @__PURE__ */ new Map();
|
|
505
|
-
for (const [
|
|
1167
|
+
for (const [path13, item] of Object.entries(prepared.paths ?? {})) {
|
|
506
1168
|
if (!item) continue;
|
|
507
1169
|
for (const method of HTTP_METHODS) {
|
|
508
1170
|
const operation = item[method];
|
|
509
1171
|
if (!operation) continue;
|
|
510
1172
|
if (naming !== "rtk") {
|
|
511
|
-
const name = naming === "path" ? buildEndpointNameFromPath(method,
|
|
1173
|
+
const name = naming === "path" ? buildEndpointNameFromPath(method, path13, options.stripPathPrefix) : naming({ method, path: path13, operation });
|
|
512
1174
|
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) {
|
|
513
|
-
throw new SdkGenerationError(`endpoints.naming: "${name}" (${method.toUpperCase()} ${
|
|
1175
|
+
throw new SdkGenerationError(`endpoints.naming: "${name}" (${method.toUpperCase()} ${path13}) is no identifier.`);
|
|
514
1176
|
}
|
|
515
1177
|
const other = pathByName.get(name);
|
|
516
1178
|
if (other !== void 0) {
|
|
517
|
-
throw new SdkGenerationError(`endpoints.naming: ${other} and ${method.toUpperCase()} ${
|
|
1179
|
+
throw new SdkGenerationError(`endpoints.naming: ${other} and ${method.toUpperCase()} ${path13} are both named "${name}".`);
|
|
518
1180
|
}
|
|
519
|
-
pathByName.set(name, `${method.toUpperCase()} ${
|
|
1181
|
+
pathByName.set(name, `${method.toUpperCase()} ${path13}`);
|
|
520
1182
|
const placeholder = `dddEndpoint${endpointNamesByPlaceholder.size}`;
|
|
521
1183
|
endpointNamesByPlaceholder.set(placeholder, name);
|
|
522
1184
|
operation.operationId = placeholder;
|
|
@@ -538,108 +1200,56 @@ function restoreEndpointNames(code, locations, endpointNamesByPlaceholder) {
|
|
|
538
1200
|
return { code: restore(code), locations: restoredLocations };
|
|
539
1201
|
}
|
|
540
1202
|
var isCookieParameter = (parameter, doc) => {
|
|
541
|
-
const resolved =
|
|
1203
|
+
const resolved = resolveParameter2(parameter, doc);
|
|
542
1204
|
return typeof resolved === "object" && resolved !== null && resolved.in === "cookie";
|
|
543
1205
|
};
|
|
544
|
-
function
|
|
1206
|
+
function resolveParameter2(parameter, doc) {
|
|
545
1207
|
const ref = parameter?.$ref;
|
|
546
1208
|
if (typeof ref !== "string" || !ref.startsWith("#/components/parameters/")) return parameter;
|
|
547
1209
|
return doc.components?.parameters?.[ref.slice("#/components/parameters/".length)];
|
|
548
|
-
}
|
|
549
|
-
function hasCookieParameters(doc) {
|
|
550
|
-
for (const item of Object.values(doc.paths ?? {})) {
|
|
551
|
-
if (!item) continue;
|
|
552
|
-
const lists = [item.parameters, ...HTTP_METHODS.map((method) => item[method]?.parameters)];
|
|
553
|
-
if (lists.some((list2) => Array.isArray(list2) && list2.some((parameter) => isCookieParameter(parameter, doc)))) return true;
|
|
554
|
-
}
|
|
555
|
-
return false;
|
|
556
|
-
}
|
|
557
|
-
function dropCookieParameters(doc) {
|
|
558
|
-
for (const item of Object.values(doc.paths ?? {})) {
|
|
559
|
-
if (!item) continue;
|
|
560
|
-
if (Array.isArray(item.parameters)) item.parameters = item.parameters.filter((parameter) => !isCookieParameter(parameter, doc));
|
|
561
|
-
for (const method of HTTP_METHODS) {
|
|
562
|
-
const operation = item[method];
|
|
563
|
-
if (operation && Array.isArray(operation.parameters)) {
|
|
564
|
-
operation.parameters = operation.parameters.filter((parameter) => !isCookieParameter(parameter, doc));
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
function titleRequestBody(operation) {
|
|
570
|
-
const content = operation.requestBody?.content;
|
|
571
|
-
for (const media of Object.values(content ?? {})) {
|
|
572
|
-
const schema = media?.schema;
|
|
573
|
-
if (!schema) continue;
|
|
574
|
-
media.schema = typeof schema.$ref === "string" ? { title: REQUEST_BODY_ARG, allOf: [{ $ref: schema.$ref }] } : { ...schema, title: REQUEST_BODY_ARG };
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
// src/codegen/spec.ts
|
|
579
|
-
import * as fs2 from "fs";
|
|
580
|
-
var SUPPORTED_CONTRACT = { min: 1, max: 1 };
|
|
581
|
-
var SCHEMA_DEFINITION_MARKUP = "<SchemaDefinition schemaRef=";
|
|
582
|
-
async function loadSpec(source, timeoutMs = 6e4) {
|
|
583
|
-
let text;
|
|
584
|
-
if (isUrl(source)) {
|
|
585
|
-
let response;
|
|
586
|
-
try {
|
|
587
|
-
response = await fetch(source, { signal: AbortSignal.timeout(timeoutMs) });
|
|
588
|
-
} catch (error) {
|
|
589
|
-
throw new SdkGenerationError(`Could not fetch spec ${source}: ${error.message}`);
|
|
590
|
-
}
|
|
591
|
-
if (!response.ok) {
|
|
592
|
-
throw new SdkGenerationError(`Could not fetch spec ${source}: HTTP ${response.status} ${response.statusText}`);
|
|
593
|
-
}
|
|
594
|
-
text = await response.text();
|
|
595
|
-
} else {
|
|
596
|
-
if (!fs2.existsSync(source)) throw new SdkGenerationError(`Spec file not found: ${source}`);
|
|
597
|
-
text = fs2.readFileSync(source, "utf-8");
|
|
598
|
-
}
|
|
599
|
-
let parsed;
|
|
600
|
-
try {
|
|
601
|
-
parsed = JSON.parse(text);
|
|
602
|
-
} catch (error) {
|
|
603
|
-
throw new SdkGenerationError(`Spec ${source} is not valid JSON: ${error.message}`);
|
|
604
|
-
}
|
|
605
|
-
if (!parsed || typeof parsed !== "object" || !("paths" in parsed)) {
|
|
606
|
-
throw new SdkGenerationError(`Spec ${source} is not an OpenAPI document (no "paths").`);
|
|
607
|
-
}
|
|
608
|
-
return parsed;
|
|
609
|
-
}
|
|
610
|
-
function validateSpec(doc, source, logger) {
|
|
611
|
-
const contract = doc.info?.["x-ddd-contract"];
|
|
612
|
-
if (contract === void 0) {
|
|
613
|
-
logger.warn(`${source}: no info.x-ddd-contract \u2014 assuming a pre-contract DDD spec.`);
|
|
614
|
-
} else {
|
|
615
|
-
const number = typeof contract === "object" && contract ? contract.contract : void 0;
|
|
616
|
-
if (typeof number !== "number" || number < SUPPORTED_CONTRACT.min || number > SUPPORTED_CONTRACT.max) {
|
|
617
|
-
throw new SdkGenerationError(
|
|
618
|
-
`${source}: DDD contract ${JSON.stringify(number ?? contract)} is not supported by this @mgamadeus/ddd-web (supported: ${SUPPORTED_CONTRACT.min}\u2013${SUPPORTED_CONTRACT.max}). Update @mgamadeus/ddd-web or the backend.`
|
|
619
|
-
);
|
|
1210
|
+
}
|
|
1211
|
+
function hasCookieParameters(doc) {
|
|
1212
|
+
for (const item of Object.values(doc.paths ?? {})) {
|
|
1213
|
+
if (!item) continue;
|
|
1214
|
+
const lists = [item.parameters, ...HTTP_METHODS.map((method) => item[method]?.parameters)];
|
|
1215
|
+
if (lists.some((list2) => Array.isArray(list2) && list2.some((parameter) => isCookieParameter(parameter, doc)))) return true;
|
|
1216
|
+
}
|
|
1217
|
+
return false;
|
|
1218
|
+
}
|
|
1219
|
+
function dropCookieParameters(doc) {
|
|
1220
|
+
for (const item of Object.values(doc.paths ?? {})) {
|
|
1221
|
+
if (!item) continue;
|
|
1222
|
+
if (Array.isArray(item.parameters)) item.parameters = item.parameters.filter((parameter) => !isCookieParameter(parameter, doc));
|
|
1223
|
+
for (const method of HTTP_METHODS) {
|
|
1224
|
+
const operation = item[method];
|
|
1225
|
+
if (operation && Array.isArray(operation.parameters)) {
|
|
1226
|
+
operation.parameters = operation.parameters.filter((parameter) => !isCookieParameter(parameter, doc));
|
|
1227
|
+
}
|
|
620
1228
|
}
|
|
621
1229
|
}
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
1230
|
+
}
|
|
1231
|
+
function titleRequestBody(operation) {
|
|
1232
|
+
const content = operation.requestBody?.content;
|
|
1233
|
+
for (const media of Object.values(content ?? {})) {
|
|
1234
|
+
const schema = media?.schema;
|
|
1235
|
+
if (!schema) continue;
|
|
1236
|
+
media.schema = typeof schema.$ref === "string" ? { title: REQUEST_BODY_ARG, allOf: [{ $ref: schema.$ref }] } : { ...schema, title: REQUEST_BODY_ARG };
|
|
627
1237
|
}
|
|
628
1238
|
}
|
|
629
1239
|
|
|
630
1240
|
// src/codegen/generate.ts
|
|
631
|
-
import * as
|
|
632
|
-
import * as
|
|
633
|
-
import * as
|
|
1241
|
+
import * as fs9 from "fs";
|
|
1242
|
+
import * as os2 from "os";
|
|
1243
|
+
import * as path11 from "path";
|
|
634
1244
|
|
|
635
1245
|
// src/codegen/typescript.ts
|
|
636
|
-
import { createRequire } from "module";
|
|
1246
|
+
import { createRequire as createRequire3 } from "module";
|
|
637
1247
|
var cached;
|
|
638
1248
|
function loadTypeScript() {
|
|
639
1249
|
if (cached) return cached;
|
|
640
|
-
const require2 =
|
|
1250
|
+
const require2 = createRequire3(import.meta.url);
|
|
641
1251
|
const codegenEntry = require2.resolve("@rtk-query/codegen-openapi");
|
|
642
|
-
cached =
|
|
1252
|
+
cached = createRequire3(codegenEntry)("typescript");
|
|
643
1253
|
return cached;
|
|
644
1254
|
}
|
|
645
1255
|
|
|
@@ -894,270 +1504,74 @@ function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
|
|
|
894
1504
|
if (!returned) continue;
|
|
895
1505
|
let url;
|
|
896
1506
|
let method;
|
|
897
|
-
let accessors = [];
|
|
898
|
-
let bodyArg;
|
|
899
|
-
for (const member of returned.properties) {
|
|
900
|
-
if (!ts.isPropertyAssignment(member) || !ts.isIdentifier(member.name)) continue;
|
|
901
|
-
const init = member.initializer;
|
|
902
|
-
if (member.name.text === "url") {
|
|
903
|
-
if (ts.isNoSubstitutionTemplateLiteral(init) || ts.isStringLiteral(init)) url = init.text;
|
|
904
|
-
else if (ts.isTemplateExpression(init)) {
|
|
905
|
-
url = init.getText(sourceFile).slice(1, -1);
|
|
906
|
-
accessors = templateAccessors(ts, init, sourceFile);
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
if (member.name.text === "method" && ts.isStringLiteral(init)) method = init.text;
|
|
910
|
-
if (member.name.text === "body" && (ts.isIdentifier(init) || ts.isPropertyAccessExpression(init))) {
|
|
911
|
-
const text = init.getText(sourceFile);
|
|
912
|
-
if (/^queryArg(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/.test(text)) bodyArg = text.replace(/^queryArg\b/, "arg");
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
if (url === void 0) {
|
|
916
|
-
logger.warn(`No extractable URL for endpoint "${key}" \u2014 skipping.`);
|
|
917
|
-
return null;
|
|
918
|
-
}
|
|
919
|
-
const path11 = location?.path ?? toOpenApiPath(url);
|
|
920
|
-
const placeholders = [...path11.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
921
|
-
const pathArgs = {};
|
|
922
|
-
placeholders.forEach((name, index) => {
|
|
923
|
-
const accessor = accessors[index];
|
|
924
|
-
if (accessor !== void 0) pathArgs[name] = accessor;
|
|
925
|
-
});
|
|
926
|
-
return {
|
|
927
|
-
key,
|
|
928
|
-
buildType,
|
|
929
|
-
url,
|
|
930
|
-
method: (location?.method ?? method ?? "GET").toUpperCase(),
|
|
931
|
-
path: path11,
|
|
932
|
-
pathArgs,
|
|
933
|
-
...bodyArg ? { bodyArg } : {},
|
|
934
|
-
...responseType ? { responseType } : {}
|
|
935
|
-
};
|
|
936
|
-
}
|
|
937
|
-
return null;
|
|
938
|
-
}
|
|
939
|
-
function parseApiEndpoints(source, logger, locations = /* @__PURE__ */ new Map()) {
|
|
940
|
-
const ts = loadTypeScript();
|
|
941
|
-
const sourceFile = ts.createSourceFile("api.ts", source, ts.ScriptTarget.Latest, true);
|
|
942
|
-
const results = [];
|
|
943
|
-
const visit = (node) => {
|
|
944
|
-
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && ts.isCallExpression(node.initializer)) {
|
|
945
|
-
const callee = node.initializer.expression;
|
|
946
|
-
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && callee.expression.text === "build") {
|
|
947
|
-
const buildType = callee.name.text;
|
|
948
|
-
if (buildType === "query" || buildType === "mutation") {
|
|
949
|
-
const key = node.name.text;
|
|
950
|
-
const info = readEndpoint(ts, key, buildType, node.initializer, sourceFile, locations.get(key), logger);
|
|
951
|
-
if (info) results.push(info);
|
|
952
|
-
return;
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
}
|
|
956
|
-
ts.forEachChild(node, visit);
|
|
957
|
-
};
|
|
958
|
-
ts.forEachChild(sourceFile, visit);
|
|
959
|
-
return results;
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
// src/codegen/files.ts
|
|
963
|
-
import * as fs3 from "fs";
|
|
964
|
-
import * as path2 from "path";
|
|
965
|
-
var OutputFiles = class {
|
|
966
|
-
files = /* @__PURE__ */ new Map();
|
|
967
|
-
lowerCaseIndex = /* @__PURE__ */ new Map();
|
|
968
|
-
set(filePath, content) {
|
|
969
|
-
const absolute = path2.resolve(filePath);
|
|
970
|
-
this.files.set(absolute, { content, generatedThisRun: true });
|
|
971
|
-
this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);
|
|
972
|
-
}
|
|
973
|
-
get(filePath) {
|
|
974
|
-
return this.files.get(path2.resolve(filePath))?.content;
|
|
975
|
-
}
|
|
976
|
-
isGeneratedThisRun(filePath) {
|
|
977
|
-
return this.files.get(path2.resolve(filePath))?.generatedThisRun ?? false;
|
|
978
|
-
}
|
|
979
|
-
/** Case-insensitive lookup; returns the stored path spelling. */
|
|
980
|
-
findPath(filePath) {
|
|
981
|
-
return this.lowerCaseIndex.get(path2.resolve(filePath).toLowerCase());
|
|
982
|
-
}
|
|
983
|
-
paths() {
|
|
984
|
-
return [...this.files.keys()];
|
|
985
|
-
}
|
|
986
|
-
/** Seeds the store with existing `.ts` files below `dir` (for runs that regenerate only some apis). */
|
|
987
|
-
seedFromDisk(dir) {
|
|
988
|
-
for (const absolute of listTsFiles(dir)) {
|
|
989
|
-
this.files.set(absolute, { content: fs3.readFileSync(absolute, "utf-8"), generatedThisRun: false });
|
|
990
|
-
this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);
|
|
991
|
-
}
|
|
992
|
-
}
|
|
993
|
-
};
|
|
994
|
-
function listTsFiles(dir) {
|
|
995
|
-
if (!fs3.existsSync(dir)) return [];
|
|
996
|
-
const result = [];
|
|
997
|
-
for (const entry of fs3.readdirSync(dir, { withFileTypes: true })) {
|
|
998
|
-
const absolute = path2.join(dir, entry.name);
|
|
999
|
-
if (entry.isDirectory()) result.push(...listTsFiles(absolute));
|
|
1000
|
-
else if (entry.isFile() && entry.name.endsWith(".ts")) result.push(absolute);
|
|
1001
|
-
}
|
|
1002
|
-
return result;
|
|
1003
|
-
}
|
|
1004
|
-
|
|
1005
|
-
// src/codegen/format.ts
|
|
1006
|
-
import { execFileSync } from "child_process";
|
|
1007
|
-
import * as fs4 from "fs";
|
|
1008
|
-
import { createRequire as createRequire2 } from "module";
|
|
1009
|
-
import * as path3 from "path";
|
|
1010
|
-
import prettier from "prettier";
|
|
1011
|
-
async function formatFiles(files) {
|
|
1012
|
-
for (const filePath of files.paths()) {
|
|
1013
|
-
const options = await prettier.resolveConfig(filePath, { editorconfig: true }) ?? {};
|
|
1014
|
-
files.set(filePath, await prettier.format(files.get(filePath), { ...options, filepath: filePath }));
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
function resolveTscOfInstallation(base) {
|
|
1018
|
-
let packageJsonPath;
|
|
1019
|
-
try {
|
|
1020
|
-
packageJsonPath = createRequire2(base).resolve("typescript/package.json");
|
|
1021
|
-
} catch {
|
|
1022
|
-
return null;
|
|
1023
|
-
}
|
|
1024
|
-
const packageJson = JSON.parse(fs4.readFileSync(packageJsonPath, "utf-8"));
|
|
1025
|
-
const binEntry = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin?.tsc;
|
|
1026
|
-
if (!binEntry) return null;
|
|
1027
|
-
const executable = path3.resolve(path3.dirname(packageJsonPath), binEntry);
|
|
1028
|
-
return fs4.existsSync(executable) ? { executable, version: packageJson.version ?? "unknown" } : null;
|
|
1029
|
-
}
|
|
1030
|
-
function resolveTypeScriptCompiler(rootDir) {
|
|
1031
|
-
const projectCompiler = resolveTscOfInstallation(path3.join(rootDir, "package.json"));
|
|
1032
|
-
if (projectCompiler) return { ...projectCompiler, origin: "project" };
|
|
1033
|
-
const ownRequire = createRequire2(import.meta.url);
|
|
1034
|
-
for (const base of [import.meta.url, ownRequire.resolve("@rtk-query/codegen-openapi")]) {
|
|
1035
|
-
const generatorCompiler = resolveTscOfInstallation(base);
|
|
1036
|
-
if (generatorCompiler) return { ...generatorCompiler, origin: "generator" };
|
|
1037
|
-
}
|
|
1038
|
-
throw new SdkGenerationError("No TypeScript compiler found for the type check (install typescript in the project, or pass --skip-tsc).");
|
|
1039
|
-
}
|
|
1040
|
-
function buildCompilerCommand(executable, args) {
|
|
1041
|
-
if (/\.(c|m)?js$/.test(executable)) return [process.execPath, [executable, ...args]];
|
|
1042
|
-
const head = fs4.readFileSync(executable).subarray(0, 100).toString("latin1");
|
|
1043
|
-
return head.startsWith("#!") && head.split("\n", 1)[0].includes("node") ? [process.execPath, [executable, ...args]] : [executable, args];
|
|
1044
|
-
}
|
|
1045
|
-
function typecheck(rootDir, tsconfig, logger) {
|
|
1046
|
-
if (!fs4.existsSync(tsconfig)) {
|
|
1047
|
-
logger.warn(`No ${path3.relative(rootDir, tsconfig) || tsconfig} \u2014 skipping the type check.`);
|
|
1048
|
-
return false;
|
|
1049
|
-
}
|
|
1050
|
-
const compiler = resolveTypeScriptCompiler(rootDir);
|
|
1051
|
-
logger.info(
|
|
1052
|
-
`Type check with TypeScript ${compiler.version} (${compiler.origin === "project" ? "the project's compiler" : "the generator's own compiler \u2014 the project has no typescript"}).`
|
|
1053
|
-
);
|
|
1054
|
-
const [command, args] = buildCompilerCommand(compiler.executable, ["--noEmit", "-p", tsconfig]);
|
|
1055
|
-
try {
|
|
1056
|
-
execFileSync(command, args, {
|
|
1057
|
-
cwd: rootDir,
|
|
1058
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
1059
|
-
encoding: "utf-8"
|
|
1060
|
-
});
|
|
1061
|
-
} catch (error) {
|
|
1062
|
-
const output = error.stdout ?? "";
|
|
1063
|
-
throw new SdkGenerationError(`Type check failed:
|
|
1064
|
-
${output.split("\n").slice(0, 40).join("\n")}`);
|
|
1065
|
-
}
|
|
1066
|
-
return true;
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
// src/codegen/models.ts
|
|
1070
|
-
import * as path4 from "path";
|
|
1071
|
-
|
|
1072
|
-
// src/contract/extensions.ts
|
|
1073
|
-
function hasSideEffects(method, operation) {
|
|
1074
|
-
const explicit = operation?.["x-ddd-side-effects"];
|
|
1075
|
-
if (typeof explicit === "boolean") {
|
|
1076
|
-
return explicit;
|
|
1077
|
-
}
|
|
1078
|
-
return !["get", "head", "options", "trace"].includes(method.toLowerCase());
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
// src/codegen/operations.ts
|
|
1082
|
-
function testPattern(pattern, value) {
|
|
1083
|
-
pattern.lastIndex = 0;
|
|
1084
|
-
const result = pattern.test(value);
|
|
1085
|
-
pattern.lastIndex = 0;
|
|
1086
|
-
return result;
|
|
1087
|
-
}
|
|
1088
|
-
function matchesOperation(override, method, path11) {
|
|
1089
|
-
if (override.method && override.method.toLowerCase() !== method) return false;
|
|
1090
|
-
return typeof override.path === "string" ? override.path === path11 : testPattern(override.path, path11);
|
|
1091
|
-
}
|
|
1092
|
-
function canonical(value) {
|
|
1093
|
-
return JSON.stringify(
|
|
1094
|
-
value,
|
|
1095
|
-
(_key, inner) => inner && typeof inner === "object" && !Array.isArray(inner) ? Object.fromEntries(Object.keys(inner).sort().map((key) => [key, inner[key]])) : inner
|
|
1096
|
-
) ?? "undefined";
|
|
1097
|
-
}
|
|
1098
|
-
function isUpsertTwin(post, patch) {
|
|
1099
|
-
if (post["x-ddd-side-effects"] !== patch["x-ddd-side-effects"]) return false;
|
|
1100
|
-
const postEntity = isEntityExtension(post["x-ddd-entity"]) ? post["x-ddd-entity"] : void 0;
|
|
1101
|
-
const patchEntity = isEntityExtension(patch["x-ddd-entity"]) ? patch["x-ddd-entity"] : void 0;
|
|
1102
|
-
if (postEntity && patchEntity) {
|
|
1103
|
-
return postEntity.action === "upsert" && patchEntity.action === "upsert" && postEntity.schema === patchEntity.schema;
|
|
1104
|
-
}
|
|
1105
|
-
if (postEntity && postEntity.action !== "upsert" || patchEntity && patchEntity.action !== "upsert") return false;
|
|
1106
|
-
if (post.summary === void 0 || post.summary !== patch.summary) return false;
|
|
1107
|
-
return ["parameters", "requestBody", "responses"].every((key) => canonical(post[key]) === canonical(patch[key]));
|
|
1108
|
-
}
|
|
1109
|
-
function isEntityExtension(value) {
|
|
1110
|
-
return !!value && typeof value === "object" && typeof value.schema === "string" && typeof value.action === "string";
|
|
1111
|
-
}
|
|
1112
|
-
function indexOperations(doc, overrides, skipUpdatePostTwins) {
|
|
1113
|
-
const byKey = /* @__PURE__ */ new Map();
|
|
1114
|
-
for (const { method, path: path11, operation } of listOperations(doc)) {
|
|
1115
|
-
const extension = operation["x-ddd-side-effects"];
|
|
1116
|
-
const override = overrides.find((candidate) => matchesOperation(candidate, method, path11));
|
|
1117
|
-
let sideEffects = hasSideEffects(method, operation);
|
|
1118
|
-
let explicit = false;
|
|
1119
|
-
if (typeof extension === "boolean") {
|
|
1120
|
-
sideEffects = extension;
|
|
1121
|
-
explicit = true;
|
|
1122
|
-
} else if (override) {
|
|
1123
|
-
sideEffects = override.sideEffects;
|
|
1124
|
-
explicit = true;
|
|
1507
|
+
let accessors = [];
|
|
1508
|
+
let bodyArg;
|
|
1509
|
+
for (const member of returned.properties) {
|
|
1510
|
+
if (!ts.isPropertyAssignment(member) || !ts.isIdentifier(member.name)) continue;
|
|
1511
|
+
const init = member.initializer;
|
|
1512
|
+
if (member.name.text === "url") {
|
|
1513
|
+
if (ts.isNoSubstitutionTemplateLiteral(init) || ts.isStringLiteral(init)) url = init.text;
|
|
1514
|
+
else if (ts.isTemplateExpression(init)) {
|
|
1515
|
+
url = init.getText(sourceFile).slice(1, -1);
|
|
1516
|
+
accessors = templateAccessors(ts, init, sourceFile);
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
if (member.name.text === "method" && ts.isStringLiteral(init)) method = init.text;
|
|
1520
|
+
if (member.name.text === "body" && (ts.isIdentifier(init) || ts.isPropertyAccessExpression(init))) {
|
|
1521
|
+
const text = init.getText(sourceFile);
|
|
1522
|
+
if (/^queryArg(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/.test(text)) bodyArg = text.replace(/^queryArg\b/, "arg");
|
|
1523
|
+
}
|
|
1125
1524
|
}
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
endpointType,
|
|
1137
|
-
...entity ? { entity } : {}
|
|
1525
|
+
if (url === void 0) {
|
|
1526
|
+
logger.warn(`No extractable URL for endpoint "${key}" \u2014 skipping.`);
|
|
1527
|
+
return null;
|
|
1528
|
+
}
|
|
1529
|
+
const path13 = location?.path ?? toOpenApiPath(url);
|
|
1530
|
+
const placeholders = [...path13.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
1531
|
+
const pathArgs = {};
|
|
1532
|
+
placeholders.forEach((name, index) => {
|
|
1533
|
+
const accessor = accessors[index];
|
|
1534
|
+
if (accessor !== void 0) pathArgs[name] = accessor;
|
|
1138
1535
|
});
|
|
1536
|
+
return {
|
|
1537
|
+
key,
|
|
1538
|
+
buildType,
|
|
1539
|
+
url,
|
|
1540
|
+
method: (location?.method ?? method ?? "GET").toUpperCase(),
|
|
1541
|
+
path: path13,
|
|
1542
|
+
pathArgs,
|
|
1543
|
+
...bodyArg ? { bodyArg } : {},
|
|
1544
|
+
...responseType ? { responseType } : {}
|
|
1545
|
+
};
|
|
1139
1546
|
}
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1547
|
+
return null;
|
|
1548
|
+
}
|
|
1549
|
+
function parseApiEndpoints(source, logger, locations = /* @__PURE__ */ new Map()) {
|
|
1550
|
+
const ts = loadTypeScript();
|
|
1551
|
+
const sourceFile = ts.createSourceFile("api.ts", source, ts.ScriptTarget.Latest, true);
|
|
1552
|
+
const results = [];
|
|
1553
|
+
const visit = (node) => {
|
|
1554
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && ts.isCallExpression(node.initializer)) {
|
|
1555
|
+
const callee = node.initializer.expression;
|
|
1556
|
+
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && callee.expression.text === "build") {
|
|
1557
|
+
const buildType = callee.name.text;
|
|
1558
|
+
if (buildType === "query" || buildType === "mutation") {
|
|
1559
|
+
const key = node.name.text;
|
|
1560
|
+
const info = readEndpoint(ts, key, buildType, node.initializer, sourceFile, locations.get(key), logger);
|
|
1561
|
+
if (info) results.push(info);
|
|
1562
|
+
return;
|
|
1563
|
+
}
|
|
1147
1564
|
}
|
|
1148
1565
|
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
const result = [];
|
|
1154
|
-
for (const info of index.byKey.values()) {
|
|
1155
|
-
const rtkDefault = info.method === "get" ? "query" : "mutation";
|
|
1156
|
-
if (info.endpointType !== rtkDefault) result.push({ method: info.method, path: info.path, type: info.endpointType });
|
|
1157
|
-
}
|
|
1158
|
-
return result;
|
|
1566
|
+
ts.forEachChild(node, visit);
|
|
1567
|
+
};
|
|
1568
|
+
ts.forEachChild(sourceFile, visit);
|
|
1569
|
+
return results;
|
|
1159
1570
|
}
|
|
1160
1571
|
|
|
1572
|
+
// src/codegen/models.ts
|
|
1573
|
+
import * as path6 from "path";
|
|
1574
|
+
|
|
1161
1575
|
// src/codegen/response-handlers.ts
|
|
1162
1576
|
var DDD_WEB_API_IMPORT = "@mgamadeus/ddd-web/api";
|
|
1163
1577
|
var TEXT_CONTENT_TYPES = ["text/html", "text/plain", "text/xml"];
|
|
@@ -1197,10 +1611,10 @@ function detectResponseKind(responses) {
|
|
|
1197
1611
|
}
|
|
1198
1612
|
function detectResponseHandlerEndpoints(doc, endpoints, overrides = []) {
|
|
1199
1613
|
const kinds = /* @__PURE__ */ new Map();
|
|
1200
|
-
for (const { method, path:
|
|
1201
|
-
const override = overrides.find((candidate) => matchesOperation(candidate, method,
|
|
1614
|
+
for (const { method, path: path13, operation } of listOperations(doc)) {
|
|
1615
|
+
const override = overrides.find((candidate) => matchesOperation(candidate, method, path13));
|
|
1202
1616
|
const kind = override ? override.handler : detectResponseKind(operation.responses);
|
|
1203
|
-
if (kind !== "json") kinds.set(operationKey(method,
|
|
1617
|
+
if (kind !== "json") kinds.set(operationKey(method, path13), kind);
|
|
1204
1618
|
}
|
|
1205
1619
|
const keys = /* @__PURE__ */ new Map();
|
|
1206
1620
|
if (kinds.size === 0) return keys;
|
|
@@ -1425,22 +1839,22 @@ function registryMatch(name, registry) {
|
|
|
1425
1839
|
return null;
|
|
1426
1840
|
}
|
|
1427
1841
|
function importSpecifier(fromFile, toFile, esm) {
|
|
1428
|
-
let
|
|
1429
|
-
if (!
|
|
1430
|
-
return esm ? `${
|
|
1842
|
+
let relative7 = path6.relative(path6.dirname(fromFile), toFile.replace(/\.ts$/, "")).replace(/\\/g, "/");
|
|
1843
|
+
if (!relative7.startsWith(".")) relative7 = `./${relative7}`;
|
|
1844
|
+
return esm ? `${relative7}.js` : relative7;
|
|
1431
1845
|
}
|
|
1432
1846
|
var EXPORTED_NAME = /^export (?:type|interface) (\w+)/m;
|
|
1433
1847
|
function extractModels(input) {
|
|
1434
1848
|
const { modelsDir, registry, files, logger } = input;
|
|
1435
1849
|
const esm = input.esm === true;
|
|
1436
1850
|
const responseKinds = input.responseKinds ?? /* @__PURE__ */ new Map();
|
|
1437
|
-
const indexPath =
|
|
1851
|
+
const indexPath = path6.join(modelsDir, "index.ts");
|
|
1438
1852
|
const nameOwners = /* @__PURE__ */ new Map();
|
|
1439
1853
|
for (const filePath of files.paths()) {
|
|
1440
|
-
const
|
|
1441
|
-
if (
|
|
1854
|
+
const relative7 = path6.relative(modelsDir, filePath);
|
|
1855
|
+
if (relative7.startsWith("..") || path6.isAbsolute(relative7) || path6.resolve(filePath) === path6.resolve(indexPath)) continue;
|
|
1442
1856
|
const name = files.get(filePath)?.match(EXPORTED_NAME)?.[1];
|
|
1443
|
-
if (name && !nameOwners.has(name)) nameOwners.set(name,
|
|
1857
|
+
if (name && !nameOwners.has(name)) nameOwners.set(name, path6.resolve(filePath).toLowerCase());
|
|
1444
1858
|
}
|
|
1445
1859
|
const documentModels = input.documentModels ?? /* @__PURE__ */ new Map();
|
|
1446
1860
|
const constsByFile = input.constsByFile ?? /* @__PURE__ */ new Map();
|
|
@@ -1448,16 +1862,16 @@ function extractModels(input) {
|
|
|
1448
1862
|
const documentModel = findDocumentModel(oldName, documentModels);
|
|
1449
1863
|
if (documentModel) {
|
|
1450
1864
|
const { segments, leafName } = placeDocumentModel(documentModel.model);
|
|
1451
|
-
const planned =
|
|
1865
|
+
const planned = path6.join(modelsDir, ...segments, `${leafName}${documentModel.suffix}.ts`);
|
|
1452
1866
|
return { filePath: files.findPath(planned) ?? planned, leafName: `${leafName}${documentModel.suffix}`, segments };
|
|
1453
1867
|
}
|
|
1454
1868
|
const match = registryMatch(oldName, registry);
|
|
1455
1869
|
if (match) {
|
|
1456
|
-
const planned =
|
|
1870
|
+
const planned = path6.join(modelsDir, ...match.segments, `${match.leafName}.ts`);
|
|
1457
1871
|
return { filePath: files.findPath(planned) ?? planned, leafName: match.leafName, segments: match.segments };
|
|
1458
1872
|
}
|
|
1459
1873
|
const folder = /^(Get|Post|Put|Patch|Delete)/.test(oldName) ? "_endpoints" : "_others";
|
|
1460
|
-
return { filePath:
|
|
1874
|
+
return { filePath: path6.join(modelsDir, folder, `${oldName}.ts`), leafName: oldName, segments: [] };
|
|
1461
1875
|
};
|
|
1462
1876
|
const originalNames = exportedTypeDeclarations(input.apiSource).map((declaration) => declaration.name);
|
|
1463
1877
|
const renameMap = /* @__PURE__ */ new Map();
|
|
@@ -1468,7 +1882,7 @@ function extractModels(input) {
|
|
|
1468
1882
|
const uniqueNameByPath = input.uniqueNameByPath ?? /* @__PURE__ */ new Map();
|
|
1469
1883
|
for (const oldName of originalNames) {
|
|
1470
1884
|
const { filePath, leafName, segments } = placement(oldName);
|
|
1471
|
-
const pathKey =
|
|
1885
|
+
const pathKey = path6.resolve(filePath).toLowerCase();
|
|
1472
1886
|
const isDocumentModel = findDocumentModel(oldName, documentModels) !== null;
|
|
1473
1887
|
let name = nameByPath.get(pathKey) ?? uniqueNameByPath.get(pathKey) ?? (isDocumentModel ? void 0 : files.get(filePath)?.match(EXPORTED_NAME)?.[1]);
|
|
1474
1888
|
if (!name) {
|
|
@@ -1500,7 +1914,7 @@ function extractModels(input) {
|
|
|
1500
1914
|
logger.warn(`Re-extracted type "${name}" not in rename map \u2014 skipping.`);
|
|
1501
1915
|
continue;
|
|
1502
1916
|
}
|
|
1503
|
-
if (input.modelsOnly &&
|
|
1917
|
+
if (input.modelsOnly && path6.relative(modelsDir, filePath).split(path6.sep)[0] === "_endpoints") continue;
|
|
1504
1918
|
entries.push({ name, body: text, filePath });
|
|
1505
1919
|
}
|
|
1506
1920
|
const pathByName = new Map(entries.map((entry) => [entry.name, entry.filePath]));
|
|
@@ -1509,7 +1923,7 @@ function extractModels(input) {
|
|
|
1509
1923
|
const usedInApi = [...new Set(entries.map((entry) => entry.name))].filter(
|
|
1510
1924
|
(name) => new RegExp(`(?<![A-Za-z0-9_$])${escapeRegExp(name)}(?![A-Za-z0-9_$])`).test(strippedSource)
|
|
1511
1925
|
);
|
|
1512
|
-
const isPresentation = (filePath) => filePath.split(
|
|
1926
|
+
const isPresentation = (filePath) => filePath.split(path6.sep).includes("Presentation");
|
|
1513
1927
|
const barrelEntries = [];
|
|
1514
1928
|
const exportNameOf = (uniqueName) => exportNameByUniqueName.get(uniqueName) ?? uniqueName;
|
|
1515
1929
|
const writeIndex = input.writeIndex !== false;
|
|
@@ -1532,7 +1946,7 @@ function extractModels(input) {
|
|
|
1532
1946
|
if (input.enumConsts && documentModel) {
|
|
1533
1947
|
const applied = applyEnumConsts(body, name, documentModel, input.modelOptions);
|
|
1534
1948
|
typedBody = applied.body;
|
|
1535
|
-
const fileKey =
|
|
1949
|
+
const fileKey = path6.resolve(filePath).toLowerCase();
|
|
1536
1950
|
const fileConsts2 = constsByFile.get(fileKey) ?? /* @__PURE__ */ new Map();
|
|
1537
1951
|
for (const [constName, text] of applied.consts) if (!fileConsts2.has(constName)) fileConsts2.set(constName, text);
|
|
1538
1952
|
if (fileConsts2.size > 0) constsByFile.set(fileKey, fileConsts2);
|
|
@@ -1560,14 +1974,14 @@ function extractModels(input) {
|
|
|
1560
1974
|
|
|
1561
1975
|
export default ${name};
|
|
1562
1976
|
`;
|
|
1563
|
-
const fileConsts = constsByFile.get(
|
|
1977
|
+
const fileConsts = constsByFile.get(path6.resolve(filePath).toLowerCase());
|
|
1564
1978
|
files.set(filePath, fileConsts ? withEnumConsts(content, name, [...fileConsts.values()]) : content);
|
|
1565
|
-
if (isPresentation(
|
|
1979
|
+
if (isPresentation(path6.relative(modelsDir, filePath))) continue;
|
|
1566
1980
|
if (name !== uniqueName) continue;
|
|
1567
1981
|
barrelEntries.push(`export * from '${importSpecifier(indexPath, filePath, esm)}';`);
|
|
1568
1982
|
}
|
|
1569
1983
|
if (writeIndex) writeBarrel(files, indexPath, barrelEntries);
|
|
1570
|
-
const others = entries.filter((entry) =>
|
|
1984
|
+
const others = entries.filter((entry) => path6.relative(modelsDir, entry.filePath).split(path6.sep)[0] === "_others");
|
|
1571
1985
|
if (others.length > 0) {
|
|
1572
1986
|
logger.warn(`${others.length} type(s) without a namespace match placed in _others/: ${others.map((e) => e.name).join(", ")}`);
|
|
1573
1987
|
}
|
|
@@ -1595,7 +2009,7 @@ function writeBarrel(files, indexPath, newEntries) {
|
|
|
1595
2009
|
for (const entry of [...existing, ...newEntries]) {
|
|
1596
2010
|
const specifier = entry.match(/from ['"](.+)['"];?\s*$/)?.[1];
|
|
1597
2011
|
if (!specifier) continue;
|
|
1598
|
-
const target =
|
|
2012
|
+
const target = path6.resolve(path6.dirname(indexPath), specifier.replace(/\.js$/, "")) + ".ts";
|
|
1599
2013
|
const key = target.toLowerCase();
|
|
1600
2014
|
if (seen.has(key) || !files.findPath(target)) continue;
|
|
1601
2015
|
seen.add(key);
|
|
@@ -1617,6 +2031,252 @@ ${defaultExport}
|
|
|
1617
2031
|
`;
|
|
1618
2032
|
}
|
|
1619
2033
|
|
|
2034
|
+
// src/codegen/msw-handlers.ts
|
|
2035
|
+
import * as path7 from "path";
|
|
2036
|
+
var IDENTIFIER2 = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
2037
|
+
function renderMswHandlers(input) {
|
|
2038
|
+
const ts = loadTypeScript();
|
|
2039
|
+
const apiFile = ts.createSourceFile("api.ts", input.apiSource, ts.ScriptTarget.Latest, true);
|
|
2040
|
+
const apiImports = readImports(ts, apiFile, input.apiFilePath, input.files);
|
|
2041
|
+
const typeArguments = readTypeArguments(ts, apiFile);
|
|
2042
|
+
const typeImports = /* @__PURE__ */ new Map();
|
|
2043
|
+
const mockImports = /* @__PURE__ */ new Map();
|
|
2044
|
+
const mockLocalBySpecifier = /* @__PURE__ */ new Map();
|
|
2045
|
+
const mockOf = (model) => {
|
|
2046
|
+
const options = input.modelMocks;
|
|
2047
|
+
if (!options) return null;
|
|
2048
|
+
const relative7 = path7.relative(input.modelsDir, model.file).replace(/\.ts$/, "").split(path7.sep).join("/");
|
|
2049
|
+
if (relative7.startsWith("..") || path7.isAbsolute(relative7)) return null;
|
|
2050
|
+
const modelName = path7.basename(relative7);
|
|
2051
|
+
const prefix = options.importPrefix.endsWith("/") || options.importPrefix === "" ? options.importPrefix : `${options.importPrefix}/`;
|
|
2052
|
+
const specifier = `${prefix}${relative7}${options.fileSuffix ?? ".mock"}`;
|
|
2053
|
+
const exported = options.exportName?.(modelName, relative7) ?? `get${modelName}Mock`;
|
|
2054
|
+
const key = `${specifier}\0${exported}`;
|
|
2055
|
+
const known = mockLocalBySpecifier.get(key);
|
|
2056
|
+
if (known) return known;
|
|
2057
|
+
let local = exported;
|
|
2058
|
+
for (let index = 2; mockImports.has(local) || typeImports.has(local); index++) local = `${exported}${index}`;
|
|
2059
|
+
mockImports.set(local, { exported, specifier });
|
|
2060
|
+
mockLocalBySpecifier.set(key, local);
|
|
2061
|
+
return local;
|
|
2062
|
+
};
|
|
2063
|
+
const useType = (text) => {
|
|
2064
|
+
for (const match of text.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)) {
|
|
2065
|
+
const imported = apiImports.get(match[0]);
|
|
2066
|
+
if (imported) typeImports.set(match[0], imported);
|
|
2067
|
+
}
|
|
2068
|
+
return text;
|
|
2069
|
+
};
|
|
2070
|
+
const entries = [];
|
|
2071
|
+
for (const endpoint of input.endpoints) {
|
|
2072
|
+
const types = typeArguments.get(endpoint.key);
|
|
2073
|
+
if (!types) continue;
|
|
2074
|
+
const method = endpoint.method.toLowerCase();
|
|
2075
|
+
const kind = input.responseKinds.get(endpoint.key) ?? "json";
|
|
2076
|
+
const operation = input.doc.paths?.[endpoint.path]?.[method];
|
|
2077
|
+
const status = kind === "blob" ? 200 : successStatus(operation?.responses);
|
|
2078
|
+
const argType = useType(types.arg ?? "void");
|
|
2079
|
+
let responseType = kind === "blob" ? "Blob | string | null" : useType(types.response ?? "unknown");
|
|
2080
|
+
let defaultMock = "null";
|
|
2081
|
+
if (kind === "json" && types.response && IDENTIFIER2.test(types.response)) {
|
|
2082
|
+
const shape = responseShape(ts, types.response, apiImports, input.files);
|
|
2083
|
+
const local = shape ? mockOf(shape.model) : null;
|
|
2084
|
+
if (shape && local) defaultMock = shape.array ? `[${local}()]` : `${local}()`;
|
|
2085
|
+
}
|
|
2086
|
+
if (kind === "text" && responseType === "unknown") responseType = "string";
|
|
2087
|
+
const pattern = `*${endpoint.path.replace(/\{[^}]+\}/g, "*")}`;
|
|
2088
|
+
const key = IDENTIFIER2.test(endpoint.key) ? endpoint.key : JSON.stringify(endpoint.key);
|
|
2089
|
+
entries.push(
|
|
2090
|
+
` ${key}: (custom?: Partial<StoryMock<${responseType}, ${argType}>>) =>
|
|
2091
|
+
mockOperation<${responseType}, ${argType}>(${JSON.stringify(method)}, ${JSON.stringify(pattern)}, ${JSON.stringify(endpoint.path)}, ${JSON.stringify(kind)}, ${status}, () => ${defaultMock}, custom),`
|
|
2092
|
+
);
|
|
2093
|
+
}
|
|
2094
|
+
const specifierOf = (file) => {
|
|
2095
|
+
let relative7 = path7.relative(path7.dirname(input.outputFile), file.replace(/\.ts$/, "")).split(path7.sep).join("/");
|
|
2096
|
+
if (!relative7.startsWith(".")) relative7 = `./${relative7}`;
|
|
2097
|
+
if (input.esm) return `${relative7}.js`;
|
|
2098
|
+
return relative7.endsWith("/index") ? relative7.slice(0, -"/index".length) : relative7;
|
|
2099
|
+
};
|
|
2100
|
+
const typeLines = groupImports([...typeImports].map(([local, { exported, file }]) => ({ local, exported, specifier: specifierOf(file) })), true);
|
|
2101
|
+
const mockLines = groupImports([...mockImports].map(([local, { exported, specifier }]) => ({ local, exported, specifier })), false);
|
|
2102
|
+
return [
|
|
2103
|
+
"// Generated by @mgamadeus/ddd-web (mswHandlers). Do not edit.",
|
|
2104
|
+
"import { delay, http, HttpResponse, type DefaultBodyType, type HttpResponseResolver, type PathParams } from 'msw';",
|
|
2105
|
+
...typeLines,
|
|
2106
|
+
...mockLines,
|
|
2107
|
+
"",
|
|
2108
|
+
RUNTIME,
|
|
2109
|
+
`/** MSW handler factories of ${input.exportName.replace(/Mocks$/, "")}: one per operation, answering its default mock. */`,
|
|
2110
|
+
`export const ${input.exportName} = {`,
|
|
2111
|
+
...entries,
|
|
2112
|
+
"};",
|
|
2113
|
+
""
|
|
2114
|
+
].join("\n");
|
|
2115
|
+
}
|
|
2116
|
+
function groupImports(names, typeOnly) {
|
|
2117
|
+
const bySpecifier = /* @__PURE__ */ new Map();
|
|
2118
|
+
for (const { local, exported, specifier } of names) {
|
|
2119
|
+
const list2 = bySpecifier.get(specifier) ?? [];
|
|
2120
|
+
list2.push(exported === local ? local : `${exported} as ${local}`);
|
|
2121
|
+
bySpecifier.set(specifier, list2);
|
|
2122
|
+
}
|
|
2123
|
+
return [...bySpecifier].map(([specifier, list2]) => `import ${typeOnly ? "type " : ""}{ ${list2.join(", ")} } from '${specifier}';`);
|
|
2124
|
+
}
|
|
2125
|
+
var RUNTIME = `type ResolverInfo = Parameters<HttpResponseResolver<PathParams, DefaultBodyType>>[0];
|
|
2126
|
+
|
|
2127
|
+
/** The path parameters and query string values of the request, by name, as the strings that arrived. */
|
|
2128
|
+
export type StoryMockParams<Arg> = { [Name in Arg extends object ? Extract<keyof Arg, string> : never]?: string } & {
|
|
2129
|
+
[name: string]: string | undefined;
|
|
2130
|
+
};
|
|
2131
|
+
|
|
2132
|
+
/** How a generated handler answers; the factories take \`Partial<StoryMock<\u2026>>\`. */
|
|
2133
|
+
export interface StoryMock<Response, Arg = void> {
|
|
2134
|
+
/** URL pattern matched instead of the generated one (any origin + the operation path, \`*\` per path parameter). */
|
|
2135
|
+
url: string;
|
|
2136
|
+
/** Default: the operation's first declared 2xx status (200 for a file download). */
|
|
2137
|
+
status: number;
|
|
2138
|
+
/** Delay before answering (MSW \`delay\`). */
|
|
2139
|
+
delay: number | 'real' | 'infinite';
|
|
2140
|
+
/** The answer, or a function computing it from the request's parameters and the default mock. */
|
|
2141
|
+
response:
|
|
2142
|
+
| Response
|
|
2143
|
+
| ((params: StoryMockParams<Arg>, defaultMock: Response | null, info: ResolverInfo) => Response | Promise<Response>);
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
type BodyKind = 'json' | 'text' | 'blob';
|
|
2147
|
+
|
|
2148
|
+
const readParams = (template: string, info: ResolverInfo): Record<string, string> => {
|
|
2149
|
+
const url = new URL(info.request.url);
|
|
2150
|
+
const params: Record<string, string> = {};
|
|
2151
|
+
url.searchParams.forEach((value, name) => {
|
|
2152
|
+
params[name] = value;
|
|
2153
|
+
});
|
|
2154
|
+
const parts = template.split(/\\{([^}]+)\\}/);
|
|
2155
|
+
const names = parts.filter((_, index) => index % 2 === 1);
|
|
2156
|
+
const pattern = parts
|
|
2157
|
+
.map((part, index) => (index % 2 === 1 ? '([^/]+)' : part.replace(/[.*+?^\${}()|[\\]\\\\]/g, '\\\\$&')))
|
|
2158
|
+
.join('');
|
|
2159
|
+
const match = new RegExp(pattern + '/?$').exec(url.pathname);
|
|
2160
|
+
names.forEach((name, index) => {
|
|
2161
|
+
const value = match?.[index + 1];
|
|
2162
|
+
if (value !== undefined) params[name] = decodeURIComponent(value);
|
|
2163
|
+
});
|
|
2164
|
+
return params;
|
|
2165
|
+
};
|
|
2166
|
+
|
|
2167
|
+
const mockOperation = <Response, Arg>(
|
|
2168
|
+
method: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options',
|
|
2169
|
+
pattern: string,
|
|
2170
|
+
template: string,
|
|
2171
|
+
kind: BodyKind,
|
|
2172
|
+
status: number,
|
|
2173
|
+
defaultMock: () => Response | null,
|
|
2174
|
+
custom: Partial<StoryMock<Response, Arg>> = {},
|
|
2175
|
+
) =>
|
|
2176
|
+
http[method](custom.url ?? pattern, async (info) => {
|
|
2177
|
+
if (custom.delay !== undefined) await delay(custom.delay);
|
|
2178
|
+
const fallback = defaultMock();
|
|
2179
|
+
const answer = custom.response;
|
|
2180
|
+
const body =
|
|
2181
|
+
typeof answer === 'function'
|
|
2182
|
+
? await (answer as (params: StoryMockParams<Arg>, defaultMock: Response | null, info: ResolverInfo) => Response | Promise<Response>)(
|
|
2183
|
+
readParams(template, info) as StoryMockParams<Arg>,
|
|
2184
|
+
fallback,
|
|
2185
|
+
info,
|
|
2186
|
+
)
|
|
2187
|
+
: answer !== undefined
|
|
2188
|
+
? answer
|
|
2189
|
+
: fallback;
|
|
2190
|
+
const init = { status: custom.status ?? status };
|
|
2191
|
+
if (body === null || body === undefined) return new HttpResponse(null, init);
|
|
2192
|
+
if (kind === 'json') return HttpResponse.json(body as never, init);
|
|
2193
|
+
return new HttpResponse(body as unknown as BodyInit, init);
|
|
2194
|
+
});
|
|
2195
|
+
`;
|
|
2196
|
+
function successStatus(responses) {
|
|
2197
|
+
const codes = Object.keys(responses ?? {}).filter((code) => /^2\d\d$/.test(code)).map(Number).sort((a, b) => a - b);
|
|
2198
|
+
return codes[0] ?? 200;
|
|
2199
|
+
}
|
|
2200
|
+
function readTypeArguments(ts, sourceFile) {
|
|
2201
|
+
const result = /* @__PURE__ */ new Map();
|
|
2202
|
+
const visit = (node) => {
|
|
2203
|
+
if (ts.isPropertyAssignment(node) && ts.isCallExpression(node.initializer)) {
|
|
2204
|
+
const callee = node.initializer.expression;
|
|
2205
|
+
if (ts.isPropertyAccessExpression(callee) && ["query", "mutation"].includes(callee.name.text)) {
|
|
2206
|
+
const key = node.name.getText(sourceFile).replace(/^["']|["']$/g, "");
|
|
2207
|
+
const [response, arg] = node.initializer.typeArguments ?? [];
|
|
2208
|
+
result.set(key, { response: response?.getText(sourceFile), arg: arg?.getText(sourceFile) });
|
|
2209
|
+
return;
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
ts.forEachChild(node, visit);
|
|
2213
|
+
};
|
|
2214
|
+
visit(sourceFile);
|
|
2215
|
+
return result;
|
|
2216
|
+
}
|
|
2217
|
+
function readImports(ts, sourceFile, filePath, files) {
|
|
2218
|
+
const result = /* @__PURE__ */ new Map();
|
|
2219
|
+
for (const statement of sourceFile.statements) {
|
|
2220
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
|
|
2221
|
+
const specifier = statement.moduleSpecifier.text;
|
|
2222
|
+
if (!specifier.startsWith(".")) continue;
|
|
2223
|
+
const base = path7.resolve(path7.dirname(filePath), specifier.replace(/\.js$/, ""));
|
|
2224
|
+
const file = files.findPath(`${base}.ts`) ?? files.findPath(path7.join(base, "index.ts"));
|
|
2225
|
+
const bindings = statement.importClause?.namedBindings;
|
|
2226
|
+
if (!file || !bindings || !ts.isNamedImports(bindings)) continue;
|
|
2227
|
+
for (const element of bindings.elements) {
|
|
2228
|
+
result.set(element.name.text, { exported: (element.propertyName ?? element.name).text, file });
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
return result;
|
|
2232
|
+
}
|
|
2233
|
+
function declaringFile(name, module, files) {
|
|
2234
|
+
const declares = (file) => new RegExp(`^export (?:type|interface) ${name}\\b`, "m").test(files.get(file) ?? "");
|
|
2235
|
+
if (declares(module)) return module;
|
|
2236
|
+
const barrel = files.get(module) ?? "";
|
|
2237
|
+
for (const match of barrel.matchAll(/from ['"](.+?)['"]/g)) {
|
|
2238
|
+
const base = path7.resolve(path7.dirname(module), match[1].replace(/\.js$/, ""));
|
|
2239
|
+
const file = files.findPath(`${base}.ts`);
|
|
2240
|
+
if (file && declares(file)) return file;
|
|
2241
|
+
}
|
|
2242
|
+
return void 0;
|
|
2243
|
+
}
|
|
2244
|
+
function responseShape(ts, responseType, apiImports, files) {
|
|
2245
|
+
const imported = apiImports.get(responseType);
|
|
2246
|
+
if (!imported) return null;
|
|
2247
|
+
const file = declaringFile(imported.exported, imported.file, files);
|
|
2248
|
+
if (!file) return null;
|
|
2249
|
+
const sourceFile = ts.createSourceFile("response.ts", files.get(file), ts.ScriptTarget.Latest, true);
|
|
2250
|
+
const alias = sourceFile.statements.find(
|
|
2251
|
+
(statement) => ts.isTypeAliasDeclaration(statement) && statement.name.text === imported.exported
|
|
2252
|
+
);
|
|
2253
|
+
if (!alias) return null;
|
|
2254
|
+
let type = alias.type;
|
|
2255
|
+
while (ts.isParenthesizedTypeNode(type)) type = type.type;
|
|
2256
|
+
if (ts.isUnionTypeNode(type)) {
|
|
2257
|
+
const members = type.types.filter(
|
|
2258
|
+
(member) => !(ts.isLiteralTypeNode(member) && member.literal.kind === ts.SyntaxKind.NullKeyword) && member.kind !== ts.SyntaxKind.UndefinedKeyword
|
|
2259
|
+
);
|
|
2260
|
+
if (members.length !== 1) return null;
|
|
2261
|
+
type = members[0];
|
|
2262
|
+
}
|
|
2263
|
+
let array = false;
|
|
2264
|
+
if (ts.isArrayTypeNode(type)) {
|
|
2265
|
+
array = true;
|
|
2266
|
+
type = type.elementType;
|
|
2267
|
+
} else if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName) && type.typeName.text === "Array" && type.typeArguments?.length === 1) {
|
|
2268
|
+
array = true;
|
|
2269
|
+
type = type.typeArguments[0];
|
|
2270
|
+
}
|
|
2271
|
+
while (ts.isParenthesizedTypeNode(type)) type = type.type;
|
|
2272
|
+
if (!ts.isTypeReferenceNode(type) || !ts.isIdentifier(type.typeName) || type.typeArguments) return null;
|
|
2273
|
+
const modelImports = readImports(ts, sourceFile, file, files);
|
|
2274
|
+
const model = modelImports.get(type.typeName.text);
|
|
2275
|
+
if (!model) return null;
|
|
2276
|
+
const modelFile = declaringFile(model.exported, model.file, files);
|
|
2277
|
+
return modelFile ? { model: { file: modelFile, exported: model.exported }, array } : null;
|
|
2278
|
+
}
|
|
2279
|
+
|
|
1620
2280
|
// src/codegen/multipart.ts
|
|
1621
2281
|
var MULTIPART_FILES_ARG = "multipartFiles";
|
|
1622
2282
|
var BODY_FIELD = "body";
|
|
@@ -1651,9 +2311,9 @@ function readMultipartOperation(doc, requestBody) {
|
|
|
1651
2311
|
}
|
|
1652
2312
|
function detectMultipartEndpoints(doc, endpoints) {
|
|
1653
2313
|
const byOperation = /* @__PURE__ */ new Map();
|
|
1654
|
-
for (const { method, path:
|
|
2314
|
+
for (const { method, path: path13, operation } of listOperations(doc)) {
|
|
1655
2315
|
const multipart = readMultipartOperation(doc, operation.requestBody);
|
|
1656
|
-
if (multipart) byOperation.set(operationKey(method,
|
|
2316
|
+
if (multipart) byOperation.set(operationKey(method, path13), multipart);
|
|
1657
2317
|
}
|
|
1658
2318
|
const keys = /* @__PURE__ */ new Map();
|
|
1659
2319
|
if (byOperation.size === 0) return keys;
|
|
@@ -1747,92 +2407,6 @@ function injectMultipartBodies(source, endpoints, logger) {
|
|
|
1747
2407
|
}
|
|
1748
2408
|
var MULTIPART_IMPORT = `import { buildDddMultipartBody } from '${DDD_WEB_API_IMPORT}';`;
|
|
1749
2409
|
|
|
1750
|
-
// src/codegen/output.ts
|
|
1751
|
-
import * as fs5 from "fs";
|
|
1752
|
-
import * as path5 from "path";
|
|
1753
|
-
function defaultMove(from, to) {
|
|
1754
|
-
fs5.mkdirSync(path5.dirname(to), { recursive: true });
|
|
1755
|
-
try {
|
|
1756
|
-
fs5.renameSync(from, to);
|
|
1757
|
-
} catch (error) {
|
|
1758
|
-
if (error.code !== "EXDEV") throw error;
|
|
1759
|
-
fs5.cpSync(from, to, { recursive: true });
|
|
1760
|
-
fs5.rmSync(from, { recursive: true, force: true });
|
|
1761
|
-
}
|
|
1762
|
-
}
|
|
1763
|
-
function commitOutput(files, modelsDir, stagingParent, options = {}) {
|
|
1764
|
-
const move = options.move ?? defaultMove;
|
|
1765
|
-
fs5.mkdirSync(stagingParent, { recursive: true });
|
|
1766
|
-
const staging = fs5.mkdtempSync(path5.join(stagingParent, ".ddd-web-sdk-"));
|
|
1767
|
-
const stagedModels = path5.join(staging, "models");
|
|
1768
|
-
const backupModels = path5.join(staging, "models.previous");
|
|
1769
|
-
const singles = [];
|
|
1770
|
-
try {
|
|
1771
|
-
fs5.mkdirSync(stagedModels, { recursive: true });
|
|
1772
|
-
for (const filePath of files.paths()) {
|
|
1773
|
-
const content = files.get(filePath);
|
|
1774
|
-
const relative5 = path5.relative(modelsDir, filePath);
|
|
1775
|
-
if (!relative5.startsWith("..") && !path5.isAbsolute(relative5)) {
|
|
1776
|
-
const staged = path5.join(stagedModels, relative5);
|
|
1777
|
-
fs5.mkdirSync(path5.dirname(staged), { recursive: true });
|
|
1778
|
-
fs5.writeFileSync(staged, content);
|
|
1779
|
-
} else {
|
|
1780
|
-
const staged = path5.join(staging, "files", String(singles.length));
|
|
1781
|
-
fs5.mkdirSync(path5.dirname(staged), { recursive: true });
|
|
1782
|
-
fs5.writeFileSync(staged, content);
|
|
1783
|
-
singles.push({ target: filePath, staged, backup: path5.join(staging, "files.previous", String(singles.length)) });
|
|
1784
|
-
}
|
|
1785
|
-
}
|
|
1786
|
-
} catch (error) {
|
|
1787
|
-
fs5.rmSync(staging, { recursive: true, force: true });
|
|
1788
|
-
throw error;
|
|
1789
|
-
}
|
|
1790
|
-
const undo = [];
|
|
1791
|
-
const rollback = () => {
|
|
1792
|
-
const failures = [];
|
|
1793
|
-
for (const step of undo.reverse()) {
|
|
1794
|
-
try {
|
|
1795
|
-
step();
|
|
1796
|
-
} catch (error) {
|
|
1797
|
-
failures.push(error);
|
|
1798
|
-
}
|
|
1799
|
-
}
|
|
1800
|
-
undo.length = 0;
|
|
1801
|
-
if (failures.length > 0) {
|
|
1802
|
-
throw new SdkGenerationError(
|
|
1803
|
-
`Could not restore the previous output; the previous output is kept in ${staging} (models.previous/, files.previous/): ${failures.map((failure) => failure.message).join("; ")}`
|
|
1804
|
-
);
|
|
1805
|
-
}
|
|
1806
|
-
fs5.rmSync(staging, { recursive: true, force: true });
|
|
1807
|
-
};
|
|
1808
|
-
const swap = (target, staged, backup, removeTarget) => {
|
|
1809
|
-
const state = { backedUp: false, movedIn: false };
|
|
1810
|
-
undo.push(() => {
|
|
1811
|
-
if (state.movedIn) removeTarget();
|
|
1812
|
-
if (state.backedUp) move(backup, target);
|
|
1813
|
-
});
|
|
1814
|
-
if (fs5.existsSync(target)) {
|
|
1815
|
-
move(target, backup);
|
|
1816
|
-
state.backedUp = true;
|
|
1817
|
-
}
|
|
1818
|
-
move(staged, target);
|
|
1819
|
-
state.movedIn = true;
|
|
1820
|
-
};
|
|
1821
|
-
try {
|
|
1822
|
-
swap(modelsDir, stagedModels, backupModels, () => fs5.rmSync(modelsDir, { recursive: true, force: true }));
|
|
1823
|
-
for (const single of singles) {
|
|
1824
|
-
swap(single.target, single.staged, single.backup, () => fs5.rmSync(single.target, { force: true }));
|
|
1825
|
-
}
|
|
1826
|
-
} catch (error) {
|
|
1827
|
-
rollback();
|
|
1828
|
-
throw error;
|
|
1829
|
-
}
|
|
1830
|
-
return {
|
|
1831
|
-
rollback,
|
|
1832
|
-
finalize: () => fs5.rmSync(staging, { recursive: true, force: true })
|
|
1833
|
-
};
|
|
1834
|
-
}
|
|
1835
|
-
|
|
1836
2410
|
// src/codegen/registry.ts
|
|
1837
2411
|
function normalizeSegment(segment) {
|
|
1838
2412
|
return segment.replace(/([A-Z])([A-Z]+)/g, (_, first, rest) => first + rest.toLowerCase());
|
|
@@ -1868,63 +2442,27 @@ function buildRegistry(docs, logger) {
|
|
|
1868
2442
|
return [...registry.entries()].sort((a, b) => b[0].length - a[0].length);
|
|
1869
2443
|
}
|
|
1870
2444
|
|
|
1871
|
-
// src/codegen/repair.ts
|
|
1872
|
-
function resolveParameter2(doc, parameter) {
|
|
1873
|
-
let current = parameter;
|
|
1874
|
-
for (let hops = 0; current?.$ref !== void 0 && hops < 10; hops++) {
|
|
1875
|
-
const match = /^#\/components\/parameters\/(.+)$/.exec(current.$ref);
|
|
1876
|
-
if (!match) return null;
|
|
1877
|
-
const name = match[1].replace(/~1/g, "/").replace(/~0/g, "~");
|
|
1878
|
-
current = doc.components?.parameters?.[name];
|
|
1879
|
-
}
|
|
1880
|
-
return current && current.$ref === void 0 ? current : null;
|
|
1881
|
-
}
|
|
1882
|
-
function repairMissingPathParameters(doc, logger) {
|
|
1883
|
-
const repairs = [];
|
|
1884
|
-
for (const { method, path: path11, operation } of listOperations(doc)) {
|
|
1885
|
-
const placeholders = [...path11.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
1886
|
-
if (placeholders.length === 0) continue;
|
|
1887
|
-
const pathLevel = doc.paths?.[path11]?.parameters ?? [];
|
|
1888
|
-
const declared = new Set(
|
|
1889
|
-
[...pathLevel, ...operation.parameters ?? []].map((parameter) => resolveParameter2(doc, parameter)).filter((parameter) => parameter !== null && parameter.in === "path").map((parameter) => parameter.name)
|
|
1890
|
-
);
|
|
1891
|
-
const missing = placeholders.filter((name) => !declared.has(name));
|
|
1892
|
-
if (missing.length > 0) repairs.push({ path: path11, method, names: missing });
|
|
1893
|
-
}
|
|
1894
|
-
if (repairs.length === 0) return doc;
|
|
1895
|
-
const copy = structuredClone(doc);
|
|
1896
|
-
for (const { path: path11, method, names } of repairs) {
|
|
1897
|
-
const operation = copy.paths[path11][method];
|
|
1898
|
-
operation.parameters = [
|
|
1899
|
-
...names.map((name) => ({ name, in: "path", required: true, schema: { type: "string" } })),
|
|
1900
|
-
...operation.parameters ?? []
|
|
1901
|
-
];
|
|
1902
|
-
logger.warn(`${method.toUpperCase()} ${path11}: path parameter(s) ${names.join(", ")} not declared in the spec \u2014 added as string.`);
|
|
1903
|
-
}
|
|
1904
|
-
return copy;
|
|
1905
|
-
}
|
|
1906
|
-
|
|
1907
2445
|
// src/codegen/rtk.ts
|
|
1908
|
-
import * as
|
|
1909
|
-
import * as
|
|
2446
|
+
import * as fs7 from "fs";
|
|
2447
|
+
import * as path9 from "path";
|
|
1910
2448
|
import prettier2 from "prettier";
|
|
1911
2449
|
|
|
1912
2450
|
// src/codegen/module-resolution.ts
|
|
1913
|
-
import Module, { createRequire as
|
|
1914
|
-
import * as
|
|
2451
|
+
import Module, { createRequire as createRequire4 } from "module";
|
|
2452
|
+
import * as path8 from "path";
|
|
1915
2453
|
var installed = false;
|
|
1916
2454
|
function installParserModuleResolution() {
|
|
1917
2455
|
if (installed) return;
|
|
1918
2456
|
installed = true;
|
|
1919
|
-
const require2 =
|
|
2457
|
+
const require2 = createRequire4(import.meta.url);
|
|
1920
2458
|
let parserRequire;
|
|
1921
2459
|
try {
|
|
1922
|
-
const codegenRequire =
|
|
1923
|
-
parserRequire =
|
|
2460
|
+
const codegenRequire = createRequire4(require2.resolve("@rtk-query/codegen-openapi"));
|
|
2461
|
+
parserRequire = createRequire4(codegenRequire.resolve("@apidevtools/swagger-parser"));
|
|
1924
2462
|
} catch {
|
|
1925
2463
|
return;
|
|
1926
2464
|
}
|
|
1927
|
-
const ajvDraft04Folder = `${
|
|
2465
|
+
const ajvDraft04Folder = `${path8.sep}ajv-draft-04${path8.sep}`;
|
|
1928
2466
|
const moduleWithResolver = Module;
|
|
1929
2467
|
const defaultResolveFilename = moduleWithResolver._resolveFilename;
|
|
1930
2468
|
moduleWithResolver._resolveFilename = function resolveAjvOfTheParser(request, parent, ...rest) {
|
|
@@ -1943,7 +2481,7 @@ async function loadRtkCodegen() {
|
|
|
1943
2481
|
}
|
|
1944
2482
|
|
|
1945
2483
|
// src/codegen/rtk.ts
|
|
1946
|
-
var OWN_KEYS = /* @__PURE__ */ new Set(["schemaFile", "apiFile", "outputFile", "audience", "baseApiImport", "skipUpdatePostTwins", "sideEffects", "responseHandlers", "invalidation"]);
|
|
2484
|
+
var OWN_KEYS = /* @__PURE__ */ new Set(["schemaFile", "apiFile", "outputFile", "audience", "baseApiImport", "skipUpdatePostTwins", "sideEffects", "responseHandlers", "invalidation", "mswHandlers"]);
|
|
1947
2485
|
function matches(matcher, name, definition) {
|
|
1948
2486
|
if (matcher === void 0) return true;
|
|
1949
2487
|
if (typeof matcher === "function") return matcher(name, definition);
|
|
@@ -1968,12 +2506,12 @@ function mergeEndpointOverrides(userOverrides, typeOverrides) {
|
|
|
1968
2506
|
}
|
|
1969
2507
|
function relativeImport(fromDir, target) {
|
|
1970
2508
|
if (!isPathLike(target)) return target;
|
|
1971
|
-
let
|
|
1972
|
-
if (!
|
|
1973
|
-
return
|
|
2509
|
+
let relative7 = path9.relative(fromDir, target).replace(/\\/g, "/");
|
|
2510
|
+
if (!relative7.startsWith(".")) relative7 = `./${relative7}`;
|
|
2511
|
+
return relative7;
|
|
1974
2512
|
}
|
|
1975
2513
|
async function runRtkCodegen(api, doc, index, specFile, prettierConfigFile, endpointNameOf = (rtkName) => rtkName) {
|
|
1976
|
-
|
|
2514
|
+
fs7.writeFileSync(specFile, JSON.stringify(doc));
|
|
1977
2515
|
const passthrough = {};
|
|
1978
2516
|
for (const [key, value] of Object.entries(api.config)) if (!OWN_KEYS.has(key)) passthrough[key] = value;
|
|
1979
2517
|
const userOverrides = (passthrough.endpointOverrides ?? []).map(
|
|
@@ -2009,19 +2547,19 @@ async function runRtkCodegen(api, doc, index, specFile, prettierConfigFile, endp
|
|
|
2009
2547
|
return { code, locations };
|
|
2010
2548
|
}
|
|
2011
2549
|
async function findPrettierConfigFile(rootDir) {
|
|
2012
|
-
return await prettier2.resolveConfigFile(
|
|
2550
|
+
return await prettier2.resolveConfigFile(path9.join(rootDir, "openapi-config.ts")) ?? void 0;
|
|
2013
2551
|
}
|
|
2014
2552
|
|
|
2015
2553
|
// src/codegen/workspace.ts
|
|
2016
|
-
import * as
|
|
2017
|
-
import * as
|
|
2554
|
+
import * as fs8 from "fs";
|
|
2555
|
+
import * as path10 from "path";
|
|
2018
2556
|
import * as readline from "readline";
|
|
2019
2557
|
var DEFAULT_ENV_FILES = [".env", ".env.local"];
|
|
2020
2558
|
var DEFAULT_URL_KEYS = ["NEXT_PUBLIC_API_URL", "EXPO_PUBLIC_API_URL", "VITE_API_URL", "VITE_API_ENDPOINT", "API_URL"];
|
|
2021
2559
|
function parseEnvFile(filePath) {
|
|
2022
|
-
if (!
|
|
2560
|
+
if (!fs8.existsSync(filePath)) return {};
|
|
2023
2561
|
const vars = {};
|
|
2024
|
-
for (const line of
|
|
2562
|
+
for (const line of fs8.readFileSync(filePath, "utf-8").split("\n")) {
|
|
2025
2563
|
const trimmed = line.trim();
|
|
2026
2564
|
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
2027
2565
|
const eq = trimmed.indexOf("=");
|
|
@@ -2039,7 +2577,7 @@ function firstHostLabel(url) {
|
|
|
2039
2577
|
}
|
|
2040
2578
|
function sniffWorkspace(rootDir, options) {
|
|
2041
2579
|
for (const file of options.envFiles ?? DEFAULT_ENV_FILES) {
|
|
2042
|
-
const vars = parseEnvFile(
|
|
2580
|
+
const vars = parseEnvFile(path10.join(rootDir, file));
|
|
2043
2581
|
for (const key of options.urlKeys ?? DEFAULT_URL_KEYS) {
|
|
2044
2582
|
const value = vars[key];
|
|
2045
2583
|
const label2 = value ? firstHostLabel(value) : null;
|
|
@@ -2049,11 +2587,11 @@ function sniffWorkspace(rootDir, options) {
|
|
|
2049
2587
|
return null;
|
|
2050
2588
|
}
|
|
2051
2589
|
function ask(question) {
|
|
2052
|
-
return new Promise((
|
|
2590
|
+
return new Promise((resolve9) => {
|
|
2053
2591
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
2054
|
-
rl.on("close", () =>
|
|
2592
|
+
rl.on("close", () => resolve9(""));
|
|
2055
2593
|
rl.question(question, (answer) => {
|
|
2056
|
-
|
|
2594
|
+
resolve9(answer.trim());
|
|
2057
2595
|
rl.close();
|
|
2058
2596
|
});
|
|
2059
2597
|
});
|
|
@@ -2079,9 +2617,9 @@ async function resolveWorkspace(rootDir, options, explicit, logger) {
|
|
|
2079
2617
|
// src/codegen/generate.ts
|
|
2080
2618
|
async function load(options, cwd) {
|
|
2081
2619
|
if (options.config && typeof options.config === "object") {
|
|
2082
|
-
return { config: options.config, configPath:
|
|
2620
|
+
return { config: options.config, configPath: path11.join(cwd, "<inline config>"), rootDir: cwd };
|
|
2083
2621
|
}
|
|
2084
|
-
return loadConfig(
|
|
2622
|
+
return loadConfig(path11.resolve(cwd, options.config ?? "openapi-config.ts"));
|
|
2085
2623
|
}
|
|
2086
2624
|
function selectApis(all, options) {
|
|
2087
2625
|
let selected = all;
|
|
@@ -2093,14 +2631,14 @@ function selectApis(all, options) {
|
|
|
2093
2631
|
}
|
|
2094
2632
|
if (options.schema) {
|
|
2095
2633
|
if (selected.length !== 1) throw new SdkGenerationError("--schema needs exactly one api (use --api).");
|
|
2096
|
-
const schemaSource = isUrl(options.schema) ? options.schema :
|
|
2634
|
+
const schemaSource = isUrl(options.schema) ? options.schema : path11.resolve(options.cwd ?? process.cwd(), options.schema);
|
|
2097
2635
|
selected = [{ ...selected[0], schemaSource }];
|
|
2098
2636
|
}
|
|
2099
2637
|
return selected;
|
|
2100
2638
|
}
|
|
2101
2639
|
async function generateSdk(options = {}) {
|
|
2102
2640
|
const logger = options.logger ?? consoleLogger;
|
|
2103
|
-
const cwd =
|
|
2641
|
+
const cwd = path11.resolve(options.cwd ?? process.cwd());
|
|
2104
2642
|
let loaded = await load(options, cwd);
|
|
2105
2643
|
if (loaded.config.workspace) {
|
|
2106
2644
|
const value = await resolveWorkspace(loaded.rootDir, loaded.config.workspace, options.workspace, logger);
|
|
@@ -2108,6 +2646,11 @@ async function generateSdk(options = {}) {
|
|
|
2108
2646
|
}
|
|
2109
2647
|
const allApis = resolveApis(loaded);
|
|
2110
2648
|
const apis = selectApis(allApis, options);
|
|
2649
|
+
const mode = options.mode ?? loaded.config.generator?.mode ?? "default";
|
|
2650
|
+
if (mode === "future" || mode === "legacy") {
|
|
2651
|
+
return generateDelegatedSdk(mode, loaded, allApis, apis, options, logger);
|
|
2652
|
+
}
|
|
2653
|
+
if (mode !== "default") throw new SdkGenerationError("SDK generator mode must be default, future, or legacy.");
|
|
2111
2654
|
const modelsDir = resolveModelsDir(loaded, allApis);
|
|
2112
2655
|
const partial = apis.length < allApis.length;
|
|
2113
2656
|
logger.info(`${apis.length} api(s): ${apis.map((api) => api.exportName).join(", ")}${partial ? " (partial run)" : ""}`);
|
|
@@ -2149,7 +2692,7 @@ async function generateSdk(options = {}) {
|
|
|
2149
2692
|
const prettierConfigFile = await findPrettierConfigFile(loaded.rootDir);
|
|
2150
2693
|
const constsByFile = /* @__PURE__ */ new Map();
|
|
2151
2694
|
const uniqueNameByPath = /* @__PURE__ */ new Map();
|
|
2152
|
-
const specDir =
|
|
2695
|
+
const specDir = fs9.mkdtempSync(path11.join(os2.tmpdir(), "ddd-web-spec-"));
|
|
2153
2696
|
try {
|
|
2154
2697
|
for (const [i, { api, write, doc: rawDoc }] of steps.entries()) {
|
|
2155
2698
|
const doc = repairMissingPathParameters(rawDoc, logger);
|
|
@@ -2177,7 +2720,7 @@ async function generateSdk(options = {}) {
|
|
|
2177
2720
|
};
|
|
2178
2721
|
const endpointNameOf = (rtkName) => preparedEndpoints.endpointNamesByPlaceholder.get(rtkName) ?? rtkName;
|
|
2179
2722
|
const runPass = async (passApi, specName, modelsOnly) => {
|
|
2180
|
-
const generated = await runRtkCodegen(passApi, preparedEndpoints.doc, index,
|
|
2723
|
+
const generated = await runRtkCodegen(passApi, preparedEndpoints.doc, index, path11.join(specDir, specName), prettierConfigFile, endpointNameOf);
|
|
2181
2724
|
const rtk = restoreEndpointNames(generated.code, generated.locations, preparedEndpoints.endpointNamesByPlaceholder);
|
|
2182
2725
|
const endpoints2 = parseApiEndpoints(rtk.code, logger, rtk.locations);
|
|
2183
2726
|
const handlerEndpoints2 = detectResponseHandlerEndpoints(doc, endpoints2, api.responseHandlers);
|
|
@@ -2191,20 +2734,23 @@ async function generateSdk(options = {}) {
|
|
|
2191
2734
|
const withHandlers = injectResponseHandlers(apiSource, handlerEndpoints2);
|
|
2192
2735
|
const finalApiSource2 = multipart.injected.length > 0 ? `${MULTIPART_IMPORT}
|
|
2193
2736
|
${withHandlers}` : withHandlers;
|
|
2194
|
-
return { endpoints: endpoints2, handlerEndpoints: handlerEndpoints2, multipartCount: multipart.injected.length, finalApiSource: finalApiSource2 };
|
|
2737
|
+
return { endpoints: endpoints2, handlerEndpoints: handlerEndpoints2, multipartCount: multipart.injected.length, finalApiSource: finalApiSource2, apiSource };
|
|
2195
2738
|
};
|
|
2196
2739
|
const buildersOfAllOperations = endpointOptions.requestBuilders === "all" && api.config.filterEndpoints !== void 0;
|
|
2197
2740
|
let requestsSourceOfAllOperations = null;
|
|
2741
|
+
let passOfAllOperations = null;
|
|
2198
2742
|
if ((modelOptions.scope === "all" || buildersOfAllOperations) && api.config.filterEndpoints !== void 0) {
|
|
2199
2743
|
const unfiltered = await runPass({ ...api, config: { ...api.config, filterEndpoints: void 0 } }, `${i}-all.json`, !buildersOfAllOperations);
|
|
2200
2744
|
if (buildersOfAllOperations) {
|
|
2745
|
+
passOfAllOperations = unfiltered;
|
|
2201
2746
|
const requestsStem = `${api.stem}Requests`;
|
|
2202
2747
|
requestsSourceOfAllOperations = splitRequestBuilders(unfiltered.finalApiSource, requestsStem, `./${requestsStem}`).requestsSource;
|
|
2203
2748
|
logger.info(" request builders of all operations (endpoints.requestBuilders all)");
|
|
2204
2749
|
}
|
|
2205
2750
|
if (modelOptions.scope === "all") logger.info(" models of all operations written (models.scope all)");
|
|
2206
2751
|
}
|
|
2207
|
-
const
|
|
2752
|
+
const mainPass = await runPass(api, `${i}.json`, false);
|
|
2753
|
+
const { endpoints, handlerEndpoints, multipartCount, finalApiSource } = mainPass;
|
|
2208
2754
|
const fileCount = [...handlerEndpoints.values()].filter((kind) => kind === "blob").length;
|
|
2209
2755
|
if (fileCount > 0) logger.info(` ${fileCount} file download endpoint(s) (blobResponseHandler)`);
|
|
2210
2756
|
if (multipartCount > 0) logger.info(` ${multipartCount} multipart endpoint(s) (multipartFiles)`);
|
|
@@ -2213,11 +2759,30 @@ ${withHandlers}` : withHandlers;
|
|
|
2213
2759
|
const requestsStem = `${api.stem}Requests`;
|
|
2214
2760
|
const split = splitRequestBuilders(finalApiSource, requestsStem, esm ? `./${requestsStem}.js` : `./${requestsStem}`);
|
|
2215
2761
|
files.set(api.outputFile, split.apiSource);
|
|
2216
|
-
files.set(
|
|
2762
|
+
files.set(path11.join(api.outputDir, `${requestsStem}.ts`), requestsSourceOfAllOperations ?? split.requestsSource);
|
|
2217
2763
|
logger.info(` ${split.count} request builder(s) used by ${api.stem}.ts`);
|
|
2218
2764
|
} else {
|
|
2219
2765
|
files.set(api.outputFile, finalApiSource);
|
|
2220
2766
|
}
|
|
2767
|
+
const msw = api.config.mswHandlers === false ? void 0 : api.config.mswHandlers ?? loaded.config.mswHandlers ? { ...loaded.config.mswHandlers, ...api.config.mswHandlers || {} } : void 0;
|
|
2768
|
+
if (msw) {
|
|
2769
|
+
const pass = passOfAllOperations ?? mainPass;
|
|
2770
|
+
const outputFile = msw.outputFile ? path11.resolve(loaded.rootDir, msw.outputFile) : path11.join(api.outputDir, `${api.stem}Mocks.ts`);
|
|
2771
|
+
files.set(outputFile, renderMswHandlers({
|
|
2772
|
+
apiSource: pass.apiSource,
|
|
2773
|
+
apiFilePath: api.outputFile,
|
|
2774
|
+
endpoints: pass.endpoints,
|
|
2775
|
+
responseKinds: new Map([...pass.handlerEndpoints].filter((entry) => entry[1] === "text" || entry[1] === "blob")),
|
|
2776
|
+
doc,
|
|
2777
|
+
files,
|
|
2778
|
+
modelsDir,
|
|
2779
|
+
outputFile,
|
|
2780
|
+
exportName: msw.exportName ?? `${api.stem}Mocks`,
|
|
2781
|
+
modelMocks: msw.modelMocks,
|
|
2782
|
+
esm
|
|
2783
|
+
}));
|
|
2784
|
+
logger.info(` MSW handlers of ${pass.endpoints.length} operation(s) (${path11.basename(outputFile)})`);
|
|
2785
|
+
}
|
|
2221
2786
|
const withExtension = (specifier) => esm ? `${specifier}.js` : specifier;
|
|
2222
2787
|
const enhanced = buildEnhancedEndpoints({
|
|
2223
2788
|
stem: api.stem,
|
|
@@ -2233,11 +2798,11 @@ ${withHandlers}` : withHandlers;
|
|
|
2233
2798
|
invalidation: api.invalidation,
|
|
2234
2799
|
logger
|
|
2235
2800
|
});
|
|
2236
|
-
files.set(
|
|
2237
|
-
files.set(
|
|
2801
|
+
files.set(path11.join(api.outputDir, `${api.stem}Enhanced.ts`), enhanced.source);
|
|
2802
|
+
files.set(path11.join(api.outputDir, `${api.stem}Tags.ts`), renderTagsFile(api.stem, enhanced.tagTypes));
|
|
2238
2803
|
}
|
|
2239
2804
|
} finally {
|
|
2240
|
-
|
|
2805
|
+
fs9.rmSync(specDir, { recursive: true, force: true });
|
|
2241
2806
|
}
|
|
2242
2807
|
if (!options.skipPrettier) {
|
|
2243
2808
|
logger.info("formatting with prettier");
|
|
@@ -2248,7 +2813,7 @@ ${withHandlers}` : withHandlers;
|
|
|
2248
2813
|
if (!options.skipTsc) {
|
|
2249
2814
|
logger.info("type check (tsc --noEmit)");
|
|
2250
2815
|
try {
|
|
2251
|
-
typechecked = typecheck(loaded.rootDir,
|
|
2816
|
+
typechecked = typecheck(loaded.rootDir, path11.resolve(loaded.rootDir, loaded.config.tsconfig ?? "tsconfig.json"), logger);
|
|
2252
2817
|
} catch (error) {
|
|
2253
2818
|
committed.rollback();
|
|
2254
2819
|
logger.error("type check failed \u2014 previous output restored");
|
|
@@ -2263,9 +2828,9 @@ ${withHandlers}` : withHandlers;
|
|
|
2263
2828
|
// src/codegen/link-skills.ts
|
|
2264
2829
|
import { spawnSync } from "child_process";
|
|
2265
2830
|
import { createHash } from "crypto";
|
|
2266
|
-
import * as
|
|
2267
|
-
import * as
|
|
2268
|
-
import * as
|
|
2831
|
+
import * as fs10 from "fs";
|
|
2832
|
+
import * as os3 from "os";
|
|
2833
|
+
import * as path12 from "path";
|
|
2269
2834
|
var PRIMARY_SKILLS_DIRECTORY = ".claude/skills";
|
|
2270
2835
|
var MIRROR_SKILLS_DIRECTORIES = [".agents/skills", ".codex/skills"];
|
|
2271
2836
|
var SKILLS_MANIFEST_FILE_NAME = ".ddd-skills.json";
|
|
@@ -2289,14 +2854,14 @@ var prefixedConsoleLogger = {
|
|
|
2289
2854
|
};
|
|
2290
2855
|
var label = (text) => text.padEnd(13);
|
|
2291
2856
|
function findSkillsRepositoryRoot(startDirectory) {
|
|
2292
|
-
const start = realpathOr(
|
|
2293
|
-
const home = realpathOr(
|
|
2857
|
+
const start = realpathOr(path12.resolve(startDirectory));
|
|
2858
|
+
const home = realpathOr(os3.homedir());
|
|
2294
2859
|
for (const marker of [".git", ".claude"]) {
|
|
2295
2860
|
let directory = start;
|
|
2296
2861
|
for (; ; ) {
|
|
2297
2862
|
const isHomeClaude = marker === ".claude" && directory === home;
|
|
2298
|
-
if (!isHomeClaude && lstatOrNull(
|
|
2299
|
-
const parent =
|
|
2863
|
+
if (!isHomeClaude && lstatOrNull(path12.join(directory, marker))) return directory;
|
|
2864
|
+
const parent = path12.dirname(directory);
|
|
2300
2865
|
if (parent === directory) break;
|
|
2301
2866
|
directory = parent;
|
|
2302
2867
|
}
|
|
@@ -2305,9 +2870,9 @@ function findSkillsRepositoryRoot(startDirectory) {
|
|
|
2305
2870
|
}
|
|
2306
2871
|
function runSkillLinks(options = {}) {
|
|
2307
2872
|
const logger = options.logger ?? prefixedConsoleLogger;
|
|
2308
|
-
const cwd =
|
|
2873
|
+
const cwd = path12.resolve(options.cwd ?? process.cwd());
|
|
2309
2874
|
const envRoot = process.env[SKILLS_ROOT_ENV];
|
|
2310
|
-
const requestedRoot = options.root ?
|
|
2875
|
+
const requestedRoot = options.root ? path12.resolve(cwd, options.root) : envRoot ? path12.resolve(cwd, envRoot) : findSkillsRepositoryRoot(cwd);
|
|
2311
2876
|
const linker = new SkillLinker(requestedRoot, options, logger);
|
|
2312
2877
|
return linker.run();
|
|
2313
2878
|
}
|
|
@@ -2412,7 +2977,7 @@ var SkillLinker = class {
|
|
|
2412
2977
|
operations.push({ kind: "link", path: linkPath, target: desiredTarget, display: `${display} -> ${desiredTarget}` });
|
|
2413
2978
|
action = "linked";
|
|
2414
2979
|
} else if (entryType === "link") {
|
|
2415
|
-
const currentTarget =
|
|
2980
|
+
const currentTarget = fs10.readlinkSync(linkPath);
|
|
2416
2981
|
if (currentTarget !== desiredTarget) {
|
|
2417
2982
|
if (!isDddVendorPath(resolveLinkTarget(primary, currentTarget))) {
|
|
2418
2983
|
warnings.push(`${label("clash")}${display}: a symlink of the app to ${currentTarget} exists; the skill of ${skill.package} is not linked`);
|
|
@@ -2428,7 +2993,7 @@ var SkillLinker = class {
|
|
|
2428
2993
|
continue;
|
|
2429
2994
|
}
|
|
2430
2995
|
this.results.push({ skill: skillName, action, target: desiredTarget, package: skill.package });
|
|
2431
|
-
let skillFileHash = createHash("sha256").update(
|
|
2996
|
+
let skillFileHash = createHash("sha256").update(fs10.readFileSync(`${skill.directory}/SKILL.md`)).digest("hex");
|
|
2432
2997
|
const previous = previousEntries[skillName];
|
|
2433
2998
|
if (previous && previous.package === skill.package && skill.version !== null && previous.version === skill.version && typeof previous.sha256 === "string" && previous.sha256 !== skillFileHash) {
|
|
2434
2999
|
warnings.push(
|
|
@@ -2449,9 +3014,9 @@ var SkillLinker = class {
|
|
|
2449
3014
|
if (managed.has(skillName) || winners.has(skillName) || !previous || typeof previous !== "object") continue;
|
|
2450
3015
|
const linkPath = `${primary}/${skillName}`;
|
|
2451
3016
|
if (getEntryType(linkPath) !== "link") continue;
|
|
2452
|
-
const currentTarget =
|
|
3017
|
+
const currentTarget = fs10.readlinkSync(linkPath);
|
|
2453
3018
|
if (!isDddVendorPath(resolveLinkTarget(primary, currentTarget))) continue;
|
|
2454
|
-
if (
|
|
3019
|
+
if (fs10.existsSync(linkPath)) {
|
|
2455
3020
|
managed.set(skillName, {
|
|
2456
3021
|
package: previous.package ?? null,
|
|
2457
3022
|
version: previous.version ?? null,
|
|
@@ -2465,8 +3030,8 @@ var SkillLinker = class {
|
|
|
2465
3030
|
const removedNames = /* @__PURE__ */ new Set();
|
|
2466
3031
|
for (const entryName of listDirectoryNames(primary)) {
|
|
2467
3032
|
const linkPath = `${primary}/${entryName}`;
|
|
2468
|
-
if (managed.has(entryName) || getEntryType(linkPath) !== "link" ||
|
|
2469
|
-
const currentTarget =
|
|
3033
|
+
if (managed.has(entryName) || getEntryType(linkPath) !== "link" || fs10.existsSync(linkPath)) continue;
|
|
3034
|
+
const currentTarget = fs10.readlinkSync(linkPath);
|
|
2470
3035
|
if (isDddVendorPath(resolveLinkTarget(primary, currentTarget))) {
|
|
2471
3036
|
removedNames.add(entryName);
|
|
2472
3037
|
operations.push({ kind: "remove", path: linkPath, display: `${PRIMARY_SKILLS_DIRECTORY}/${entryName} (broken link to ${currentTarget})` });
|
|
@@ -2479,7 +3044,7 @@ var SkillLinker = class {
|
|
|
2479
3044
|
const mirrorLogical = `${this.root}/${mirrorName}`;
|
|
2480
3045
|
if (getEntryType(mirrorLogical) === "missing" || !isDirectory(mirrorLogical)) continue;
|
|
2481
3046
|
const mirror = realpathOr(mirrorLogical);
|
|
2482
|
-
const mirrorParent = realpathOr(
|
|
3047
|
+
const mirrorParent = realpathOr(path12.dirname(mirrorLogical));
|
|
2483
3048
|
if (mirror === primary || mirrorParent === primary) continue;
|
|
2484
3049
|
mirrorGitignoreNames.set(mirror, []);
|
|
2485
3050
|
for (const skillName of managedNames) {
|
|
@@ -2491,7 +3056,7 @@ var SkillLinker = class {
|
|
|
2491
3056
|
if (entryType === "missing") {
|
|
2492
3057
|
operations.push({ kind: "link", path: linkPath, target: desiredTarget, display: `${display} -> ${desiredTarget}` });
|
|
2493
3058
|
} else if (entryType === "link") {
|
|
2494
|
-
const currentTarget =
|
|
3059
|
+
const currentTarget = fs10.readlinkSync(linkPath);
|
|
2495
3060
|
if (currentTarget !== desiredTarget) {
|
|
2496
3061
|
const resolvedTarget = resolveLinkTarget(mirror, currentTarget);
|
|
2497
3062
|
const pointsToPrimary = resolvedTarget === primaryEntryPath || resolvedTarget === `${primary}/${skillName}`;
|
|
@@ -2512,34 +3077,34 @@ var SkillLinker = class {
|
|
|
2512
3077
|
for (const entryName of listDirectoryNames(mirror)) {
|
|
2513
3078
|
const linkPath = `${mirror}/${entryName}`;
|
|
2514
3079
|
if (managed.has(entryName) || getEntryType(linkPath) !== "link") continue;
|
|
2515
|
-
const currentTarget =
|
|
3080
|
+
const currentTarget = fs10.readlinkSync(linkPath);
|
|
2516
3081
|
const resolvedTarget = resolveLinkTarget(mirror, currentTarget);
|
|
2517
3082
|
const pointsToPrimary = resolvedTarget === `${primaryLogical}/${entryName}` || resolvedTarget === `${primary}/${entryName}`;
|
|
2518
|
-
const isBrokenDddLink = !
|
|
2519
|
-
const isFormerMirror = pointsToPrimary && (removedNames.has(entryName) || entryName in previousEntries) && (!
|
|
3083
|
+
const isBrokenDddLink = !fs10.existsSync(linkPath) && isDddVendorPath(resolvedTarget);
|
|
3084
|
+
const isFormerMirror = pointsToPrimary && (removedNames.has(entryName) || entryName in previousEntries) && (!fs10.existsSync(`${primary}/${entryName}`) || removedNames.has(entryName));
|
|
2520
3085
|
if (isBrokenDddLink || isFormerMirror) {
|
|
2521
3086
|
operations.push({ kind: "remove", path: linkPath, display: `${mirrorName}/${entryName} (link to removed ${currentTarget})` });
|
|
2522
3087
|
}
|
|
2523
3088
|
}
|
|
2524
3089
|
}
|
|
2525
|
-
const
|
|
3090
|
+
const manifestPath2 = `${primary}/${SKILLS_MANIFEST_FILE_NAME}`;
|
|
2526
3091
|
const manifestContent = encodeManifest(managedNames, managed);
|
|
2527
|
-
if ((isFile(
|
|
2528
|
-
operations.push({ kind: "write", path:
|
|
3092
|
+
if ((isFile(manifestPath2) ? fs10.readFileSync(manifestPath2, "utf-8") : null) !== manifestContent) {
|
|
3093
|
+
operations.push({ kind: "write", path: manifestPath2, content: manifestContent, display: `${PRIMARY_SKILLS_DIRECTORY}/${SKILLS_MANIFEST_FILE_NAME}` });
|
|
2529
3094
|
}
|
|
2530
3095
|
const primaryGitignoreEntries = [`/${SKILLS_MANIFEST_FILE_NAME}`];
|
|
2531
3096
|
for (const skillName of managedNames) {
|
|
2532
3097
|
primaryGitignoreEntries.push(`/${skillName}`);
|
|
2533
3098
|
gitPaths.push(`${primary}/${skillName}`);
|
|
2534
3099
|
}
|
|
2535
|
-
gitPaths.push(
|
|
3100
|
+
gitPaths.push(manifestPath2);
|
|
2536
3101
|
const gitignoreTargets = /* @__PURE__ */ new Map([[primary, primaryGitignoreEntries]]);
|
|
2537
3102
|
for (const [mirror, names] of mirrorGitignoreNames) {
|
|
2538
3103
|
gitignoreTargets.set(mirror, [...names].sort(compareBytes).map((name) => `/${name}`));
|
|
2539
3104
|
}
|
|
2540
3105
|
for (const [directory, entries] of gitignoreTargets) {
|
|
2541
3106
|
const gitignorePath = `${directory}/.gitignore`;
|
|
2542
|
-
const currentContent = isFile(gitignorePath) ?
|
|
3107
|
+
const currentContent = isFile(gitignorePath) ? fs10.readFileSync(gitignorePath, "utf-8") : null;
|
|
2543
3108
|
const newContent = createGitignoreContent(currentContent, entries);
|
|
2544
3109
|
if (newContent === null) {
|
|
2545
3110
|
warnings.push(
|
|
@@ -2591,8 +3156,8 @@ var SkillLinker = class {
|
|
|
2591
3156
|
return { winners, warnings };
|
|
2592
3157
|
}
|
|
2593
3158
|
legacySourcePackage(sourceDir) {
|
|
2594
|
-
const skillsDirectory =
|
|
2595
|
-
const packageJson = readJson(
|
|
3159
|
+
const skillsDirectory = path12.resolve(path12.resolve(this.options.cwd ?? process.cwd()), sourceDir);
|
|
3160
|
+
const packageJson = readJson(path12.join(skillsDirectory, "..", "..", "package.json"));
|
|
2596
3161
|
return {
|
|
2597
3162
|
package: typeof packageJson?.name === "string" ? packageJson.name : "@mgamadeus/ddd-web",
|
|
2598
3163
|
version: typeof packageJson?.version === "string" ? packageJson.version : null,
|
|
@@ -2607,10 +3172,10 @@ var SkillLinker = class {
|
|
|
2607
3172
|
for (const folderName of listDirectoryNames(composerScope)) {
|
|
2608
3173
|
const packageDirectory = `${composerScope}/${folderName}`;
|
|
2609
3174
|
if (!isDirectory(packageDirectory)) continue;
|
|
2610
|
-
const
|
|
3175
|
+
const packageName2 = `mgamadeus/${folderName}`;
|
|
2611
3176
|
packages.push({
|
|
2612
|
-
package:
|
|
2613
|
-
version: installedVersions.get(
|
|
3177
|
+
package: packageName2,
|
|
3178
|
+
version: installedVersions.get(packageName2) ?? readJsonVersion(`${packageDirectory}/composer.json`),
|
|
2614
3179
|
skillsDirectory: `${packageDirectory}/.claude/skills`
|
|
2615
3180
|
});
|
|
2616
3181
|
}
|
|
@@ -2656,13 +3221,13 @@ var SkillLinker = class {
|
|
|
2656
3221
|
}
|
|
2657
3222
|
applyOperations(operations) {
|
|
2658
3223
|
const primary = this.resolvePrimaryDirectory();
|
|
2659
|
-
|
|
3224
|
+
fs10.mkdirSync(primary, { recursive: true });
|
|
2660
3225
|
for (const kind of ["remove", "relink", "link", "write"]) {
|
|
2661
3226
|
for (const operation of operations) {
|
|
2662
3227
|
if (operation.kind !== kind) continue;
|
|
2663
|
-
if (kind === "remove" || kind === "relink")
|
|
2664
|
-
if (kind === "relink" || kind === "link")
|
|
2665
|
-
if (kind === "write")
|
|
3228
|
+
if (kind === "remove" || kind === "relink") fs10.unlinkSync(operation.path);
|
|
3229
|
+
if (kind === "relink" || kind === "link") fs10.symlinkSync(operation.target, operation.path, "dir");
|
|
3230
|
+
if (kind === "write") fs10.writeFileSync(operation.path, operation.content);
|
|
2666
3231
|
}
|
|
2667
3232
|
}
|
|
2668
3233
|
}
|
|
@@ -2680,9 +3245,9 @@ var SkillLinker = class {
|
|
|
2680
3245
|
this.logger[level](line);
|
|
2681
3246
|
}
|
|
2682
3247
|
};
|
|
2683
|
-
function readManifestEntries(
|
|
2684
|
-
if (!isFile(
|
|
2685
|
-
const manifest = readJson(
|
|
3248
|
+
function readManifestEntries(manifestPath2) {
|
|
3249
|
+
if (!isFile(manifestPath2)) return {};
|
|
3250
|
+
const manifest = readJson(manifestPath2);
|
|
2686
3251
|
if (!manifest || typeof manifest.skills !== "object" || manifest.skills === null || Array.isArray(manifest.skills)) return null;
|
|
2687
3252
|
return manifest.skills;
|
|
2688
3253
|
}
|
|
@@ -2738,7 +3303,7 @@ function readJsonVersion(jsonPath) {
|
|
|
2738
3303
|
}
|
|
2739
3304
|
function readJson(jsonPath) {
|
|
2740
3305
|
try {
|
|
2741
|
-
return JSON.parse(
|
|
3306
|
+
return JSON.parse(fs10.readFileSync(jsonPath, "utf-8"));
|
|
2742
3307
|
} catch {
|
|
2743
3308
|
return null;
|
|
2744
3309
|
}
|
|
@@ -2751,35 +3316,35 @@ function getEntryType(entryPath) {
|
|
|
2751
3316
|
}
|
|
2752
3317
|
function lstatOrNull(entryPath) {
|
|
2753
3318
|
try {
|
|
2754
|
-
return
|
|
3319
|
+
return fs10.lstatSync(entryPath);
|
|
2755
3320
|
} catch {
|
|
2756
3321
|
return null;
|
|
2757
3322
|
}
|
|
2758
3323
|
}
|
|
2759
3324
|
function isDirectory(entryPath) {
|
|
2760
3325
|
try {
|
|
2761
|
-
return
|
|
3326
|
+
return fs10.statSync(entryPath).isDirectory();
|
|
2762
3327
|
} catch {
|
|
2763
3328
|
return false;
|
|
2764
3329
|
}
|
|
2765
3330
|
}
|
|
2766
3331
|
function isFile(entryPath) {
|
|
2767
3332
|
try {
|
|
2768
|
-
return
|
|
3333
|
+
return fs10.statSync(entryPath).isFile();
|
|
2769
3334
|
} catch {
|
|
2770
3335
|
return false;
|
|
2771
3336
|
}
|
|
2772
3337
|
}
|
|
2773
3338
|
function realpathOr(entryPath) {
|
|
2774
3339
|
try {
|
|
2775
|
-
return
|
|
3340
|
+
return fs10.realpathSync(entryPath);
|
|
2776
3341
|
} catch {
|
|
2777
3342
|
return entryPath;
|
|
2778
3343
|
}
|
|
2779
3344
|
}
|
|
2780
3345
|
function listDirectoryNames(directory) {
|
|
2781
3346
|
try {
|
|
2782
|
-
return
|
|
3347
|
+
return fs10.readdirSync(directory).sort(compareBytes);
|
|
2783
3348
|
} catch {
|
|
2784
3349
|
return [];
|
|
2785
3350
|
}
|
|
@@ -2792,10 +3357,10 @@ function isDddVendorPath(candidate) {
|
|
|
2792
3357
|
return withSlash.includes("/vendor/mgamadeus/") || withSlash.includes("/node_modules/@mgamadeus/");
|
|
2793
3358
|
}
|
|
2794
3359
|
function resolveLinkTarget(linkDirectory, target) {
|
|
2795
|
-
return
|
|
3360
|
+
return path12.posix.resolve(linkDirectory, target);
|
|
2796
3361
|
}
|
|
2797
3362
|
function relativePath(fromDirectory, toPath) {
|
|
2798
|
-
return
|
|
3363
|
+
return path12.posix.relative(fromDirectory, toPath) || ".";
|
|
2799
3364
|
}
|
|
2800
3365
|
function quoteShellArgument(argument) {
|
|
2801
3366
|
return /^[A-Za-z0-9._/@+=:-]+$/.test(argument) ? argument : `'${argument.replace(/'/g, "'\\''")}'`;
|
|
@@ -2808,13 +3373,14 @@ export {
|
|
|
2808
3373
|
silentLogger,
|
|
2809
3374
|
SdkGenerationError,
|
|
2810
3375
|
broadInvalidation,
|
|
2811
|
-
buildEndpointNameFromPath,
|
|
2812
3376
|
SUPPORTED_CONTRACT,
|
|
2813
3377
|
loadSpec,
|
|
2814
3378
|
validateSpec,
|
|
3379
|
+
generateLegacySdk,
|
|
3380
|
+
buildEndpointNameFromPath,
|
|
2815
3381
|
generateSdk,
|
|
2816
3382
|
findSkillsRepositoryRoot,
|
|
2817
3383
|
runSkillLinks,
|
|
2818
3384
|
linkSkills
|
|
2819
3385
|
};
|
|
2820
|
-
//# sourceMappingURL=chunk-
|
|
3386
|
+
//# sourceMappingURL=chunk-HZ4VYIHY.js.map
|