Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch from Reify to SWC for ensuring compatability with older browsers. #693

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
234 changes: 234 additions & 0 deletions buildLib/commandLineHelper.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
import process from 'node:process';

/**
* @file This file handles parsing command line arguments for any custom build tools used in building opentype.js
*/

export default function createCommandLineArgumentsHandler(validArguments) {
yne marked this conversation as resolved.
Show resolved Hide resolved
const validTypes = ['json', 'string', 'number', 'boolean'];
const argumentInfo = {};
const shortArgsMap = {};
const defaultTemplate = {};
{
const inputKeys = Object.keys(validArguments);
for(let i = 0; i < inputKeys.length; i++) {
const key = inputKeys[i];
const firstCode = key[0].charCodeAt(0);
if((firstCode < 65 || firstCode > 90) && (firstCode < 97 || firstCode > 122))
continue;
const argument = validArguments[key];
if(argument.type && validTypes.includes(argument.type)){
argumentInfo[key] = {};
argumentInfo[key].type = argument.type;
argumentInfo[key].hasShortKey = argument.shortKey??(argument.type === 'boolean');
argumentInfo[key].takesParameter = (argument.type !== 'boolean'? true : argument.takesParameter??false);
argumentInfo[key].acceptsPropertySyntax = argument.propertySyntax;
if(argument.default){
defaultTemplate[key] = argument.default;
}
}
}
validArguments = null;
}
const argumentKeys = Object.keys(argumentInfo);
for(let i = 0; i < argumentKeys.length; i++) {
const key = argumentKeys[i];
if(!argumentInfo[key].hasShortKey)
continue;
let shortKey = null;
let shortKeyCandidate = key[0].toLowerCase();
for(let j = 0; j < 26; j++){
if(!shortArgsMap[shortKeyCandidate]){
shortArgsMap[shortKeyCandidate] = key;
shortKey = shortKeyCandidate;
break;
}else if(!shortArgsMap[shortKeyCandidate.toUpperCase()]){
shortArgsMap[shortKeyCandidate.toUpperCase()] = key;
shortKey = shortKeyCandidate.toUpperCase();
break;
}
shortKeyCandidate = String.fromCharCode(((shortKeyCandidate.charCodeAt(0)-95)%26)+96);
console.log(shortKeyCandidate);
}
if(!shortKey)
throw new Error(`Could not assign short key for argument: ${key}`);
}

function checkForSplitValue(value, args, index){
if(value[0] == "'"){
return value[value.length-1] !== "'";
}else if(value[0] == '"'){
return value[value.length-1] !== '"';
}
return false;
}

function parseBooleanArgument(key, args, index, options, value){
if(value !== null && !argumentInfo[key].takesParameter){
throw new Error(`Invalid option: ${key}`);
}else if(value === null && !argumentInfo[key].takesParameter){
options[key] = true;
return 0;
}else if(argumentInfo[key].takesParameter){
let increment = 0;
if(value === null && args.length > index+1){
value = args[index+1];
increment = 1;
}else if(value === null){
throw new Error(`Invalid option: ${key}`);
}else if(checkForSplitValue(value)){
do{
if(args.length <= index+increment)
throw new Error(`Unclosed option value: ${key}`);
value += ' ' + args[index+1];
increment++;
}while(checkForSplitValue(value));
value = value.slice(1,-1);
}
options[key] = value;
return increment;
}else{
throw new Error(`Invalid option: ${key}`);
}
}

function parseNumberArgument(key, args, index, options, value){
let increment = 0;
if(value === null && args.length > index+1){
value = args[index+1];
increment = 1;
}
if(value === null)
throw new Error(`Invalid option: ${key}`);
if(checkForSplitValue(value))
throw new Error(`Unclosed option value: ${key}`);
if(value.startsWith("0x")){
options[key] = parseInt(value.slice(2), 16);
}else if(value.startsWith("0o")){
options[key] = parseInt(value.slice(2), 8);
}else if(value.startsWith("0b")){
options[key] = parseInt(value.slice(2), 2);
}else{
if(value.startsWith("0d")){
options[key]=parseInt(value.slice(2),10);
} else options[key] = parseFloat(value);
}
return increment;
}

function parseStringArgument(key, args, index, options, value){
let increment = 0;
if(value === null && args.length > index+1){
value = args[index+1];
increment = 1;
}
if(value === null)
throw new Error(`Invalid option: ${key}`);
if(checkForSplitValue(value)){
do{
if(args.length <= index+increment)
throw new Error(`Unclosed option value: ${key}`);
value += ' ' + args[index+1];
increment++;
}while(checkForSplitValue(value));
value = value.slice(1,-1);
}
options[key] = value;
return increment;
}

function parseJsonArgument(key, args, index, options, value){
let increment = 0;
if(value === null && args.length > index+1){
value = args[index+1];
increment = 1;
}
if(value === null)
throw new Error(`Invalid option: ${key}`);
if(checkForSplitValue(value)){
do{
if(args.length <= index+increment)
throw new Error(`Unclosed option value: ${key}`);
value += ' ' + args[index+1];
increment++;
}while(checkForSplitValue(value));
value = value.slice(1,-1);
}
options[key] = JSON.parse(value.replaceAll("'", "\""));
return increment;
}


return function() {
const args = process.argv.slice(2);
const parsedArgs = {args: [], options: Object.assign({}, defaultTemplate)};

for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg.startsWith('--')) {
const longArg = arg.slice(2);
let key = longArg;
let value = null;
if (!argumentInfo[key.replace(/-/g, '_')]) {
let splitproperty = longArg.split("=");
if (splitproperty.length > 1) {
key = splitproperty[0];
value = splitproperty[1];
}else{
throw new Error(`Invalid option: ${key}`);
}
if(!argumentInfo[key])
throw new Error(`Invalid option: ${key}`);
if(!argumentInfo[key].acceptsPropertySyntax)
throw new Error(`Invalid property syntax for option: ${key}`);
}
if(key.indexOf('_') !== -1)
throw new Error(`Invalid option: ${key}`);
key = key.replace(/-/g, '_');
switch(argumentInfo[key].type) {
case 'boolean':
i += parseBooleanArgument(key, args, i, parsedArgs.options, value);
break;
case 'number':
i += parseNumberArgument(key, args, i, parsedArgs.options, value);
break;
case 'string':
i += parseStringArgument(key, args, i, parsedArgs.options, value);
break;
case 'json':
i += parseJsonArgument(key, args, i, parsedArgs.options, value);
break;
}
} else if (arg.startsWith('-')) {
const shortArg = arg.slice(1);
for (let j = 0; j < shortArg.length; j++) {
const key = shortArgsMap[shortArg[j]];
if (!key) {
throw new Error(`Invalid option: ${shortArg[j]}`);
}
if(argumentInfo[key].type === 'boolean'){
i += parseBooleanArgument(key, args, i, parsedArgs.options, null);
}else if(j > 0 || shortArg.length > 1){
throw new Error(`Invalid option: ${shortArg}`);
}else{
switch(argumentInfo[key].type) {
case 'number':
i += parseNumberArgument(key, args, i, parsedArgs.options, null);
break;
case 'string':
i += parseStringArgument(key, args, i, parsedArgs.options, null);
break;
case 'json':
i += parseJsonArgument(key, args, i, parsedArgs.options, null);
break;
}
}
}
}else{
parsedArgs.args.push(arg);
}
}

