Skip to content

Commit

Permalink
Publish to JSR
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Feb 9, 2025
1 parent 212c282 commit f6c4ed2
Show file tree
Hide file tree
Showing 7 changed files with 187 additions and 3 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,5 @@ packages/babel-standalone/babel.min.js.map
.module-type

*.tsbuildinfo

deno.json
2 changes: 1 addition & 1 deletion .yarn/plugins/@yarnpkg/plugin-conditions.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ ${u.esmHeader}
export const { ${U.join(", ")} } = bool(process.env[${JSON.stringify(i)}]) ? ${d.imported} : ${u.imported};
${x&&`export default (bool(process.env[${JSON.stringify(i)}]) ? ${d.imported} : ${u.imported}).default;`}
`}return X(t,e.project,C,m,y)}};var J=g("@yarnpkg/core");var ge=Function.call.bind(Object.prototype.hasOwnProperty);async function ee(n,t){let{project:e}=n,i=!1;for(let o of q){let s=n.manifest.getForScope(o).values();for(let r of s){if(!k(r.range))continue;let{test:a,consequent:c,alternate:l}=j(r),p=H(e,a)?c:l,d=J.structUtils.stringifyIdent(r),u=o==="dependencies"&&!t.dependencies[d]&&t.optionalDependencies?.[d]?"optionalDependencies":o;p?(t[u][d]=p,n.manifest.raw[u][d]=p,n.manifest[o].set(r.identHash,J.structUtils.makeDescriptor(r,p))):(delete t[u][d],delete n.manifest.raw[u][d],n.manifest[o].delete(r.identHash)),i=!0}}if(ge(t,"conditions")){i=!0;let o=t.conditions;for(let[s,[r,a]]of Object.entries(o)){let c=H(e,s)?r:a;if(c)for(let[l,p]of Object.entries(c))p===null?delete t[l]:t[l]=p}delete t.conditions}i&&await n.project.configuration.triggerHook(o=>o.beforeWorkspacePacking,n,t)}var h=g("@yarnpkg/core"),te=g("@yarnpkg/cli"),w=g("clipanion"),ne=pe(g("typanion"));var he=Function.call.bind(Object.prototype.hasOwnProperty),oe=(n,t,...e)=>he(n,t)&&(e.length===0||oe(n[t],...e)),E=class extends te.BaseCommand{constructor(){super(...arguments);this.condition=w.Option.String({required:!0});this.true=w.Option.Boolean("--true",!1);this.false=w.Option.Boolean("--false",!1)}async execute(){let{project:e,workspace:i,cache:o,configuration:s}=await this.getRoot();T(e,this.condition);let r=this.false?!1:this.true?!0:H(e,this.condition);for(let c of this.nestedWorkspaces(i,e))this.materializeCondition(r,c);let a=await h.StreamReport.start({configuration:s,stdout:this.context.stdout,includeLogs:!0},async c=>{await e.resolveEverything({cache:o,report:c})});if(a.hasErrors())return a.exitCode();await e.persist()}*nestedWorkspaces(e,i){yield e;for(let o of e.workspacesCwds){let s=i.workspacesByCwd.get(o);s&&(yield*this.nestedWorkspaces(s,i))}}materializeCondition(e,i){for(let s of q){let r=i.manifest.getForScope(s).values();for(let a of r){if(!k(a.range))continue;let{test:c,consequent:l,alternate:p}=j(a);if(c!==this.condition)continue;let d=e?l:p;d?i.manifest[s].set(a.identHash,h.structUtils.makeDescriptor(a,d)):i.manifest[s].delete(a.identHash)}}let o=i.manifest.raw;if(oe(o,"conditions",this.condition)){let[s,r]=o.conditions[this.condition],a=e?s:r;if(a)for(let[c,l]of Object.entries(a))l===null?delete o[c]:o[c]=l;Object.keys(o.conditions).length===1?delete o.conditions:delete o.conditions[this.condition]}}async getRoot(){let e=await h.Configuration.find(this.context.cwd,this.context.plugins),[{project:i,workspace:o},s]=await Promise.all([h.Project.find(e,this.context.cwd),h.Cache.find(e,{immutable:!0})]);return{configuration:e,project:i,workspace:o,cache:s}}};E.paths=[["condition","materialize"]],E.usage=w.Command.Usage({description:"Evaluate and replace a condition in package.json files",details:"\n This command will replace all the occurrences of `<condition>` in the current workspace and in nested workspaces.\n\n The value of the condition (`true` or `false`) is based on the following sources, in descending priority order:\n\n - the `--true` or `--false` option;\n - the `<condition>` environment variable;\n - the default value specified in the Yarn configuration;\n - `false` by default.\n "}),E.schema=[ne.hasMutuallyExclusiveKeys(["true","false"])];var ye={configuration:K,commands:[E],fetchers:[_],resolvers:[I],hooks:{beforeWorkspacePacking:ee}};return de(ke);})();
`}return X(t,e.project,C,m,y)}};var J=g("@yarnpkg/core");var ge=Function.call.bind(Object.prototype.hasOwnProperty);async function ee(n,t){let{project:e}=n,i=!1;for(let o of q){let s=n.manifest.getForScope(o).values();for(let r of s){if(!k(r.range))continue;let{test:a,consequent:c,alternate:l}=j(r),p=H(e,a)?c:l,d=J.structUtils.stringifyIdent(r),u=o==="dependencies"&&!t.dependencies[d]&&t.optionalDependencies?.[d]?"optionalDependencies":o;p?(t[u][d]=p,n.manifest.raw[u][d]=p,n.manifest[o].set(r.identHash,J.structUtils.makeDescriptor(r,p))):(delete t[u][d],delete n.manifest.raw[u][d],n.manifest[o].delete(r.identHash)),i=!0}}if(ge(t,"conditions")){i=!0;let o=t.conditions;for(let[s,[r,a]]of Object.entries(o)){let c=H(e,s)?r:a;if(c)for(let[l,p]of Object.entries(c))p===null?delete t[l]:t[l]=p}delete t.conditions}i&&await n.project.configuration.triggerHook(o=>o.beforeWorkspacePacking,n,t)}var h=g("@yarnpkg/core"),te=g("@yarnpkg/cli"),w=g("clipanion"),ne=pe(g("typanion"));var he=Function.call.bind(Object.prototype.hasOwnProperty),oe=(n,t,...e)=>he(n,t)&&(e.length===0||oe(n[t],...e)),E=class extends te.BaseCommand{constructor(){super(...arguments);this.condition=w.Option.String({required:!0});this.true=w.Option.Boolean("--true",!1);this.false=w.Option.Boolean("--false",!1)}async execute(){let{project:e,workspace:i,cache:o,configuration:s}=await this.getRoot();T(e,this.condition);let r=this.false?!1:this.true?!0:H(e,this.condition);for(let c of this.nestedWorkspaces(i,e))this.materializeCondition(r,c);let a=await h.StreamReport.start({configuration:s,stdout:this.context.stdout,includeLogs:!0},async c=>{await e.resolveEverything({cache:o,report:c})});if(a.hasErrors())return a.exitCode();await e.persist()}*nestedWorkspaces(e,i){yield e;for(let o of e.workspacesCwds){let s=i.workspacesByCwd.get(o);s&&(yield*this.nestedWorkspaces(s,i))}}materializeCondition(e,i){for(let s of q){let r=i.manifest.getForScope(s).values();for(let a of r){if(!k(a.range))continue;let{test:c,consequent:l,alternate:p}=j(a);if(c!==this.condition)continue;let d=e?l:p;d?i.manifest[s].set(a.identHash,h.structUtils.makeDescriptor(a,d)):i.manifest[s].delete(a.identHash)}}let o=i.manifest.raw;if(oe(o,"conditions",this.condition)){let[s,r]=o.conditions[this.condition],a=e?s:r;if(a)for(let[c,l]of Object.entries(a))l===null?delete o[c]:o[c]=l;Object.keys(o.conditions).length===1?delete o.conditions:delete o.conditions[this.condition]}}async getRoot(){let e=await h.Configuration.find(this.context.cwd,this.context.plugins),[{project:i,workspace:o},s]=await Promise.all([h.Project.find(e,this.context.cwd),h.Cache.find(e,{immutable:!0})]);return{configuration:e,project:i,workspace:o,cache:s}}};E.paths=[["condition","materialize"]],E.usage=w.Command.Usage({description:"Evaluate and replace a condition in package.json files",details:"\n This command will replace all the occurrences of `<condition>` in the current workspace and in nested workspaces.\n\n The value of the condition (`true` or `false`) is based on the following sources, in descending priority order:\n\n - the `--true` or `--false` option;\n - the `<condition>` environment variable;\n - the default value specified in the Yarn configuration;\n - `false` by default.\n "}),E.schema=[];var ye={configuration:K,commands:[E],fetchers:[_],resolvers:[I],hooks:{beforeWorkspacePacking:ee}};return de(ke);})();
return plugin;
}
};
9 changes: 9 additions & 0 deletions Gulpfile.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,12 @@ function buildRollup(packages, buildStandalone) {
) {
return;
}
if (
warning.exporter.endsWith("polyfill-node.module.js") &&
warning.binding === "createRequire"
) {
return;
}
}

