@batijs/build 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @batijs/build
2
+
3
+ WIP
@@ -0,0 +1,107 @@
1
+ import {
2
+ evalCondition
3
+ } from "./chunk-U7QQNTGA.js";
4
+ import {
5
+ lazyfy
6
+ } from "./chunk-5XFUXMWM.js";
7
+
8
+ // src/parse.ts
9
+ import recast, { print, prettyPrint, types } from "recast";
10
+ import { createRequire } from "module";
11
+ var require2 = createRequire(import.meta.url);
12
+ function ast(code) {
13
+ return recast.parse(code, {
14
+ parser: require2("recast/parsers/typescript")
15
+ });
16
+ }
17
+ function simpleAstExpression(code) {
18
+ return ast(code).body[0];
19
+ }
20
+ var metaAst = lazyfy({
21
+ VIKE_FRAMEWORK: () => simpleAstExpression("import.meta.VIKE_FRAMEWORK"),
22
+ VIKE_DATABASE: () => simpleAstExpression("import.meta.VIKE_DATABASE")
23
+ });
24
+ function transformAst(tree, meta) {
25
+ const imports = /* @__PURE__ */ new Map();
26
+ const identifiers = /* @__PURE__ */ new Set();
27
+ types.visit(tree, {
28
+ visitIdentifier(path) {
29
+ if (path.value.name === "VIKE_REMOVE") {
30
+ if (!path.parent) {
31
+ throw new Error("TODO");
32
+ }
33
+ if (!types.namedTypes.ArrayExpression.check(path.parent?.parent?.value)) {
34
+ throw new Error("TODO: Not supported");
35
+ }
36
+ path.parent.prune();
37
+ this.traverse(path);
38
+ return;
39
+ }
40
+ if (types.namedTypes.ImportDefaultSpecifier.check(path.parent.value) || types.namedTypes.ImportSpecifier.check(path.parent.value)) {
41
+ let importParent = path.parent;
42
+ while (importParent.value && importParent.value.type !== "ImportDeclaration") {
43
+ importParent = importParent.parent;
44
+ }
45
+ imports.set(path.value.name, importParent);
46
+ } else {
47
+ identifiers.add(path.value.name);
48
+ }
49
+ this.traverse(path);
50
+ },
51
+ visitConditionalExpression(path) {
52
+ this.visitIfStatement(path);
53
+ },
54
+ visitIfStatement(path) {
55
+ let found = false;
56
+ this.traverse(path.get("test"), {
57
+ visitMemberExpression(path2) {
58
+ if (print(path2.value).code.startsWith("import.meta.VIKE_")) {
59
+ found = true;
60
+ }
61
+ this.traverse(path2);
62
+ }
63
+ });
64
+ if (!found) {
65
+ this.traverse(path);
66
+ return;
67
+ }
68
+ if (!evalCondition(print(path.value.test).code, meta)) {
69
+ if (path.value.alternate) {
70
+ if (types.namedTypes.BlockStatement.check(path.value.alternate)) {
71
+ path.replace(...path.value.alternate.body);
72
+ } else {
73
+ path.replace(path.value.alternate);
74
+ }
75
+ } else {
76
+ path.prune();
77
+ }
78
+ } else {
79
+ if (types.namedTypes.BlockStatement.check(path.value.consequent)) {
80
+ path.replace(...path.value.consequent.body);
81
+ } else {
82
+ path.replace(path.value.consequent);
83
+ }
84
+ }
85
+ this.traverse(path.parent ? path.parent : path);
86
+ }
87
+ });
88
+ const importsToRemove = new Set(
89
+ Array.from(imports.entries()).filter(([name]) => !identifiers.has(name)).map(([, node]) => node)
90
+ );
91
+ importsToRemove.forEach((node) => node.prune());
92
+ return tree;
93
+ }
94
+ function transform(tree, meta) {
95
+ return prettyPrint(transformAst(tree, meta), {
96
+ tabWidth: 2,
97
+ reuseWhitespace: false,
98
+ wrapColumn: 120
99
+ }).code;
100
+ }
101
+
102
+ export {
103
+ ast,
104
+ metaAst,
105
+ transformAst,
106
+ transform
107
+ };
@@ -0,0 +1,24 @@
1
+ // src/utils.ts
2
+ function lazyGetter(obj, key, getter) {
3
+ Object.defineProperty(obj, key, {
4
+ enumerable: false,
5
+ configurable: true,
6
+ get() {
7
+ delete this[key];
8
+ this[key] = getter();
9
+ return this[key];
10
+ }
11
+ });
12
+ }
13
+ function lazyfy(obj) {
14
+ const ret = {};
15
+ for (const [k, getter] of Object.entries(obj)) {
16
+ lazyGetter(ret, k, getter);
17
+ }
18
+ return ret;
19
+ }
20
+
21
+ export {
22
+ lazyGetter,
23
+ lazyfy
24
+ };
@@ -0,0 +1,26 @@
1
+ // src/eval.ts
2
+ import ts from "typescript";
3
+ function evalCondition(obj, meta = {}) {
4
+ obj = obj.replaceAll("import.meta", "VIKE_META");
5
+ obj = `var VIKE_META = ${JSON.stringify(meta)};(${obj})`;
6
+ obj = ts.transpile(obj, {
7
+ strict: true,
8
+ allowJs: true,
9
+ checkJs: true,
10
+ esModuleInterop: true,
11
+ forceConsistentCasingInFileNames: true,
12
+ resolveJsonModule: true,
13
+ skipLibCheck: true,
14
+ sourceMap: false,
15
+ module: ts.ModuleKind.ESNext,
16
+ moduleResolution: ts.ModuleResolutionKind.Node10,
17
+ target: ts.ScriptTarget.ES2020,
18
+ lib: ["DOM", "DOM.Iterable", "ESNext"],
19
+ types: ["@types/node"]
20
+ });
21
+ return (0, eval)(obj);
22
+ }
23
+
24
+ export {
25
+ evalCondition
26
+ };
package/dist/eval.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ declare function evalCondition(obj: string, meta?: VikeMeta): any;
2
+
3
+ export { evalCondition };
package/dist/eval.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ evalCondition
3
+ } from "./chunk-U7QQNTGA.js";
4
+ export {
5
+ evalCondition
6
+ };
package/dist/exec.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ declare function main(options: {
2
+ dist: string;
3
+ }, meta: VikeMeta): Promise<void>;
4
+
5
+ export { main as default };
package/dist/exec.js ADDED
@@ -0,0 +1,103 @@
1
+ import {
2
+ ast,
3
+ transform
4
+ } from "./chunk-3EUYSS5H.js";
5
+ import "./chunk-U7QQNTGA.js";
6
+ import "./chunk-5XFUXMWM.js";
7
+
8
+ // src/exec.ts
9
+ import { readFile, opendir, copyFile, mkdir, writeFile, unlink } from "fs/promises";
10
+ import path from "path";
11
+ import { fileURLToPath } from "url";
12
+ var __filename = fileURLToPath(import.meta.url);
13
+ var __dirname = path.dirname(__filename);
14
+ var __files = path.resolve(__dirname, "..", "files");
15
+ function evalDirCondition(obj, meta) {
16
+ obj = obj.replaceAll("VIKE_", "VIKE_META.VIKE_");
17
+ obj = `var VIKE_META = ${JSON.stringify(meta)};(${obj})`;
18
+ return (0, eval)(obj);
19
+ }
20
+ function shouldWalkDir(dirname, meta) {
21
+ if (!dirname.includes("VIKE_"))
22
+ return true;
23
+ return evalDirCondition(dirname, meta);
24
+ }
25
+ function toDist(filepath, dist) {
26
+ const split = filepath.split(path.sep).filter((p) => !p.includes("VIKE_"));
27
+ split[split.length - 1] = split[split.length - 1].replace(/^\$(.*)\.ts$/, "$1");
28
+ return split.join(path.sep).replace(__files, dist);
29
+ }
30
+ async function safeCopyFile(source, destination) {
31
+ const destinationDir = path.dirname(destination);
32
+ await mkdir(destinationDir, {
33
+ recursive: true
34
+ });
35
+ await copyFile(source, destination);
36
+ }
37
+ async function safeWriteFile(destination, content) {
38
+ const destinationDir = path.dirname(destination);
39
+ await mkdir(destinationDir, {
40
+ recursive: true
41
+ });
42
+ await writeFile(destination, content, { encoding: "utf-8" });
43
+ }
44
+ async function* walk(dir, meta) {
45
+ for await (const d of await opendir(dir)) {
46
+ const entry = path.join(dir, d.name);
47
+ if (d.isDirectory()) {
48
+ if (shouldWalkDir(d.name, meta)) {
49
+ yield* walk(entry, meta);
50
+ }
51
+ } else if (d.isFile())
52
+ yield entry;
53
+ }
54
+ }
55
+ function transformFileAfterExec(filepath, fileContent) {
56
+ const parsed = path.parse(filepath);
57
+ switch (parsed.ext) {
58
+ case ".json":
59
+ return JSON.stringify(fileContent, null, 2);
60
+ default:
61
+ throw new Error(`Unsupported extension ${parsed.ext} (${filepath})`);
62
+ }
63
+ }
64
+ async function main(options, meta) {
65
+ for await (const p of walk(__files, meta)) {
66
+ const target = toDist(p, options.dist);
67
+ if (p.match(/\.[tj]sx?$/)) {
68
+ let code;
69
+ try {
70
+ const tree = ast(await readFile(p, { encoding: "utf8" }));
71
+ code = transform(tree, meta);
72
+ } catch (e) {
73
+ console.error(`File: ${p}`);
74
+ throw e;
75
+ }
76
+ const parsed = path.parse(p);
77
+ if (parsed.name.startsWith("$")) {
78
+ const tmpfile = path.join(
79
+ parsed.dir,
80
+ `${parsed.name}.${(/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-")}${parsed.ext}`
81
+ );
82
+ let fileContent = null;
83
+ try {
84
+ await writeFile(tmpfile, code, { encoding: "utf-8" });
85
+ const f = await import(tmpfile);
86
+ fileContent = transformFileAfterExec(target, await f.default());
87
+ } finally {
88
+ await unlink(tmpfile);
89
+ }
90
+ if (fileContent !== null) {
91
+ await safeWriteFile(target, fileContent);
92
+ }
93
+ } else {
94
+ await safeWriteFile(target, code);
95
+ }
96
+ } else {
97
+ await safeCopyFile(p, target);
98
+ }
99
+ }
100
+ }
101
+ export {
102
+ main as default
103
+ };
@@ -0,0 +1,11 @@
1
+ import recast from 'recast';
2
+
3
+ declare function ast(code: string): any;
4
+ declare const metaAst: {
5
+ VIKE_FRAMEWORK: recast.types.namedTypes.ExpressionStatement;
6
+ VIKE_DATABASE: recast.types.namedTypes.ExpressionStatement;
7
+ };
8
+ declare function transformAst(tree: ReturnType<typeof ast>, meta: VikeMeta): any;
9
+ declare function transform(tree: ReturnType<typeof ast>, meta: VikeMeta): string;
10
+
11
+ export { ast, metaAst, transform, transformAst };
package/dist/parse.js ADDED
@@ -0,0 +1,14 @@
1
+ import {
2
+ ast,
3
+ metaAst,
4
+ transform,
5
+ transformAst
6
+ } from "./chunk-3EUYSS5H.js";
7
+ import "./chunk-U7QQNTGA.js";
8
+ import "./chunk-5XFUXMWM.js";
9
+ export {
10
+ ast,
11
+ metaAst,
12
+ transform,
13
+ transformAst
14
+ };
@@ -0,0 +1,6 @@
1
+ import { ast } from './parse.js';
2
+ import 'recast';
3
+
4
+ declare function assertEquivalentAst(ast1: ReturnType<typeof ast>, ast2: ReturnType<typeof ast>): void;
5
+
6
+ export { assertEquivalentAst };