Best JavaScript code snippet using ts-auto-mock
generate.ts
Source:generate.ts
...49 { propertyName: "$revision", type: "Revision" },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(...
TypeEmitter.ts
Source:TypeEmitter.ts
...48const createFieldsTypeNode = (49 opts: TypeEmitterOptions,50 fields: Field[],51): ts.TypeNode =>52 createTypeLiteralNode(53 fields.reduce<ts.TypeElement[]>(54 (typeElements, field) => [55 ...typeElements,56 createPropertySignature(57 [],58 field.name,59 field.required === false60 ? createToken(SyntaxKind.QuestionToken)61 : undefined,62 createRequiredFieldTypeNode(opts, field),63 ),64 ],65 [],66 ),67 );68const createCodeFieldTypeNode = (): ts.TypeNode =>69 createTypeLiteralNode([70 createPropertySignature(71 [],72 `code`,73 undefined,74 createKeywordTypeNode(SyntaxKind.StringKeyword),75 ),76 createPropertySignature(77 [],78 `lang`,79 createToken(SyntaxKind.QuestionToken),80 createKeywordTypeNode(SyntaxKind.StringKeyword),81 ),82 ]);83const createListFieldTypeNode = (84 opts: TypeEmitterOptions,85 field: ListField,86): ts.TypeNode => {87 if (field.fields) {88 return createArrayTypeNode(createFieldsTypeNode(opts, field.fields));89 }90 return createArrayTypeNode(createKeywordTypeNode(SyntaxKind.StringKeyword));91};92const createObjectFieldTypeNode = (93 opts: TypeEmitterOptions,94 field: ObjectField,95): ts.TypeNode => createFieldsTypeNode(opts, field.fields);96const createRelationFieldTypeNode = (field: RelationField): ts.TypeNode => {97 if (field.multiple) {98 return createArrayTypeNode(createKeywordTypeNode(SyntaxKind.StringKeyword));99 }100 return createKeywordTypeNode(SyntaxKind.StringKeyword);101};102const createSelectFieldOptionTypeNode = (103 option: SelectFieldOption,104): ts.TypeNode => {105 if (typeof option === `string`) {106 return createLiteralTypeNode(createStringLiteral(option));107 }108 return createLiteralTypeNode(createStringLiteral(option.value));109};110const createSelectFieldTypeNode = (field: SelectField): ts.TypeNode => {111 const optionUnionTypeNode = createUnionTypeNode(112 field.options.map(createSelectFieldOptionTypeNode),113 );114 if (field.multiple) {115 return createArrayTypeNode(optionUnionTypeNode);116 }117 return optionUnionTypeNode;118};119const createRequiredFieldTypeNode = (120 opts: TypeEmitterOptions,121 field: Field,122): ts.TypeNode => {123 if (field.widget === `boolean`) {124 return createKeywordTypeNode(SyntaxKind.BooleanKeyword);125 }126 if (field.widget === `code`) {127 return createCodeFieldTypeNode();128 }129 if (field.widget === `color`) {130 return createKeywordTypeNode(SyntaxKind.StringKeyword);131 }132 if (field.widget === `datetime`) {133 return createTypeReferenceNode(`Date`);134 }135 if (field.widget === `file`) {136 return createKeywordTypeNode(SyntaxKind.StringKeyword);137 }138 if (field.widget === `hidden`) {139 return createKeywordTypeNode(SyntaxKind.UnknownKeyword);140 }141 if (field.widget === `image`) {142 return createKeywordTypeNode(SyntaxKind.StringKeyword);143 }144 if (field.widget === `list`) {145 return createListFieldTypeNode(opts, field);146 }147 if (field.widget === `map`) {148 return createKeywordTypeNode(SyntaxKind.StringKeyword);149 }150 if (field.widget === `markdown`) {151 return createTypeReferenceNode(`Markdown`);152 }153 if (field.widget === `number`) {154 return createKeywordTypeNode(SyntaxKind.NumberKeyword);155 }156 if (field.widget === `object`) {157 return createObjectFieldTypeNode(opts, field);158 }159 if (field.widget === `relation`) {160 return createRelationFieldTypeNode(field);161 }162 if (field.widget === `select`) {163 return createSelectFieldTypeNode(field);164 }165 if (field.widget === `string`) {166 return createKeywordTypeNode(SyntaxKind.StringKeyword);167 }168 if (field.widget === `text`) {169 return createKeywordTypeNode(SyntaxKind.StringKeyword);170 }171 return createKeywordTypeNode(SyntaxKind.UnknownKeyword);172};173const createLocaleTypeNode = (locales: string[]): ts.TypeNode =>174 createUnionTypeNode(175 locales.map((locale) => createLiteralTypeNode(createStringLiteral(locale))),176 );177const createSlugTypeNode = (178 opts: TypeEmitterOptions,179 slugs: string[],180): ts.TypeNode => {181 if (!opts.narrowSlugs) {182 return createKeywordTypeNode(SyntaxKind.StringKeyword);183 }184 if (slugs.length === 0) {185 return createKeywordTypeNode(SyntaxKind.NeverKeyword);186 }187 if (slugs.length === 1) {188 return createLiteralTypeNode(createStringLiteral(slugs[0]));189 }190 return createUnionTypeNode(191 slugs.map((slug) => createLiteralTypeNode(createStringLiteral(slug))),192 );193};194const createCollectionTypeNode = (195 opts: TypeEmitterOptions,196 {197 collection,198 file,199 kind,200 i18n,201 fields,202 slugs,203 }: {204 readonly collection: string;205 readonly file?: string;206 readonly kind: string;207 readonly i18n?: FolderCollectionI18n | FilesCollectionI18n;208 readonly fields: Field[];209 readonly slugs: string[];210 },211): ts.TypeNode => {212 const properties: [key: string, type: ts.TypeNode][] = [213 [`collection`, createLiteralTypeNode(createStringLiteral(collection))],214 [`kind`, createLiteralTypeNode(createStringLiteral(kind))],215 [`slug`, createSlugTypeNode(opts, slugs)],216 [217 `locale`,218 i18n219 ? createIndexedAccessTypeNode(220 createTypeReferenceNode(`Schema`),221 createLiteralTypeNode(createStringLiteral(`locales`)),222 )223 : createLiteralTypeNode(createNull()),224 ],225 [`props`, createFieldsTypeNode(opts, fields)],226 ];227 if (file) {228 properties.unshift([229 `file`,230 createLiteralTypeNode(createStringLiteral(file)),231 ]);232 }233 if (opts.raw) {234 properties.push([`raw`, createKeywordTypeNode(SyntaxKind.StringKeyword)]);235 }236 if (opts.sourceLocation) {237 properties.push([238 `sourceLocation`,239 createKeywordTypeNode(SyntaxKind.StringKeyword),240 ]);241 }242 return createTypeLiteralNode(243 properties.map(([key, node]) =>244 createPropertySignature([], key, undefined, node),245 ),246 );247};248const createFolderCollectionTypeNode = (249 opts: TypeEmitterOptions,250 collection: FolderTaggedCollection,251 slugs: string[],252): ts.TypeNode =>253 createCollectionTypeNode(opts, {254 collection: collection.name,255 kind: `folder`,256 fields: collection.fields,257 i18n: collection.i18n,258 slugs,259 });260const createFilesCollectionItemTypeNode = (261 opts: TypeEmitterOptions,262 collection: FilesCollection,263 item: FilesCollectionItem,264 slugs: string[],265): ts.TypeNode => {266 return createCollectionTypeNode(opts, {267 collection: collection.name,268 kind: `files`,269 fields: item.fields,270 file: item.name,271 i18n: item.i18n,272 slugs,273 });274};275const createSchemaTypeNode = (276 opts: TypeEmitterOptions,277 schema: Schema,278 collectionAstNodes: CollectionAstNode[],279): ts.TypeNode =>280 createTypeLiteralNode([281 createPropertySignature(282 [],283 `locales`,284 undefined,285 schema.i18n286 ? createLocaleTypeNode(schema.i18n.locales)287 : createKeywordTypeNode(SyntaxKind.NeverKeyword),288 ),289 createPropertySignature(290 [],291 `collections`,292 undefined,293 createTypeLiteralNode(294 schema.collections.map(tagCollection).map((collection) =>295 createPropertySignature(296 [],297 createComputedPropertyName(createStringLiteral(collection.name)),298 undefined,299 collection.kind === `folder`300 ? createFolderCollectionTypeNode(301 opts,302 collection,303 deduplicate(304 findStrict(305 collectionAstNodes,306 (collectionAstNode) =>307 collectionAstNode.collection.name === collection.name,308 ).contents.map((content) => content.slug),309 ),310 )311 : createTypeLiteralNode(312 collection.files.map((item) =>313 createPropertySignature(314 [],315 createComputedPropertyName(316 createStringLiteral(item.name),317 ),318 undefined,319 createFilesCollectionItemTypeNode(320 opts,321 collection,322 item,323 deduplicate(324 findStrict(325 collectionAstNodes,326 (collectionAstNode) =>327 collectionAstNode.collection.name ===328 collection.name,329 )330 .contents.filter(331 (content) =>332 content.kind === `files` &&333 content.file === item.name,334 )335 .map((content) => content.slug),336 ),337 ),338 ),339 ),340 ),341 ),342 ),343 ),344 ),345 ]);346export const createSchemaTypeAliasDeclaration = (347 opts: TypeEmitterOptions,348 schema: Schema,349 collectionAstNodes: CollectionAstNode[],350): ts.TypeAliasDeclaration =>351 createTypeAliasDeclaration(352 [],353 [createModifier(SyntaxKind.ExportKeyword)],354 `Schema`,355 [],356 createSchemaTypeNode(opts, schema, collectionAstNodes),357 );358const createContentsTypeNode = (schema: Schema): ts.TypeNode =>359 createTypeReferenceNode(`Readonly`, [360 createTypeLiteralNode(361 schema.collections362 .map(tagCollection)363 .map((collection): ts.PropertySignature => {364 if (collection.kind === `folder`) {365 return createPropertySignature(366 [],367 createComputedPropertyName(createStringLiteral(collection.name)),368 undefined,369 createArrayTypeNode(370 createIndexedAccessTypeNode(371 createIndexedAccessTypeNode(372 createTypeReferenceNode(`Schema`),373 createLiteralTypeNode(createStringLiteral(`collections`)),374 ),375 createLiteralTypeNode(createStringLiteral(collection.name)),376 ),377 ),378 );379 }380 return createPropertySignature(381 [],382 createComputedPropertyName(createStringLiteral(collection.name)),383 undefined,384 createTypeLiteralNode(385 collection.files.map(386 (item): ts.PropertySignature =>387 createPropertySignature(388 [],389 createComputedPropertyName(createStringLiteral(item.name)),390 undefined,391 createArrayTypeNode(392 createIndexedAccessTypeNode(393 createIndexedAccessTypeNode(394 createIndexedAccessTypeNode(395 createTypeReferenceNode(`Schema`),396 createLiteralTypeNode(397 createStringLiteral(`collections`),398 ),...
generator.ts
Source:generator.ts
...156 ts.createPropertySignature(157 /*modifiers*/ undefined,158 'pathParams',159 /*questionToken */undefined,160 /*type*/ ts.createTypeLiteralNode(pathParams),161 /*initializer*/ undefined162 )163 ];164}165function optionalToken (thrutly: boolean) {166 return thrutly ? ts.createToken(ts.SyntaxKind.QuestionToken) : undefined;167}168function createRouteOptionsQueryParams (options: RouteOptionsDefinition) {169 const paramsDefinition = options.queryParams;170 if (typeof paramsDefinition === 'undefined') {171 return [];172 }173 const pathParams = Object.keys(paramsDefinition).map(param => {174 const definition = ts.createPropertySignature(175 /*modifiers*/ undefined,176 param,177 optionalToken(paramsDefinition[param].optional),178 /*type*/ mapTypes(paramsDefinition[param].type),179 /*initializer*/ undefined180 );181 return withTypeDocComment(definition, paramsDefinition[param].description);182 });183 return [184 ts.createPropertySignature(185 /*modifiers*/ undefined,186 'queryParams',187 /*questionToken*/ undefined,188 /*type*/ ts.createTypeLiteralNode(pathParams),189 /*initializer*/ undefined190 )191 ];192}193function createRouteOptionsBody (options: RouteOptionsDefinition) {194 if (typeof options.body === 'undefined') {195 return [];196 }197 return [198 ts.createPropertySignature(199 /*modifiers*/ undefined,200 'body',201 /*questionToken*/ undefined,202 /*type*/ ts.createTypeLiteralNode(undefined),203 /*initializer*/ undefined204 )205 ];206}207function createRouteOptions (definition: RouteDefinition) {208 if (typeof definition.options === 'undefined') {209 return ts.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword);210 }211 return ts.createTypeLiteralNode([212 ...createRouteOptionsPathParams(definition.options),213 ...createRouteOptionsQueryParams(definition.options),214 ...createRouteOptionsBody(definition.options)215 ]);216}217function createRouteResponses (definition: RouteDefinition) {218 return ts.createTypeLiteralNode(undefined);219}220function createRoute (path: string, definition: RouteDefinition) {221 return ts.createPropertySignature(222 /*modifiers*/ undefined,223 ts.createStringLiteral(path),224 /*questionToken*/ undefined,225 ts.createTypeLiteralNode([226 ts.createPropertySignature(227 /*modifiers*/ undefined,228 'options',229 /*questionToken*/ undefined,230 /*type*/ createRouteOptions(definition),231 /*initializer*/ undefined232 ),233 ts.createPropertySignature(234 /*modifiers*/ undefined,235 'responses',236 /*questionToken*/ undefined,237 /*type*/ createRouteResponses(definition),238 /*initializer*/ undefined239 )240 ]),241 /*initializer*/ undefined242 );243}244function createVerbEndpoints (verb: string, routes: Record<string, RouteDefinition>) {245 const nodeRoutes = Object.keys(routes).map(path => createRoute(path, routes[path]));246 return ts.createPropertySignature(247 /*modifiers*/ undefined,248 verb,249 /*questionToken */undefined,250 /*type*/ ts.createTypeLiteralNode(nodeRoutes),251 /*initializer*/ undefined252 );253}254interface EndpointDefinitions {255 name: string;256 routes: Record<string, Record<string, RouteDefinition>>;257}258function createEndpoints (definition: EndpointDefinitions) {259 const members =260 Object261 .keys(definition.routes)262 .map(verb => createVerbEndpoints(verb, definition.routes[verb]));263 return ts.createInterfaceDeclaration(264 /*decorators*/ undefined,...
Using AI Code Generation
1import { createTypeLiteralNode } from 'ts-auto-mock/extension';2import * as ts from 'typescript';3const sourceFile = ts.createSourceFile(4);5const typeLiteralNode = createTypeLiteralNode({6 {7 },8 {9 },10});11const printer = ts.createPrinter();12const resultFile = printer.printNode(13);14console.log(resultFile);15import { createTypeLiteralNode } from 'ts-auto-mock/extension';16import * as ts from 'typescript';17const sourceFile = ts.createSourceFile(18);19const typeLiteralNode = createTypeLiteralNode({20 {21 },22 {23 },24 {25 },26});27const printer = ts.createPrinter();28const resultFile = printer.printNode(29);30console.log(resultFile);
Using AI Code Generation
1import { createTypeLiteralNode } from 'ts-auto-mock';2import { createMock } from 'ts-auto-mock';3import { createMockFactory } from 'ts-auto-mock';4import { createMockMethod } from 'ts-auto-mock';5import { createMockMethodFactory } from 'ts-auto-mock';6import { createMockProperty } from 'ts-auto-mock';7import { createMockPropertyFactory } from 'ts-auto-mock';8import { createMockStaticMethod } from 'ts-auto-mock';9import { createMockStaticMethodFactory } from 'ts-auto-mock';10import { createMockStaticProperty } from 'ts-auto-mock';11import { createMockStaticPropertyFactory } from 'ts-auto-mock';12import { createMockType } from 'ts-auto-mock';13import { createMockTypeFactory } from 'ts-auto-mock';14import { createMockTypeInstance } from 'ts-auto-mock';15import { createMockTypeInstanceFactory } from 'ts-auto-mock';16import { createMockTypeMethod } from 'ts-auto-mock';17import { createMockTypeMethodFactory } from 'ts-auto-mock';18import { createMockTypeProperty } from '
Using AI Code Generation
1import { createTypeLiteralNode } from 'ts-auto-mock/extension';2import { TypeLiteralNode } from 'ts-morph';3import { createMock } from 'ts-auto-mock';4const typeLiteralNode: TypeLiteralNode = createTypeLiteralNode('interface A{a:string}');5const mock: A = createMock(typeLiteralNode);6console.log(mock);7import { createTypeLiteralNode } from 'ts-auto-mock/extension';8import { TypeLiteralNode } from 'ts-morph';9import { createMock } from 'ts-auto-mock';10const typeLiteralNode: TypeLiteralNode = createTypeLiteralNode('type A={a:string}');11const mock: A = createMock(typeLiteralNode);12console.log(mock);13import { createTypeLiteralNode } from 'ts-auto-mock/extension';14import { TypeLiteralNode } from 'ts-morph';15import { createMock } from 'ts-auto-mock';16const typeLiteralNode: TypeLiteralNode = createTypeLiteralNode('type A={a:string}', true);17const mock: A = createMock(typeLiteralNode);18console.log(mock);19import { createTypeLiteralNode } from 'ts-auto-mock/extension';20import { TypeLiteralNode } from 'ts-morph';21import { createMock } from 'ts-auto-mock';22const typeLiteralNode: TypeLiteralNode = createTypeLiteralNode('interface A{a:string}', true);23const mock: A = createMock(typeLiteralNode);24console.log(mock);25import { createTypeLiteralNode } from 'ts-auto-mock/extension';26import { TypeLiteralNode } from 'ts-morph';27import { createMock } from 'ts-auto-mock';28const typeLiteralNode: TypeLiteralNode = createTypeLiteralNode('type A={a:number}', true);29const mock: A = createMock(typeLiteralNode);30console.log(mock);31import { createTypeLiteralNode }
Using AI Code Generation
1import { createTypeLiteralNode } from 'ts-auto-mock/extension';2const typeLiteral = createTypeLiteralNode({3 {4 },5 {6 },7});8import { createTypeLiteralNode } from 'ts-auto-mock/extension';9const typeLiteral = createTypeLiteralNode({10 {11 },12 {13 },14});15import { createTypeLiteralNode } from 'ts-auto-mock/extension';16const typeLiteral = createTypeLiteralNode({17 {18 },19 {20 },21});22import { createTypeLiteralNode } from 'ts-auto-mock/extension';23const typeLiteral = createTypeLiteralNode({24 {25 },26 {27 },28});29import { createTypeLiteralNode } from 'ts-auto-mock/extension';30const typeLiteral = createTypeLiteralNode({31 {32 },33 {34 },35});36import { createTypeLiteralNode } from 'ts-auto-mock/extension';37const typeLiteral = createTypeLiteralNode({
Using AI Code Generation
1import tsAutoMock from 'ts-auto-mock';2const typeLiteralNode = tsAutoMock.createTypeLiteralNode({3 {4 },5});6import tsAutoMock from 'ts-auto-mock';7const typeLiteralNode = tsAutoMock.createTypeLiteralNode({8 {9 },10});11import tsAutoMock from 'ts-auto-mock';12const typeLiteralNode = tsAutoMock.createTypeLiteralNode({13 {14 },15});16import tsAutoMock from 'ts-auto-mock';17const typeLiteralNode = tsAutoMock.createTypeLiteralNode({18 {19 },20});21import tsAutoMock from 'ts-auto-mock';22const typeLiteralNode = tsAutoMock.createTypeLiteralNode({23 {24 },25});26import tsAutoMock from 'ts-auto-mock';27const typeLiteralNode = tsAutoMock.createTypeLiteralNode({28 {29 },30});31import tsAutoMock from 'ts-auto-mock';32const typeLiteralNode = tsAutoMock.createTypeLiteralNode({
Using AI Code Generation
1import { createTypeLiteralNode } from "ts-auto-mock/extension";2const typeLiteralNode = createTypeLiteralNode({3 {4 },5});6console.log(typeLiteralNode);7import { createTypeLiteralNode } from "ts-auto-mock/extension";8const typeLiteralNode = createTypeLiteralNode({9 {10 },11});12console.log(typeLiteralNode);13import { createTypeLiteralNode } from "ts-auto-mock/extension";14const typeLiteralNode = createTypeLiteralNode({15 {16 },17});18console.log(typeLiteralNode);
Using AI Code Generation
1import { createTypeLiteralNode } from 'ts-auto-mock/extension';2const typeLiteralNode = createTypeLiteralNode('interface Foo { bar: string; }');3console.log(typeLiteralNode);4import { createTypeLiteralNode } from 'ts-auto-mock/extension';5const typeLiteralNode = createTypeLiteralNode('interface Foo { bar: string; }');6console.log(typeLiteralNode);7import { createTypeLiteralNode } from 'ts-auto-mock/extension';8const typeLiteralNode = createTypeLiteralNode('interface Foo { bar: string; }');9console.log(typeLiteralNode);10import { createTypeLiteralNode } from 'ts-auto-mock/extension';11const typeLiteralNode = createTypeLiteralNode('interface Foo { bar: string; }');12console.log(typeLiteralNode);13import { createTypeLiteralNode } from 'ts-auto-mock/extension';14const typeLiteralNode = createTypeLiteralNode('interface Foo { bar: string; }');15console.log(typeLiteralNode);16import { createTypeLiteralNode } from 'ts-auto-mock/extension';17const typeLiteralNode = createTypeLiteralNode('interface Foo { bar: string; }');18console.log(typeLiteralNode);19import { createTypeLiteralNode } from 'ts-auto-mock/extension';20const typeLiteralNode = createTypeLiteralNode('interface Foo { bar: string; }');21console.log(typeLiteralNode);22import { createTypeLiteralNode } from 'ts-auto-mock/extension';23const typeLiteralNode = createTypeLiteralNode('interface Foo { bar: string; }');24console.log(typeLiteralNode);
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!!