Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 77 additions & 24 deletions generate_models.sh
Original file line number Diff line number Diff line change
@@ -1,29 +1,82 @@
#!/bin/bash

if [[ -z "$1" ]]; then
echo "Error: spec directory path is required."
echo "Usage: $0 <spec_dir>"
echo "Example: npm run generate -- /path/to/spec"
set -euo pipefail

if [[ -z "${1:-}" ]]; then
echo "Error: schema directory path is required."
echo "Usage: $0 <spec_dir_or_ucp_repo_root>"
echo "Examples:"
echo " npm run generate -- /path/to/legacy-ucp/spec"
echo " npm run generate -- /path/to/legacy-ucp"
exit 1
fi

INPUT_DIR="${1%/}"

if [[ -d "$INPUT_DIR/schemas/shopping" ]]; then
SPEC_DIR="$INPUT_DIR"
SCHEMA_LAYOUT="legacy"
elif [[ -d "$INPUT_DIR/spec/schemas/shopping" ]]; then
SPEC_DIR="$INPUT_DIR/spec"
SCHEMA_LAYOUT="legacy"
elif [[ -d "$INPUT_DIR/source/schemas/shopping" ]]; then
SPEC_DIR="$INPUT_DIR/source"
SCHEMA_LAYOUT="source"
else
echo "Error: could not find a supported UCP schema directory."
echo "Expected one of:"
echo " <input>/schemas/shopping"
echo " <input>/spec/schemas/shopping"
echo " <input>/source/schemas/shopping"
exit 1
fi

SPEC_DIR="${1%/}"

