Skip to content

Commit

Permalink
Moved ambient module generation to the template files
Browse files Browse the repository at this point in the history
  • Loading branch information
JumpLink committed Jul 19, 2024
1 parent 7713ab2 commit b77dc89
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 103 deletions.
61 changes: 2 additions & 59 deletions packages/generator-typescript/src/module-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ import {
import { writeFile, mkdir } from 'fs/promises'
import { dirname } from 'path'

import { wrapIntoAmbientModule } from './utils.js'
import { TemplateProcessor } from './template-processor.js'
import { PackageDataParser } from './package-data-parser.js'
import { NpmPackage } from './npm-package.js'
Expand Down Expand Up @@ -1604,71 +1603,16 @@ export class ModuleGenerator extends FormatGenerator<string[]> {
}
}

/**
* Used to only generate ambient types for a module.
* Used if package.json support is disabled
*/
protected async exportModuleAmbientOnly(): Promise<void> {
const { namespace: girModule } = this
const namespaceContent = await this.generateNamespace(girModule)

if (!namespaceContent) {
this.log.error('Failed to generate namespace')
return
}

// Ambient module with version
const output = wrapIntoAmbientModule(girModule.namespace, girModule.version, namespaceContent, undefined, {
protocol: 'gi',
})

// Ambient module without version
if (!this.config.onlyVersionPrefix) {
const reexport = [
`import ${girModule.importNamespace} from 'gi://${girModule.namespace}?version=${girModule.version}';`,
`export default ${girModule.importNamespace};`,
]
wrapIntoAmbientModule(girModule.namespace, null, reexport, output, { protocol: 'gi' })
}

const target = `${girModule.importName}.d.ts`

const formatter = this.dependencyManager.getFormatter('dts')

let contents!: string
try {
contents = this.config.noPrettyPrint ? output.join('\n') : await formatter.format(output.join('\n'))
} catch (error) {
this.log.error('Failed to format output...', error)
contents = output.join('\n')
}

if (this.config.outdir) {
const outputPath = this.moduleTemplateProcessor.getOutputPath(this.config.outdir, target)

if (this.config.verbose) {
this.log.debug(`Outputting ${target} to ${outputPath}`)
}

// write template result file
await mkdir(dirname(outputPath), { recursive: true })
await writeFile(outputPath, contents, { encoding: 'utf8', flag: 'w' })
} else {
this.log.log(contents)
}
}

async exportModuleTS(): Promise<void> {
const { namespace: girModule } = this
const output = await this.generateNamespace(girModule)
const target = `${girModule.importName}.d.ts`

if (!output) {
this.log.error('Failed to generate namespace')
return
}

const target = `${girModule.importName}.d.ts`

const formatter = this.dependencyManager.getFormatter('dts')

let contents!: string
Expand Down Expand Up @@ -1843,7 +1787,6 @@ export class ModuleGenerator extends FormatGenerator<string[]> {
await this.exportModuleIndexTS()
await this.exportModuleIndexJS()

await this.exportModuleTS()
await this.exportModuleJS(girModule)

await this.exportModuleAmbientTS(girModule)
Expand All @@ -1855,7 +1798,7 @@ export class ModuleGenerator extends FormatGenerator<string[]> {
const pkg = new NpmPackage(this.config, this.dependencyManager, girModule, girModule.transitiveDependencies)
await pkg.exportNPMPackage()
} else {
await this.exportModuleAmbientOnly()
await this.exportModuleTS()
}
}
}
31 changes: 15 additions & 16 deletions packages/generator-typescript/src/type-definition-generator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Generator } from '@ts-for-gir/generator-base'
import { Logger, DependencyManager, NSRegistry, OptionsGeneration, GirModule } from '@ts-for-gir/lib'

