Best JavaScript code snippet using ts-auto-mock
index.ts
Source:index.ts
...57 factory.createIdentifier(`${endpoint.pathName}HandleQueryType`),58 undefined,59 factory.createTypeLiteralNode(60 [61 factory.createPropertySignature(62 undefined,63 factory.createIdentifier("body"),64 undefined,65 factory.createTypeReferenceNode(66 factory.createIdentifier(`${endpoint.pathName}Body`),67 undefined68 )69 ),70 factory.createPropertySignature(71 undefined,72 factory.createIdentifier("query"),73 undefined,74 factory.createTypeReferenceNode(75 factory.createIdentifier(`${endpoint.pathName}Query`),76 undefined77 )78 )79 ]80 )81 )]82}83export function processParametersAndRequestBody(parameters: Parameters[] | undefined, endpoint: Endpoint, property: SchemaProperty | undefined): Statement[] {84 if (parameters === void 0) {85 // if endpoint does not accept any parameters86 parameters = []87 }88 return [89 ...createZodSchemaAndType({90 parameters: parameters.filter(param => param.in === "query"),91 endpoint: endpoint,92 type: 'Query'93 }),94 ...createZodSchemaAndType({95 property: property,96 endpoint: endpoint,97 type: 'Body'98 }),99 ...createHandlePropsType({100 endpoint: endpoint101 })102 ]103}104export function createExportClassStatement(endpoints: Endpoint[]) {105 return factory.createVariableStatement(106 [factory.createModifier(ts.SyntaxKind.ExportKeyword)],107 factory.createVariableDeclarationList(108 [factory.createVariableDeclaration(109 factory.createIdentifier("endpoints"),110 undefined,111 undefined,112 factory.createObjectLiteralExpression(113 endpoints.map(endpoint => {114 return (factory.createPropertyAssignment(115 factory.createIdentifier(endpoint.operationId),116 factory.createNewExpression(117 factory.createIdentifier(endpoint.pathName),118 undefined,119 []120 )121 ))122 }),123 true124 )125 )],126 ts.NodeFlags.Const127 )128 );129}130export function createImportStatement() {131 return [factory.createImportDeclaration(132 undefined,133 undefined,134 factory.createImportClause(135 false,136 undefined,137 factory.createNamedImports([138 factory.createImportSpecifier(139 false,140 undefined,141 factory.createIdentifier("method")142 ),143 factory.createImportSpecifier(144 false,145 undefined,146 factory.createIdentifier("__handle")147 ),148 factory.createImportSpecifier(149 false,150 undefined,151 factory.createIdentifier("SchemaType")152 )153 ])154 ),155 factory.createStringLiteral("./index"),156 undefined157 ),158 factory.createImportDeclaration(159 undefined,160 undefined,161 factory.createImportClause(162 false,163 undefined,164 factory.createNamedImports([factory.createImportSpecifier(165 false,166 undefined,167 factory.createIdentifier("z")168 )])169 ),170 factory.createStringLiteral("zod"),171 undefined172 )173 ]174}175export function convertASTtoCode(astList: ts.Node[]): string[] {176 return astList.map(ast => {177 return printer.printNode(ts.EmitHint.Unspecified, ast, source)178 })179}180export function createResType(endpoint: Endpoint) {181 type resData = {182 statusCode: string,183 responseType: string,184 schema: ResSchema185 }186 const typeDataList: resData[] = []187 Object.keys(endpoint.responses).forEach(statusCode => {188 const response = endpoint.responses[statusCode]189 Object.keys(response.content).forEach(responseType => {190 const content = response.content[responseType]191 typeDataList.push({192 schema: content.schema,193 statusCode,194 responseType195 })196 })197 })198 function getMembers(typeData: resData): TypeNode {199 if (typeData.schema.type === 'object') {200 const properties = typeData.schema.properties201 return factory.createTypeLiteralNode(202 Object.keys(properties).map(key => {203 const property = properties[key]204 return convertResPropertyToAstTypeNode(property, key)205 })206 )207 } else {208 switch (typeData.schema.type) {209 case "string":210 return factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)211 case "boolean":212 return factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword)213 case "array":214 return factory.createArrayTypeNode(factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword))215 case "file":216 return factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)217 case "number":218 return factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword)219 case "integer":220 return factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword)221 }222 }223 }224 return factory.createTypeAliasDeclaration(225 undefined,226 undefined,227 factory.createIdentifier(`${endpoint.pathName}Res`),228 undefined,229 factory.createUnionTypeNode(230 typeDataList.map(typeData => factory.createTypeLiteralNode(231 [232 factory.createPropertySignature(233 undefined,234 factory.createStringLiteral("statusCode"),235 undefined,236 factory.createLiteralTypeNode(factory.createStringLiteral(typeData.statusCode))237 ),238 factory.createPropertySignature(239 undefined,240 factory.createStringLiteral("responseType"),241 undefined,242 factory.createLiteralTypeNode(factory.createStringLiteral(typeData.responseType))243 ),244 factory.createPropertySignature(245 undefined,246 factory.createStringLiteral("data"),247 undefined,248 getMembers(typeData)249 )250 ]251 ))252 )253 )254}255export function createClass(endpoint: Endpoint) {256 return factory.createClassDeclaration(257 undefined,258 [factory.createModifier(ts.SyntaxKind.ExportKeyword)],259 factory.createIdentifier(endpoint.pathName),260 undefined,261 undefined,262 [263 factory.createPropertyDeclaration(264 undefined,265 undefined,266 factory.createIdentifier("path"),267 undefined,268 factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),269 undefined270 ),271 factory.createPropertyDeclaration(272 undefined,273 undefined,274 factory.createIdentifier("method"),275 undefined,276 factory.createTypeReferenceNode(277 factory.createIdentifier("method"),278 undefined279 ),280 undefined281 ), factory.createPropertyDeclaration(282 undefined,283 undefined,284 factory.createIdentifier("parseRequiredQueryList"),285 undefined,286 factory.createArrayTypeNode(factory.createTypeLiteralNode([287 factory.createPropertySignature(288 undefined,289 factory.createIdentifier("key"),290 undefined,291 factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)292 ),293 factory.createPropertySignature(294 undefined,295 factory.createIdentifier("type"),296 undefined,297 factory.createTypeReferenceNode(298 factory.createIdentifier("Exclude"),299 [300 factory.createTypeReferenceNode(301 factory.createIdentifier("SchemaType"),302 undefined303 ),304 factory.createLiteralTypeNode(factory.createStringLiteral("file"))305 ]306 )307 )308 ]))309 ,310 undefined311 ),312 factory.createConstructorDeclaration(313 undefined,314 undefined,315 [],316 factory.createBlock(317 [318 factory.createExpressionStatement(factory.createBinaryExpression(319 factory.createPropertyAccessExpression(320 factory.createThis(),321 factory.createIdentifier("path")322 ),323 factory.createToken(ts.SyntaxKind.EqualsToken),324 factory.createStringLiteral(endpoint.path)325 )),326 factory.createExpressionStatement(factory.createBinaryExpression(327 factory.createPropertyAccessExpression(328 factory.createThis(),329 factory.createIdentifier("method")330 ),331 factory.createToken(ts.SyntaxKind.EqualsToken),332 factory.createStringLiteral(endpoint.method)333 )),334 factory.createExpressionStatement(factory.createBinaryExpression(335 factory.createPropertyAccessExpression(336 factory.createThis(),337 factory.createIdentifier("parseRequiredQueryList")338 ),339 factory.createToken(ts.SyntaxKind.EqualsToken),340 factory.createArrayLiteralExpression(341 [342 ...endpoint.parameters343 .filter(param => [344 'array', 'boolean', 'integer', 'number', 'object'345 ].includes(param.schema.type))346 .map(param => factory.createObjectLiteralExpression(347 [348 factory.createPropertyAssignment(349 factory.createIdentifier("key"),350 factory.createStringLiteral(param.name)351 ),352 factory.createPropertyAssignment(353 factory.createIdentifier("type"),354 factory.createStringLiteral(param.schema.type)355 )356 ],357 true358 )),359 ],360 false361 )362 ))363 ],364 true365 )366 ),367 factory.createMethodDeclaration(368 undefined,369 undefined,370 undefined,371 factory.createIdentifier("handle"),372 undefined,373 undefined,374 [factory.createParameterDeclaration(375 undefined,376 undefined,377 undefined,378 factory.createObjectBindingPattern([379 factory.createBindingElement(380 undefined,381 undefined,382 factory.createIdentifier("cb"),383 undefined384 ),385 factory.createBindingElement(386 undefined,387 undefined,388 factory.createIdentifier("onValidationFailure"),389 undefined390 )391 ]),392 undefined,393 factory.createTypeLiteralNode([394 factory.createPropertySignature(395 undefined,396 factory.createIdentifier("cb"),397 undefined,398 factory.createFunctionTypeNode(399 undefined,400 [factory.createParameterDeclaration(401 undefined,402 undefined,403 undefined,404 factory.createIdentifier("data"),405 undefined,406 factory.createTypeReferenceNode(407 factory.createIdentifier(`${endpoint.pathName}HandleQueryType`),408 undefined409 ),410 undefined411 )],412 factory.createTypeReferenceNode(413 factory.createIdentifier("Promise"),414 [factory.createTypeReferenceNode(415 factory.createIdentifier(`${endpoint.pathName}Res`),416 undefined417 )]418 )419 )420 ),421 factory.createPropertySignature(422 undefined,423 factory.createIdentifier("onValidationFailure"),424 factory.createToken(ts.SyntaxKind.QuestionToken),425 factory.createFunctionTypeNode(426 undefined,427 [factory.createParameterDeclaration(428 undefined,429 undefined,430 undefined,431 factory.createIdentifier("res"),432 undefined,433 factory.createTypeReferenceNode(434 factory.createQualifiedName(435 factory.createIdentifier("Express"),436 factory.createIdentifier("Response")437 ),438 undefined439 ),440 undefined441 )],442 factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword)443 )444 )445 ]),446 undefined447 )],448 undefined,449 factory.createBlock(450 [factory.createExpressionStatement(factory.createCallExpression(451 factory.createIdentifier("__handle"),452 [453 factory.createTypeReferenceNode(454 factory.createIdentifier(`${endpoint.pathName}Body`),455 undefined456 ),457 factory.createTypeReferenceNode(458 factory.createIdentifier(`${endpoint.pathName}Query`),459 undefined460 ),461 factory.createTypeReferenceNode(462 factory.createIdentifier(`${endpoint.pathName}Res`),463 undefined464 )465 ],466 [467 factory.createObjectLiteralExpression(468 [469 factory.createPropertyAssignment(470 factory.createIdentifier("path"),471 factory.createPropertyAccessExpression(472 factory.createThis(),473 factory.createIdentifier("path")474 )475 ),476 factory.createPropertyAssignment(477 factory.createIdentifier("method"),478 factory.createPropertyAccessExpression(479 factory.createThis(),480 factory.createIdentifier("method")481 )482 ),483 factory.createPropertyAssignment(484 factory.createIdentifier("handleMethod"),485 factory.createArrowFunction(486 [factory.createModifier(ts.SyntaxKind.AsyncKeyword)],487 undefined,488 [489 factory.createParameterDeclaration(490 undefined,491 undefined,492 undefined,493 factory.createIdentifier("body"),494 undefined,495 undefined,496 undefined497 ),498 factory.createParameterDeclaration(499 undefined,500 undefined,501 undefined,502 factory.createIdentifier("query"),503 undefined,504 undefined,505 undefined506 )507 ],508 undefined,509 factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken),510 factory.createBlock(511 [factory.createReturnStatement(factory.createCallExpression(512 factory.createIdentifier("cb"),513 undefined,514 [factory.createObjectLiteralExpression(515 [516 factory.createShorthandPropertyAssignment(517 factory.createIdentifier("body"),518 undefined519 ),520 factory.createShorthandPropertyAssignment(521 factory.createIdentifier("query"),522 undefined523 )524 ],525 false526 )]527 ))],528 true529 )530 )531 ),532 factory.createPropertyAssignment(533 factory.createIdentifier("zodBodySchema"),534 factory.createIdentifier(`${endpoint.pathName}BodySchema`)535 ),536 factory.createPropertyAssignment(537 factory.createIdentifier("zodQuerySchema"),538 factory.createIdentifier(`${endpoint.pathName}QuerySchema`)539 ),540 factory.createPropertyAssignment(541 factory.createIdentifier("onValidationFailure"),542 factory.createIdentifier("onValidationFailure")543 ),544 factory.createPropertyAssignment(545 factory.createIdentifier("parseRequiredQueryList"),546 factory.createPropertyAccessExpression(547 factory.createThis(),548 factory.createIdentifier("parseRequiredQueryList")549 )550 )551 ],552 true553 )554 ]555 ))],556 true557 )558 )559 ]560 )561 ;562}563type PropsOfCreateZodSchemaAndType = {564 parameters: Parameters[],565 endpoint: Endpoint,566 type: "Query"567} | {568 endpoint: Endpoint569 property?: SchemaProperty570 type: "Body"571}572export function propsToZodElement(props: PropsOfCreateZodSchemaAndType) {573 if (props.type === 'Query') {574 const {parameters, endpoint, type} = props575 function getMembers() {576 return parameters.map(param => {577 return factory.createPropertyAssignment(578 factory.createIdentifier(param.name),579 convertSchemaToZodSchemaElement(param.schema),580 )581 })582 }583 function getObject() {584 return factory.createCallExpression(585 factory.createPropertyAccessExpression(586 factory.createIdentifier("z"),587 factory.createIdentifier("object")588 ),589 undefined,590 [factory.createObjectLiteralExpression(591 getMembers(),592 true593 )]594 )595 }596 return factory.createVariableStatement(597 undefined,598 factory.createVariableDeclarationList(599 [factory.createVariableDeclaration(600 factory.createIdentifier(`${endpoint.pathName}${type}Schema`),601 undefined,602 undefined,603 getObject()604 )],605 ts.NodeFlags.Const606 )607 )608 } else {609 const {property, endpoint, type} = props610 function getInitializer() {611 if (property === void 0) {612 return factory.createCallExpression(613 factory.createPropertyAccessExpression(614 factory.createIdentifier("z"),615 factory.createIdentifier("object")616 ),617 undefined,618 [factory.createObjectLiteralExpression()]619 )620 }621 return convertSchemaToZodSchemaElement(property)622 }623 return factory.createVariableStatement(624 undefined,625 factory.createVariableDeclarationList(626 [factory.createVariableDeclaration(627 factory.createIdentifier(`${endpoint.pathName}${type}Schema`),628 undefined,629 undefined,630 getInitializer()631 )],632 ts.NodeFlags.Const633 )634 )635 }636}637export function createZodSchemaAndType(props: PropsOfCreateZodSchemaAndType) {638 return [639 propsToZodElement(props),640 factory.createTypeAliasDeclaration(641 undefined,642 [factory.createModifier(ts.SyntaxKind.ExportKeyword)],643 factory.createIdentifier(`${props.endpoint.pathName}${props.type}`),644 undefined,645 factory.createTypeReferenceNode(646 factory.createQualifiedName(647 factory.createIdentifier("z"),648 factory.createIdentifier("infer")649 ),650 [factory.createTypeQueryNode(factory.createIdentifier(`${props.endpoint.pathName}${props.type}Schema`))]651 )652 )653 ]654}655export function convertResPropertyToAstTypeNode(property: ResponseSchemaProperty, key: string) {656 if (property.type === 'string') {657 return factory.createPropertySignature(658 undefined,659 factory.createIdentifier(key),660 undefined,661 factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)662 )663 }664 throw 'ERROR'665}666export function convertPropertiesToZodElement(properties: Properties) {667 function getElement(property: SchemaProperty, name: string): PropertyAssignment {668 switch (property.type) {669 case 'object':670 return factory.createPropertyAssignment(671 factory.createIdentifier(name),...
generate.ts
Source:generate.ts
...50];51// https://developer.cybozu.io/hc/ja/articles/20216633052const simpleParameterTypeMappings: Record<string, ts.TypeLiteralNode> = {53 CREATOR: f.createTypeLiteralNode([54 f.createPropertySignature(55 undefined,56 f.createIdentifier("value"),57 undefined,58 f.createTypeLiteralNode([59 f.createPropertySignature(60 undefined,61 f.createIdentifier("code"),62 undefined,63 f.createTypeReferenceNode(f.createIdentifier("string"))64 ),65 ])66 ),67 ]),68 CREATED_TIME: f.createTypeLiteralNode([69 f.createPropertySignature(70 undefined,71 f.createIdentifier("value"),72 undefined,73 f.createTypeReferenceNode(f.createIdentifier("string"))74 ),75 ]),76 MODIFIER: f.createTypeLiteralNode([77 f.createPropertySignature(78 undefined,79 f.createIdentifier("value"),80 undefined,81 f.createTypeLiteralNode([82 f.createPropertySignature(83 undefined,84 f.createIdentifier("code"),85 undefined,86 f.createTypeReferenceNode(f.createIdentifier("string"))87 ),88 ])89 ),90 ]),91 UPDATED_TIME: f.createTypeLiteralNode([92 f.createPropertySignature(93 undefined,94 f.createIdentifier("value"),95 undefined,96 f.createTypeReferenceNode(f.createIdentifier("string"))97 ),98 ]),99 SINGLE_LINE_TEXT: f.createTypeLiteralNode([100 f.createPropertySignature(101 undefined,102 f.createIdentifier("value"),103 undefined,104 f.createTypeReferenceNode(f.createIdentifier("string"))105 ),106 ]),107 MULTI_LINE_TEXT: f.createTypeLiteralNode([108 f.createPropertySignature(109 undefined,110 f.createIdentifier("value"),111 undefined,112 f.createTypeReferenceNode(f.createIdentifier("string"))113 ),114 ]),115 RICH_TEXT: f.createTypeLiteralNode([116 f.createPropertySignature(117 undefined,118 f.createIdentifier("value"),119 undefined,120 f.createTypeReferenceNode(f.createIdentifier("string"))121 ),122 ]),123 NUMBER: f.createTypeLiteralNode([124 f.createPropertySignature(125 undefined,126 f.createIdentifier("value"),127 undefined,128 f.createTypeReferenceNode(f.createIdentifier("string"))129 ),130 ]),131 // CALC type can`t update.132 CHECK_BOX: f.createTypeLiteralNode([133 f.createPropertySignature(134 undefined,135 f.createIdentifier("value"),136 undefined,137 f.createArrayTypeNode(138 f.createTypeReferenceNode(f.createIdentifier("string"))139 )140 ),141 ]),142 RADIO_BUTTON: f.createTypeLiteralNode([143 f.createPropertySignature(144 undefined,145 f.createIdentifier("value"),146 undefined,147 f.createTypeReferenceNode(f.createIdentifier("string"))148 ),149 ]),150 MULTI_SELECT: f.createTypeLiteralNode([151 f.createPropertySignature(152 undefined,153 f.createIdentifier("value"),154 undefined,155 f.createArrayTypeNode(156 f.createTypeReferenceNode(f.createIdentifier("string"))157 )158 ),159 ]),160 DROP_DOWN: f.createTypeLiteralNode([161 f.createPropertySignature(162 undefined,163 f.createIdentifier("value"),164 undefined,165 f.createTypeReferenceNode(f.createIdentifier("string"))166 ),167 ]),168 USER_SELECT: f.createTypeLiteralNode([169 f.createPropertySignature(170 undefined,171 f.createIdentifier("value"),172 undefined,173 f.createArrayTypeNode(174 f.createTypeLiteralNode([175 f.createPropertySignature(176 undefined,177 f.createIdentifier("code"),178 undefined,179 f.createTypeReferenceNode(f.createIdentifier("string"))180 ),181 ])182 )183 ),184 ]),185 ORGANIZATION_SELECT: f.createTypeLiteralNode([186 f.createPropertySignature(187 undefined,188 f.createIdentifier("value"),189 undefined,190 f.createArrayTypeNode(191 f.createTypeLiteralNode([192 f.createPropertySignature(193 undefined,194 f.createIdentifier("code"),195 undefined,196 f.createTypeReferenceNode(f.createIdentifier("string"))197 ),198 ])199 )200 ),201 ]),202 GROUP_SELECT: f.createTypeLiteralNode([203 f.createPropertySignature(204 undefined,205 f.createIdentifier("value"),206 undefined,207 f.createArrayTypeNode(208 f.createTypeLiteralNode([209 f.createPropertySignature(210 undefined,211 f.createIdentifier("code"),212 undefined,213 f.createTypeReferenceNode(f.createIdentifier("string"))214 ),215 ])216 )217 ),218 ]),219 DATE: f.createTypeLiteralNode([220 f.createPropertySignature(221 undefined,222 f.createIdentifier("value"),223 undefined,224 f.createTypeReferenceNode(f.createIdentifier("string"))225 ),226 ]),227 TIME: f.createTypeLiteralNode([228 f.createPropertySignature(229 undefined,230 f.createIdentifier("value"),231 undefined,232 f.createTypeReferenceNode(f.createIdentifier("string"))233 ),234 ]),235 DATETIME: f.createTypeLiteralNode([236 f.createPropertySignature(237 undefined,238 f.createIdentifier("value"),239 undefined,240 f.createTypeReferenceNode(f.createIdentifier("string"))241 ),242 ]),243 LINK: f.createTypeLiteralNode([244 f.createPropertySignature(245 undefined,246 f.createIdentifier("value"),247 undefined,248 f.createTypeReferenceNode(f.createIdentifier("string"))249 ),250 ]),251 FILE: f.createTypeLiteralNode([252 f.createPropertySignature(253 undefined,254 f.createIdentifier("value"),255 undefined,256 f.createArrayTypeNode(257 f.createTypeLiteralNode([258 f.createPropertySignature(259 undefined,260 f.createIdentifier("fileKey"),261 undefined,262 f.createTypeReferenceNode(f.createIdentifier("string"))263 ),264 ])265 )266 ),267 ]),268 // CATEGORY type can`t update.269 // STATUS type can`t update.270 // STATUS_ASSIGNEE type can`t update.271};272export interface GenerateParams {273 appIds?: Array<string>;274}275export const generate = async ({276 params,277 config,278 clientConfig,279}: {280 params: GenerateParams;281 config: Config;282 clientConfig: ClientConfig;283}) => {284 const client = new Client(clientConfig);285 // get app286 cliLogger.info("fetch Kintone app info...");287 const appIds = params.appIds?.filter((appId) => appId) ?? [];288 const apps = await client.getApps({ ids: appIds });289 for (const appId of appIds) {290 if (!apps.find((app) => app.appId === appId)) {291 throw new Error(`not found: appId=${appId}`);292 }293 }294 if (apps.length === 0) {295 throw new Error("There is no apps in your Kintone account.");296 }297 logger.info("appIds:", appIds);298 cliLogger.info(`target app count: ${apps.length}`);299 // generate300 cliLogger.info("generating models...");301 const interfaceNames: Set<string> = new Set();302 const nodes: Array<ts.Node> = [];303 const fieldTypes: Set<string> = new Set();304 const forParameterLaxIdentifier = f.createIdentifier("ForParameterLax");305 // For each application306 for (const { appId, code: appCode, name: appName } of apps) {307 if (config.ignoreAppIds?.includes(appId)) {308 cliLogger.info(309 `ignore: id=${appId}, name=${appName}, code=${appCode || "-"}`310 );311 continue;312 }313 logger.info("appId:", appId);314 cliLogger.info(`app: id=${appId}, name=${appName}, code=${appCode || "-"}`);315 const { properties, revision } = await client.getFormFields({ appId });316 const propertyNames: Set<string> = new Set();317 const propertyElements: Array<ts.TypeElement> = [];318 const parameterPropertyElements: Array<ts.TypeElement> = [];319 // add meta fields320 for (const { propertyName, type } of metaTypes) {321 logger.debug("propertyName:", propertyName);322 fieldTypes.add(type);323 propertyElements.push(324 withJSDocComments(325 f.createPropertySignature(326 undefined,327 f.createStringLiteral(propertyName),328 undefined,329 f.createTypeReferenceNode(type)330 ),331 [type, `@type ${type}`]332 )333 );334 }335 // For each property336 for (const code of Object.keys(properties).sort()) {337 logger.debug("code:", code);338 const field = properties[code];339 const { type, label } = field;340 const propertyName = code;341 if (propertyNames.has(propertyName)) {342 throw new Error(343 `duplicate: appId=${appId}, code=${code}, propertyName=${propertyName}`344 );345 }346 propertyNames.add(propertyName);347 if (type === "SUBTABLE") {348 // For each property in subtable field349 const inSubtablePropertySignatures: Array<ts.PropertySignature> = [];350 const parameterInSubtablePropertySignatures: Array<ts.PropertySignature> =351 [];352 for (const inSubtableCode of Object.keys(field.fields)) {353 logger.debug("inSubtableCode:", inSubtableCode);354 const inSubtableField = field.fields[inSubtableCode];355 const { type: inSubtableType, label: inSubtableLabel } =356 inSubtableField;357 if (simpleTypeMappings[inSubtableType]) {358 fieldTypes.add(simpleTypeMappings[inSubtableType]);359 inSubtablePropertySignatures.push(360 withJSDocComments(361 f.createPropertySignature(362 undefined,363 f.createStringLiteral(inSubtableCode),364 undefined,365 f.createTypeReferenceNode(366 f.createIdentifier(simpleTypeMappings[inSubtableType])367 )368 ),369 [370 inSubtableLabel,371 inSubtableCode,372 inSubtableType,373 `@type ${simpleTypeMappings[inSubtableType]}`,374 ]375 )376 );377 // for parameter378 if (simpleParameterTypeMappings[inSubtableType]) {379 parameterInSubtablePropertySignatures.push(380 withJSDocComments(381 f.createPropertySignature(382 undefined,383 f.createStringLiteral(inSubtableCode),384 f.createToken(ts.SyntaxKind.QuestionToken),385 f.createTypeLiteralNode([386 f.createPropertySignature(387 undefined,388 f.createIdentifier("value"),389 undefined,390 f.createTypeReferenceNode(f.createIdentifier("string"))391 ),392 ])393 ),394 [395 inSubtableLabel,396 inSubtableCode,397 inSubtableType,398 `@type ${simpleTypeMappings[inSubtableType]}`,399 ]400 )401 );402 } else {403 logger.debug(404 `skip parameter: appId=${appId}, code=${code}, inSubtableCode=${inSubtableCode}, inSubtableType=${inSubtableType}`405 );406 }407 } else {408 logger.debug(409 `skip: appId=${appId}, code=${code}, inSubtableCode=${inSubtableCode}, inSubtableType=${inSubtableType}`410 );411 }412 }413 fieldTypes.add(customTypeMappings.SUBTABLE);414 propertyElements.push(415 withJSDocComments(416 f.createPropertySignature(417 undefined,418 f.createStringLiteral(propertyName),419 undefined,420 f.createTypeReferenceNode(customTypeMappings.SUBTABLE, [421 f.createTypeLiteralNode(inSubtablePropertySignatures),422 ])423 ),424 [label, code, `@type ${customTypeMappings.SUBTABLE}`]425 )426 );427 // for Parameter428 parameterPropertyElements.push(429 withJSDocComments(430 f.createPropertySignature(431 undefined,432 f.createStringLiteral(propertyName),433 f.createToken(ts.SyntaxKind.QuestionToken),434 f.createTypeLiteralNode([435 f.createPropertySignature(436 undefined,437 f.createIdentifier("value"),438 undefined,439 f.createArrayTypeNode(440 f.createTypeLiteralNode([441 withJSDocComments(442 f.createPropertySignature(443 undefined,444 f.createIdentifier("id"),445 undefined,446 f.createTypeReferenceNode("string")447 ),448 ["id", "@type string"]449 ),450 f.createPropertySignature(451 undefined,452 f.createIdentifier("value"),453 undefined,454 f.createTypeLiteralNode(455 parameterInSubtablePropertySignatures456 )457 ),458 ])459 )460 ),461 ])462 ),463 [`${label}`, code, type, `@type Object`]464 )465 );466 } else if (simpleTypeMappings[type]) {467 // Simple type468 fieldTypes.add(simpleTypeMappings[type]);469 propertyElements.push(470 withJSDocComments(471 f.createPropertySignature(472 undefined,473 f.createStringLiteral(propertyName),474 undefined,475 f.createTypeReferenceNode(simpleTypeMappings[type])476 ),477 [label, code, type, `@type ${simpleTypeMappings[type]}`]478 )479 );480 // for Parameter481 if (simpleParameterTypeMappings[type]) {482 parameterPropertyElements.push(483 withJSDocComments(484 f.createPropertySignature(485 undefined,486 f.createStringLiteral(propertyName),487 f.createToken(ts.SyntaxKind.QuestionToken),488 simpleParameterTypeMappings[type]489 ),490 [label, code, type, "@type Object"]491 )492 );493 } else {494 logger.debug(495 `skip parameter: appId=${appId}, code=${code}, type=${type}`496 );497 }498 } else {499 logger.debug(`skip: appId=${appId}, code=${code}, type=${type}`);500 }501 }502 const appIdName = `App${appId}`;503 let interfaceName: string;504 if (config.modelNameMapping && config.modelNameMapping[appId]) {505 interfaceName = config.modelNameMapping[appId];506 } else if (config.modelNaming === "appCode") {507 interfaceName = appCode;508 } else {509 interfaceName = appIdName;510 }511 if (config.modelNamePrefix) {512 interfaceName = config.modelNamePrefix + interfaceName;513 }514 if (config.modelNameSuffix) {515 interfaceName = interfaceName + config.modelNameSuffix;516 }517 interfaceName = sanitizeInterfaceName(interfaceName);518 if (interfaceNames.has(interfaceName)) {519 if (config.modelNamingDuplicationStrategy === "skip") {520 cliLogger.warn(521 `duplicate: appId=${appId}, interfaceName=${interfaceName}`522 );523 // to next app524 continue;525 } else if (526 config.modelNamingDuplicationStrategy === "uniquifyWithAppId"527 ) {528 interfaceName = sanitizeInterfaceName(interfaceName + appIdName);529 if (interfaceNames.has(interfaceName)) {530 throw new Error(531 `duplicate: appId=${appId}, interfaceName=${interfaceName}`532 );533 }534 } else {535 throw new Error(536 `duplicate: appId=${appId}, interfaceName=${interfaceName}`537 );538 }539 }540 interfaceNames.add(interfaceName);541 nodes.push(542 withJSDocComments(543 f.createInterfaceDeclaration(544 undefined,545 [f.createToken(ts.SyntaxKind.ExportKeyword)],546 f.createIdentifier(interfaceName),547 undefined,548 [549 f.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [550 f.createExpressionWithTypeArguments(551 f.createIdentifier(kintoneRecordTypeName),552 undefined553 ),554 ]),555 ],556 propertyElements557 ),558 [559 interfaceName,560 appName,561 `id: ${appId}`,562 `revision: ${revision}`,563 appCode && `code: ${appCode}`,564 `@see ${clientConfig.baseUrl}/k/${appId}/`,565 ].filter((c) => c)566 )567 );568 // for parameter569 const typeNameForParameter = `${interfaceName}ForParameter`;570 const interfaceNameForParameterStrict = `${typeNameForParameter}Strict`;571 const interfaceNameForParameterStrictIdentifier = f.createIdentifier(572 interfaceNameForParameterStrict573 );574 nodes.push(575 withJSDocComments(576 f.createTypeAliasDeclaration(577 undefined,578 [f.createToken(ts.SyntaxKind.ExportKeyword)],579 f.createIdentifier(typeNameForParameter),580 undefined,581 f.createIntersectionTypeNode([582 f.createTypeReferenceNode(583 interfaceNameForParameterStrictIdentifier584 ),585 f.createTypeReferenceNode(forParameterLaxIdentifier),586 ])587 ),588 [589 typeNameForParameter,590 appName,591 `id: ${appId}`,592 `revision: ${revision}`,593 appCode && `code: ${appCode}`,594 `@see ${clientConfig.baseUrl}/k/${appId}/`,595 ].filter((c) => c)596 )597 );598 nodes.push(599 withJSDocComments(600 f.createInterfaceDeclaration(601 undefined,602 [f.createToken(ts.SyntaxKind.ExportKeyword)],603 interfaceNameForParameterStrictIdentifier,604 undefined,605 undefined,606 parameterPropertyElements607 ),608 [609 interfaceNameForParameterStrict,610 appName,611 `id: ${appId}`,612 `revision: ${revision}`,613 appCode && `code: ${appCode}`,614 `@see ${clientConfig.baseUrl}/k/${appId}/`,615 ].filter((c) => c)616 )617 );618 }619 // if all ignored620 if (nodes.length === 0) {621 throw new Error("all apps ignored.");622 }623 // for Parameter624 const forParameterLaxDeclaration = f.createTypeAliasDeclaration(625 undefined,626 [f.createToken(ts.SyntaxKind.ExportKeyword)],627 forParameterLaxIdentifier,628 undefined,629 f.createTypeLiteralNode([630 f.createIndexSignature(631 undefined,632 undefined,633 [634 f.createParameterDeclaration(635 undefined,636 undefined,637 undefined,638 f.createIdentifier("fieldCode"),639 undefined,640 f.createTypeReferenceNode("string")641 ),642 ],643 f.createTypeLiteralNode([644 f.createPropertySignature(645 undefined,646 f.createIdentifier("value"),647 undefined,648 f.createTypeReferenceNode(f.createIdentifier("unknown"))649 ),650 ])651 ),652 ])653 );654 // import definition655 const importSpecifiers: Array<ts.ImportSpecifier> = [];656 for (const fieldType of Array.from(fieldTypes).sort()) {657 importSpecifiers.push(658 f.createImportSpecifier(false, undefined, f.createIdentifier(fieldType))...
generateTypescriptDeclaration.ts
Source:generateTypescriptDeclaration.ts
...29function createModuleDeclaration(theme: Theme, relativeFilepath: string) {30 const declaredModuleName = '@theme-ui/css'31 const interfaceMembers: ts.TypeElement[] = Object.entries(theme)32 .map(([key, value]) =>33 createPropertySignature(key, createLiteralTypeNodes(value))34 )35 .filter(notUndefined)36 const moduleBlock = ts.factory.createModuleBlock([37 ts.factory.createInterfaceDeclaration(38 undefined,39 [createExportToken()],40 createIdentifier('Theme'),41 undefined,42 undefined,43 interfaceMembers44 ),45 ])46 const comment = ts.factory.createJSDocComment(47 `This file has been generated by theme-ui.macro from "${relativeFilepath}"\nany direct modifications to this file may be lost.\n`48 )49 const moduleDeclaration = ts.factory.createModuleDeclaration(50 undefined,51 [createDeclareToken()],52 createStringLiteral(declaredModuleName),53 moduleBlock54 )55 /**56 * We create an export node so we opt-out of "ambient" mode for this declaration57 */58 const exportDeclaration = ts.factory.createExportDeclaration(59 undefined,60 undefined,61 false,62 ts.factory.createNamedExports([]),63 undefined64 )65 return ts.factory.createNodeArray([66 comment,67 moduleDeclaration,68 exportDeclaration,69 ])70}71function createTupleTypeNodeFromArray(array: Array<any>) {72 const elements = array73 .map(createLiteralFromPrimitive)74 .filter(notUndefined)75 .map((literal) => ts.factory.createLiteralTypeNode(literal))76 return ts.factory.createTupleTypeNode(elements)77}78function createLiteralFromPrimitive(primitive: any) {79 switch (typeof primitive) {80 case 'boolean':81 return primitive ? ts.factory.createTrue() : ts.factory.createFalse()82 case 'string':83 return createStringLiteral(primitive)84 case 'number':85 return ts.factory.createNumericLiteral(primitive)86 case 'bigint':87 return ts.factory.createBigIntLiteral(String(primitive))88 }89}90function createLiteralTypeNodes(object: object | Array<any>) {91 if (Array.isArray(object)) {92 return createTupleTypeNodeFromArray(object)93 }94 const propertySignatures: ts.PropertySignature[] = Object.entries(object)95 .map(([key, value]) => {96 let typeNode = undefined97 if (Array.isArray(value)) {98 typeNode = createTupleTypeNodeFromArray(value)99 } else {100 if (typeof value === 'object') {101 typeNode = createLiteralTypeNodes(value)102 } else {103 const literal = createLiteralFromPrimitive(value)104 if (literal) {105 typeNode = ts.factory.createLiteralTypeNode(literal)106 }107 }108 }109 if (typeNode) {110 return createPropertySignature(key, typeNode)111 }112 })113 .filter(notUndefined)114 return ts.factory.createTypeLiteralNode(propertySignatures)115}116function createPropertySignature(117 identifier: string,118 typeNode: ts.TypeNode,119 readonly?: boolean120) {121 return ts.factory.createPropertySignature(122 readonly ? [createReadonlyToken()] : undefined,123 createIdentifier(identifier),124 undefined,125 typeNode126 )127}128function createExportToken() {129 return ts.factory.createToken(ts.SyntaxKind.ExportKeyword)130}131function createDeclareToken() {132 return ts.factory.createToken(ts.SyntaxKind.DeclareKeyword)133}134function createReadonlyToken() {135 return ts.factory.createToken(ts.SyntaxKind.ReadonlyKeyword)...
Using AI Code Generation
1import { createPropertySignature } from 'ts-auto-mock';2import { createTypeAliasDeclaration } from 'ts-auto-mock';3import { createInterfaceDeclaration } from 'ts-auto-mock';4import { createFunctionDeclaration } from 'ts-auto-mock';5import { createVariableStatement } from 'ts-auto-mock';6import { createEnumDeclaration } from 'ts-auto-mock';7import { createEnumMember } from 'ts-auto-mock';8import { createIndexSignature } from 'ts-auto-mock';9import { createMethodSignature } from 'ts-auto-mock';10import { createMethodDeclaration } from 'ts-auto-mock';11import { createConstructorDeclaration } from 'ts-auto-mock';12import { createGetAccessorDeclaration } from 'ts-auto-mock';13import { createSetAccessorDeclaration } from 'ts-auto-mock';14import { createCallSignature } from 'ts-auto-mock';15import { createConstructSignature } from 'ts-auto-mock';16import { createExportAssignment } from 'ts-auto-mock';17import { createExportDeclaration } from 'ts-auto-mock';18import { createExportSpecifier } from 'ts-auto-mock';19import { createExternalModule
Using AI Code Generation
1import {createPropertySignature} from 'ts-auto-mock';2const propertySignature = createPropertySignature('name', 'string');3const propertySignature = createPropertySignature('name', 'string', true);4const propertySignature = createPropertySignature('name', 'string', false);5const propertySignature = createPropertySignature('name', 'string', true, true);6const propertySignature = createPropertySignature('name', 'string', false, true);7const propertySignature = createPropertySignature('name', 'string', true, false);8const propertySignature = createPropertySignature('name', 'string', false, false);9const propertySignature = createPropertySignature('name', 'string', false, false, true);10const propertySignature = createPropertySignature('name', 'string', false, false, false);11const propertySignature = createPropertySignature('name', 'string', false, false, false, true);
Using AI Code Generation
1import { createPropertySignature } from 'ts-auto-mock';2const propertySignature = createPropertySignature('myProperty', 'string');3console.log(propertySignature);4import { createPropertySignature } from 'ts-auto-mock';5const propertySignature = createPropertySignature('myProperty', 'string', true);6console.log(propertySignature);7import { createPropertySignature } from 'ts-auto-mock';8const propertySignature = createPropertySignature('myProperty', 'string', false, true);9console.log(propertySignature);10import { createPropertySignature } from 'ts-auto-mock';11const propertySignature = createPropertySignature('myProperty', 'string', true, true);12console.log(propertySignature);13import { createPropertySignature } from 'ts-auto-mock';14const propertySignature = createPropertySignature('myProperty', 'string', true, true, 'myComment');15console.log(propertySignature);16import { createPropertySignature } from 'ts-auto-mock';
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!