Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/pr-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:

strategy:
matrix:
node-version: [12.20.0, 14.x]
node-version: [14.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/

steps:
Expand Down
23 changes: 9 additions & 14 deletions client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import hydrate from './hydrate';
import router from './router';
import settings from './settings';
import worker from './worker';
import klassMap from './klassMap';
import windowEvent from './windowEvent'

context.page = page;
Expand All @@ -42,7 +41,6 @@ export default class Nullstack {
static invoke = invoke;
static fragment = fragment;
static use = useClientPlugins;
static klassMap = {}
static context = generateContext({})

static start(Starter) {
Expand Down Expand Up @@ -108,29 +106,26 @@ export default class Nullstack {
}

if (module.hot) {
Nullstack.serverHashes ??= {}
const socket = new WebSocket('ws' + router.base.slice(4) + '/ws');
window.lastHash
socket.onmessage = async function (e) {
const data = JSON.parse(e.data)
if (data.type === 'NULLSTACK_SERVER_STARTED') {
(window.needsReload || !environment.hot) && window.location.reload()
} else if (data.type === 'hash') {
const newHash = data.data.slice(20)
if (newHash === window.lastHash) {
window.needsReload = true
} else {
window.lastHash = newHash
}
if (data.type === 'NULLSTACK_SERVER_STARTED' && (Nullstack.needsReload || !environment.hot)) {
window.location.reload()
}
};
Nullstack.updateInstancesPrototypes = function updateInstancesPrototypes(hash, klass) {
Nullstack.updateInstancesPrototypes = function updateInstancesPrototypes(klass, hash, serverHashes) {
for (const key in context.instances) {
const instance = context.instances[key]
if (instance.constructor.hash === hash) {
Object.setPrototypeOf(instance, klass.prototype);
}
}
klassMap[hash] = klass
if (Nullstack.serverHashes[hash] && Nullstack.serverHashes[hash] !== serverHashes) {
Nullstack.needsReload = true
}
Nullstack.serverHashes[hash] = serverHashes
client.update()
}
Nullstack.hotReload = function hotReload(klass) {
if (client.skipHotReplacement) {
Expand Down
3 changes: 0 additions & 3 deletions client/klassMap.js

This file was deleted.

4 changes: 2 additions & 2 deletions loaders/inject-hmr.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ module.exports = function (source) {

return source + `
if (module.hot) {
if (window.needsClientReload) {
if (Nullstack.needsClientReload) {
window.location.reload()
}
module.hot.accept()
window.needsClientReload = true
Nullstack.needsClientReload = true
module.hot.accept('${klassPath}', () => {
Nullstack.hotReload(${klassName})
})
Expand Down
23 changes: 14 additions & 9 deletions loaders/remove-import-from-client.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,42 @@
const parse = require('@babel/parser').parse;
const traverse = require("@babel/traverse").default;

module.exports = function(source) {
const parentTypes = ['ImportDefaultSpecifier', 'ImportSpecifier', 'ImportNamespaceSpecifier']

module.exports = function (source) {
const ast = parse(source, {
sourceType: 'module',
plugins: ['classProperties', 'jsx']
});
const imports = {};
function findImports(path) {
if(path.node.local.name !== 'Nullstack') {
if (path.node.local.name !== 'Nullstack') {
const parent = path.findParent((path) => path.isImportDeclaration());
const start = parent.node.loc.start.line;
const end = parent.node.loc.end.line;
const lines = new Array(end - start + 1).fill().map((d, i) => i + start);
const key = lines.join('.');
imports[path.node.local.name] = {lines, key};
imports[path.node.local.name] = { lines, key };
}
}
function findIdentifiers(path) {
if(path.parent.type !== 'ImportDefaultSpecifier' && path.parent.type !== 'ImportSpecifier') {
if (parentTypes.indexOf(path.parent.type) === -1) {
const target = imports[path.node.name];
if(target) {
for(const name in imports) {
if(imports[name].key === target.key) {
delete imports[name];
if (target) {
for (const name in imports) {
if (imports[name].key === target.key) {
if (path.parent.type !== 'MemberExpression' || path.parent.object?.type !== 'ThisExpression') {
delete imports[name];
}
}
}
}
}
}
traverse(ast, {
ImportSpecifier: findImports,
ImportDefaultSpecifier: findImports
ImportDefaultSpecifier: findImports,
ImportNamespaceSpecifier: findImports
});
traverse(ast, {
Identifier: findIdentifiers,
Expand Down
5 changes: 4 additions & 1 deletion loaders/remove-static-from-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const traverse = require("@babel/traverse").default;
module.exports = function removeStaticFromClient(source) {
const id = this.resourcePath.replace(this.rootContext, '')
const hash = crypto.createHash('md5').update(id).digest("hex");
let serverSource = ''
let hashPosition;
let klassName;
const injections = {};
Expand All @@ -25,6 +26,7 @@ module.exports = function removeStaticFromClient(source) {
ClassMethod(path) {
if (path.node.static && path.node.async) {
injections[path.node.start] = { end: path.node.end, name: path.node.key.name };
serverSource += source.slice(path.node.start, path.node.end)
if (!positions.includes(path.node.start)) {
positions.push(path.node.start);
}
Expand Down Expand Up @@ -56,7 +58,8 @@ module.exports = function removeStaticFromClient(source) {
}
let newSource = outputs.reverse().join('')
if (klassName) {
newSource += `\nif (module.hot) { Nullstack.updateInstancesPrototypes(${klassName}.hash, ${klassName}) }`;
const serverHash = crypto.createHash('md5').update(serverSource).digest("hex");
newSource += `\nif (module.hot) { module.hot.accept(); Nullstack.updateInstancesPrototypes(${klassName}, ${klassName}.hash, '${serverHash}') }`;
}
return newSource
}
10 changes: 9 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nullstack",
"version": "0.16.2",
"version": "0.16.3",
"description": "Full-stack Javascript Components for one-dev armies",
"main": "nullstack.js",
"author": "Mortaro",
Expand All @@ -12,9 +12,17 @@
},
"types": "./types/index.d.ts",
"dependencies": {
"@babel/core": "^7.18.13",
"@babel/parser": "7.17.12",
"@babel/preset-env": "^7.18.10",
"@babel/plugin-proposal-class-properties": "^7.18.6",
"@babel/plugin-proposal-export-default-from": "^7.18.10",
"@babel/plugin-transform-react-jsx": "^7.18.10",
"@babel/plugin-transform-typescript": "^7.18.12",
"@babel/preset-react": "^7.18.6",
"@babel/traverse": "7.17.12",
"@swc/core": "1.2.179",
"babel-loader": "^8.2.5",
"body-parser": "1.20.0",
"commander": "8.3.0",
"copy-webpack-plugin": "^11.0.0",
Expand Down
9 changes: 5 additions & 4 deletions scripts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { version } = require('../package.json');

const webpack = require('webpack');
const path = require('path');
const { existsSync, rmdirSync, readdir, unlink } = require('fs');
const { existsSync, readdir, unlink } = require('fs');
const customConfig = path.resolve(process.cwd(), './webpack.config.js');
const config = existsSync(customConfig) ? require(customConfig) : require('../webpack.config');
const dotenv = require('dotenv')
Expand Down Expand Up @@ -61,7 +61,7 @@ function clearOutput(outputPath) {
});
}

async function start({ input, port, env, mode = 'spa', cold, disk }) {
async function start({ input, port, env, mode = 'spa', cold, disk, loader = 'swc' }) {
const environment = 'development'
console.log(` 🚀️ Starting your application in ${environment} mode...`);
loadEnv(env)
Expand All @@ -85,7 +85,7 @@ async function start({ input, port, env, mode = 'spa', cold, disk }) {
host: process.env['NULLSTACK_PROJECT_DOMAIN'],
devMiddleware: {
index: false,
stats: 'none',
stats: 'errors-only',
writeToDisk,
},
client: {
Expand Down Expand Up @@ -135,7 +135,7 @@ async function start({ input, port, env, mode = 'spa', cold, disk }) {
webSocketServer: require.resolve('./socket'),
port: process.env['NULLSTACK_SERVER_PORT']
};
const compiler = getCompiler({ environment, input, disk });
const compiler = getCompiler({ environment, input, disk, loader });
clearOutput(compiler.compilers[0].outputPath)
const server = new WebpackDevServer(devServerOptions, compiler);
const portChecker = require('express')().listen(process.env['NULLSTACK_SERVER_PORT'], () => {
Expand Down Expand Up @@ -173,6 +173,7 @@ program
.option('-e, --env <name>', 'Name of the environment file that should be loaded')
.option('-d, --disk', 'Write files to disk')
.option('-c, --cold', 'Disable hot module replacement')
.addOption(new program.Option('-l, --loader <loader>', 'Use Babel or SWC loader').choices(['swc', 'babel']))
.helpOption('-h, --help', 'Learn more about this command')
.action(start)

Expand Down
2 changes: 2 additions & 0 deletions tests/src/Application.njs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import TextObserver from './TextObserver';
import BodyFragment from './BodyFragment';
import ArrayAttributes from './ArrayAttributes';
import RouteScroll from './RouteScroll';
import IsomorphicImport from './IsomorphicImport.njs';

class Application extends Nullstack {

Expand Down Expand Up @@ -133,6 +134,7 @@ class Application extends Nullstack {
<BodyFragment route="/body-fragment" />
<ArrayAttributes route="/array-attributes" />
<RouteScroll route="/route-scroll/*" key="routeScroll" />
<IsomorphicImport route="/isomorphic-import" />
<ErrorPage route="*" />
</body>
)
Expand Down
40 changes: 40 additions & 0 deletions tests/src/IsomorphicImport.njs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Nullstack from 'nullstack';
import { clientOnly } from './helpers';
import { serverOnly } from './helpers';
import { serverOnly as serverOnlyAlias } from './helpers';
import { clientOnly as clientOnlyAlias } from './helpers';
import * as namespacedImport from './helpers';

class IsomorphicImport extends Nullstack {

static async serverFunction() {
return {
serverOnly: serverOnly(),
serverOnlyAlias: serverOnlyAlias(),
namespacedServerOnly: namespacedImport.serverOnly(),
}
}

async initiate() {
const data = await this.serverFunction()
Object.assign(this, data)
this.clientOnly = clientOnly()
this.clientOnlyAlias = clientOnlyAlias()
}

render() {
return (
<div
data-hydrated={this.hydrated}
data-server-only={this.serverOnly}
data-server-only-alias={this.serverOnlyAlias}
data-client-only={this.clientOnly}
data-client-only-alias={this.clientOnlyAlias}
data-namespaced-server-only={this.namespacedServerOnly}
/>
)
}

}

export default IsomorphicImport;
33 changes: 33 additions & 0 deletions tests/src/IsomorphicImport.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
describe('IsomorphicImport', () => {

beforeEach(async () => {
await page.goto('http://localhost:6969/isomorphic-import');
await page.waitForSelector('[data-hydrated]');
});

test('isomorphic imports used in the client stay in the client bundle', async () => {
const element = await page.$('[data-client-only]');
expect(element).toBeTruthy();
});

test('isomorphic aliased imports used in the client stay in the client bundle', async () => {
const element = await page.$('[data-client-only-alias]');
expect(element).toBeTruthy();
});

test('isomorphic imports used in the server only are removed from the client bundle', async () => {
const element = await page.$('[data-server-only]');
expect(element).toBeTruthy();
});

test('isomorphic aliased imports used in the server only are removed from the client bundle', async () => {
const element = await page.$('[data-server-only-alias]');
expect(element).toBeTruthy();
});

test('isomorphic namespaced imports used in the server only are removed from the client bundle', async () => {
const element = await page.$('[data-namespaced-server-only]');
expect(element).toBeTruthy();
});

});
4 changes: 0 additions & 4 deletions tests/src/ServerFunctions.njs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// server function works
import { readFileSync } from 'fs';
import Nullstack from 'nullstack';
import { clientOnly, serverOnly } from './helpers';

const decodedString = "! * ' ( ) ; : @ & = + $ , / ? % # [ ]"

Expand Down Expand Up @@ -40,7 +39,6 @@ class ServerFunctions extends Nullstack {
}

static async useNodeFileSystem() {
serverOnly();
const text = readFileSync('src/ServerFunctions.njs', 'utf-8');
return text.split(`\n`)[0].trim();
}
Expand Down Expand Up @@ -76,7 +74,6 @@ class ServerFunctions extends Nullstack {

async hydrate() {
this.underlineRemovedFromClient = !ServerFunctions._privateFunction;
this.clientOnly = clientOnly();
this.doublePlusOneClient = await ServerFunctions.getDoublePlusOne({ number: 34 })
this.acceptsSpecialCharacters = await this.getEncodedString({ string: decodedString })
this.hydratedOriginalUrl = await ServerFunctions.getRequestUrl()
Expand All @@ -92,7 +89,6 @@ class ServerFunctions extends Nullstack {
<div data-year={this.year} />
<div data-statement={this.statement} />
<div data-response={this.response} />
<div data-client-only={this.clientOnly} />
<div data-double-plus-one-server={this.doublePlusOneServer === 69} />
<div data-double-plus-one-client={this.doublePlusOneClient === 69} />
<div data-accepts-special-characters={this.acceptsSpecialCharacters} />
Expand Down
5 changes: 0 additions & 5 deletions tests/src/ServerFunctions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,6 @@ describe('ServerFunctions', () => {
expect(element).toBeTruthy();
});

test('isomorphic imports stay in the client', async () => {
const element = await page.$('[data-client-only]');
expect(element).toBeTruthy();
});

test('server functions can be invoked from the constructor constant on server', async () => {
await page.waitForSelector('[data-double-plus-one-server]');
const element = await page.$('[data-double-plus-one-server]');
Expand Down
2 changes: 1 addition & 1 deletion types/ClientContext.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export type NullstackClientContext<TProps = unknown> = TProps & {
/**
* Callback function that bootstrap the context for the application.
*/
start?: () => void;
start?: () => Promise<void>;

/**
* Information about the document `head` metatags.
Expand Down
2 changes: 1 addition & 1 deletion types/ServerContext.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export type NullstackServerContext<TProps = unknown> = TProps & {
/**
* Callback function that bootstrap the context for the application.
*/
start?: () => void;
start?: () => Promise<void>;

/**
* Information about the app manifest and some metatags.
Expand Down
Loading