import { wrapIntoAmbientModule } from './utils.js'
import { TemplateProcessor } from './template-processor.js'
import { PackageDataParser } from './package-data-parser.js'
import { NpmPackage } from './npm-package.js'
Expand Down Expand Up @@ -76,25 +75,25 @@ export class TypeDefinitionGenerator implements Generator {
await templateProcessor.write(gjsContent.prepend + '\n' + gjsContent.append, config.outdir, 'gjs.d.ts')

const gettextContent = await templateProcessor.load('gjs/gettext.d.ts')
const gettextContentAmbient = wrapIntoAmbientModule('gettext', null, [
gettextContent.prepend,
gettextContent.append,
])
await templateProcessor.write(gettextContentAmbient.join('\n'), config.outdir, 'gettext.d.ts')
await templateProcessor.write(
gettextContent.prepend + '\n' + gettextContent.append,
config.outdir,
'gettext.d.ts',
)

const systemContent = await templateProcessor.load('gjs/system.d.ts')
const systemContentAmbient = wrapIntoAmbientModule('system', null, [
systemContent.prepend,
systemContent.append,
])
await templateProcessor.write(systemContentAmbient.join('\n'), config.outdir, 'system.d.ts')
await templateProcessor.write(
systemContent.prepend + '\n' + systemContent.append,
config.outdir,
'system.d.ts',
)

const cairoContent = await templateProcessor.load('gjs/cairo.d.ts')
const cairoContentAmbient = wrapIntoAmbientModule('cairo', null, [
cairoContent.prepend,
cairoContent.append,
])
await templateProcessor.write(cairoContentAmbient.join('\n'), config.outdir, 'cairo.d.ts')
await templateProcessor.write(
cairoContent.prepend + '\n' + cairoContent.append,
config.outdir,
'cairo.d.ts',
)

// Additional DOM types supported by GJS
const domContent = await templateProcessor.load('gjs/dom.d.ts')
Expand Down
22 changes: 0 additions & 22 deletions packages/generator-typescript/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,3 @@ import { dirname, resolve } from 'path'
const __filename = fileURLToPath(import.meta.url)
// Get __dirname on ESM, resolve to the root directory of this package
export const __dirname = resolve(dirname(__filename), '..')

export const mergeLargeStringArrays = (target: string[], source: string[], chunkSize: number = 1000): string[] => {
for (let i = 0; i < source.length; i += chunkSize) {
target.push(...source.slice(i, i + chunkSize))
}
return target
}

export const wrapIntoAmbientModule = (
namespace: string,
version: string | null,
content: string[],
target: string[] = [],
options: { protocol?: string } = {},
): string[] => {
target.push(
`declare module '${options.protocol ? `${options.protocol}://` : ''}${namespace}${version ? `?version=${version}` : ''}' {`,
)
mergeLargeStringArrays(target, content)
target.push('}')
return target
}
8 changes: 8 additions & 0 deletions packages/generator-typescript/templates/gjs/cairo.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
<%_ if(!package){ -%>
declare module 'cairo' {
<% } -%>

// TODO: See ./cairo-1.0.d.ts
<%- package ? 'declare' : '' %> const Cairo: any;

export default Cairo;

<%_ if(!package){ -%>
}
<% } -%>
9 changes: 8 additions & 1 deletion packages/generator-typescript/templates/gjs/gettext.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
<%_ if(!package){ -%>
declare module 'gettext' {
<% } -%>
export enum LocaleCategory {
ALL,
COLLATE,
Expand Down Expand Up @@ -38,4 +41,8 @@ export function domain(domainName: string): {
domain: typeof domain,
}

export default Gettext
export default Gettext

<%_ if(!package){ -%>
}
<% } -%>
8 changes: 4 additions & 4 deletions packages/generator-typescript/templates/gjs/gjs.d.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
<%_ const GObject = await dep.get('GObject', '2.0') _%>
<%_ const GLib = await dep.get('GLib', '2.0') _%>
<%_ if(!package){ -%>
<%_ if(GObject){ -%>
<%_ if(GObject){ -%>
/// <reference path="./gobject-2.0.d.ts" />
<% } -%>
<%_ if(GLib){ -%>
<% } -%>
<%_ if(GLib){ -%>
/// <reference path="./glib-2.0.d.ts" />
<% } -%>
<% } -%>
/// <reference path="./gettext.d.ts" />
/// <reference path="./system.d.ts" />
/// <reference path="./cairo.d.ts" />
Expand Down
10 changes: 9 additions & 1 deletion packages/generator-typescript/templates/gjs/system.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
/// <reference path="./gobject-2.0.d.ts" />
<%_ } -%>

<%_ if(!package){ -%>
declare module 'system' {
<% } -%>

<%- GObject ? GObject.importDef : '' %>

/**
Expand Down Expand Up @@ -176,4 +180,8 @@ export function exit(code: number): void
exit: typeof exit,
}

export default System
export default System

<%_ if(!package){ -%>
}
<% } -%>
10 changes: 10 additions & 0 deletions packages/generator-typescript/templates/module.append.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,11 @@
<%_ if(!package){ -%>
}

<%_ if(!onlyVersionPrefix){ -%>
declare module 'gi://<%- girModule.namespace %>' {
import <%- girModule.importNamespace %> from 'gi://<%- girModule.namespace %>?version=<%- girModule.version %>';
export default <%- girModule.importNamespace %>;
}
<% } -%>
<% } -%>
// END
4 changes: 4 additions & 0 deletions packages/generator-typescript/templates/module.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@
* These type definitions are automatically generated, do not edit them by hand.
* If you found a bug fix it in `<%= APP_NAME %>` or create a bug report on <%= APP_SOURCE %>
*/

<%_ if(!package){ -%>
declare module 'gi://<%- girModule.namespace %>?version=<%- girModule.version %>' {
<% } -%>
14 changes: 14 additions & 0 deletions packages/lib/src/utils/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,17 @@ export const underscores = (str: string): string => {
export const generateIndent = (indents = 1, spaceForIndent = 4): string => {
return ' '.repeat(indents * spaceForIndent)
}

/**
* Merge a large array of strings by using a smaller chunk size
* @param target The target array to merge into
* @param source The source array to merge from
* @param chunkSize The size of the chunks to merge
* @returns The merged array
*/
export const mergeLargeStringArray = (target: string[], source: string[], chunkSize: number = 1000): string[] => {
for (let i = 0; i < source.length; i += chunkSize) {
target.push(...source.slice(i, i + chunkSize))
}
return target
}

0 comments on commit b77dc89

Please sign in to comment.