@mgamadeus/ddd-web 0.18.0 → 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 +6 -2
- package/.claude/skills/ddd-web-specialist/references/consumer.md +26 -0
- package/CHANGELOG.md +24 -0
- package/README.md +29 -0
- package/dist/{chunk-AGECBV52.js → chunk-HZ4VYIHY.js} +459 -103
- package/dist/chunk-HZ4VYIHY.js.map +1 -0
- package/dist/codegen/cli.js +1 -1
- package/dist/codegen/index.d.ts +71 -15
- package/dist/codegen/index.js +1 -1
- package/package.json +2 -1
- package/dist/chunk-AGECBV52.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) } : {},
|
|
@@ -657,9 +657,9 @@ function testPattern(pattern, value) {
|
|
|
657
657
|
pattern.lastIndex = 0;
|
|
658
658
|
return result;
|
|
659
659
|
}
|
|
660
|
-
function matchesOperation(override, method,
|
|
660
|
+
function matchesOperation(override, method, path13) {
|
|
661
661
|
if (override.method && override.method.toLowerCase() !== method) return false;
|
|
662
|
-
return typeof override.path === "string" ? override.path ===
|
|
662
|
+
return typeof override.path === "string" ? override.path === path13 : testPattern(override.path, path13);
|
|
663
663
|
}
|
|
664
664
|
function canonical(value) {
|
|
665
665
|
return JSON.stringify(
|
|
@@ -683,9 +683,9 @@ function isEntityExtension(value) {
|
|
|
683
683
|
}
|
|
684
684
|
function indexOperations(doc, overrides, skipUpdatePostTwins) {
|
|
685
685
|
const byKey = /* @__PURE__ */ new Map();
|
|
686
|
-
for (const { method, path:
|
|
686
|
+
for (const { method, path: path13, operation } of listOperations(doc)) {
|
|
687
687
|
const extension = operation["x-ddd-side-effects"];
|
|
688
|
-
const override = overrides.find((candidate) => matchesOperation(candidate, method,
|
|
688
|
+
const override = overrides.find((candidate) => matchesOperation(candidate, method, path13));
|
|
689
689
|
let sideEffects = hasSideEffects(method, operation);
|
|
690
690
|
let explicit = false;
|
|
691
691
|
if (typeof extension === "boolean") {
|
|
@@ -699,9 +699,9 @@ function indexOperations(doc, overrides, skipUpdatePostTwins) {
|
|
|
699
699
|
const classifiedType = explicit ? sideEffects ? "mutation" : "query" : naturalType;
|
|
700
700
|
const endpointType = typeof extension !== "boolean" && override?.endpointType || classifiedType;
|
|
701
701
|
const entity = isEntityExtension(operation["x-ddd-entity"]) ? operation["x-ddd-entity"] : void 0;
|
|
702
|
-
byKey.set(operationKey(method,
|
|
702
|
+
byKey.set(operationKey(method, path13), {
|
|
703
703
|
method,
|
|
704
|
-
path:
|
|
704
|
+
path: path13,
|
|
705
705
|
operation,
|
|
706
706
|
sideEffects,
|
|
707
707
|
sideEffectsExplicit: explicit,
|
|
@@ -711,11 +711,11 @@ function indexOperations(doc, overrides, skipUpdatePostTwins) {
|
|
|
711
711
|
}
|
|
712
712
|
const skippedTwins = /* @__PURE__ */ new Set();
|
|
713
713
|
if (skipUpdatePostTwins) {
|
|
714
|
-
for (const [
|
|
714
|
+
for (const [path13, item] of Object.entries(doc.paths ?? {})) {
|
|
715
715
|
const post = item?.post;
|
|
716
716
|
const patch = item?.patch;
|
|
717
717
|
if (post && patch && isUpsertTwin(post, patch)) {
|
|
718
|
-
skippedTwins.add(operationKey("post",
|
|
718
|
+
skippedTwins.add(operationKey("post", path13));
|
|
719
719
|
}
|
|
720
720
|
}
|
|
721
721
|
}
|
|
@@ -754,9 +754,9 @@ function commitOutput(files, modelsDir, stagingParent, options = {}) {
|
|
|
754
754
|
fs5.mkdirSync(stagedModels, { recursive: true });
|
|
755
755
|
for (const filePath of files.paths()) {
|
|
756
756
|
const content = files.get(filePath);
|
|
757
|
-
const
|
|
758
|
-
if (
|
|
759
|
-
const staged = path4.join(stagedModels,
|
|
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
760
|
fs5.mkdirSync(path4.dirname(staged), { recursive: true });
|
|
761
761
|
fs5.writeFileSync(staged, content);
|
|
762
762
|
} else {
|
|
@@ -831,25 +831,25 @@ function resolveParameter(doc, parameter) {
|
|
|
831
831
|
}
|
|
832
832
|
function repairMissingPathParameters(doc, logger) {
|
|
833
833
|
const repairs = [];
|
|
834
|
-
for (const { method, path:
|
|
835
|
-
const placeholders = [...
|
|
834
|
+
for (const { method, path: path13, operation } of listOperations(doc)) {
|
|
835
|
+
const placeholders = [...path13.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
836
836
|
if (placeholders.length === 0) continue;
|
|
837
|
-
const pathLevel = doc.paths?.[
|
|
837
|
+
const pathLevel = doc.paths?.[path13]?.parameters ?? [];
|
|
838
838
|
const declared = new Set(
|
|
839
839
|
[...pathLevel, ...operation.parameters ?? []].map((parameter) => resolveParameter(doc, parameter)).filter((parameter) => parameter !== null && parameter.in === "path").map((parameter) => parameter.name)
|
|
840
840
|
);
|
|
841
841
|
const missing = placeholders.filter((name) => !declared.has(name));
|
|
842
|
-
if (missing.length > 0) repairs.push({ path:
|
|
842
|
+
if (missing.length > 0) repairs.push({ path: path13, method, names: missing });
|
|
843
843
|
}
|
|
844
844
|
if (repairs.length === 0) return doc;
|
|
845
845
|
const copy = structuredClone(doc);
|
|
846
|
-
for (const { path:
|
|
847
|
-
const operation = copy.paths[
|
|
846
|
+
for (const { path: path13, method, names } of repairs) {
|
|
847
|
+
const operation = copy.paths[path13][method];
|
|
848
848
|
operation.parameters = [
|
|
849
849
|
...names.map((name) => ({ name, in: "path", required: true, schema: { type: "string" } })),
|
|
850
850
|
...operation.parameters ?? []
|
|
851
851
|
];
|
|
852
|
-
logger.warn(`${method.toUpperCase()} ${
|
|
852
|
+
logger.warn(`${method.toUpperCase()} ${path13}: path parameter(s) ${names.join(", ")} not declared in the spec \u2014 added as string.`);
|
|
853
853
|
}
|
|
854
854
|
return copy;
|
|
855
855
|
}
|
|
@@ -908,12 +908,100 @@ async function generateLegacySdk(options) {
|
|
|
908
908
|
}
|
|
909
909
|
}
|
|
910
910
|
}
|
|
911
|
+
const prune = options.prune ? planLegacyPrune(options.sources, results, cwd, options.manifestFile) : void 0;
|
|
911
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
|
+
}
|
|
912
930
|
return results;
|
|
913
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
|
+
}
|
|
914
1002
|
function contains(parent, child) {
|
|
915
|
-
const
|
|
916
|
-
return
|
|
1003
|
+
const relative7 = path5.relative(parent, child);
|
|
1004
|
+
return relative7 !== ".." && !relative7.startsWith(".." + path5.sep) && !path5.isAbsolute(relative7);
|
|
917
1005
|
}
|
|
918
1006
|
function assertGeneratedDirectory(directory) {
|
|
919
1007
|
const entry = fs6.lstatSync(directory, { throwIfNoEntry: false });
|
|
@@ -1054,8 +1142,8 @@ async function generateDelegatedSdk(mode, loaded, allApis, apis, options, logger
|
|
|
1054
1142
|
var REQUEST_BODY_ARG = "requestBody";
|
|
1055
1143
|
var DEFAULT_STRIP_PATH_PREFIX = /^\/(?:app\/)?api(?=\/)/;
|
|
1056
1144
|
var upperFirst = (value) => value.charAt(0).toUpperCase() + value.slice(1);
|
|
1057
|
-
function buildEndpointNameFromPath(method,
|
|
1058
|
-
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, "");
|
|
1059
1147
|
let lastInnerParameter = null;
|
|
1060
1148
|
const withoutInnerParameters = stripped.replace(/\{([^}]+)\}\//g, (_, parameter) => {
|
|
1061
1149
|
lastInnerParameter = parameter;
|
|
@@ -1076,21 +1164,21 @@ function prepareDocumentForEndpoints(doc, options) {
|
|
|
1076
1164
|
const prepared = structuredClone(doc);
|
|
1077
1165
|
if (dropsCookieParameters) dropCookieParameters(prepared);
|
|
1078
1166
|
const pathByName = /* @__PURE__ */ new Map();
|
|
1079
|
-
for (const [
|
|
1167
|
+
for (const [path13, item] of Object.entries(prepared.paths ?? {})) {
|
|
1080
1168
|
if (!item) continue;
|
|
1081
1169
|
for (const method of HTTP_METHODS) {
|
|
1082
1170
|
const operation = item[method];
|
|
1083
1171
|
if (!operation) continue;
|
|
1084
1172
|
if (naming !== "rtk") {
|
|
1085
|
-
const name = naming === "path" ? buildEndpointNameFromPath(method,
|
|
1173
|
+
const name = naming === "path" ? buildEndpointNameFromPath(method, path13, options.stripPathPrefix) : naming({ method, path: path13, operation });
|
|
1086
1174
|
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) {
|
|
1087
|
-
throw new SdkGenerationError(`endpoints.naming: "${name}" (${method.toUpperCase()} ${
|
|
1175
|
+
throw new SdkGenerationError(`endpoints.naming: "${name}" (${method.toUpperCase()} ${path13}) is no identifier.`);
|
|
1088
1176
|
}
|
|
1089
1177
|
const other = pathByName.get(name);
|
|
1090
1178
|
if (other !== void 0) {
|
|
1091
|
-
throw new SdkGenerationError(`endpoints.naming: ${other} and ${method.toUpperCase()} ${
|
|
1179
|
+
throw new SdkGenerationError(`endpoints.naming: ${other} and ${method.toUpperCase()} ${path13} are both named "${name}".`);
|
|
1092
1180
|
}
|
|
1093
|
-
pathByName.set(name, `${method.toUpperCase()} ${
|
|
1181
|
+
pathByName.set(name, `${method.toUpperCase()} ${path13}`);
|
|
1094
1182
|
const placeholder = `dddEndpoint${endpointNamesByPlaceholder.size}`;
|
|
1095
1183
|
endpointNamesByPlaceholder.set(placeholder, name);
|
|
1096
1184
|
operation.operationId = placeholder;
|
|
@@ -1152,7 +1240,7 @@ function titleRequestBody(operation) {
|
|
|
1152
1240
|
// src/codegen/generate.ts
|
|
1153
1241
|
import * as fs9 from "fs";
|
|
1154
1242
|
import * as os2 from "os";
|
|
1155
|
-
import * as
|
|
1243
|
+
import * as path11 from "path";
|
|
1156
1244
|
|
|
1157
1245
|
// src/codegen/typescript.ts
|
|
1158
1246
|
import { createRequire as createRequire3 } from "module";
|
|
@@ -1438,8 +1526,8 @@ function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
|
|
|
1438
1526
|
logger.warn(`No extractable URL for endpoint "${key}" \u2014 skipping.`);
|
|
1439
1527
|
return null;
|
|
1440
1528
|
}
|
|
1441
|
-
const
|
|
1442
|
-
const placeholders = [...
|
|
1529
|
+
const path13 = location?.path ?? toOpenApiPath(url);
|
|
1530
|
+
const placeholders = [...path13.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
1443
1531
|
const pathArgs = {};
|
|
1444
1532
|
placeholders.forEach((name, index) => {
|
|
1445
1533
|
const accessor = accessors[index];
|
|
@@ -1450,7 +1538,7 @@ function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
|
|
|
1450
1538
|
buildType,
|
|
1451
1539
|
url,
|
|
1452
1540
|
method: (location?.method ?? method ?? "GET").toUpperCase(),
|
|
1453
|
-
path:
|
|
1541
|
+
path: path13,
|
|
1454
1542
|
pathArgs,
|
|
1455
1543
|
...bodyArg ? { bodyArg } : {},
|
|
1456
1544
|
...responseType ? { responseType } : {}
|
|
@@ -1523,10 +1611,10 @@ function detectResponseKind(responses) {
|
|
|
1523
1611
|
}
|
|
1524
1612
|
function detectResponseHandlerEndpoints(doc, endpoints, overrides = []) {
|
|
1525
1613
|
const kinds = /* @__PURE__ */ new Map();
|
|
1526
|
-
for (const { method, path:
|
|
1527
|
-
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));
|
|
1528
1616
|
const kind = override ? override.handler : detectResponseKind(operation.responses);
|
|
1529
|
-
if (kind !== "json") kinds.set(operationKey(method,
|
|
1617
|
+
if (kind !== "json") kinds.set(operationKey(method, path13), kind);
|
|
1530
1618
|
}
|
|
1531
1619
|
const keys = /* @__PURE__ */ new Map();
|
|
1532
1620
|
if (kinds.size === 0) return keys;
|
|
@@ -1751,9 +1839,9 @@ function registryMatch(name, registry) {
|
|
|
1751
1839
|
return null;
|
|
1752
1840
|
}
|
|
1753
1841
|
function importSpecifier(fromFile, toFile, esm) {
|
|
1754
|
-
let
|
|
1755
|
-
if (!
|
|
1756
|
-
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;
|
|
1757
1845
|
}
|
|
1758
1846
|
var EXPORTED_NAME = /^export (?:type|interface) (\w+)/m;
|
|
1759
1847
|
function extractModels(input) {
|
|
@@ -1763,8 +1851,8 @@ function extractModels(input) {
|
|
|
1763
1851
|
const indexPath = path6.join(modelsDir, "index.ts");
|
|
1764
1852
|
const nameOwners = /* @__PURE__ */ new Map();
|
|
1765
1853
|
for (const filePath of files.paths()) {
|
|
1766
|
-
const
|
|
1767
|
-
if (
|
|
1854
|
+
const relative7 = path6.relative(modelsDir, filePath);
|
|
1855
|
+
if (relative7.startsWith("..") || path6.isAbsolute(relative7) || path6.resolve(filePath) === path6.resolve(indexPath)) continue;
|
|
1768
1856
|
const name = files.get(filePath)?.match(EXPORTED_NAME)?.[1];
|
|
1769
1857
|
if (name && !nameOwners.has(name)) nameOwners.set(name, path6.resolve(filePath).toLowerCase());
|
|
1770
1858
|
}
|
|
@@ -1943,6 +2031,252 @@ ${defaultExport}
|
|
|
1943
2031
|
`;
|
|
1944
2032
|
}
|
|
1945
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
|
+
|
|
1946
2280
|
// src/codegen/multipart.ts
|
|
1947
2281
|
var MULTIPART_FILES_ARG = "multipartFiles";
|
|
1948
2282
|
var BODY_FIELD = "body";
|
|
@@ -1977,9 +2311,9 @@ function readMultipartOperation(doc, requestBody) {
|
|
|
1977
2311
|
}
|
|
1978
2312
|
function detectMultipartEndpoints(doc, endpoints) {
|
|
1979
2313
|
const byOperation = /* @__PURE__ */ new Map();
|
|
1980
|
-
for (const { method, path:
|
|
2314
|
+
for (const { method, path: path13, operation } of listOperations(doc)) {
|
|
1981
2315
|
const multipart = readMultipartOperation(doc, operation.requestBody);
|
|
1982
|
-
if (multipart) byOperation.set(operationKey(method,
|
|
2316
|
+
if (multipart) byOperation.set(operationKey(method, path13), multipart);
|
|
1983
2317
|
}
|
|
1984
2318
|
const keys = /* @__PURE__ */ new Map();
|
|
1985
2319
|
if (byOperation.size === 0) return keys;
|
|
@@ -2110,12 +2444,12 @@ function buildRegistry(docs, logger) {
|
|
|
2110
2444
|
|
|
2111
2445
|
// src/codegen/rtk.ts
|
|
2112
2446
|
import * as fs7 from "fs";
|
|
2113
|
-
import * as
|
|
2447
|
+
import * as path9 from "path";
|
|
2114
2448
|
import prettier2 from "prettier";
|
|
2115
2449
|
|
|
2116
2450
|
// src/codegen/module-resolution.ts
|
|
2117
2451
|
import Module, { createRequire as createRequire4 } from "module";
|
|
2118
|
-
import * as
|
|
2452
|
+
import * as path8 from "path";
|
|
2119
2453
|
var installed = false;
|
|
2120
2454
|
function installParserModuleResolution() {
|
|
2121
2455
|
if (installed) return;
|
|
@@ -2128,7 +2462,7 @@ function installParserModuleResolution() {
|
|
|
2128
2462
|
} catch {
|
|
2129
2463
|
return;
|
|
2130
2464
|
}
|
|
2131
|
-
const ajvDraft04Folder = `${
|
|
2465
|
+
const ajvDraft04Folder = `${path8.sep}ajv-draft-04${path8.sep}`;
|
|
2132
2466
|
const moduleWithResolver = Module;
|
|
2133
2467
|
const defaultResolveFilename = moduleWithResolver._resolveFilename;
|
|
2134
2468
|
moduleWithResolver._resolveFilename = function resolveAjvOfTheParser(request, parent, ...rest) {
|
|
@@ -2147,7 +2481,7 @@ async function loadRtkCodegen() {
|
|
|
2147
2481
|
}
|
|
2148
2482
|
|
|
2149
2483
|
// src/codegen/rtk.ts
|
|
2150
|
-
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"]);
|
|
2151
2485
|
function matches(matcher, name, definition) {
|
|
2152
2486
|
if (matcher === void 0) return true;
|
|
2153
2487
|
if (typeof matcher === "function") return matcher(name, definition);
|
|
@@ -2172,9 +2506,9 @@ function mergeEndpointOverrides(userOverrides, typeOverrides) {
|
|
|
2172
2506
|
}
|
|
2173
2507
|
function relativeImport(fromDir, target) {
|
|
2174
2508
|
if (!isPathLike(target)) return target;
|
|
2175
|
-
let
|
|
2176
|
-
if (!
|
|
2177
|
-
return
|
|
2509
|
+
let relative7 = path9.relative(fromDir, target).replace(/\\/g, "/");
|
|
2510
|
+
if (!relative7.startsWith(".")) relative7 = `./${relative7}`;
|
|
2511
|
+
return relative7;
|
|
2178
2512
|
}
|
|
2179
2513
|
async function runRtkCodegen(api, doc, index, specFile, prettierConfigFile, endpointNameOf = (rtkName) => rtkName) {
|
|
2180
2514
|
fs7.writeFileSync(specFile, JSON.stringify(doc));
|
|
@@ -2213,12 +2547,12 @@ async function runRtkCodegen(api, doc, index, specFile, prettierConfigFile, endp
|
|
|
2213
2547
|
return { code, locations };
|
|
2214
2548
|
}
|
|
2215
2549
|
async function findPrettierConfigFile(rootDir) {
|
|
2216
|
-
return await prettier2.resolveConfigFile(
|
|
2550
|
+
return await prettier2.resolveConfigFile(path9.join(rootDir, "openapi-config.ts")) ?? void 0;
|
|
2217
2551
|
}
|
|
2218
2552
|
|
|
2219
2553
|
// src/codegen/workspace.ts
|
|
2220
2554
|
import * as fs8 from "fs";
|
|
2221
|
-
import * as
|
|
2555
|
+
import * as path10 from "path";
|
|
2222
2556
|
import * as readline from "readline";
|
|
2223
2557
|
var DEFAULT_ENV_FILES = [".env", ".env.local"];
|
|
2224
2558
|
var DEFAULT_URL_KEYS = ["NEXT_PUBLIC_API_URL", "EXPO_PUBLIC_API_URL", "VITE_API_URL", "VITE_API_ENDPOINT", "API_URL"];
|
|
@@ -2243,7 +2577,7 @@ function firstHostLabel(url) {
|
|
|
2243
2577
|
}
|
|
2244
2578
|
function sniffWorkspace(rootDir, options) {
|
|
2245
2579
|
for (const file of options.envFiles ?? DEFAULT_ENV_FILES) {
|
|
2246
|
-
const vars = parseEnvFile(
|
|
2580
|
+
const vars = parseEnvFile(path10.join(rootDir, file));
|
|
2247
2581
|
for (const key of options.urlKeys ?? DEFAULT_URL_KEYS) {
|
|
2248
2582
|
const value = vars[key];
|
|
2249
2583
|
const label2 = value ? firstHostLabel(value) : null;
|
|
@@ -2253,11 +2587,11 @@ function sniffWorkspace(rootDir, options) {
|
|
|
2253
2587
|
return null;
|
|
2254
2588
|
}
|
|
2255
2589
|
function ask(question) {
|
|
2256
|
-
return new Promise((
|
|
2590
|
+
return new Promise((resolve9) => {
|
|
2257
2591
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
2258
|
-
rl.on("close", () =>
|
|
2592
|
+
rl.on("close", () => resolve9(""));
|
|
2259
2593
|
rl.question(question, (answer) => {
|
|
2260
|
-
|
|
2594
|
+
resolve9(answer.trim());
|
|
2261
2595
|
rl.close();
|
|
2262
2596
|
});
|
|
2263
2597
|
});
|
|
@@ -2283,9 +2617,9 @@ async function resolveWorkspace(rootDir, options, explicit, logger) {
|
|
|
2283
2617
|
// src/codegen/generate.ts
|
|
2284
2618
|
async function load(options, cwd) {
|
|
2285
2619
|
if (options.config && typeof options.config === "object") {
|
|
2286
|
-
return { config: options.config, configPath:
|
|
2620
|
+
return { config: options.config, configPath: path11.join(cwd, "<inline config>"), rootDir: cwd };
|
|
2287
2621
|
}
|
|
2288
|
-
return loadConfig(
|
|
2622
|
+
return loadConfig(path11.resolve(cwd, options.config ?? "openapi-config.ts"));
|
|
2289
2623
|
}
|
|
2290
2624
|
function selectApis(all, options) {
|
|
2291
2625
|
let selected = all;
|
|
@@ -2297,14 +2631,14 @@ function selectApis(all, options) {
|
|
|
2297
2631
|
}
|
|
2298
2632
|
if (options.schema) {
|
|
2299
2633
|
if (selected.length !== 1) throw new SdkGenerationError("--schema needs exactly one api (use --api).");
|
|
2300
|
-
const schemaSource = isUrl(options.schema) ? options.schema :
|
|
2634
|
+
const schemaSource = isUrl(options.schema) ? options.schema : path11.resolve(options.cwd ?? process.cwd(), options.schema);
|
|
2301
2635
|
selected = [{ ...selected[0], schemaSource }];
|
|
2302
2636
|
}
|
|
2303
2637
|
return selected;
|
|
2304
2638
|
}
|
|
2305
2639
|
async function generateSdk(options = {}) {
|
|
2306
2640
|
const logger = options.logger ?? consoleLogger;
|
|
2307
|
-
const cwd =
|
|
2641
|
+
const cwd = path11.resolve(options.cwd ?? process.cwd());
|
|
2308
2642
|
let loaded = await load(options, cwd);
|
|
2309
2643
|
if (loaded.config.workspace) {
|
|
2310
2644
|
const value = await resolveWorkspace(loaded.rootDir, loaded.config.workspace, options.workspace, logger);
|
|
@@ -2358,7 +2692,7 @@ async function generateSdk(options = {}) {
|
|
|
2358
2692
|
const prettierConfigFile = await findPrettierConfigFile(loaded.rootDir);
|
|
2359
2693
|
const constsByFile = /* @__PURE__ */ new Map();
|
|
2360
2694
|
const uniqueNameByPath = /* @__PURE__ */ new Map();
|
|
2361
|
-
const specDir = fs9.mkdtempSync(
|
|
2695
|
+
const specDir = fs9.mkdtempSync(path11.join(os2.tmpdir(), "ddd-web-spec-"));
|
|
2362
2696
|
try {
|
|
2363
2697
|
for (const [i, { api, write, doc: rawDoc }] of steps.entries()) {
|
|
2364
2698
|
const doc = repairMissingPathParameters(rawDoc, logger);
|
|
@@ -2386,7 +2720,7 @@ async function generateSdk(options = {}) {
|
|
|
2386
2720
|
};
|
|
2387
2721
|
const endpointNameOf = (rtkName) => preparedEndpoints.endpointNamesByPlaceholder.get(rtkName) ?? rtkName;
|
|
2388
2722
|
const runPass = async (passApi, specName, modelsOnly) => {
|
|
2389
|
-
const generated = await runRtkCodegen(passApi, preparedEndpoints.doc, index,
|
|
2723
|
+
const generated = await runRtkCodegen(passApi, preparedEndpoints.doc, index, path11.join(specDir, specName), prettierConfigFile, endpointNameOf);
|
|
2390
2724
|
const rtk = restoreEndpointNames(generated.code, generated.locations, preparedEndpoints.endpointNamesByPlaceholder);
|
|
2391
2725
|
const endpoints2 = parseApiEndpoints(rtk.code, logger, rtk.locations);
|
|
2392
2726
|
const handlerEndpoints2 = detectResponseHandlerEndpoints(doc, endpoints2, api.responseHandlers);
|
|
@@ -2400,20 +2734,23 @@ async function generateSdk(options = {}) {
|
|
|
2400
2734
|
const withHandlers = injectResponseHandlers(apiSource, handlerEndpoints2);
|
|
2401
2735
|
const finalApiSource2 = multipart.injected.length > 0 ? `${MULTIPART_IMPORT}
|
|
2402
2736
|
${withHandlers}` : withHandlers;
|
|
2403
|
-
return { endpoints: endpoints2, handlerEndpoints: handlerEndpoints2, multipartCount: multipart.injected.length, finalApiSource: finalApiSource2 };
|
|
2737
|
+
return { endpoints: endpoints2, handlerEndpoints: handlerEndpoints2, multipartCount: multipart.injected.length, finalApiSource: finalApiSource2, apiSource };
|
|
2404
2738
|
};
|
|
2405
2739
|
const buildersOfAllOperations = endpointOptions.requestBuilders === "all" && api.config.filterEndpoints !== void 0;
|
|
2406
2740
|
let requestsSourceOfAllOperations = null;
|
|
2741
|
+
let passOfAllOperations = null;
|
|
2407
2742
|
if ((modelOptions.scope === "all" || buildersOfAllOperations) && api.config.filterEndpoints !== void 0) {
|
|
2408
2743
|
const unfiltered = await runPass({ ...api, config: { ...api.config, filterEndpoints: void 0 } }, `${i}-all.json`, !buildersOfAllOperations);
|
|
2409
2744
|
if (buildersOfAllOperations) {
|
|
2745
|
+
passOfAllOperations = unfiltered;
|
|
2410
2746
|
const requestsStem = `${api.stem}Requests`;
|
|
2411
2747
|
requestsSourceOfAllOperations = splitRequestBuilders(unfiltered.finalApiSource, requestsStem, `./${requestsStem}`).requestsSource;
|
|
2412
2748
|
logger.info(" request builders of all operations (endpoints.requestBuilders all)");
|
|
2413
2749
|
}
|
|
2414
2750
|
if (modelOptions.scope === "all") logger.info(" models of all operations written (models.scope all)");
|
|
2415
2751
|
}
|
|
2416
|
-
const
|
|
2752
|
+
const mainPass = await runPass(api, `${i}.json`, false);
|
|
2753
|
+
const { endpoints, handlerEndpoints, multipartCount, finalApiSource } = mainPass;
|
|
2417
2754
|
const fileCount = [...handlerEndpoints.values()].filter((kind) => kind === "blob").length;
|
|
2418
2755
|
if (fileCount > 0) logger.info(` ${fileCount} file download endpoint(s) (blobResponseHandler)`);
|
|
2419
2756
|
if (multipartCount > 0) logger.info(` ${multipartCount} multipart endpoint(s) (multipartFiles)`);
|
|
@@ -2422,11 +2759,30 @@ ${withHandlers}` : withHandlers;
|
|
|
2422
2759
|
const requestsStem = `${api.stem}Requests`;
|
|
2423
2760
|
const split = splitRequestBuilders(finalApiSource, requestsStem, esm ? `./${requestsStem}.js` : `./${requestsStem}`);
|
|
2424
2761
|
files.set(api.outputFile, split.apiSource);
|
|
2425
|
-
files.set(
|
|
2762
|
+
files.set(path11.join(api.outputDir, `${requestsStem}.ts`), requestsSourceOfAllOperations ?? split.requestsSource);
|
|
2426
2763
|
logger.info(` ${split.count} request builder(s) used by ${api.stem}.ts`);
|
|
2427
2764
|
} else {
|
|
2428
2765
|
files.set(api.outputFile, finalApiSource);
|
|
2429
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
|
+
}
|
|
2430
2786
|
const withExtension = (specifier) => esm ? `${specifier}.js` : specifier;
|
|
2431
2787
|
const enhanced = buildEnhancedEndpoints({
|
|
2432
2788
|
stem: api.stem,
|
|
@@ -2442,8 +2798,8 @@ ${withHandlers}` : withHandlers;
|
|
|
2442
2798
|
invalidation: api.invalidation,
|
|
2443
2799
|
logger
|
|
2444
2800
|
});
|
|
2445
|
-
files.set(
|
|
2446
|
-
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));
|
|
2447
2803
|
}
|
|
2448
2804
|
} finally {
|
|
2449
2805
|
fs9.rmSync(specDir, { recursive: true, force: true });
|
|
@@ -2457,7 +2813,7 @@ ${withHandlers}` : withHandlers;
|
|
|
2457
2813
|
if (!options.skipTsc) {
|
|
2458
2814
|
logger.info("type check (tsc --noEmit)");
|
|
2459
2815
|
try {
|
|
2460
|
-
typechecked = typecheck(loaded.rootDir,
|
|
2816
|
+
typechecked = typecheck(loaded.rootDir, path11.resolve(loaded.rootDir, loaded.config.tsconfig ?? "tsconfig.json"), logger);
|
|
2461
2817
|
} catch (error) {
|
|
2462
2818
|
committed.rollback();
|
|
2463
2819
|
logger.error("type check failed \u2014 previous output restored");
|
|
@@ -2474,7 +2830,7 @@ import { spawnSync } from "child_process";
|
|
|
2474
2830
|
import { createHash } from "crypto";
|
|
2475
2831
|
import * as fs10 from "fs";
|
|
2476
2832
|
import * as os3 from "os";
|
|
2477
|
-
import * as
|
|
2833
|
+
import * as path12 from "path";
|
|
2478
2834
|
var PRIMARY_SKILLS_DIRECTORY = ".claude/skills";
|
|
2479
2835
|
var MIRROR_SKILLS_DIRECTORIES = [".agents/skills", ".codex/skills"];
|
|
2480
2836
|
var SKILLS_MANIFEST_FILE_NAME = ".ddd-skills.json";
|
|
@@ -2498,14 +2854,14 @@ var prefixedConsoleLogger = {
|
|
|
2498
2854
|
};
|
|
2499
2855
|
var label = (text) => text.padEnd(13);
|
|
2500
2856
|
function findSkillsRepositoryRoot(startDirectory) {
|
|
2501
|
-
const start = realpathOr(
|
|
2857
|
+
const start = realpathOr(path12.resolve(startDirectory));
|
|
2502
2858
|
const home = realpathOr(os3.homedir());
|
|
2503
2859
|
for (const marker of [".git", ".claude"]) {
|
|
2504
2860
|
let directory = start;
|
|
2505
2861
|
for (; ; ) {
|
|
2506
2862
|
const isHomeClaude = marker === ".claude" && directory === home;
|
|
2507
|
-
if (!isHomeClaude && lstatOrNull(
|
|
2508
|
-
const parent =
|
|
2863
|
+
if (!isHomeClaude && lstatOrNull(path12.join(directory, marker))) return directory;
|
|
2864
|
+
const parent = path12.dirname(directory);
|
|
2509
2865
|
if (parent === directory) break;
|
|
2510
2866
|
directory = parent;
|
|
2511
2867
|
}
|
|
@@ -2514,9 +2870,9 @@ function findSkillsRepositoryRoot(startDirectory) {
|
|
|
2514
2870
|
}
|
|
2515
2871
|
function runSkillLinks(options = {}) {
|
|
2516
2872
|
const logger = options.logger ?? prefixedConsoleLogger;
|
|
2517
|
-
const cwd =
|
|
2873
|
+
const cwd = path12.resolve(options.cwd ?? process.cwd());
|
|
2518
2874
|
const envRoot = process.env[SKILLS_ROOT_ENV];
|
|
2519
|
-
const requestedRoot = options.root ?
|
|
2875
|
+
const requestedRoot = options.root ? path12.resolve(cwd, options.root) : envRoot ? path12.resolve(cwd, envRoot) : findSkillsRepositoryRoot(cwd);
|
|
2520
2876
|
const linker = new SkillLinker(requestedRoot, options, logger);
|
|
2521
2877
|
return linker.run();
|
|
2522
2878
|
}
|
|
@@ -2688,7 +3044,7 @@ var SkillLinker = class {
|
|
|
2688
3044
|
const mirrorLogical = `${this.root}/${mirrorName}`;
|
|
2689
3045
|
if (getEntryType(mirrorLogical) === "missing" || !isDirectory(mirrorLogical)) continue;
|
|
2690
3046
|
const mirror = realpathOr(mirrorLogical);
|
|
2691
|
-
const mirrorParent = realpathOr(
|
|
3047
|
+
const mirrorParent = realpathOr(path12.dirname(mirrorLogical));
|
|
2692
3048
|
if (mirror === primary || mirrorParent === primary) continue;
|
|
2693
3049
|
mirrorGitignoreNames.set(mirror, []);
|
|
2694
3050
|
for (const skillName of managedNames) {
|
|
@@ -2731,17 +3087,17 @@ var SkillLinker = class {
|
|
|
2731
3087
|
}
|
|
2732
3088
|
}
|
|
2733
3089
|
}
|
|
2734
|
-
const
|
|
3090
|
+
const manifestPath2 = `${primary}/${SKILLS_MANIFEST_FILE_NAME}`;
|
|
2735
3091
|
const manifestContent = encodeManifest(managedNames, managed);
|
|
2736
|
-
if ((isFile(
|
|
2737
|
-
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}` });
|
|
2738
3094
|
}
|
|
2739
3095
|
const primaryGitignoreEntries = [`/${SKILLS_MANIFEST_FILE_NAME}`];
|
|
2740
3096
|
for (const skillName of managedNames) {
|
|
2741
3097
|
primaryGitignoreEntries.push(`/${skillName}`);
|
|
2742
3098
|
gitPaths.push(`${primary}/${skillName}`);
|
|
2743
3099
|
}
|
|
2744
|
-
gitPaths.push(
|
|
3100
|
+
gitPaths.push(manifestPath2);
|
|
2745
3101
|
const gitignoreTargets = /* @__PURE__ */ new Map([[primary, primaryGitignoreEntries]]);
|
|
2746
3102
|
for (const [mirror, names] of mirrorGitignoreNames) {
|
|
2747
3103
|
gitignoreTargets.set(mirror, [...names].sort(compareBytes).map((name) => `/${name}`));
|
|
@@ -2800,8 +3156,8 @@ var SkillLinker = class {
|
|
|
2800
3156
|
return { winners, warnings };
|
|
2801
3157
|
}
|
|
2802
3158
|
legacySourcePackage(sourceDir) {
|
|
2803
|
-
const skillsDirectory =
|
|
2804
|
-
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"));
|
|
2805
3161
|
return {
|
|
2806
3162
|
package: typeof packageJson?.name === "string" ? packageJson.name : "@mgamadeus/ddd-web",
|
|
2807
3163
|
version: typeof packageJson?.version === "string" ? packageJson.version : null,
|
|
@@ -2889,9 +3245,9 @@ var SkillLinker = class {
|
|
|
2889
3245
|
this.logger[level](line);
|
|
2890
3246
|
}
|
|
2891
3247
|
};
|
|
2892
|
-
function readManifestEntries(
|
|
2893
|
-
if (!isFile(
|
|
2894
|
-
const manifest = readJson(
|
|
3248
|
+
function readManifestEntries(manifestPath2) {
|
|
3249
|
+
if (!isFile(manifestPath2)) return {};
|
|
3250
|
+
const manifest = readJson(manifestPath2);
|
|
2895
3251
|
if (!manifest || typeof manifest.skills !== "object" || manifest.skills === null || Array.isArray(manifest.skills)) return null;
|
|
2896
3252
|
return manifest.skills;
|
|
2897
3253
|
}
|
|
@@ -3001,10 +3357,10 @@ function isDddVendorPath(candidate) {
|
|
|
3001
3357
|
return withSlash.includes("/vendor/mgamadeus/") || withSlash.includes("/node_modules/@mgamadeus/");
|
|
3002
3358
|
}
|
|
3003
3359
|
function resolveLinkTarget(linkDirectory, target) {
|
|
3004
|
-
return
|
|
3360
|
+
return path12.posix.resolve(linkDirectory, target);
|
|
3005
3361
|
}
|
|
3006
3362
|
function relativePath(fromDirectory, toPath) {
|
|
3007
|
-
return
|
|
3363
|
+
return path12.posix.relative(fromDirectory, toPath) || ".";
|
|
3008
3364
|
}
|
|
3009
3365
|
function quoteShellArgument(argument) {
|
|
3010
3366
|
return /^[A-Za-z0-9._/@+=:-]+$/.test(argument) ? argument : `'${argument.replace(/'/g, "'\\''")}'`;
|
|
@@ -3027,4 +3383,4 @@ export {
|
|
|
3027
3383
|
runSkillLinks,
|
|
3028
3384
|
linkSkills
|
|
3029
3385
|
};
|
|
3030
|
-
//# sourceMappingURL=chunk-
|
|
3386
|
+
//# sourceMappingURL=chunk-HZ4VYIHY.js.map
|