@navita/core 0.0.10 → 0.0.11

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.
@@ -2,12 +2,16 @@
2
2
 
3
3
  var engine = require('@navita/engine');
4
4
  var MagicString = require('magic-string');
5
- var evaluateAndProcess = require('./evaluateAndProcess.js');
5
+ var evaluateAndProcess = require('./evaluateAndProcess.cjs');
6
6
  require('node:path');
7
7
  require('@navita/swc');
8
+ require('./helpers/createCompiledFunction.cjs');
8
9
  require('node:vm');
10
+ require('./helpers/magicProxy.cjs');
11
+ require('./helpers/createDefineFunction.cjs');
9
12
  require('node:fs');
10
13
  require('enhanced-resolve');
14
+ require('./helpers/setAdapter.cjs');
11
15
  require('@navita/adapter');
12
16
 
13
17
  function createRenderer({ resolver , readFile , importMap =[] , engineOptions , context }) {
@@ -3,9 +3,13 @@ import MagicString from 'magic-string';
3
3
  import { evaluateAndProcess } from './evaluateAndProcess.mjs';
4
4
  import 'node:path';
5
5
  import '@navita/swc';
6
+ import './helpers/createCompiledFunction.mjs';
6
7
  import 'node:vm';
8
+ import './helpers/magicProxy.mjs';
9
+ import './helpers/createDefineFunction.mjs';
7
10
  import 'node:fs';
8
11
  import 'enhanced-resolve';
12
+ import './helpers/setAdapter.mjs';
9
13
  import '@navita/adapter';
10
14
 
11
15
  function createRenderer({ resolver , readFile , importMap =[] , engineOptions , context }) {
@@ -0,0 +1,78 @@
1
+ 'use strict';
2
+
3
+ var path = require('node:path');
4
+ var swc = require('@navita/swc');
5
+ var helpers_createCompiledFunction = require('./helpers/createCompiledFunction.cjs');
6
+ var helpers_createDefineFunction = require('./helpers/createDefineFunction.cjs');
7
+ var helpers_setAdapter = require('./helpers/setAdapter.cjs');
8
+ require('node:vm');
9
+ require('./helpers/magicProxy.cjs');
10
+ require('node:fs');
11
+ require('enhanced-resolve');
12
+ require('@navita/adapter');
13
+ require('@navita/engine');
14
+
15
+ const rootDir = path.resolve(__dirname, "../../");
16
+ const isExternal = (dependency)=>dependency.startsWith(rootDir) || dependency.includes('node_modules');
17
+ const defaultNodeModuleCache = {};
18
+ const defaultResolverCache = {};
19
+ const defaultModuleCache = new Map();
20
+ const collectedResults = {};
21
+ async function evaluateAndProcess({ type , filePath , source , engine , resolver , readFile , importMap , nodeModuleCache =defaultNodeModuleCache , resolverCache =defaultResolverCache , moduleCache =defaultModuleCache }) {
22
+ const cacheKey = `${filePath}:${type}`;
23
+ const compiledFn = await (async ()=>{
24
+ if (moduleCache.has(cacheKey)) {
25
+ const cache = moduleCache.get(cacheKey);
26
+ if (cache.source === source) {
27
+ return cache.compiledFn;
28
+ }
29
+ }
30
+ const newSource = await swc.extraction(source, {
31
+ filename: filePath,
32
+ entryPoint: type === 'entryPoint',
33
+ importMap
34
+ });
35
+ const define = helpers_createDefineFunction.createDefineFunction({
36
+ filePath,
37
+ resolver,
38
+ isExternal,
39
+ resolverCache,
40
+ nodeModuleCache,
41
+ setAdapter: ()=>helpers_setAdapter.setAdapter({
42
+ engine,
43
+ collectResults: collectedResults
44
+ })
45
+ }, (dependency)=>readFile(dependency).then((source)=>evaluateAndProcess({
46
+ type: 'dependency',
47
+ source: source.toString(),
48
+ filePath: dependency,
49
+ engine,
50
+ resolver,
51
+ readFile,
52
+ importMap,
53
+ nodeModuleCache,
54
+ resolverCache,
55
+ moduleCache
56
+ })).then(({ result })=>result));
57
+ const compiledFn = helpers_createCompiledFunction.createCompiledFunction(`return ${newSource}`, define);
58
+ moduleCache.set(cacheKey, {
59
+ source,
60
+ compiledFn
61
+ });
62
+ return compiledFn;
63
+ })();
64
+ return compiledFn().then(({ dependencies , exports })=>{
65
+ if (type === 'entryPoint') {
66
+ return {
67
+ result: collectedResults[filePath] || [],
68
+ dependencies
69
+ };
70
+ }
71
+ return {
72
+ result: exports,
73
+ dependencies
74
+ };
75
+ });
76
+ }
77
+
78
+ exports.evaluateAndProcess = evaluateAndProcess;
@@ -4,203 +4,15 @@ import { dirname as dirname$1 } from 'path';
4
4
  const __dirname = dirname$1(__filename);
5
5
  import path from 'node:path';
6
6
  import { extraction } from '@navita/swc';
7
- import vm from 'node:vm';
8
- import fs from 'node:fs';
9
- import enhancedResolve from 'enhanced-resolve';
10
- import { setAdapter as setAdapter$1 } from '@navita/adapter';
11
- import { ClassList } from '@navita/engine';
12
-
13
- function createMagicProxy() {
14
- // Todo: at some point, the magic proxy should notify the user
15
- // that they are using a browser API in a node environment
16
- return new Proxy({}, {
17
- get: ()=>createMagicProxy()
18
- });
19
- }
20
-
21
- const context = vm.createContext({
22
- global
23
- });
24
- const vmGlobalsRecord = new vm.Script(`
25
- Object
26
- .getOwnPropertyNames(globalThis)
27
- .reduce((acc, name) => ({
28
- ...acc,
29
- [name]: globalThis[name],
30
- }), {});
31
- `).runInContext(context);
32
- const vmGlobalsNonEnumerableRecord = {};
33
- Object.getOwnPropertyNames(global).forEach((name)=>{
34
- // The second condition here is to prevent jest's Symbol polyfill from being added.
35
- // https://github.com/jestjs/jest/blob/25a8785584c9d54a05887001ee7f498d489a5441/packages/jest-util/src/installCommonGlobals.ts#L49
36
- if (!vmGlobalsRecord[name] && global[name] !== globalThis.Symbol) {
37
- vmGlobalsNonEnumerableRecord[name] = global[name];
38
- }
39
- });
40
- function createCompiledFunction(source, define) {
41
- // This looks a bit weird, but it's much quicker to do it this way than to
42
- // run vm.runInContext. There's a bit more information in this issue:
43
- // https://github.com/nodejs/node/issues/31658
44
- const sandbox = {
45
- define,
46
- ...vmGlobalsRecord,
47
- ...vmGlobalsNonEnumerableRecord,
48
- window: createMagicProxy(),
49
- document: createMagicProxy(),
50
- navigator: createMagicProxy(),
51
- console
52
- };
53
- const params = Object.keys(sandbox);
54
- const implementations = Object.values(sandbox);
55
- const compiledFunction = vm.compileFunction(source, params, {
56
- parsingContext: context
57
- });
58
- return ()=>compiledFunction(...implementations);
59
- }
60
-
61
- const { ResolverFactory , CachedInputFileSystem } = enhancedResolve;
62
- const resolver = ResolverFactory.createResolver({
63
- fileSystem: new CachedInputFileSystem(fs, 4000),
64
- extensions: [
65
- ".js",
66
- ".cjs",
67
- ".mjs"
68
- ],
69
- conditionNames: [
70
- "import",
71
- "require"
72
- ]
73
- });
74
- const requireResolveLike = (request, paths = [])=>Promise.any(paths.map((path)=>new Promise((resolve, reject)=>{
75
- resolver.resolve({}, path, request, {}, (err, result)=>{
76
- if (err || !result) {
77
- return reject(err);
78
- }
79
- resolve(result);
80
- });
81
- })));
82
- const importWithRequireResolution = async (request, startPath = __dirname)=>{
83
- return import(await requireResolveLike(request, [
84
- startPath
85
- ]) || request);
86
- };
87
- function createDefineFunction({ filePath , resolver , isExternal , resolverCache , nodeModuleCache , setAdapter }, resolveDependency) {
88
- const filepathDirectory = path.dirname(filePath);
89
- return async function define(dependencies, factoryFn) {
90
- const exports = {};
91
- const dependencyMap = {
92
- require: importWithRequireResolution,
93
- exports
94
- };
95
- const resolvedDependencies = await Promise.all(dependencies.filter((dependency)=>!(dependency in dependencyMap)).map((dependency)=>{
96
- if (!resolverCache[filepathDirectory]) {
97
- resolverCache[filepathDirectory] = {};
98
- }
99
- if (resolverCache[filepathDirectory][dependency]) {
100
- return resolverCache[filepathDirectory][dependency];
101
- }
102
- const resolved = resolver(filePath, dependency).catch(()=>undefined).then((resolvedDependency)=>{
103
- if (!resolvedDependency || isExternal(resolvedDependency)) {
104
- return requireResolveLike(dependency, [
105
- filepathDirectory,
106
- __dirname
107
- ]).catch(()=>{
108
- throw new Error(`Failed to resolve dependency "${dependency}" in ${filePath}`);
109
- });
110
- }
111
- return resolvedDependency;
112
- });
113
- resolverCache[filepathDirectory][dependency] = resolved;
114
- return resolved;
115
- })).catch((error)=>{
116
- throw error;
117
- });
118
- for (const dependency of resolvedDependencies){
119
- if (nodeModuleCache[dependency]) {
120
- dependencyMap[dependency] = nodeModuleCache[dependency];
121
- continue;
122
- }
123
- /**
124
- * Ignore everything that's not:
125
- * .js, .ts, .jsx, .tsx, .mts, .mjs, .cjs, .cts
126
- */ if (/\.(?![mc]?[tj]sx?$)[^.]+$/.test(dependency)) {
127
- dependencyMap[dependency] = {};
128
- continue;
129
- }
130
- if (isExternal(dependency)) {
131
- const module = importWithRequireResolution(dependency, filepathDirectory);
132
- if (!nodeModuleCache[dependency]) {
133
- nodeModuleCache[dependency] = module;
134
- }
135
- dependencyMap[dependency] = nodeModuleCache[dependency];
136
- continue;
137
- }
138
- dependencyMap[dependency] = resolveDependency(dependency);
139
- }
140
- const dependencyValues = await Promise.all(Object.values(dependencyMap));
141
- // The adapter needs to be set before factoryFn is called.
142
- setAdapter();
143
- factoryFn(...dependencyValues);
144
- return {
145
- dependencies: resolvedDependencies.filter((x)=>!isExternal(x)),
146
- exports
147
- };
148
- };
149
- }
150
-
151
- function setAdapter({ engine , collectResults , }) {
152
- setAdapter$1({
153
- generateIdentifier: (value)=>engine.generateIdentifier(value),
154
- addStaticCss: (selector, css)=>engine.addStatic(selector, css),
155
- addCss: (css)=>engine.addStyle(css),
156
- addKeyframe: (keyframe)=>engine.addKeyframes(keyframe),
157
- addFontFace: (fontFace)=>{
158
- const hasFontFamily = (Array.isArray(fontFace) ? fontFace : [
159
- fontFace
160
- ]).some((fontFace)=>'fontFamily' in fontFace);
161
- if (hasFontFamily) {
162
- throw new Error('This function creates and returns a font-family name, so the "fontFamily" property should not be provided.');
163
- }
164
- return engine.addFontFace(fontFace);
165
- },
166
- collectResult ({ index , filePath , identifier , result: resultFactory , sourceMap: { line , column } , position , }) {
167
- if (index === 0) {
168
- if (collectResults) {
169
- collectResults[filePath] = [];
170
- }
171
- engine.clearUsedIds(filePath);
172
- }
173
- engine.setFilePath(filePath);
174
- let result = resultFactory();
175
- engine.setFilePath(undefined);
176
- if (result instanceof ClassList) {
177
- const extraClass = engine.addSourceMapReference({
178
- index,
179
- identifier,
180
- classList: result,
181
- filePath,
182
- line,
183
- column
184
- });
185
- if (extraClass) {
186
- result = new ClassList([
187
- result.toString(),
188
- extraClass
189
- ].join(' '));
190
- }
191
- }
192
- if (collectResults) {
193
- const [start, end] = position;
194
- collectResults[filePath][index] = {
195
- start,
196
- end,
197
- value: result === undefined ? "undefined" : JSON.stringify(result)
198
- };
199
- }
200
- return result;
201
- }
202
- });
203
- }
7
+ import { createCompiledFunction } from './helpers/createCompiledFunction.mjs';
8
+ import { createDefineFunction } from './helpers/createDefineFunction.mjs';
9
+ import { setAdapter } from './helpers/setAdapter.mjs';
10
+ import 'node:vm';
11
+ import './helpers/magicProxy.mjs';
12
+ import 'node:fs';
13
+ import 'enhanced-resolve';
14
+ import '@navita/adapter';
15
+ import '@navita/engine';
204
16
 
205
17
  const rootDir = path.resolve(__dirname, "../../");
206
18
  const isExternal = (dependency)=>dependency.startsWith(rootDir) || dependency.includes('node_modules');
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ var vm = require('node:vm');
4
+ var helpers_magicProxy = require('./magicProxy.cjs');
5
+
6
+ const context = vm.createContext({
7
+ global
8
+ });
9
+ const vmGlobalsRecord = new vm.Script(`
10
+ Object
11
+ .getOwnPropertyNames(globalThis)
12
+ .reduce((acc, name) => ({
13
+ ...acc,
14
+ [name]: globalThis[name],
15
+ }), {});
16
+ `).runInContext(context);
17
+ const vmGlobalsNonEnumerableRecord = {};
18
+ Object.getOwnPropertyNames(global).forEach((name)=>{
19
+ // The second condition here is to prevent jest's Symbol polyfill from being added.
20
+ // https://github.com/jestjs/jest/blob/25a8785584c9d54a05887001ee7f498d489a5441/packages/jest-util/src/installCommonGlobals.ts#L49
21
+ if (!vmGlobalsRecord[name] && global[name] !== globalThis.Symbol) {
22
+ vmGlobalsNonEnumerableRecord[name] = global[name];
23
+ }
24
+ });
25
+ function createCompiledFunction(source, define) {
26
+ // This looks a bit weird, but it's much quicker to do it this way than to
27
+ // run vm.runInContext. There's a bit more information in this issue:
28
+ // https://github.com/nodejs/node/issues/31658
29
+ const sandbox = {
30
+ define,
31
+ ...vmGlobalsRecord,
32
+ ...vmGlobalsNonEnumerableRecord,
33
+ window: helpers_magicProxy.createMagicProxy(),
34
+ document: helpers_magicProxy.createMagicProxy(),
35
+ navigator: helpers_magicProxy.createMagicProxy(),
36
+ console
37
+ };
38
+ const params = Object.keys(sandbox);
39
+ const implementations = Object.values(sandbox);
40
+ const compiledFunction = vm.compileFunction(source, params, {
41
+ parsingContext: context
42
+ });
43
+ return ()=>compiledFunction(...implementations);
44
+ }
45
+
46
+ exports.createCompiledFunction = createCompiledFunction;
@@ -0,0 +1,44 @@
1
+ import vm from 'node:vm';
2
+ import { createMagicProxy } from './magicProxy.mjs';
3
+
4
+ const context = vm.createContext({
5
+ global
6
+ });
7
+ const vmGlobalsRecord = new vm.Script(`
8
+ Object
9
+ .getOwnPropertyNames(globalThis)
10
+ .reduce((acc, name) => ({
11
+ ...acc,
12
+ [name]: globalThis[name],
13
+ }), {});
14
+ `).runInContext(context);
15
+ const vmGlobalsNonEnumerableRecord = {};
16
+ Object.getOwnPropertyNames(global).forEach((name)=>{
17
+ // The second condition here is to prevent jest's Symbol polyfill from being added.
18
+ // https://github.com/jestjs/jest/blob/25a8785584c9d54a05887001ee7f498d489a5441/packages/jest-util/src/installCommonGlobals.ts#L49
19
+ if (!vmGlobalsRecord[name] && global[name] !== globalThis.Symbol) {
20
+ vmGlobalsNonEnumerableRecord[name] = global[name];
21
+ }
22
+ });
23
+ function createCompiledFunction(source, define) {
24
+ // This looks a bit weird, but it's much quicker to do it this way than to
25
+ // run vm.runInContext. There's a bit more information in this issue:
26
+ // https://github.com/nodejs/node/issues/31658
27
+ const sandbox = {
28
+ define,
29
+ ...vmGlobalsRecord,
30
+ ...vmGlobalsNonEnumerableRecord,
31
+ window: createMagicProxy(),
32
+ document: createMagicProxy(),
33
+ navigator: createMagicProxy(),
34
+ console
35
+ };
36
+ const params = Object.keys(sandbox);
37
+ const implementations = Object.values(sandbox);
38
+ const compiledFunction = vm.compileFunction(source, params, {
39
+ parsingContext: context
40
+ });
41
+ return ()=>compiledFunction(...implementations);
42
+ }
43
+
44
+ export { createCompiledFunction };
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+
3
+ var fs = require('node:fs');
4
+ var path = require('node:path');
5
+ var enhancedResolve = require('enhanced-resolve');
6
+
7
+ const { ResolverFactory , CachedInputFileSystem } = enhancedResolve;
8
+ const resolver = ResolverFactory.createResolver({
9
+ fileSystem: new CachedInputFileSystem(fs, 4000),
10
+ extensions: [
11
+ ".js",
12
+ ".cjs",
13
+ ".mjs"
14
+ ],
15
+ conditionNames: [
16
+ "import",
17
+ "require"
18
+ ]
19
+ });
20
+ const requireResolveLike = (request, paths = [])=>Promise.any(paths.map((path)=>new Promise((resolve, reject)=>{
21
+ resolver.resolve({}, path, request, {}, (err, result)=>{
22
+ if (err || !result) {
23
+ return reject(err);
24
+ }
25
+ resolve(result);
26
+ });
27
+ })));
28
+ const importWithRequireResolution = async (request, startPath = __dirname)=>{
29
+ return import(await requireResolveLike(request, [
30
+ startPath
31
+ ]) || request);
32
+ };
33
+ function createDefineFunction({ filePath , resolver , isExternal , resolverCache , nodeModuleCache , setAdapter }, resolveDependency) {
34
+ const filepathDirectory = path.dirname(filePath);
35
+ return async function define(dependencies, factoryFn) {
36
+ const exports = {};
37
+ const dependencyMap = {
38
+ require: importWithRequireResolution,
39
+ exports
40
+ };
41
+ const resolvedDependencies = await Promise.all(dependencies.filter((dependency)=>!(dependency in dependencyMap)).map((dependency)=>{
42
+ if (!resolverCache[filepathDirectory]) {
43
+ resolverCache[filepathDirectory] = {};
44
+ }
45
+ if (resolverCache[filepathDirectory][dependency]) {
46
+ return resolverCache[filepathDirectory][dependency];
47
+ }
48
+ const resolved = resolver(filePath, dependency).catch(()=>undefined).then((resolvedDependency)=>{
49
+ if (!resolvedDependency || isExternal(resolvedDependency)) {
50
+ return requireResolveLike(dependency, [
51
+ filepathDirectory,
52
+ __dirname
53
+ ]).catch(()=>{
54
+ throw new Error(`Failed to resolve dependency "${dependency}" in ${filePath}`);
55
+ });
56
+ }
57
+ return resolvedDependency;
58
+ });
59
+ resolverCache[filepathDirectory][dependency] = resolved;
60
+ return resolved;
61
+ })).catch((error)=>{
62
+ throw error;
63
+ });
64
+ for (const dependency of resolvedDependencies){
65
+ if (nodeModuleCache[dependency]) {
66
+ dependencyMap[dependency] = nodeModuleCache[dependency];
67
+ continue;
68
+ }
69
+ /**
70
+ * Ignore everything that's not:
71
+ * .js, .ts, .jsx, .tsx, .mts, .mjs, .cjs, .cts
72
+ */ if (/\.(?![mc]?[tj]sx?$)[^.]+$/.test(dependency)) {
73
+ dependencyMap[dependency] = {};
74
+ continue;
75
+ }
76
+ if (isExternal(dependency)) {
77
+ const module = importWithRequireResolution(dependency, filepathDirectory);
78
+ if (!nodeModuleCache[dependency]) {
79
+ nodeModuleCache[dependency] = module;
80
+ }
81
+ dependencyMap[dependency] = nodeModuleCache[dependency];
82
+ continue;
83
+ }
84
+ dependencyMap[dependency] = resolveDependency(dependency);
85
+ }
86
+ const dependencyValues = await Promise.all(Object.values(dependencyMap));
87
+ // The adapter needs to be set before factoryFn is called.
88
+ setAdapter();
89
+ factoryFn(...dependencyValues);
90
+ return {
91
+ dependencies: resolvedDependencies.filter((x)=>!isExternal(x)),
92
+ exports
93
+ };
94
+ };
95
+ }
96
+
97
+ exports.createDefineFunction = createDefineFunction;
@@ -0,0 +1,99 @@
1
+ import { fileURLToPath as fileURLToPath$1 } from 'url';
2
+ const __filename = fileURLToPath$1(import.meta.url);
3
+ import { dirname as dirname$1 } from 'path';
4
+ const __dirname = dirname$1(__filename);
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import enhancedResolve from 'enhanced-resolve';
8
+
9
+ const { ResolverFactory , CachedInputFileSystem } = enhancedResolve;
10
+ const resolver = ResolverFactory.createResolver({
11
+ fileSystem: new CachedInputFileSystem(fs, 4000),
12
+ extensions: [
13
+ ".js",
14
+ ".cjs",
15
+ ".mjs"
16
+ ],
17
+ conditionNames: [
18
+ "import",
19
+ "require"
20
+ ]
21
+ });
22
+ const requireResolveLike = (request, paths = [])=>Promise.any(paths.map((path)=>new Promise((resolve, reject)=>{
23
+ resolver.resolve({}, path, request, {}, (err, result)=>{
24
+ if (err || !result) {
25
+ return reject(err);
26
+ }
27
+ resolve(result);
28
+ });
29
+ })));
30
+ const importWithRequireResolution = async (request, startPath = __dirname)=>{
31
+ return import(await requireResolveLike(request, [
32
+ startPath
33
+ ]) || request);
34
+ };
35
+ function createDefineFunction({ filePath , resolver , isExternal , resolverCache , nodeModuleCache , setAdapter }, resolveDependency) {
36
+ const filepathDirectory = path.dirname(filePath);
37
+ return async function define(dependencies, factoryFn) {
38
+ const exports = {};
39
+ const dependencyMap = {
40
+ require: importWithRequireResolution,
41
+ exports
42
+ };
43
+ const resolvedDependencies = await Promise.all(dependencies.filter((dependency)=>!(dependency in dependencyMap)).map((dependency)=>{
44
+ if (!resolverCache[filepathDirectory]) {
45
+ resolverCache[filepathDirectory] = {};
46
+ }
47
+ if (resolverCache[filepathDirectory][dependency]) {
48
+ return resolverCache[filepathDirectory][dependency];
49
+ }
50
+ const resolved = resolver(filePath, dependency).catch(()=>undefined).then((resolvedDependency)=>{
51
+ if (!resolvedDependency || isExternal(resolvedDependency)) {
52
+ return requireResolveLike(dependency, [
53
+ filepathDirectory,
54
+ __dirname
55
+ ]).catch(()=>{
56
+ throw new Error(`Failed to resolve dependency "${dependency}" in ${filePath}`);
57
+ });
58
+ }
59
+ return resolvedDependency;
60
+ });
61
+ resolverCache[filepathDirectory][dependency] = resolved;
62
+ return resolved;
63
+ })).catch((error)=>{
64
+ throw error;
65
+ });
66
+ for (const dependency of resolvedDependencies){
67
+ if (nodeModuleCache[dependency]) {
68
+ dependencyMap[dependency] = nodeModuleCache[dependency];
69
+ continue;
70
+ }
71
+ /**
72
+ * Ignore everything that's not:
73
+ * .js, .ts, .jsx, .tsx, .mts, .mjs, .cjs, .cts
74
+ */ if (/\.(?![mc]?[tj]sx?$)[^.]+$/.test(dependency)) {
75
+ dependencyMap[dependency] = {};
76
+ continue;
77
+ }
78
+ if (isExternal(dependency)) {
79
+ const module = importWithRequireResolution(dependency, filepathDirectory);
80
+ if (!nodeModuleCache[dependency]) {
81
+ nodeModuleCache[dependency] = module;
82
+ }
83
+ dependencyMap[dependency] = nodeModuleCache[dependency];
84
+ continue;
85
+ }
86
+ dependencyMap[dependency] = resolveDependency(dependency);
87
+ }
88
+ const dependencyValues = await Promise.all(Object.values(dependencyMap));
89
+ // The adapter needs to be set before factoryFn is called.
90
+ setAdapter();
91
+ factoryFn(...dependencyValues);
92
+ return {
93
+ dependencies: resolvedDependencies.filter((x)=>!isExternal(x)),
94
+ exports
95
+ };
96
+ };
97
+ }
98
+
99
+ export { createDefineFunction };
@@ -0,0 +1,11 @@
1
+ 'use strict';
2
+
3
+ function createMagicProxy() {
4
+ // Todo: at some point, the magic proxy should notify the user
5
+ // that they are using a browser API in a node environment
6
+ return new Proxy({}, {
7
+ get: ()=>createMagicProxy()
8
+ });
9
+ }
10
+
11
+ exports.createMagicProxy = createMagicProxy;
@@ -0,0 +1,9 @@
1
+ function createMagicProxy() {
2
+ // Todo: at some point, the magic proxy should notify the user
3
+ // that they are using a browser API in a node environment
4
+ return new Proxy({}, {
5
+ get: ()=>createMagicProxy()
6
+ });
7
+ }
8
+
9
+ export { createMagicProxy };
@@ -0,0 +1,60 @@
1
+ 'use strict';
2
+
3
+ var adapter = require('@navita/adapter');
4
+ var engine = require('@navita/engine');
5
+
6
+ function setAdapter({ engine: engine$1 , collectResults , }) {
7
+ adapter.setAdapter({
8
+ generateIdentifier: (value)=>engine$1.generateIdentifier(value),
9
+ addStaticCss: (selector, css)=>engine$1.addStatic(selector, css),
10
+ addCss: (css)=>engine$1.addStyle(css),
11
+ addKeyframe: (keyframe)=>engine$1.addKeyframes(keyframe),
12
+ addFontFace: (fontFace)=>{
13
+ const hasFontFamily = (Array.isArray(fontFace) ? fontFace : [
14
+ fontFace
15
+ ]).some((fontFace)=>'fontFamily' in fontFace);
16
+ if (hasFontFamily) {
17
+ throw new Error('This function creates and returns a font-family name, so the "fontFamily" property should not be provided.');
18
+ }
19
+ return engine$1.addFontFace(fontFace);
20
+ },
21
+ collectResult ({ index , filePath , identifier , result: resultFactory , sourceMap: { line , column } , position , }) {
22
+ if (index === 0) {
23
+ if (collectResults) {
24
+ collectResults[filePath] = [];
25
+ }
26
+ engine$1.clearUsedIds(filePath);
27
+ }
28
+ engine$1.setFilePath(filePath);
29
+ let result = resultFactory();
30
+ engine$1.setFilePath(undefined);
31
+ if (result instanceof engine.ClassList) {
32
+ const extraClass = engine$1.addSourceMapReference({
33
+ index,
34
+ identifier,
35
+ classList: result,
36
+ filePath,
37
+ line,
38
+ column
39
+ });
40
+ if (extraClass) {
41
+ result = new engine.ClassList([
42
+ result.toString(),
43
+ extraClass
44
+ ].join(' '));
45
+ }
46
+ }
47
+ if (collectResults) {
48
+ const [start, end] = position;
49
+ collectResults[filePath][index] = {
50
+ start,
51
+ end,
52
+ value: result === undefined ? "undefined" : JSON.stringify(result)
53
+ };
54
+ }
55
+ return result;
56
+ }
57
+ });
58
+ }
59
+
60
+ exports.setAdapter = setAdapter;
@@ -0,0 +1,58 @@
1
+ import { setAdapter as setAdapter$1 } from '@navita/adapter';
2
+ import { ClassList } from '@navita/engine';
3
+
4
+ function setAdapter({ engine , collectResults , }) {
5
+ setAdapter$1({
6
+ generateIdentifier: (value)=>engine.generateIdentifier(value),
7
+ addStaticCss: (selector, css)=>engine.addStatic(selector, css),
8
+ addCss: (css)=>engine.addStyle(css),
9
+ addKeyframe: (keyframe)=>engine.addKeyframes(keyframe),
10
+ addFontFace: (fontFace)=>{
11
+ const hasFontFamily = (Array.isArray(fontFace) ? fontFace : [
12
+ fontFace
13
+ ]).some((fontFace)=>'fontFamily' in fontFace);
14
+ if (hasFontFamily) {
15
+ throw new Error('This function creates and returns a font-family name, so the "fontFamily" property should not be provided.');
16
+ }
17
+ return engine.addFontFace(fontFace);
18
+ },
19
+ collectResult ({ index , filePath , identifier , result: resultFactory , sourceMap: { line , column } , position , }) {
20
+ if (index === 0) {
21
+ if (collectResults) {
22
+ collectResults[filePath] = [];
23
+ }
24
+ engine.clearUsedIds(filePath);
25
+ }
26
+ engine.setFilePath(filePath);
27
+ let result = resultFactory();
28
+ engine.setFilePath(undefined);
29
+ if (result instanceof ClassList) {
30
+ const extraClass = engine.addSourceMapReference({
31
+ index,
32
+ identifier,
33
+ classList: result,
34
+ filePath,
35
+ line,
36
+ column
37
+ });
38
+ if (extraClass) {
39
+ result = new ClassList([
40
+ result.toString(),
41
+ extraClass
42
+ ].join(' '));
43
+ }
44
+ }
45
+ if (collectResults) {
46
+ const [start, end] = position;
47
+ collectResults[filePath][index] = {
48
+ start,
49
+ end,
50
+ value: result === undefined ? "undefined" : JSON.stringify(result)
51
+ };
52
+ }
53
+ return result;
54
+ }
55
+ });
56
+ }
57
+
58
+ export { setAdapter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@navita/core",
3
- "version": "0.0.10",
3
+ "version": "0.0.11",
4
4
  "description": "Core package for Navita. Used for creating integrations.",
5
5
  "keywords": [
6
6
  "core",
@@ -12,20 +12,15 @@
12
12
  "sideEffects": false,
13
13
  "types": "./src/index.ts",
14
14
  "exports": {
15
- ".": {
16
- "import": "./index.mjs",
17
- "require": "./index.js",
18
- "types": "./index.d.ts"
19
- },
20
15
  "./package.json": "./package.json",
21
16
  "./createRenderer": {
22
17
  "import": "./createRenderer.mjs",
23
- "require": "./createRenderer.js",
18
+ "require": "./createRenderer.cjs",
24
19
  "types": "./createRenderer.d.ts"
25
20
  },
26
21
  "./evaluateAndProcess": {
27
22
  "import": "./evaluateAndProcess.mjs",
28
- "require": "./evaluateAndProcess.js",
23
+ "require": "./evaluateAndProcess.cjs",
29
24
  "types": "./evaluateAndProcess.d.ts"
30
25
  }
31
26
  },
@@ -33,10 +28,10 @@
33
28
  "enhanced-resolve": "^5.15.0",
34
29
  "outdent": "^0.8.0",
35
30
  "magic-string": "^0.30.3",
36
- "@navita/types": "0.0.8",
37
- "@navita/adapter": "0.0.9",
38
- "@navita/swc": "0.0.9",
39
- "@navita/engine": "0.0.10"
31
+ "@navita/types": "0.0.9",
32
+ "@navita/adapter": "0.0.10",
33
+ "@navita/swc": "0.0.10",
34
+ "@navita/engine": "0.0.11"
40
35
  },
41
36
  "license": "MIT",
42
37
  "author": "Eagerpatch",
@@ -1,266 +0,0 @@
1
- 'use strict';
2
-
3
- var path = require('node:path');
4
- var swc = require('@navita/swc');
5
- var vm = require('node:vm');
6
- var fs = require('node:fs');
7
- var enhancedResolve = require('enhanced-resolve');
8
- var adapter = require('@navita/adapter');
9
- var engine = require('@navita/engine');
10
-
11
- function createMagicProxy() {
12
- // Todo: at some point, the magic proxy should notify the user
13
- // that they are using a browser API in a node environment
14
- return new Proxy({}, {
15
- get: ()=>createMagicProxy()
16
- });
17
- }
18
-
19
- const context = vm.createContext({
20
- global
21
- });
22
- const vmGlobalsRecord = new vm.Script(`
23
- Object
24
- .getOwnPropertyNames(globalThis)
25
- .reduce((acc, name) => ({
26
- ...acc,
27
- [name]: globalThis[name],
28
- }), {});
29
- `).runInContext(context);
30
- const vmGlobalsNonEnumerableRecord = {};
31
- Object.getOwnPropertyNames(global).forEach((name)=>{
32
- // The second condition here is to prevent jest's Symbol polyfill from being added.
33
- // https://github.com/jestjs/jest/blob/25a8785584c9d54a05887001ee7f498d489a5441/packages/jest-util/src/installCommonGlobals.ts#L49
34
- if (!vmGlobalsRecord[name] && global[name] !== globalThis.Symbol) {
35
- vmGlobalsNonEnumerableRecord[name] = global[name];
36
- }
37
- });
38
- function createCompiledFunction(source, define) {
39
- // This looks a bit weird, but it's much quicker to do it this way than to
40
- // run vm.runInContext. There's a bit more information in this issue:
41
- // https://github.com/nodejs/node/issues/31658
42
- const sandbox = {
43
- define,
44
- ...vmGlobalsRecord,
45
- ...vmGlobalsNonEnumerableRecord,
46
- window: createMagicProxy(),
47
- document: createMagicProxy(),
48
- navigator: createMagicProxy(),
49
- console
50
- };
51
- const params = Object.keys(sandbox);
52
- const implementations = Object.values(sandbox);
53
- const compiledFunction = vm.compileFunction(source, params, {
54
- parsingContext: context
55
- });
56
- return ()=>compiledFunction(...implementations);
57
- }
58
-
59
- const { ResolverFactory , CachedInputFileSystem } = enhancedResolve;
60
- const resolver = ResolverFactory.createResolver({
61
- fileSystem: new CachedInputFileSystem(fs, 4000),
62
- extensions: [
63
- ".js",
64
- ".cjs",
65
- ".mjs"
66
- ],
67
- conditionNames: [
68
- "import",
69
- "require"
70
- ]
71
- });
72
- const requireResolveLike = (request, paths = [])=>Promise.any(paths.map((path)=>new Promise((resolve, reject)=>{
73
- resolver.resolve({}, path, request, {}, (err, result)=>{
74
- if (err || !result) {
75
- return reject(err);
76
- }
77
- resolve(result);
78
- });
79
- })));
80
- const importWithRequireResolution = async (request, startPath = __dirname)=>{
81
- return import(await requireResolveLike(request, [
82
- startPath
83
- ]) || request);
84
- };
85
- function createDefineFunction({ filePath , resolver , isExternal , resolverCache , nodeModuleCache , setAdapter }, resolveDependency) {
86
- const filepathDirectory = path.dirname(filePath);
87
- return async function define(dependencies, factoryFn) {
88
- const exports = {};
89
- const dependencyMap = {
90
- require: importWithRequireResolution,
91
- exports
92
- };
93
- const resolvedDependencies = await Promise.all(dependencies.filter((dependency)=>!(dependency in dependencyMap)).map((dependency)=>{
94
- if (!resolverCache[filepathDirectory]) {
95
- resolverCache[filepathDirectory] = {};
96
- }
97
- if (resolverCache[filepathDirectory][dependency]) {
98
- return resolverCache[filepathDirectory][dependency];
99
- }
100
- const resolved = resolver(filePath, dependency).catch(()=>undefined).then((resolvedDependency)=>{
101
- if (!resolvedDependency || isExternal(resolvedDependency)) {
102
- return requireResolveLike(dependency, [
103
- filepathDirectory,
104
- __dirname
105
- ]).catch(()=>{
106
- throw new Error(`Failed to resolve dependency "${dependency}" in ${filePath}`);
107
- });
108
- }
109
- return resolvedDependency;
110
- });
111
- resolverCache[filepathDirectory][dependency] = resolved;
112
- return resolved;
113
- })).catch((error)=>{
114
- throw error;
115
- });
116
- for (const dependency of resolvedDependencies){
117
- if (nodeModuleCache[dependency]) {
118
- dependencyMap[dependency] = nodeModuleCache[dependency];
119
- continue;
120
- }
121
- /**
122
- * Ignore everything that's not:
123
- * .js, .ts, .jsx, .tsx, .mts, .mjs, .cjs, .cts
124
- */ if (/\.(?![mc]?[tj]sx?$)[^.]+$/.test(dependency)) {
125
- dependencyMap[dependency] = {};
126
- continue;
127
- }
128
- if (isExternal(dependency)) {
129
- const module = importWithRequireResolution(dependency, filepathDirectory);
130
- if (!nodeModuleCache[dependency]) {
131
- nodeModuleCache[dependency] = module;
132
- }
133
- dependencyMap[dependency] = nodeModuleCache[dependency];
134
- continue;
135
- }
136
- dependencyMap[dependency] = resolveDependency(dependency);
137
- }
138
- const dependencyValues = await Promise.all(Object.values(dependencyMap));
139
- // The adapter needs to be set before factoryFn is called.
140
- setAdapter();
141
- factoryFn(...dependencyValues);
142
- return {
143
- dependencies: resolvedDependencies.filter((x)=>!isExternal(x)),
144
- exports
145
- };
146
- };
147
- }
148
-
149
- function setAdapter({ engine: engine$1 , collectResults , }) {
150
- adapter.setAdapter({
151
- generateIdentifier: (value)=>engine$1.generateIdentifier(value),
152
- addStaticCss: (selector, css)=>engine$1.addStatic(selector, css),
153
- addCss: (css)=>engine$1.addStyle(css),
154
- addKeyframe: (keyframe)=>engine$1.addKeyframes(keyframe),
155
- addFontFace: (fontFace)=>{
156
- const hasFontFamily = (Array.isArray(fontFace) ? fontFace : [
157
- fontFace
158
- ]).some((fontFace)=>'fontFamily' in fontFace);
159
- if (hasFontFamily) {
160
- throw new Error('This function creates and returns a font-family name, so the "fontFamily" property should not be provided.');
161
- }
162
- return engine$1.addFontFace(fontFace);
163
- },
164
- collectResult ({ index , filePath , identifier , result: resultFactory , sourceMap: { line , column } , position , }) {
165
- if (index === 0) {
166
- if (collectResults) {
167
- collectResults[filePath] = [];
168
- }
169
- engine$1.clearUsedIds(filePath);
170
- }
171
- engine$1.setFilePath(filePath);
172
- let result = resultFactory();
173
- engine$1.setFilePath(undefined);
174
- if (result instanceof engine.ClassList) {
175
- const extraClass = engine$1.addSourceMapReference({
176
- index,
177
- identifier,
178
- classList: result,
179
- filePath,
180
- line,
181
- column
182
- });
183
- if (extraClass) {
184
- result = new engine.ClassList([
185
- result.toString(),
186
- extraClass
187
- ].join(' '));
188
- }
189
- }
190
- if (collectResults) {
191
- const [start, end] = position;
192
- collectResults[filePath][index] = {
193
- start,
194
- end,
195
- value: result === undefined ? "undefined" : JSON.stringify(result)
196
- };
197
- }
198
- return result;
199
- }
200
- });
201
- }
202
-
203
- const rootDir = path.resolve(__dirname, "../../");
204
- const isExternal = (dependency)=>dependency.startsWith(rootDir) || dependency.includes('node_modules');
205
- const defaultNodeModuleCache = {};
206
- const defaultResolverCache = {};
207
- const defaultModuleCache = new Map();
208
- const collectedResults = {};
209
- async function evaluateAndProcess({ type , filePath , source , engine , resolver , readFile , importMap , nodeModuleCache =defaultNodeModuleCache , resolverCache =defaultResolverCache , moduleCache =defaultModuleCache }) {
210
- const cacheKey = `${filePath}:${type}`;
211
- const compiledFn = await (async ()=>{
212
- if (moduleCache.has(cacheKey)) {
213
- const cache = moduleCache.get(cacheKey);
214
- if (cache.source === source) {
215
- return cache.compiledFn;
216
- }
217
- }
218
- const newSource = await swc.extraction(source, {
219
- filename: filePath,
220
- entryPoint: type === 'entryPoint',
221
- importMap
222
- });
223
- const define = createDefineFunction({
224
- filePath,
225
- resolver,
226
- isExternal,
227
- resolverCache,
228
- nodeModuleCache,
229
- setAdapter: ()=>setAdapter({
230
- engine,
231
- collectResults: collectedResults
232
- })
233
- }, (dependency)=>readFile(dependency).then((source)=>evaluateAndProcess({
234
- type: 'dependency',
235
- source: source.toString(),
236
- filePath: dependency,
237
- engine,
238
- resolver,
239
- readFile,
240
- importMap,
241
- nodeModuleCache,
242
- resolverCache,
243
- moduleCache
244
- })).then(({ result })=>result));
245
- const compiledFn = createCompiledFunction(`return ${newSource}`, define);
246
- moduleCache.set(cacheKey, {
247
- source,
248
- compiledFn
249
- });
250
- return compiledFn;
251
- })();
252
- return compiledFn().then(({ dependencies , exports })=>{
253
- if (type === 'entryPoint') {
254
- return {
255
- result: collectedResults[filePath] || [],
256
- dependencies
257
- };
258
- }
259
- return {
260
- result: exports,
261
- dependencies
262
- };
263
- });
264
- }
265
-
266
- exports.evaluateAndProcess = evaluateAndProcess;
package/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
-
2
- export { }
package/index.js DELETED
@@ -1,2 +0,0 @@
1
- 'use strict';
2
-
package/index.mjs DELETED
@@ -1 +0,0 @@
1
-