Skip to content

Commit

Permalink
Add type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
putnik committed Jul 22, 2024
1 parent 5ea46c1 commit 31f47b7
Show file tree
Hide file tree
Showing 15 changed files with 94 additions and 94 deletions.
2 changes: 1 addition & 1 deletion src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ export async function getMessages( messageKeys: string[], language: string ): Pr

export async function sparqlRequest( request: string ): Promise<SparqlResponse> {
const $ = require( 'jquery' );
const url = 'https://query.wikidata.org/sparql?format=json';
const url: string = 'https://query.wikidata.org/sparql?format=json';
return $.post( url, { query: request } );
}
8 changes: 4 additions & 4 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,15 +233,15 @@ export async function init(): Promise<any> {
return;
}

$( '.infobox-export' ).find( 'tr > th + td, tr > td + td' ).each( function () {
$( '.infobox-export' ).find( 'tr > th + td, tr > td + td' ).each( function (): void {
const $label: JQuery = $( this ).prev();
$label.addClass( 'infobox-export-label' );
} );
$fields = $( '.infobox-export:not(.vertical-navbox):not([data-from]) .infobox-export-label + td' );
const typeIds: ItemId[] = getItemPropertyValues( claims, 'P31' );
await preloadAvailableProperties( typeIds );
}
await Promise.all( $fields.map( async function () {
await Promise.all( $fields.map( async function (): Promise<void> {
const $field: JQuery = $( this );
const propertyId: PropertyId | undefined = $field.attr( 'data-wikidata-property-id' ) as ( PropertyId | undefined );
if ( typeof propertyId !== 'undefined' ) {
Expand All @@ -260,7 +260,7 @@ export async function init(): Promise<any> {
}

const $fieldQualifiers = $field.closest( 'tr' ).find( '[data-wikidata-qualifier-id]' );
$fieldQualifiers.each( function () {
$fieldQualifiers.each( function (): void {
propertyIds.add( $( this ).data( 'wikidata-qualifier-id' ) );
} );

Expand All @@ -275,7 +275,7 @@ export async function init(): Promise<any> {
const $label: JQuery = $field.parent().children( 'th, .infobox-export-label' ).first();
const guessedPropertyIds: PropertyId[] = await guessPropertyIdByLabel( $label, itemId, claims );
let guessedProperties: Property[] = ( await Promise.all( guessedPropertyIds.map(
async ( propertyId: PropertyId ) => await getOrLoadProperty( propertyId )
async ( propertyId: PropertyId ): Promise<Property> => await getOrLoadProperty( propertyId )
) ) ).filter( ( property: Property | undefined ) => property );

// If at least one of these properties with same name and datatype already filled,
Expand Down
20 changes: 10 additions & 10 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ function prepareUnit( unitId: ItemId, unitData: any ): string[] {
}

async function loadUnits( units: ItemId[] ): Promise<void> {
for ( let idx = 0; idx < unique( units ).length; idx += 50 ) {
for ( let idx: number = 0; idx < unique( units ).length; idx += 50 ) {
const unitData: ApiResponse = await wdApiRequest( {
action: 'wbgetentities',
languages: contentLanguage,
Expand Down Expand Up @@ -280,7 +280,7 @@ async function loadUnitsSparql( typeIds: ItemId[], onlyUnitIds?: ItemId[] ): Pro
}
const unitIds: ItemId[] = [];
const unitsData: UnitsData = {};
for ( let i = 0; i < data.results.bindings.length; i++ ) {
for ( let i: number = 0; i < data.results.bindings.length; i++ ) {
const bindings: SparqlUnitBindings = data.results.bindings[ i ];
const unitId: ItemId = bindings.unitId.value as ItemId;

Expand All @@ -298,7 +298,7 @@ async function loadUnitsSparql( typeIds: ItemId[], onlyUnitIds?: ItemId[] ): Pro
}
unit.push( prepareUnitSearchString( bindings.code?.value ) );
if ( bindings.unitAltLabel?.value ) {
bindings.unitAltLabel.value.split( ',' ).forEach( function ( alias: string ) {
bindings.unitAltLabel.value.split( ',' ).forEach( function ( alias: string ): void {
unit.push( prepareUnitSearchString( alias ) );
} );
}
Expand Down Expand Up @@ -422,7 +422,7 @@ async function realLoadProperties( propertyIds: PropertyId[] ): Promise<void> {
case 'Q21510851': // Allowed qualifiers
case 'Q21510856': // Required qualifiers
qualifiers = constraint.qualifiers?.P2306 || [];
for ( let idx = 0; idx < qualifiers.length; idx++ ) {
for ( let idx: number = 0; idx < qualifiers.length; idx++ ) {
const qualifierId: PropertyId | undefined = ( qualifiers[ idx ]?.datavalue as PropertyDataValue | undefined )?.value?.id;
if ( qualifierId ) {
propertyData.constraints.qualifier.push( qualifierId );
Expand All @@ -432,7 +432,7 @@ async function realLoadProperties( propertyIds: PropertyId[] ): Promise<void> {

case 'Q21514353': // Units
qualifiers = constraint.qualifiers?.P2305 || [];
for ( let idx = 0; idx < qualifiers.length; idx++ ) {
for ( let idx: number = 0; idx < qualifiers.length; idx++ ) {
const unitId: ItemId = ( qualifiers[ idx ]?.datavalue as ItemDataValue | undefined )?.value?.id;
if ( unitId ) {
propertyData.units.push( unitId );
Expand All @@ -456,7 +456,7 @@ async function realLoadProperties( propertyIds: PropertyId[] ): Promise<void> {
}
const typeReplacementId: PropertyId | null = ( constraint.qualifiers?.P6824?.[ 0 ]?.datavalue?.value as PropertyValue | undefined )?.id || null;
qualifiers = constraint.qualifiers?.P2305 || [];
for ( let idx = 0; idx < qualifiers.length; idx++ ) {
for ( let idx: number = 0; idx < qualifiers.length; idx++ ) {
const qualifierId: ItemId | undefined = ( qualifiers[ idx ]?.datavalue as ItemDataValue | undefined )?.value?.id;
if ( qualifierId ) {
propertyData.constraints.noneOfTypes[ qualifierId ] = typeReplacementId;
Expand All @@ -466,7 +466,7 @@ async function realLoadProperties( propertyIds: PropertyId[] ): Promise<void> {

case 'Q21510859': // One-of constraint
qualifiers = constraint.qualifiers?.P2305 || [];
for ( let idx = 0; idx < qualifiers.length; idx++ ) {
for ( let idx: number = 0; idx < qualifiers.length; idx++ ) {
const qualifierId: ItemId | undefined = ( qualifiers[ idx ]?.datavalue as ItemDataValue | undefined )?.value?.id;
if ( qualifierId ) {
propertyData.constraints.oneOfValues.push( qualifierId );
Expand All @@ -476,7 +476,7 @@ async function realLoadProperties( propertyIds: PropertyId[] ): Promise<void> {

case 'Q21510865': // Value-type constraint
qualifiers = constraint.qualifiers?.P2308 || [];
for ( let idx = 0; idx < qualifiers.length; idx++ ) {
for ( let idx: number = 0; idx < qualifiers.length; idx++ ) {
const itemTypeId: ItemId | undefined = ( qualifiers[ idx ]?.datavalue as ItemDataValue | undefined )?.value?.id;
if ( itemTypeId ) {
propertyData.constraints.valueType.push( itemTypeId );
Expand All @@ -487,7 +487,7 @@ async function realLoadProperties( propertyIds: PropertyId[] ): Promise<void> {
case 'Q52558054': // None-of values constraint
const valueReplacementId: ItemId | undefined = ( constraint.qualifiers?.P9729?.[ 0 ]?.datavalue?.value as ItemValue | undefined )?.id;
qualifiers = constraint.qualifiers?.P2305 || [];
for ( let idx = 0; idx < qualifiers.length; idx++ ) {
for ( let idx: number = 0; idx < qualifiers.length; idx++ ) {
const qualifierId: ItemId | undefined = ( qualifiers[ idx ]?.datavalue as ItemDataValue | undefined )?.value?.id;
if ( qualifierId ) {
propertyData.constraints.noneOfValues[ qualifierId ] = valueReplacementId;
Expand Down Expand Up @@ -542,7 +542,7 @@ export async function loadProperties( propertyIdSet: Set<PropertyId> ): Promise<

if ( neededPropertyIds.length ) {
const apiChunkSize: number = 50;
for ( let i = 0; i < neededPropertyIds.length; i += apiChunkSize ) {
for ( let i: number = 0; i < neededPropertyIds.length; i += apiChunkSize ) {
const propertyIdsChunk: PropertyId[] = neededPropertyIds.slice( i, i + apiChunkSize );
await realLoadProperties( propertyIdsChunk );
}
Expand Down
6 changes: 3 additions & 3 deletions src/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function formatReference( reference: Reference ): JQuery | void {

export function formatReferences( references: Reference[] ): JQuery {
const $result: JQuery = $( '<span>' );
for ( let i = 0; i < references.length; i++ ) {
for ( let i: number = 0; i < references.length; i++ ) {
const $refSup: JQuery | void = formatReference( references[ i ] );
if ( $refSup ) {
$result.append( $refSup );
Expand Down Expand Up @@ -120,10 +120,10 @@ function formatTimeValue( value: TimeValue ): JQuery {
if ( value.precision > 10 ) {
options.day = 'numeric';
}
const parsedDate = new Date( Date.parse( value.time.slice( 1 ).replace( /-00/g, '-01' ) ) );
const parsedDate: Date = new Date( Date.parse( value.time.slice( 1 ).replace( /-00/g, '-01' ) ) );
dateString = parsedDate.toLocaleString( userLanguage, options ) + ( value.precision === 8 ? getI18n( 'decade-postfix' ) : '' ) + bceMark;
}
const calendar = value.calendarmodel.includes( '1985727' ) ? getI18n( 'grigorian-calendar' ) : getI18n( 'julian-calendar' );
const calendar: string = value.calendarmodel.includes( '1985727' ) ? getI18n( 'grigorian-calendar' ) : getI18n( 'julian-calendar' );

$label
.append( $( '<strong>' ).text( dateString ) )
Expand Down
14 changes: 7 additions & 7 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export async function addQualifiers( $field: JQuery, statement: Statement ): Pro
const $qualifiers: JQuery = $field.find( '[data-wikidata-qualifier-id]' );

const qualifierTitles: KeyValue = {};
for ( let q = 0; q < $qualifiers.length; q++ ) {
for ( let q: number = 0; q < $qualifiers.length; q++ ) {
const $qualifier: JQuery = $( $qualifiers[ q ] );
const qualifierId: PropertyId = $qualifier.data( 'wikidata-qualifier-id' );
let qualifierValue: Value | void = $qualifier.text().replace( /\n/g, ' ' ).trim();
Expand Down Expand Up @@ -147,7 +147,7 @@ export async function prepareCommonsMedia( context: Context ): Promise<Statement
const statements: Statement[] = [];
const $imgs: JQuery = context.$field.find( 'img' );
const imgs: JQuery[] = [];
$imgs.each( function () {
$imgs.each( function (): void {
imgs.push( $( this ) );
} );
const references: Reference[] = getReferences( context.$wrapper );
Expand All @@ -158,7 +158,7 @@ export async function prepareCommonsMedia( context: Context ): Promise<Statement
return;
}
const srcParts: string[] = src.split( '/' );
let fileName = srcParts.pop();
let fileName: string = srcParts.pop();
if ( fileName.match( /(?:^|-)\d+px-/ ) ) {
fileName = srcParts.pop();
}
Expand Down Expand Up @@ -204,7 +204,7 @@ export async function prepareExternalId( context: Context ): Promise<Statement[]
return [];
}

const sparql = `SELECT ?item WHERE { ?item wdt:${ context.propertyId } "${ externalId }" } LIMIT 1`;
const sparql: string = `SELECT ?item WHERE { ?item wdt:${ context.propertyId } "${ externalId }" } LIMIT 1`;
const data: SparqlResponse = await sparqlRequest( sparql );
if ( data.results.bindings.length ) {
const url: string = data.results.bindings[ 0 ].item.value;
Expand Down Expand Up @@ -236,7 +236,7 @@ export function prepareMonolingualText( context: Context ): Statement[] {
const values: { [ key: string ]: MonolingualTextValue } = {};
const statements: Statement[] = [];
let $items: JQuery = context.$field.find( 'span[lang], i[lang]' );
$items.each( function () {
$items.each( function (): void {
const $item: JQuery = $( this );
const language: string = $item.attr( 'lang' ).trim();
values[ language ] = {
Expand All @@ -245,10 +245,10 @@ export function prepareMonolingualText( context: Context ): Statement[] {
};
} );
if ( !Object.values( values ).length ) {
const text = context.$field.text().trim();
const text: string = context.$field.text().trim();
if ( text ) {
$items = mw.util.$content.find( 'span[lang]' );
$items.each( function () {
$items.each( function (): void {
const $item: JQuery = $( this );
if ( $item.text().trim().startsWith( text ) ) {
const language: string = $item.attr( 'lang' ).trim();
Expand Down
2 changes: 1 addition & 1 deletion src/parser/coordinates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ function parseGeohackParams( url: string ): ( number | null )[] {
export async function prepareGlobeCoordinate( context: Context ): Promise<Statement[]> {
const statements: Statement[] = [];
const $links: JQuery = context.$field.find( 'a' );
$links.each( function () {
$links.each( function (): false | void {
const $link: JQuery = $( this );
let latitude: number | null = null;
let longitude: number | null = null;
Expand Down
20 changes: 10 additions & 10 deletions src/parser/item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export async function filterItemStatements( propertyId: PropertyId, statements:
}

if ( property.constraints.noneOfValues ) {
statements = statements.map( ( statement: Statement ) => {
statements = statements.map( ( statement: Statement ): Statement | null => {
const itemId: ItemId = ( statement.mainsnak.datavalue.value as ItemValue ).id;
if ( typeof property.constraints.noneOfValues[ itemId ] === 'undefined' ) {
return statement;
Expand All @@ -68,7 +68,7 @@ export async function filterItemStatements( propertyId: PropertyId, statements:
}
statement.mainsnak = generateItemSnak( propertyId, property.constraints.noneOfValues[ itemId ] );
return statement;
} ).filter( ( statement: Statement | null ) => ( statement !== null ) );
} ).filter( ( statement: Statement | null ): boolean => ( statement !== null ) );
}

if ( property.constraints.oneOfValues && property.constraints.oneOfValues.length ) {
Expand All @@ -87,7 +87,7 @@ export async function filterItemStatements( propertyId: PropertyId, statements:
const data: SparqlResponse = await sparqlRequest( sparql );
const validItemIds: ItemId[] = [];

for ( let i = 0; i < data.results.bindings.length; i++ ) {
for ( let i: number = 0; i < data.results.bindings.length; i++ ) {
const itemId: ItemId = data.results.bindings[ i ].item.value.replace( /^.+\/(Q\d+)$/, '$1' ) as ItemId;
validItemIds.push( itemId );
}
Expand All @@ -105,7 +105,7 @@ export async function parseItem( context: Context ): Promise<Statement[]> {

const fixedValues: FixedValue[] = getConfig( 'fixed-values' );
const references: Reference[] = getReferences( context.$wrapper );
for ( let k = 0; k < fixedValues.length; k++ ) {
for ( let k: number = 0; k < fixedValues.length; k++ ) {
const fixedValue: FixedValue = fixedValues[ k ];
const regexp: RegExp = new RegExp( fixedValue.search );
if (
Expand All @@ -122,7 +122,7 @@ export async function parseItem( context: Context ): Promise<Statement[]> {
const redirects: string[] = [];

if ( $links.length ) {
for ( let j = 0; j < $links.length; j++ ) {
for ( let j: number = 0; j < $links.length; j++ ) {
const $link: JQuery = $( $links[ j ] );
if ( $link.parents( '[data-wikidata-qualifier-id]' ).length ) {
continue;
Expand Down Expand Up @@ -191,8 +191,8 @@ export async function parseItem( context: Context ): Promise<Statement[]> {
titles: redirects
} );
if ( data.query && data.query.redirects ) {
for ( let i = 0; i < data.query.redirects.length; i++ ) {
for ( let j = 0; j < titles.length; j++ ) {
for ( let i: number = 0; i < data.query.redirects.length; i++ ) {
for ( let j: number = 0; j < titles.length; j++ ) {
const lcTitle: string = lowercaseFirst( titles[ j ].label );
const lcRedirect: string = lowercaseFirst( data.query.redirects[ i ].from );
if ( lcTitle === lcRedirect ) {
Expand All @@ -209,7 +209,7 @@ export async function parseItem( context: Context ): Promise<Statement[]> {
}
}

let statements = await getStatements( context.propertyId, titles, references );
let statements: Statement[] = await getStatements( context.propertyId, titles, references );
statements = await filterItemStatements( context.propertyId, statements );
if ( statements.length === 1 ) {
statements[ 0 ] = await addQualifiers( context.$field, statements[ 0 ] );
Expand All @@ -229,12 +229,12 @@ export async function canExportItem( propertyId: PropertyId, wikidataStatements:
const localStatements: Statement[] = await parseItem( context );
alreadyExistingItems[ propertyId ] = [];
const invalidValues: Set<ItemId> = new Set();
for ( let i = 0; i < localStatements.length; i++ ) {
for ( let i: number = 0; i < localStatements.length; i++ ) {
const localValue: ItemValue = localStatements[ i ].mainsnak.datavalue.value as ItemValue;
if ( localStatements[ i ].meta?.subclassItem ) {
invalidValues.add( localValue.id );
}
for ( let j = 0; j < wikidataStatements.length; j++ ) {
for ( let j: number = 0; j < wikidataStatements.length; j++ ) {
const existingValue: ItemValue = wikidataStatements[ j ].mainsnak.datavalue?.value as ItemValue | undefined;
if ( existingValue?.id === undefined ) {
continue;
Expand Down
20 changes: 10 additions & 10 deletions src/parser/quantity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export function parseQuantity( text: string, propertyId: PropertyId, forceIntege
};

// Sourcing circumstances (P1480) = circa (Q5727902)
const circaMatch = text.match( getConfig( 're-circa' ) );
const circaMatch: RegExpMatchArray = text.match( getConfig( 're-circa' ) );
if ( circaMatch ) {
statement.qualifiers = {
P1480: [
Expand Down Expand Up @@ -186,8 +186,8 @@ async function recognizeUnits( text: string, units: KeyValue, label?: string ):
if ( !search?.length ) {
continue;
}
for ( let j = 0; j < search.length; j++ ) {
let expr = search[ j ];
for ( let j: number = 0; j < search.length; j++ ) {
let expr: string = search[ j ];
if ( search[ j ].charAt( 0 ) !== '^' ) {
if ( search[ j ].length < 5 ) {
expr = `^${ expr }|[\\d\\s\\.]${ expr }\\.?$`;
Expand All @@ -203,7 +203,7 @@ async function recognizeUnits( text: string, units: KeyValue, label?: string ):
if ( search[ j ].charAt( 0 ) === '^' || label === undefined ) {
continue;
}
const labelRegExp = new RegExp( `\\s${ search[ j ] }:?$` );
const labelRegExp: RegExp = new RegExp( `\\s${ search[ j ] }:?$` );
if ( label.match( labelRegExp ) ) {
result.push( `http://www.wikidata.org/entity/${ itemId }` );
break;
Expand All @@ -219,7 +219,7 @@ async function removeUnitString( text: string, unit: Unit ): Promise<string> {
}
const itemId: ItemId = unit.replace( /^.+\/(Q\d+)$/, '$1' ) as ItemId;
const searches: string[] = await getOrLoadUnit( itemId );
searches.forEach( function ( search: string ) {
searches.forEach( function ( search: string ): void {
text = text.replace( search, '' );
} );
return text;
Expand All @@ -237,8 +237,8 @@ export async function prepareQuantity( context: Context ): Promise<Statement[]>
const match: string[] = text.replace( getConfig( 're-min-sec' ), '$1:$2' )
.match( /^(?:(\d+):)?(\d+):(\d+)$/ );
if ( match ) {
let amount = 0;
for ( let i = 1; i < match.length; i++ ) {
let amount: number = 0;
for ( let i: number = 1; i < match.length; i++ ) {
if ( match[ i ] !== undefined ) {
amount = amount * 60 + parseInt( match[ i ], 10 );
}
Expand All @@ -255,7 +255,7 @@ export async function prepareQuantity( context: Context ): Promise<Statement[]>
}

const forceInteger: boolean = property?.constraints?.integer || false;
for ( let u = 0; u < foundUnits.length; u++ ) {
for ( let u: number = 0; u < foundUnits.length; u++ ) {
const textWithoutUnit: string = await removeUnitString( text, foundUnits[ u ] );
let statement: Statement | void = parseQuantity( textWithoutUnit, context.propertyId, forceInteger );
if ( !statement ) {
Expand Down Expand Up @@ -300,7 +300,7 @@ export async function prepareQuantity( context: Context ): Promise<Statement[]>
const qualifierQuantitySnak: Snak = qualifierTempStatement.mainsnak;
const qualifierQuantity: QuantityValue = qualifierQuantitySnak.datavalue.value as QuantityValue;
const supportedProperties: PropertyId[] = [ 'P2076', 'P2077' ];
for ( let j = 0; j < supportedProperties.length; j++ ) {
for ( let j: number = 0; j < supportedProperties.length; j++ ) {
const supportedProperty: Property | undefined = await getOrLoadProperty( supportedProperties[ j ] );
const units: ItemId[] = supportedProperty?.units || [];
if ( units.length === 1 ) {
Expand Down Expand Up @@ -328,7 +328,7 @@ export async function prepareQuantity( context: Context ): Promise<Statement[]>
}

export function canExportQuantity( statements: Statement[], $field: JQuery ): boolean {
for ( let i = 0; i < Object.keys( statements ).length; i++ ) {
for ( let i: number = 0; i < Object.keys( statements ).length; i++ ) {
const parsedTime: TimeValue | void = createTimeValue( ( $field.text().match( /\(([^)]*\d{4})[,)\s]/ ) || [] )[ 1 ] );
if ( parsedTime && statements[ i ].qualifiers?.P585 ) {
const pointInTimeValue: TimeValue = statements[ i ].qualifiers.P585[ 0 ].datavalue.value as TimeValue;
Expand Down
Loading

0 comments on commit 31f47b7

Please sign in to comment.