Skip to content

Commit

Permalink
Merge pull request #692 from smapiot/develop
Browse files Browse the repository at this point in the history
Release 1.5.4
  • Loading branch information
FlorianRappl authored Apr 23, 2024
2 parents ef6b384 + 9d8c3d9 commit 93f2192
Show file tree
Hide file tree
Showing 16 changed files with 247 additions and 71 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Piral Changelog

## 1.5.4 (tbd)

- Fixed `pilet build` with `--type standalone` to end up at feed selection
- Improved handling of server restart (#687)
- Updated `piral-cli` to also include the *.krasrc* from the current directory (#691)
- Updated `piral-blazor` to contain support for Piral.Blazor providers
- Added `defineVue3Middleware` function to `piral-vue3` (#689)

## 1.5.3 (April 10, 2024)

- Fixed handling of Zone.js across different Angular versions
Expand Down
2 changes: 1 addition & 1 deletion src/converters/piral-blazor/src/interop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function prepareForStartup() {
function createBlazorStarter(publicPath: string): (opts: WebAssemblyStartOptions) => Promise<BlazorRootConfig> {
const root = document.body.appendChild(document.createElement('div'));

root.style.display = 'none';
root.style.display = 'contents';
root.id = 'blazor-root';

if (publicPath) {
Expand Down
43 changes: 43 additions & 0 deletions src/converters/piral-vue-3/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,49 @@ Transforms a standard Vue@3 component into a component that can be used in Piral

The extension slot component to be used in Vue@3 components. This is not really needed, as it is made available automatically via a Vue@3 custom element named `extension-component`.

### `defineVue3Middleware`

This function is used to declare additional middleware such as plugins when setting up Vue3.

Example in a standalone pilet:

```ts
import { fromVue3, defineVue3Middleware } from 'piral-vue-3/convert';
import Page from './Page.vue';
import i18next from 'i18next';
import I18NextVue from 'i18next-vue';
import type { PiletApi } from 'sample-piral';

i18next.init({
lng: 'de',
interpolation: {
escapeValue: false
},
fallbackLng: false,
resources: {
en: {
translation: {
greeter: "Welcome",
},
},
de: {
translation: {
greeter: "Willkommen",
},
},
}
});

export function setup(app: PiletApi) {
defineVue3Middleware(vue => {
vue.use(I18NextVue, { i18next });
});
app.registerPage('/sample', fromVue3(Page));
}
```

Here we integrate the `i18next` plugin using the `i18next-vue` package. By defining the middleware using the `defineVue3Middleware` and the provided callback, we can integrate the plugin without requiring any access to the original `app` instance of Vue.

## Usage

::: summary: For pilet authors
Expand Down
7 changes: 4 additions & 3 deletions src/converters/piral-vue-3/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@ export interface Vue3Converter {
export function createVue3Converter(...params: Parameters<typeof createConverter>) {
const convert = createConverter(...params);
const Extension = convert.Extension;
const defineMiddleware = convert.defineMiddleware;
const from: Vue3Converter = (root, captured) => ({
type: 'html',
component: convert(root, captured),
});

return { from, Extension };
return { from, Extension, defineMiddleware };
}

const { from: fromVue3, Extension: Vue3Extension } = createVue3Converter();
const { from: fromVue3, Extension: Vue3Extension, defineMiddleware: defineVue3Middleware } = createVue3Converter();

export { fromVue3, Vue3Extension };
export { fromVue3, Vue3Extension, defineVue3Middleware };
10 changes: 9 additions & 1 deletion src/converters/piral-vue-3/src/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { ForeignComponent, BaseComponentProps } from 'piral-core';
import { Component, App } from 'vue';
import { createExtension } from './extension';
import { mountVue } from './mount';
import { Vue3MiddlewareHandler } from './types';

export interface Vue3ConverterOptions {
/**
Expand All @@ -23,15 +24,17 @@ interface Vue3State {
export function createConverter(config: Vue3ConverterOptions = {}) {
const { rootName = 'piral-slot', selector = 'extension-component' } = config;
const Extension = createExtension(rootName);
const middlewares: Array<Vue3MiddlewareHandler> = [];
const convert = <TProps extends BaseComponentProps>(
root: Component<TProps>,
captured?: Record<string, any>,
): ForeignComponent<TProps> => ({
mount(parent, data, ctx, locals: Vue3State) {
const el = parent.appendChild(document.createElement(rootName));
const app = mountVue(root, data, ctx, captured);
app.mount(el);
middlewares.forEach((middleware) => middleware(app));
app.component(selector, createExtension(rootName));
app.mount(el);
!app._props && (app._props = {});
locals.instance = app;
},
Expand All @@ -47,5 +50,10 @@ export function createConverter(config: Vue3ConverterOptions = {}) {
},
});
convert.Extension = Extension;
convert.defineMiddleware = (middleware: Vue3MiddlewareHandler) => {
if (!middlewares.includes(middleware)) {
middlewares.push(middleware);
}
};
return convert;
}
1 change: 1 addition & 0 deletions src/converters/piral-vue-3/src/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export function createVue3Api(config: Vue3Config = {}): PiralPlugin<PiletVue3Api
};
},
Vue3Extension: convert.Extension,
defineVue3Middleware: convert.defineMiddleware,
};
};
}
16 changes: 15 additions & 1 deletion src/converters/piral-vue-3/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Component } from 'vue';
import type { App, Component } from 'vue';
import type { ForeignComponent, ExtensionSlotProps } from 'piral-core';

declare module 'piral-core/lib/types/custom' {
Expand All @@ -9,6 +9,16 @@ declare module 'piral-core/lib/types/custom' {
}
}

/**
* Defines a handler to set up Vue 3 middleware.
*/
export interface Vue3MiddlewareHandler {
/**
* Receives the app instance to integrate middleware.
*/
(app: App<Element>): void;
}

export interface Vue3Component<TProps> {
/**
* The root component of Vue rendering tree.
Expand Down Expand Up @@ -39,4 +49,8 @@ export interface PiletVue3Api {
* Vue component for displaying extensions of the given name.
*/
Vue3Extension: Component<ExtensionSlotProps>;
/**
* Function to use for declaring a callback to setup additional middleware.
*/
defineVue3Middleware(setup: Vue3MiddlewareHandler): void;
}
18 changes: 14 additions & 4 deletions src/tooling/piral-cli/src/apps/build-pilet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import {
retrievePiletsInfo,
flattenExternals,
triggerBuildPilet,
readText,
writeText,
} from '../common';

interface PiletData {
Expand Down Expand Up @@ -200,6 +202,7 @@ export async function buildPilet(baseDir = process.cwd(), options: BuildPiletOpt
const publicUrl = normalizePublicUrl(originalPublicUrl);
const fullBase = resolve(process.cwd(), baseDir);
const entryList = Array.isArray(entry) ? entry : [entry];
const manifest = 'pilets.json';
setLogLevel(logLevel);

await hooks.onBegin?.({ options, fullBase });
Expand Down Expand Up @@ -246,6 +249,7 @@ export async function buildPilet(baseDir = process.cwd(), options: BuildPiletOpt
if (type === 'standalone') {
const distDir = dirname(resolve(fullBase, target));
const outDir = resolve(distDir, 'standalone');
const outFile = 'index.html';
const { apps, root } = pilets[0];

if (apps.length === 0) {
Expand All @@ -264,7 +268,7 @@ export async function buildPilet(baseDir = process.cwd(), options: BuildPiletOpt

await copyPilets(outDir, pilets);

await createMetadata(outDir, '$pilet-api', pilets, publicUrl);
await createMetadata(outDir, manifest, pilets, publicUrl);

if (isEmulator) {
// in case of an emulator assets are not "seen" by the bundler, so we
Expand All @@ -287,7 +291,7 @@ export async function buildPilet(baseDir = process.cwd(), options: BuildPiletOpt
minify,
externals: [],
publicUrl,
outFile: 'index.html',
outFile,
outDir,
entryFiles: appFile,
logLevel,
Expand All @@ -313,7 +317,7 @@ export async function buildPilet(baseDir = process.cwd(), options: BuildPiletOpt
minify,
externals: flattenExternals(externals),
publicUrl,
outFile: 'index.html',
outFile,
outDir,
entryFiles: appFile,
logLevel,
Expand All @@ -324,9 +328,15 @@ export async function buildPilet(baseDir = process.cwd(), options: BuildPiletOpt
);
}

const html = await readText(outDir, outFile);
const newHtml = html.replace(
'<script', // place the assignment before the first seen script
`<script>window['dbg:pilet-api']=${JSON.stringify(publicUrl + manifest)};</script><script`,
);
await writeText(outDir, outFile, newHtml);

logDone(`Standalone app available at "${outDir}"!`);
} else if (type === 'manifest') {
const manifest = 'pilets.json';
const outDir = dirname(resolve(fullBase, target));

logInfo('Building pilet manifest ...');
Expand Down
57 changes: 37 additions & 20 deletions src/tooling/piral-cli/src/apps/debug-pilet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,27 +235,23 @@ export async function debugPilet(baseDir = process.cwd(), options: DebugPiletOpt

await hooks.onBegin?.({ options, fullBase });

const watcherRef = await watcherTask(async (watcherContext) => {
progress('Reading configuration ...');
const entryList = Array.isArray(entry) ? entry : [entry];
const multi = entryList.length > 1 || entryList[0].indexOf('*') !== -1;
log(
'generalDebug_0003',
`Looking for (${multi ? 'multi' : 'single'}) "${entryList.join('", "')}" in "${fullBase}".`,
);
progress('Reading configuration ...');

const allEntries = await matchAnyPilet(fullBase, entryList);
const maxListeners = Math.max(2 + allEntries.length * 2, 16);
log('generalDebug_0003', `Found the following entries: ${allEntries.join(', ')}`);
const entryList = Array.isArray(entry) ? entry : [entry];
const multi = entryList.length > 1 || entryList[0].indexOf('*') !== -1;
log(
'generalDebug_0003',
`Looking for (${multi ? 'multi' : 'single'}) "${entryList.join('", "')}" in "${fullBase}".`,
);

if (allEntries.length === 0) {
fail('entryFileMissing_0077');
}
const allEntries = await matchAnyPilet(fullBase, entryList);
log('generalDebug_0003', `Found the following entries: ${allEntries.join(', ')}`);

process.stderr?.setMaxListeners(maxListeners);
process.stdout?.setMaxListeners(maxListeners);
process.stdin?.setMaxListeners(maxListeners);
if (allEntries.length === 0) {
fail('entryFileMissing_0077');
}

const buildRef = await watcherTask(async (watcherContext) => {
const pilets = await concurrentWorkers(allEntries, concurrency, async (entryModule) => {
const targetDir = dirname(entryModule);
const { peerDependencies, peerModules, root, apps, ignored, importmap, schema } = await retrievePiletData(
Expand Down Expand Up @@ -326,14 +322,25 @@ export async function debugPilet(baseDir = process.cwd(), options: DebugPiletOpt
// sanity check see #250
checkSanity(pilets);

Promise.all(pilets.map((p) => p.bundler.ready())).then(() => logDone(`Ready!`));

return { pilets };
});

const watcherRef = await watcherTask(async (watcherContext) => {
const { pilets } = buildRef.data;
const maxListeners = Math.max(2 + allEntries.length * 2, 16);

process.stderr?.setMaxListeners(maxListeners);
process.stdout?.setMaxListeners(maxListeners);
process.stdin?.setMaxListeners(maxListeners);

await hooks.beforeApp?.({ appInstanceDir, pilets });

const appInstances: Array<PiralInstanceInfo> = appInstanceDir
? [[appInstanceDir, 0]]
: await getOrMakeApps(pilets[0], logLevel);

Promise.all(pilets.map((p) => p.bundler.ready())).then(() => logDone(`Ready!`));

pilets.forEach((p) => p.bundler.start());

if (appInstances.length === 0) {
Expand All @@ -351,7 +358,7 @@ export async function debugPilet(baseDir = process.cwd(), options: DebugPiletOpt
});
}

await platform.startModule({
const update = await platform.startModule({
appDir,
pilets,
customkrasrc,
Expand All @@ -369,6 +376,16 @@ export async function debugPilet(baseDir = process.cwd(), options: DebugPiletOpt
return watcherContext.watch(file);
},
});

const handleUpdate = () => {
const { pilets } = buildRef.data;
pilets.forEach((p) => p.bundler.start());
update({ pilets });
};

buildRef.on(handleUpdate);

watcherContext.onClean(() => buildRef.off(handleUpdate));
}),
);

Expand Down
11 changes: 9 additions & 2 deletions src/tooling/piral-cli/src/apps/debug-piral.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,11 +180,10 @@ export async function debugPiral(baseDir = process.cwd(), options: DebugPiralOpt
const platform = configurePlatform();

const serverRef = await watcherTask(async (watcherContext) => {
watcherContext.dependOn(buildRef);
const { bundler, entryFiles, root } = buildRef.data;
const targetDir = dirname(entryFiles);

await platform.startShell({
const update = await platform.startShell({
bundler,
customkrasrc,
feed,
Expand All @@ -202,6 +201,14 @@ export async function debugPiral(baseDir = process.cwd(), options: DebugPiralOpt
return watcherContext.watch(file);
},
});

const handleUpdate = () => {
const { bundler } = buildRef.data;
update({ bundler });
};

buildRef.on(handleUpdate);
watcherContext.onClean(() => buildRef.off(handleUpdate));
});

await Promise.all([buildRef.end, serverRef.end]);
Expand Down
8 changes: 6 additions & 2 deletions src/tooling/piral-cli/src/common/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@ export interface NodePlatformSettings {

export type PlatformSettings = WebPlatformSettings | NodePlatformSettings;

export interface UpdatePlatformOptions {
(options: any): void;
}

export interface PlatformTarget {
startShell(options: PlatformStartShellOptions): Promise<void>;
startModule(options: PlatformStartModuleOptions): Promise<void>;
startShell(options: PlatformStartShellOptions): Promise<UpdatePlatformOptions>;
startModule(options: PlatformStartModuleOptions): Promise<UpdatePlatformOptions>;
}

export function configurePlatform(target: Partial<PlatformSettings> = {}): PlatformTarget {
Expand Down
Loading

0 comments on commit 93f2192

Please sign in to comment.