All files / services/document document-factory.ts

90% Statements 81/90
80.39% Branches 41/51
95.45% Functions 21/22
89.41% Lines 76/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338                                                                    90x                   90x                         90x 90x 90x   90x 810x           810x                 9x 47x   47x 8x       1x                       9x                 11x                 4x 2x     8x                 3x                 3x   3x                 10x                 17x   17x                       11x   11x 1x     10x   10x 1x     9x   2x   1x   1x   1x   1x   1x   1x   1x         106x   106x   17x   89x         106x   17x               89x                       14x 14x   14x 98x                   14x 126x   126x 112x       14x 7x 9x   9x 8x 8x 8x   8x 7x           14x                 9x                 8x                                                     14x 14x   14x 7x     7x 7x 7x   7x   7x 7x      
import * as vscode from 'vscode';
import { Utils } from 'vscode-uri';
import { Store, VocabularyRepository } from '@faubulous/mentor-rdf';
import { RdfSyntax } from '@faubulous/mentor-rdf-parsers';
import { ISettingsService } from '@src/services/core/settings-service.interface';
import { TurtleDocument, SparqlDocument, XmlDocument } from '@src/languages';
import { PresetGraphDocument } from '@src/languages/turtle/preset-graph-document';
import { MentorVfsUri } from '@src/providers/mentor-vfs-uri';
import { IDocumentContext } from './document-context.interface';
import { ILanguageInfo } from './document-factory.interface';
import { RDF_LANGUAGE_IDS } from './document-languages';
import { getLog } from '@src/utilities/vscode/log';
 
export { RDF_LANGUAGE_IDS };
 
/**
 * Metadata about a supported file extension.
 */
export interface FileExtensionInfo {
	/**
	 * The language identifier associated with the file extension (e.g. 'turtle' for '.ttl').
	 */
	language: string;
 
	/**
	 * Indicates whether files with this extension can be loaded as triple sources into the RDF store.
	 */
	isTripleSource: boolean;
}
 
/**
 * A factory for creating RDF document contexts.
 */
export class DocumentFactory {
	private readonly _convertibleLanguages = ['ntriples', 'nquads', 'turtle', 'xml'];
 
	/**
	 * The supported languages.
	 */
	readonly supportedLanguages: Set<string>;
 
	/**
	 * The supported file extensions.
	 */
	readonly supportedExtensions: { [key: string]: FileExtensionInfo } = {
		'.ttl': { language: 'turtle', isTripleSource: true },
		'.n3': { language: 'n3', isTripleSource: true },
		'.nt': { language: 'ntriples', isTripleSource: true },
		'.nq': { language: 'nquads', isTripleSource: true },
		'.trig': { language: 'trig', isTripleSource: true },
		'.sparql': { language: 'sparql', isTripleSource: false },
		'.rq': { language: 'sparql', isTripleSource: false },
		'.rdf': { language: 'xml', isTripleSource: true },
		'.mnb': { language: 'json', isTripleSource: false }
	}
 
	constructor(
		private readonly _store: Store,
		private readonly _vocabulary: VocabularyRepository,
		private readonly _settings: ISettingsService
	) {
		const extensions = Object.keys(this.supportedExtensions);
		const languages = extensions.map(e => this.supportedExtensions[e].language);
 
		// Notebook container files (.mnb → 'json') are opened by the notebook
		// serializer, not as document contexts: create() has no 'json' case, and
		// admitting the language here would try (and fail) to create a context
		// on every edit of any JSON file.
		this.supportedLanguages = new Set(languages.filter(language => language !== 'json'));
	}
 
	/**
	 * Indicates whether a language is a triple source language, meaning that documents in this language can be loaded as RDF triples into the store.
	 * @param languageId The language ID to check (e.g. 'turtle', 'sparql').
	 * @returns `true` if the language is a triple source language, otherwise `false`.
	 */
	isTripleSourceLanguage(languageId: string): boolean {
		for (const ext in this.supportedExtensions) {
			const info = this.supportedExtensions[ext];
 
			if (info.language === languageId) {
				return info.isTripleSource;
			}
		}
 
		return false;
	}
 