return parsedArgs;
}
};
127 changes: 127 additions & 0 deletions buildLib/esbuild-plugin-swc.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
This file's license:

MIT License

Copyright (c) 2021 sanyuan et al.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/**
* @file This file contains the esbuild plugin for SWC
*/

import { transform, transformSync } from '@swc/core';
import path from 'node:path';
import fs from 'node:fs/promises';
import { existsSync } from 'node:fs';

function getNodeModulesDirectoryForPath(currentDir){
let relativePath = "node_modules";
let resolvedPath = path.resolve(currentDir, relativePath);

function countSeparators(str) {
let count = 0;
for(let i = 0; i < str.length; i++) {
if(str[i] == path.sep)
count++;
}
return count;
}

while(!existsSync(resolvedPath)){
if(countSeparators(resolvedPath) <= 1){
throw new Error("Could not find node_modules directory");
}
relativePath = path.join("..", relativePath);
resolvedPath = path.resolve(currentDir, relativePath);
}
return resolvedPath;
}

function assignDeep(target, source) {
for (const key in source) {
if (source[key] instanceof Object && !(source[key] instanceof Function)) {
if (!target[key]) {
target[key] = {};
}
assignDeep(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}

export default function swcPlugin(options, isAsync) {
options = options ?? {};
isAsync = isAsync ?? true;
return {
name: 'esbuild:swc',
setup(builder) {
builder.onResolve({ filter: /\.(m?[tj]s)$/ }, (args) => {
let fullPath;
let defaultPath = path.resolve(args.resolveDir, args.path);
if(args.kind == 'import-statement'){
if(existsSync(defaultPath)){
fullPath = defaultPath;
}else{
let nodeModulesPath = getNodeModulesDirectoryForPath(args.resolveDir);
fullPath = path.join(nodeModulesPath, args.path);
}
}else{
fullPath = defaultPath;
}
return {
path: fullPath,
};
});
builder.onLoad({ filter: /\.(m?[tj]s)$/ }, async (args) => {
const code = await fs.readFile(args.path, 'utf-8');
const isTS = args.path.endsWith('.ts');
const isCoreJs = args.path.indexOf('core-js') !== -1;
const initialOptions = {
jsc: {
parser: {
syntax: isTS ? 'typescript' : 'ecmascript',
}
},
filename: args.path,
sourceMaps: true,
sourceFileName: path.relative(options.root,args.path)
};
const finalOptions = assignDeep(assignDeep({}, initialOptions), options);
if(isCoreJs){
delete finalOptions.env.mode;
}
let result;
if (isAsync) {
result = await transform(code, finalOptions);
}else{
result = transformSync(code, finalOptions);
}
return {
contents: result.code+(finalOptions.sourceMaps?`\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(result.map).toString('base64')}`:''),
loader: 'js'
};
});
}
}
}
Loading
Loading