// We use console.warn here since it prints more info than just "warn",
Expand Down Expand Up @@ -483,6 +489,9 @@ function buildRollup(packages, buildStandalone) {

const outputFile = path.join(src, dest, filename || "index.js");
await bundle.write({
banner: outputFile.endsWith("index.js")
? `/* @ts-self-types="./index.d.ts" */`
: null,
esModule: true,
file: outputFile,
format,
Expand Down
23 changes: 23 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ module.exports = function (api) {
["@babel/preset-typescript", presetTsOpts],
],
plugins: [
jsrCommentPlugin,

["@babel/transform-object-rest-spread", { useBuiltIns: true }],

convertESM ? "@babel/transform-export-namespace-from" : null,
Expand Down Expand Up @@ -1198,3 +1200,24 @@ function pluginGeneratorOptimization({ types: t }) {
},
};
}

/**
* @param {import("@babel/core")} pluginAPI
* @returns {import("@babel/core").PluginObject}
*/
function jsrCommentPlugin({ types: t }) {
return {
post(file) {
const dtsFilename = pathUtils
.basename(this.filename)
.replace(/\.[mc]?ts/, ".d.ts");

t.addComment(
file.ast.program,
"leading",
` @ts-self-types=${JSON.stringify("./" + dtsFilename)} `,
false
);
},
};
}
28 changes: 28 additions & 0 deletions jsr-script.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const token = "jsrp_yBNa3hql5CZ32pdZbtHydK3YL8xbB3jWHew";

const allPackages = (
await import("./deno.json", { with: { type: "json" } })
).default.workspace.map(pkg =>
pkg
.split("/")
.at(-1)
.replace(/^babel-/, "")
);

for (const pkgName of allPackages) {
const res = await fetch(
"https://api.jsr.io/scopes/babel-test-6ae45912/packages",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
body: JSON.stringify({ package: pkgName }),
}
);
if (res.status !== 409) {
console.log(res.status, await res.text());
}
console.log(".");
}
3 changes: 1 addition & 2 deletions packages/babel-core/src/config/files/module-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,7 @@ You are using a ${ext} config file, but Babel only supports transpiling .cts con

function getTSPreset(filepath: string) {
try {
// eslint-disable-next-line import/no-extraneous-dependencies
return require("@babel/preset-typescript");
return require("@babel/preset-typescript" + "");
} catch (error) {
if (error.code !== "MODULE_NOT_FOUND") throw error;

Expand Down
123 changes: 123 additions & 0 deletions scripts/generators/deno-json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { glob } from "glob";
import { repoRoot } from "$repo-utils";
import { existsSync, readFileSync, writeFileSync } from "fs";
import path from "path";

const packages = glob
.sync("./packages/*", {
cwd: repoRoot,
absolute: true,
})
.filter(packageDir => {
return existsSync(path.join(packageDir, "package.json"));
});

const allPackages = [];

const babelVersion = `0.0.1-${
JSON.parse(readFileSync(path.join(repoRoot, "package.json"), "utf8"))
.version_babel8
}`;

for (const packageDir of packages) {
if (
packageDir.includes("babel-runtime-corejs2") ||
packageDir.includes("babel-cli") ||
packageDir.includes("babel-node")
) {
continue;
}

const packageJson = JSON.parse(
readFileSync(path.join(packageDir, "package.json"), "utf8")
);

if (packageJson.private) {
continue;
}

allPackages.push(packageDir);

const imports = {};
takeDeps(imports, packageJson.dependencies);
takeDeps(imports, packageJson.peerDependencies);

const denoJson = {
name: jsrify(packageJson.name),
version: babelVersion,
exports: objectMap(packageJson.exports, (values, key) => {
if (!Array.isArray(values)) values = [values];
for (let value of values) {
if (typeof value === "object") {
value = value.default;
}
if (typeof value === "string") {
if (value === "./regenerator/*.js") return undefined;
if (value === "./regenerator/") return undefined;
if (value === "./core-js/*.js") return undefined;
if (value === "./core-js/") return undefined;
if (value === "./core-js-stable/*.js") return undefined;
if (value === "./core-js-stable/") return undefined;
return value;
}
}
throw new Error(`Unexpected exports value for ${key} in ${packageDir}`);
}),
imports,
publish: {
exclude: [
"test/",
"!lib/",
packageDir.includes("babel-runtime") ? "!helpers/" : null,
packageDir.includes("babel-runtime") ? "!core-js/" : null,
packageDir.includes("babel-runtime") ? "!core-js-stable/" : null,
packageDir.includes("babel-standalone") ? "!babel.js/" : null,
packageDir.includes("babel-standalone") ? "!babel.min.js/" : null,
].filter(Boolean),
},
};

writeFileSync(
path.join(packageDir, "deno.json"),
JSON.stringify(denoJson, null, 2) + "\n"
);
}

writeFileSync(
path.join(repoRoot, "deno.json"),
JSON.stringify({ workspace: allPackages }, null, 2) + "\n"
);

function objectMap(obj, cb) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, cb(v, k)]));
}

function jsrify(npmName) {
// prettier-ignore
const [/* scope */ , name] = npmName.split("/");
return `@babel-test-6ae45912/${name.slice(0, 58)}`;
}

function takeDeps(imports, dependencies) {
if (!dependencies) return;

// eslint-disable-next-line prefer-const
for (let [name, version] of Object.entries(dependencies)) {
if (version.startsWith("condition:")) {
const match =
/condition:\s*\w+\s*\?\s*(?:(?<ifTrue>[\w.^~*]+)\s*)?:\s*(?:[\w.^~*]+\s*)?/.exec(
version
);
if (!match) {
throw new Error(`Invalid condition: ${version}`);
}
if (!match.groups.ifTrue) continue;
version = match.groups.ifTrue;
}
if (version.startsWith("workspace:")) {
imports[name] = `jsr:${jsrify(name)}@${babelVersion}`;
} else {
imports[name] = `npm:${name}@${version}`;
}
}
}

0 comments on commit f6c4ed2

Please sign in to comment.