	/**
	 * Indicates whether a language is one of Mentor's first-class RDF authoring languages
	 * (see {@link RDF_LANGUAGE_IDS}) — i.e. one in which resources can be authored,
	 * referenced and described. Used to gate resource-oriented editor features such as
	 * "Describe Resource".
	 * @param languageId The language ID to check (e.g. 'turtle', 'sparql').
	 * @returns `true` if the language is an RDF language, otherwise `false`.
	 */
	isRdfLanguage(languageId: string): boolean {
		return (RDF_LANGUAGE_IDS as readonly string[]).includes(languageId);
	}
 
	/**
	 * Checks if a document can be converted to another format.
	 * @param languageId The language ID of the document.
	 * @returns `true` if the document can be converted, otherwise `false`.
	 */
	isConvertibleLanguage(languageId: string): boolean {
		return this._convertibleLanguages.includes(languageId);
	}
 
	/**
	 * Gets the target languages a document can be converted to.
	 * @param sourceLanguageId The source document language ID.
	 * @returns The supported target language IDs.
	 */
	getConvertibleTargetLanguageIds(sourceLanguageId: string): string[] {
		if (!this.isConvertibleLanguage(sourceLanguageId)) {
			return [];
		}
 
		return this._convertibleLanguages.filter(languageId => languageId !== sourceLanguageId);
	}
 
	/**
	 * Checks if a file is supported by the factory.
	 * @param uri The URI of the file.
	 * @returns `true` if the file is supported, otherwise `false`.
	 */
	isSupportedFile(uri: vscode.Uri): boolean {
		return this.getDocumentLanguageId(uri) !== undefined;
	}
 
	/**
	 * Checks if a notebook file is supported by Mentor.
	 * @param uri The URI of the notebook file.
	 * @returns `true` if the notebook file is supported, otherwise `false`.
	 */
	isSupportedNotebookFile(uri: vscode.Uri): boolean {
		const extension = Utils.extname(uri).toLowerCase();
 
		return extension === '.mnb';
	}
 
	/**
	 * Checks if a file is supported by the factory.
	 * @param ext The lower-case file extension including the dot (e.g. '.ttl').
	 * @returns `true` if the file is supported, otherwise `false`.
	 */
	isSupportedExtension(ext: string): boolean {
		return this.supportedExtensions[ext] !== undefined;
	}
 
	/**
	 * Get the language ID for a file URI.
	 * @param uri The URI of the file.
	 * @returns A language ID if the file is supported, otherwise `undefined`.
	 */
	getDocumentLanguageId(uri: vscode.Uri): string | undefined {
		const extension = Utils.extname(uri).toLowerCase();
 
		return this.supportedExtensions[extension]?.language;
	}
 
	/**
	 * Loads a document and returns a document context.
	 * @param document A text document.
	 * @returns A document context.
	 */
	create(documentUri: vscode.Uri, languageId?: string): IDocumentContext {
		// If the language ID is provided, use it to create the document context
		// as this is more reliable than the file extension. For unsaved documents,
		// the file extension is not available.
		let language = languageId ?? this.getDocumentLanguageId(documentUri);
 
		if (!language) {
			throw new Error('Unable to determine the document language: ' + documentUri.toString());
		}
 
		const presetGraph = MentorVfsUri.getGraph(documentUri);
 
		if (presetGraph) {
			return new PresetGraphDocument(documentUri, presetGraph, this._store, this._vocabulary, this._settings);
		}
 
		switch (language) {
			case 'turtle':
				return new TurtleDocument(documentUri, RdfSyntax.Turtle, this._store, this._vocabulary, this._settings);
			case 'ntriples':
				return new TurtleDocument(documentUri, RdfSyntax.NTriples, this._store, this._vocabulary, this._settings);
			case 'nquads':
				return new TurtleDocument(documentUri, RdfSyntax.NQuads, this._store, this._vocabulary, this._settings);
			case 'n3':
				return new TurtleDocument(documentUri, RdfSyntax.N3, this._store, this._vocabulary, this._settings);
			case 'trig':
				return new TurtleDocument(documentUri, RdfSyntax.TriG, this._store, this._vocabulary, this._settings);
			case 'sparql':
				return new SparqlDocument(documentUri, this._store, this._vocabulary, this._settings);
			case 'xml':
				return new XmlDocument(documentUri, this._store, this._vocabulary, this._settings);
			default:
				throw new Error('Unsupported language:' + language);
		}
	}
 