quicktype \
--lang typescript-zod \
--src-lang schema \
--src "$SPEC_DIR"/discovery/*.json \
--src "$SPEC_DIR"/schemas/shopping/*.json \
--src "$SPEC_DIR"/schemas/shopping/types/*.json \
--src "$SPEC_DIR/schemas/shopping/ap2_mandate.json#/\$defs/complete_request_with_ap2" \
--src "$SPEC_DIR/schemas/shopping/ap2_mandate.json#/\$defs/checkout_response_with_ap2" \
--src "$SPEC_DIR/schemas/shopping/buyer_consent.create_req.json#/\$defs/checkout" \
--src "$SPEC_DIR/schemas/shopping/buyer_consent.update_req.json#/\$defs/checkout" \
--src "$SPEC_DIR/schemas/shopping/buyer_consent_resp.json#/\$defs/checkout" \
--src "$SPEC_DIR/schemas/shopping/discount.create_req.json#/\$defs/checkout" \
--src "$SPEC_DIR/schemas/shopping/discount.update_req.json#/\$defs/checkout" \
--src "$SPEC_DIR/schemas/shopping/discount_resp.json#/\$defs/checkout" \
--src "$SPEC_DIR/schemas/shopping/fulfillment.create_req.json#/\$defs/checkout" \
--src "$SPEC_DIR/schemas/shopping/fulfillment.update_req.json#/\$defs/checkout" \
--src "$SPEC_DIR/schemas/shopping/fulfillment_resp.json#/\$defs/checkout" \
-o src/spec_generated.ts
TMP_OUTPUT="$(mktemp "${TMPDIR:-/tmp}/ucp-spec-generated.XXXXXX.ts")"
PROJECTED_SPEC_DIR=""
cleanup() {
rm -f "$TMP_OUTPUT"
if [[ -n "$PROJECTED_SPEC_DIR" ]]; then
rm -rf "$PROJECTED_SPEC_DIR"
fi
}
trap cleanup EXIT

if [[ "$SCHEMA_LAYOUT" == "source" ]]; then
PROJECTED_SPEC_DIR="$(mktemp -d "${TMPDIR:-/tmp}/ucp-js-sdk-projected.XXXXXX")"
node scripts/project-current-ucp-schemas.mjs "$SPEC_DIR" "$PROJECTED_SPEC_DIR"
SPEC_DIR="$PROJECTED_SPEC_DIR"
fi

QUICKTYPE_ARGS=(
--lang typescript-zod
--src-lang schema
--src "$SPEC_DIR"/discovery/*.json
--src "$SPEC_DIR/schemas/shopping/checkout.create_req.json"
--src "$SPEC_DIR/schemas/shopping/checkout.update_req.json"
--src "$SPEC_DIR/schemas/shopping/checkout_resp.json"
--src "$SPEC_DIR/schemas/shopping/order.json"
--src "$SPEC_DIR/schemas/shopping/payment.create_req.json"
--src "$SPEC_DIR/schemas/shopping/payment.update_req.json"
--src "$SPEC_DIR/schemas/shopping/payment_data.json"
--src "$SPEC_DIR/schemas/shopping/payment_resp.json"
--src "$SPEC_DIR/schemas/shopping/ap2_mandate.json#/\$defs/complete_request_with_ap2"
--src "$SPEC_DIR/schemas/shopping/ap2_mandate.json#/\$defs/checkout_response_with_ap2"
--src "$SPEC_DIR/schemas/shopping/buyer_consent.create_req.json#/\$defs/checkout"
--src "$SPEC_DIR/schemas/shopping/buyer_consent.update_req.json#/\$defs/checkout"
--src "$SPEC_DIR/schemas/shopping/buyer_consent_resp.json#/\$defs/checkout"
--src "$SPEC_DIR/schemas/shopping/discount.create_req.json#/\$defs/checkout"
--src "$SPEC_DIR/schemas/shopping/discount.update_req.json#/\$defs/checkout"
--src "$SPEC_DIR/schemas/shopping/discount_resp.json#/\$defs/checkout"
--src "$SPEC_DIR/schemas/shopping/fulfillment.create_req.json#/\$defs/checkout"
--src "$SPEC_DIR/schemas/shopping/fulfillment.update_req.json#/\$defs/checkout"
--src "$SPEC_DIR/schemas/shopping/fulfillment_resp.json#/\$defs/checkout"
-o "$TMP_OUTPUT"
)

if [[ "$SCHEMA_LAYOUT" == "legacy" ]]; then
QUICKTYPE_ARGS+=(--src "$SPEC_DIR"/schemas/shopping/types/*.json)
fi

npx quicktype "${QUICKTYPE_ARGS[@]}"

node scripts/normalize-generated-schemas.mjs "$TMP_OUTPUT" src/spec_generated.ts
189 changes: 189 additions & 0 deletions scripts/normalize-generated-schemas.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import fs from "node:fs";
import path from "node:path";
import ts from "typescript";

const [, , inputPath, outputPath] = process.argv;

if (!inputPath || !outputPath) {
console.error(
"Usage: node scripts/normalize-generated-schemas.mjs <input.ts> <output.ts>"
);
process.exit(1);
}

const sourcePath = path.resolve(inputPath);
const destinationPath = path.resolve(outputPath);
const sourceText = fs.readFileSync(sourcePath, "utf8");
const sourceFile = ts.createSourceFile(
sourcePath,
sourceText,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS
);

const canonicalNames = new Map([
["AdjustmentLineItem", "LineItemQuantityRef"],
["AdjustmentLineItemClass", "LineItemQuantityRef"],
["AllocationClass", "Allocation"],
["AllocationElement", "Allocation"],
["AppliedAllocation", "Allocation"],
["BillingAddressClass", "PostalAddress"],
["BuyerClass", "Buyer"],
["CardPaymentInstrument", "PaymentInstrument"],
["CheckoutUpdateRequestPayment", "PaymentSelection"],
["EventLineItem", "LineItemQuantityRef"],
["ExpectationLineItem", "LineItemQuantityRef"],
["ExpectationLineItemClass", "LineItemQuantityRef"],
["FluffyConsent", "Consent"],
["FulfillmentDestinationRequestElement", "FulfillmentDestinationRequest"],
["FulfillmentEventLineItem", "LineItemQuantityRef"],
["GroupClass", "FulfillmentGroupUpdateRequest"],
["GroupElement", "FulfillmentGroupCreateRequest"],
["IdentityClass", "PaymentIdentity"],
["ItemClass", "ItemReference"],
["ItemCreateRequest", "ItemReference"],
["ItemUpdateRequest", "ItemReference"],
["LineItemClass", "LineItemUpdateRequest"],
["LineItemElement", "LineItemCreateRequest"],
["LineItemItem", "ItemReference"],
["LinkElement", "Link"],
["Mcp", "SchemaEndpoint"],
["MessageElement", "Message"],
["MethodElement", "FulfillmentMethodCreateRequest"],
["OrderClass", "OrderConfirmation"],
["OrderLineItemQuantity", "LineItemQuantity"],
["PaymentClass", "PaymentSelection"],
["PaymentCreateRequest", "PaymentSelection"],
["PaymentUpdateRequest", "PaymentSelection"],
["PurpleConsent", "Consent"],
["Rest", "SchemaEndpoint"],
["TentacledConsent", "Consent"],
["TokenCredentialCreateRequest", "TokenCredentialRequest"],
["TokenCredentialUpdateRequest", "TokenCredentialRequest"],
["UcpCheckoutResponse", "UcpResponse"],
["UcpOrderResponse", "UcpResponse"],
]);

function normalizeSchemaText(text) {
return text.replace(/\s+/g, " ").trim();
}

function aliasBlock(aliasName, canonicalName) {
return `export const ${aliasName}Schema = ${canonicalName}Schema;\nexport type ${aliasName} = ${canonicalName};`;
}

const schemaBlocks = new Map();

for (let index = 0; index < sourceFile.statements.length; index += 1) {
const statement = sourceFile.statements[index];
if (!ts.isVariableStatement(statement)) {
continue;
}

const declaration = statement.declarationList.declarations[0];
if (
!declaration ||
!ts.isIdentifier(declaration.name) ||
!declaration.initializer ||
!declaration.name.text.endsWith("Schema")
) {
continue;
}

const schemaName = declaration.name.text.slice(0, -6);
const nextStatement = sourceFile.statements[index + 1];

if (
!nextStatement ||
!ts.isTypeAliasDeclaration(nextStatement) ||
nextStatement.name.text !== schemaName
) {
continue;
}

schemaBlocks.set(schemaName, {
schemaName,
start: statement.getStart(sourceFile),
end: nextStatement.end,
initializerText: declaration.initializer.getText(sourceFile),
normalizedInitializer: normalizeSchemaText(
declaration.initializer.getText(sourceFile)
),
});
}

const duplicateGroups = new Map();
for (const block of schemaBlocks.values()) {
const group = duplicateGroups.get(block.normalizedInitializer) ?? [];
group.push(block.schemaName);
duplicateGroups.set(block.normalizedInitializer, group);
}

const replacements = [];

for (const [normalizedInitializer, names] of duplicateGroups.entries()) {
if (names.length === 1) {
continue;
}

const canonicalName =
names.map((name) => canonicalNames.get(name)).find(Boolean) ?? names[0];
const keepName = names
.map((name) => schemaBlocks.get(name))
.filter(Boolean)
.sort((left, right) => left.start - right.start)[0]?.schemaName;
const keepBlock = schemaBlocks.get(keepName);

if (!keepBlock) {
continue;
}

const aliases = new Set(names.filter((name) => name !== canonicalName));
if (keepName !== canonicalName) {
aliases.add(keepName);
}

const canonicalBlock = [
`export const ${canonicalName}Schema = ${keepBlock.initializerText};`,
`export type ${canonicalName} = z.infer<typeof ${canonicalName}Schema>;`,
...Array.from(aliases)
.sort((left, right) => left.localeCompare(right))
.map((name) => aliasBlock(name, canonicalName)),
].join("\n");

replacements.push({
start: keepBlock.start,
end: keepBlock.end,
text: `${canonicalBlock}\n`,
});

for (const name of names) {
if (name === keepName) {
continue;
}

const block = schemaBlocks.get(name);
if (!block) {
continue;
}

replacements.push({
start: block.start,
end: block.end,
text: "",
});
}
}

replacements.sort((left, right) => right.start - left.start);

let outputText = sourceText;
for (const replacement of replacements) {
outputText =
outputText.slice(0, replacement.start) +
replacement.text +
outputText.slice(replacement.end);
}

fs.writeFileSync(destinationPath, outputText);
Loading