Skip to content

Commit

Permalink
#296: second iteration
Browse files Browse the repository at this point in the history
mandatory caller in imports.
  • Loading branch information
petermasking committed Apr 5, 2024
1 parent ff8d8d1 commit e3f95ed
Show file tree
Hide file tree
Showing 17 changed files with 74 additions and 81 deletions.
17 changes: 9 additions & 8 deletions packages/caching/src/building/SegmentCacheWriter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ export default class SegmentCacheWriter

async #writeWorkerCache(cache: SegmentCache): Promise<void>
{
const importCode = this.#createImportCode(cache.imports);
const segmentCode = this.#createSegmentCode(cache.name, cache.procedures);

const filename = createWorkerFilename(cache.name);
const importCode = this.#createImportCode(cache.imports, filename);
const segmentCode = this.#createSegmentCode(cache.name, cache.procedures, filename);

const code = `${importCode}\n${segmentCode}`;

return this.#fileManager.write(filename, code);
Expand All @@ -37,28 +37,29 @@ export default class SegmentCacheWriter
async #writeRepositoryCache(cache: SegmentCache): Promise<void>
{
const filename = createRepositoryFilename(cache.name);
const code = `export const files = [\n\t"${[...cache.files].join('",\n\t"')}"\n];`;
const files = cache.files.map(file => `./${file}`);
const code = `export const files = [\n\t"${[...files].join('",\n\t"')}"\n];`;

return this.#fileManager.write(filename, code);
}

#createImportCode(imports: SegmentImport[]): string
#createImportCode(imports: SegmentImport[], filename: string): string
{
const codes: string[] = [];

for (const { members, from } of imports)
{
codes.push(`const { ${members.join(', ')} } = await __import("./${from}", "application", false);`);
codes.push(`const { ${members.join(', ')} } = await __import("${filename}", "./${from}", "application", false);`);
}

return codes.join('\n');
}

#createSegmentCode(name: string, procedures: SegmentProcedure[]): string
#createSegmentCode(name: string, procedures: SegmentProcedure[], filename: string): string
{
const codes: string[] = [];

codes.push('const { Segment, Procedure, Implementation, Version, NamedParameter, ArrayParameter, ObjectParameter } = await __import("jitar", "runtime", false);');
codes.push(`const { Segment, Procedure, Implementation, Version, NamedParameter, ArrayParameter, ObjectParameter } = await __import("${filename}", "jitar", "runtime", false);`);
codes.push(`export const segment = new Segment("${name}")`);

for (const procedure of procedures)
Expand Down
5 changes: 3 additions & 2 deletions packages/caching/src/building/utils/ImportRewriter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,18 @@ export default class ImportRewriter

#rewriteImport(dependency: ReflectionImport, scope: string, filename: string): string
{
const caller = this.#ensureRoot(filename);
const from = this.#rewriteImportFrom(dependency, filename);

if (dependency.members.length === 0)
{
return `await __import("${from}", "${scope}", true, "${filename}");`;
return `await __import("${caller}", "${from}", "${scope}", true);`;
}

const members = this.#rewriteImportMembers(dependency);
const extractDefault = this.#mustUseAs(dependency) ? 'true' : 'false';

return `const ${members} = await __import("${from}", "${scope}", ${extractDefault}, "${filename}");`;
return `const ${members} = await __import("${caller}", "${from}", "${scope}", ${extractDefault});`;
}

#rewriteImportFrom(dependency: ReflectionImport, filename: string): string
Expand Down
1 change: 1 addition & 0 deletions packages/jitar/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export
NamedParameter,
ArrayParameter,
ObjectParameter,
Import,
BadRequest,
Forbidden,
NotFound,
Expand Down
18 changes: 12 additions & 6 deletions packages/plugin-vite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ async function createImportCode(code: string, id: string, jitarFullPath: string,
exportCode += `export { ${functionKeys.join(', ')} };\n`;
}

return 'import { getClient } from "/jitar/client.js";\n'
+ `const module = await (await getClient()).import("./${jitarPath}${relativeId}");\n`
return 'import { getClient, Import } from "/jitar/client.js";\n'
+ `const module = await (await getClient()).import(new Import("", "./${jitarPath}${relativeId}", "application", false));\n`
+ importCode
+ exportCode;
}
Expand Down Expand Up @@ -105,23 +105,29 @@ export default function viteJitar(sourcePath: string, jitarPath: string, jitarUr
jitarFullPath = path.join(resolvedConfig.root, sourcePath, jitarPath);
},

resolveId(source: string)
resolveId(id: string)
{
if (source === '/jitar/client.js')
if (id === '/jitar/client.js')
{
return { id: source, external: 'absolute' };
return { id, external: 'absolute' };
}

return null;
},

async transform(code: string, id: string)
{
if (jitarFullPath === undefined || id.includes(jitarFullPath) === false)
if (jitarFullPath === undefined)
{
return code;
}

if (id.includes(jitarFullPath))
{
return undefined;
}

// TODO: refactor createImportCode to rewrite all the jitar (domain) related imports
return createImportCode(code, id, jitarFullPath, jitarPath);
},

Expand Down
6 changes: 2 additions & 4 deletions packages/runtime/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function getRuntime(): ProcedureRuntime
return _runtime;
}