	private _getTypeName(languageId: string, alias?: string): string {
		const name = alias ? alias : languageId;
 
		switch (languageId) {
			case 'sparql':
				return name + ' Query';
			default:
				return name + ' File';
		}
	}
 
	private _getIconName(languageId: string): string {
		switch (languageId) {
			case 'sparql':
				return 'sparql-file';
			case 'ntriples':
			case 'nquads':
			case 'n3':
			case 'turtle':
			case 'trig':
			case 'xml':
			case 'json':
				return 'rdf-file';
			default:
				return 'file';
		}
	}
 
	/**
	 * Retrieves language information including readable names and icons from package.json.
	 * @param factory The DocumentFactory instance.
	 * @returns An array of language information objects.
	 */
	async getSupportedLanguagesInfo(): Promise<ILanguageInfo[]> {
		const packageJson = await this._getPackageJson();
		const languageMap = new Map<string, ILanguageInfo>();
 
		for (const language of this.supportedLanguages) {
			languageMap.set(language, {
				id: language,
				name: language, // fallback name
				typeName: this._getTypeName(language),
				icon: this._getIconName(language),
				extensions: [],
				mimetypes: []
			});
		}
 
		for (const [extension, extensionInfo] of Object.entries(this.supportedExtensions)) {
			const info = languageMap.get(extensionInfo.language);
 
			if (info) {
				info.extensions.push(extension);
			}
		}
 
		if (packageJson?.contributes?.languages) {
			for (const lang of packageJson.contributes.languages) {
				const info = languageMap.get(lang.id);
 
				if (info) {
					info.name = lang.aliases?.[0] || lang.id;
					info.typeName = this._getTypeName(lang.id, info.name) || lang.id;
					info.icon = this._getIconName(lang.id);
 
					for (const mimetype of lang.mimetypes || []) {
						info.mimetypes.push(mimetype);
					}
				}
			}
		}
 
		return Array.from(languageMap.values());
	}
 
	/**
	 * Get language metadata such as the name and extensions from package.json
	 * @param languageId The language identifier.
	 * @returns A `LanguageInfo` object if the language is supported by this factory, `undefined` otherwise.
	 */
	async getSupportedLanguageInfoFromId(languageId: string): Promise<ILanguageInfo | undefined> {
		return (await this.getSupportedLanguagesInfo()).find(l => l.id === languageId);
	}
 
	/**
	 * Retrieves language information from a MIME type.
	 * @param mimetype The MIME type to look up.
	 * @returns The corresponding `LanguageInfo` object, or `undefined` if not found.
	 */
	async getSupportedLanguageInfoFromMimeType(mimetype: string): Promise<ILanguageInfo | undefined> {
		return (await this.getSupportedLanguagesInfo()).find(l => l.mimetypes.includes(mimetype));
	}
 
	/**
	 * Retrieves the language ID from a MIME type, defaulting to 'plaintext' if not found.
	 * @param mimetype The MIME type to look up.
	 * @returns The corresponding language ID, or 'plaintext' if not found.
	 */
	async getLanguageIdFromMimeType(mimetype: string): Promise<string> {
		const languageInfo = await this.getSupportedLanguageInfoFromMimeType(mimetype);
 
		if (languageInfo) {
			return languageInfo.id;
		} else if (mimetype.includes('html')) {
			return 'html';
		} else if (mimetype.includes('csv')) {
			return 'csv';
		} else {
			return 'plaintext';
		}
	}
 
	/**
	 * Helper function to read package.json from the extension.
	 * @returns The parsed package.json content.
	 */
	private async _getPackageJson(): Promise<any> {
		try {
			const extensionPath = vscode.extensions.getExtension('faubulous.mentor')?.extensionPath;
 
			if (!extensionPath) {
				throw new Error('Extension path not found');
			}
 
			const packageJsonUri = vscode.Uri.joinPath(vscode.Uri.file(extensionPath), 'package.json');
			const buffer = await vscode.workspace.fs.readFile(packageJsonUri);
			const content = new TextDecoder().decode(buffer);
 
			return JSON.parse(content);
		} catch (error) {
			getLog().warn('Could not read package.json:', error);
			return null;
		}
	}
}