export async function importModule(specifier: string, executionScope: ExecutionScope, extractDefault: boolean, source?: string): Promise<unknown>
export async function importModule(caller: string, specifier: string, executionScope: ExecutionScope, extractDefault: boolean): Promise<unknown>
{
const runtime = getRuntime();

Expand All @@ -33,9 +33,7 @@ export async function importModule(specifier: string, executionScope: ExecutionS
specifier = 'RUNTIME_HOOKS_LOCATION';
}

console.log('importModule', specifier, source);

const importModel = new Import(specifier, executionScope, extractDefault, source);
const importModel = new Import(caller, specifier, executionScope, extractDefault);
const module = await runtime.import(importModel);

return importModel.extractDefault && module.default !== undefined ? module.default : module;
Expand Down
10 changes: 5 additions & 5 deletions packages/runtime/src/models/Import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,24 @@ import { ExecutionScope } from '../definitions/ExecutionScope.js';

export default class Import
{
#caller: string;
#specifier: string;
#scope: ExecutionScope;
#extractDefault: boolean;
#source?: string;

constructor(specifier: string, scope: ExecutionScope, extractDefault: boolean = true, source?: string)
constructor(caller: string, specifier: string, scope: ExecutionScope, extractDefault: boolean = true)
{
this.#caller = caller;
this.#specifier = specifier;
this.#scope = scope;
this.#extractDefault = extractDefault;
this.#source = source;
}

get caller() { return this.#caller; }

get specifier() { return this.#specifier; }

get scope() { return this.#scope; }

get extractDefault() { return this.#extractDefault; }

get source() { return this.#source; }
}
35 changes: 21 additions & 14 deletions packages/runtime/src/services/LocalRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export default class LocalRepository extends Repository
return this.#readFile(filename);
}

readModule(source: string, specifier: string): Promise<File>
readModule(caller: string, specifier: string): Promise<File>
{
if (isSegmentFilename(specifier))
{
Expand All @@ -132,10 +132,13 @@ export default class LocalRepository extends Repository

if (this.#isSegmented(specifier) === false)
{
console.log('NOT SEGMENTED', specifier);
return this.#readWorkerModule(specifier);
}

return this.#bbb(source, specifier)
console.log('IS SEGMENTED', specifier);

return this.#inSameSegment(caller, specifier)
? this.#readWorkerModule(specifier)
: this.#readRemoteModule(specifier);
}
Expand All @@ -147,26 +150,22 @@ export default class LocalRepository extends Repository
return ModuleLoader.load(filename);
}

#bbb(source: string, specifier: string): boolean
async #readWorkerModule(specifier: string): Promise<File>
{
const sourceSegments = this.#aaa(source);
const specifierSegments = this.#aaa(specifier);

return sourceSegments.some(segmentName => specifierSegments.includes(segmentName));
}
console.log('WORKER MODULE', specifier);

async #readWorkerModule(name: string): Promise<File>
{
const filename = this.#getModuleFilename(name);
const filename = this.#getModuleFilename(specifier);
const file = await this.#readFile(filename);
const code = file.content.toString();

return new File(filename, 'application/javascript', code);
}

#readRemoteModule(name: string): Promise<File>
#readRemoteModule(specifier: string): Promise<File>
{
const remoteFilename = convertToRemoteFilename(name);
console.log('REMOTE MODULE', specifier);

const remoteFilename = convertToRemoteFilename(specifier);

return this.#readFile(remoteFilename);
}
Expand Down Expand Up @@ -196,7 +195,15 @@ export default class LocalRepository extends Repository
return this.#fileManager.read(filename);
}

#aaa(filename: string): string[]
#inSameSegment(firstFilename: string, secondFilename: string): boolean
{
const firstSegments = this.#filterSegments(firstFilename);
const secondSegments = this.#filterSegments(secondFilename);

return firstSegments.some(segmentName => secondSegments.includes(segmentName));
}

#filterSegments(filename: string): string[]
{
const segmentNames = [...this.#segments.keys()];

Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/src/services/LocalWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export default class LocalWorker extends Worker
async #loadSegment(name: string): Promise<void>
{
const filename = createWorkerFilename(name);
const importModel = new Import(filename, ExecutionScopes.APPLICATION);
const importModel = new Import('', filename, ExecutionScopes.APPLICATION);
const module = await this.import(importModel);
const segment = module.segment as Segment;

Expand Down
6 changes: 3 additions & 3 deletions packages/runtime/src/services/ProcedureRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,15 +112,15 @@ export default abstract class ProcedureRuntime extends Runtime implements Runner
}
}

async #importMiddleware(url: string): Promise<void>
async #importMiddleware(specifier: string): Promise<void>
{
const importModel = new Import(url, ExecutionScopes.APPLICATION);
const importModel = new Import('', specifier, ExecutionScopes.APPLICATION);
const module = await this.import(importModel);
const middleware = module.default as Middleware;

if (middleware?.handle === undefined)
{
throw new InvalidMiddleware(url);
throw new InvalidMiddleware(specifier);
}

this.addMiddleware(middleware);
Expand Down
1 change: 0 additions & 1 deletion packages/runtime/src/services/Remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ export default class Remote
async loadFile(filename: string): Promise<File>
{
const url = `${this.#url}/${filename}`;
console.log('load file', url);
const options = { method: 'GET' };

const response = await this.#callRemote(url, options);
Expand Down
4 changes: 2 additions & 2 deletions packages/runtime/src/services/RemoteRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ export default class RemoteRepository extends Repository
return this.#remote.loadFile(filename);
}

readModule(source: string, specifier: string): Promise<File>
readModule(caller: string, specifier: string): Promise<File>
{
return this.#remote.loadFile(`modules/${specifier}?source=${source}`);
return this.#remote.loadFile(`modules/${specifier}?caller=${caller}`);
}

loadModule(specifier: string): Promise<Module>
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/src/services/Repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default abstract class Repository extends Runtime

abstract readAsset(filename: string): Promise<File>;

abstract readModule(source: string, specifier: string): Promise<File>;
abstract readModule(caller: string, specifier: string): Promise<File>;

abstract loadModule(specifier: string): Promise<Module>;
}
6 changes: 3 additions & 3 deletions packages/runtime/src/services/Runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,15 @@ export default abstract class Runtime
}
}

async #importHealthCheck(url: string): Promise<void>
async #importHealthCheck(specifier: string): Promise<void>
{
const importModel = new Import(url, ExecutionScopes.APPLICATION);
const importModel = new Import('', specifier, ExecutionScopes.APPLICATION);
const module = await this.import(importModel);
const healthCheck = module.default as HealthCheck;

if (healthCheck?.isHealthy === undefined)
{
throw new InvalidHealthCheck(url);
throw new InvalidHealthCheck(specifier);
}

this.addHealthCheck(healthCheck as HealthCheck);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,11 @@ import LocalRepository from '../../../src/services/LocalRepository';
import { TestFileManager } from '../interfaces/FileManager.fixture';
import { SEGMENT_FILES } from '../models/Segment.fixture';

const CLIENT = { id: '' };

const defaultRepository = new LocalRepository(new TestFileManager());
defaultRepository.assets = new Set(['index.html']);

await defaultRepository.registerSegment('first', SEGMENT_FILES.FIRST);
await defaultRepository.registerSegment('second', SEGMENT_FILES.SECOND);
await defaultRepository.registerClient(['first']).then(clientId => CLIENT.id = clientId);

const dummyRepository = new DummyRepository();

Expand All @@ -33,4 +30,4 @@ const REPOSITORY_FILES =

Object.freeze(REPOSITORY_FILES);

export { REPOSITORIES, REPOSITORY_FILES, CLIENT };
export { REPOSITORIES, REPOSITORY_FILES };
19 changes: 1 addition & 18 deletions packages/runtime/test/services/LocalRepository.spec.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,15 @@

import { describe, expect, it } from 'vitest';

import InvalidClientId from '../../src/errors/InvalidClientId';
import ClientNotFound from '../../src/errors/ClientNotFound';

import FileNotFound from '../../src/errors/FileNotFound';
import { REPOSITORIES, REPOSITORY_FILES, CLIENT } from '../_fixtures/services/LocalRepository.fixture';
import { REPOSITORIES, REPOSITORY_FILES } from '../_fixtures/services/LocalRepository.fixture';

const repository = REPOSITORIES.DEFAULT;

describe('services/LocalRepository', () =>
{
describe('.readModule(clientId, filename)', () =>
{
it('should not accept an invalid client id', () =>
{
const run = async () => repository.readModule('/some/file', 'INVALID');

expect(run).rejects.toEqual(new InvalidClientId('INVALID'));
});

it('should not accept an unknown client id', () =>
{
const run = async () => repository.readModule('/some/file', 'CLIENT_9999');

expect(run).rejects.toEqual(new ClientNotFound('CLIENT_9999'));
});

it('should return an unsegmented module file', async () =>
{
const result = await repository.readModule(REPOSITORY_FILES.UNSEGMENTED, CLIENT.id);
Expand Down
4 changes: 2 additions & 2 deletions packages/server-nodejs/src/JitarServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ export default class JitarServer

for (const setUpScript of setUpScripts)
{
const importModel = new Import(setUpScript, ExecutionScopes.APPLICATION);
const importModel = new Import('', setUpScript, ExecutionScopes.APPLICATION);

await runtime.import(importModel);
}
Expand All @@ -243,7 +243,7 @@ export default class JitarServer

for (const tearDownScript of tearDownScripts)
{
const importModel = new Import(tearDownScript, ExecutionScopes.APPLICATION);
const importModel = new Import('', tearDownScript, ExecutionScopes.APPLICATION);

await runtime.import(importModel);
}
Expand Down
Loading

0 comments on commit e3f95ed

Please sign in to comment.