Skip to content

Commit

Permalink
v1.1.12
Browse files Browse the repository at this point in the history
Moved base_addon folder to fetch from github
  • Loading branch information
dakln committed Oct 17, 2024
1 parent c88f88f commit 6c18f58
Show file tree
Hide file tree
Showing 8 changed files with 115 additions and 105 deletions.
3 changes: 3 additions & 0 deletions addon_base/plugin/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ const SCRIPTS = [];

const FILES = [];

const ICON_NAME = "";
const ICON_TYPE = "";

const SDK = globalThis.SDK;

const PLUGIN_CLASS = SDK.Plugins[ADDON_ID] = class LostPlugin extends SDK.IPluginBase {
Expand Down
33 changes: 16 additions & 17 deletions cli.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,17 @@
#!/usr/bin/env deno run --allow-read --allow-write --unstable
import { getLibraryDirectory, path } from "./deps.ts"
import { parseArgs } from "jsr:@std/[email protected]";
import { Colors } from "./deps.ts";
import { buildAddon } from "./cli/main.ts";
import type { AddonType } from "./lib/common.ts";

//const __dirname: string = getLibraryDirectory();

let __dirname: string //= path.dirname(path.fromFileUrl(import.meta.url));

if (import.meta.url.startsWith('file:')) {
__dirname = path.fromFileUrl(import.meta.url);
} else {
// Обработка https: URL
__dirname = new URL(import.meta.url).pathname;
}

const VERSION = '1.1.11'
const VERSION = '1.1.12'

type LostCommand = 'none' | 'help' | 'version' | 'build' | 'create' | 'serve';

async function main() {
const { _, ...flags } = parseArgs(Deno.args, {
boolean: ["plugin"],
alias: {p: "plugin"},
boolean: ["plugin", "local-base"],
alias: {p: "plugin", l: "local-base"},
"--": true,
});

Expand All @@ -48,10 +36,20 @@ async function main() {
}
break;
case 'build':
await buildAddon({ serve: false, LIB_PATH: __dirname });
if (!flags['local-base']) {
await buildAddon({ serve: false, localBase: false});
}
if (flags['local-base']) {
await buildAddon({ serve: false, localBase: true });
}
break;
case 'serve':
await buildAddon({ serve: true, LIB_PATH: __dirname });
if (!flags['local-base']) {
await buildAddon({ serve: true, localBase: false});
}
if (flags['local-base']) {
await buildAddon({ serve: true, localBase: true });
}
break;
case 'none':
console.error('❌', Colors.red(Colors.bold(`Unknown command:`)), Colors.italic(command));
Expand Down Expand Up @@ -97,5 +95,6 @@ function printHelp() {
console.log(' ⚙️', Colors.gray(' --plugin, -p'), ' Creates a bare-bones for "plugin" addon type.');

console.log(` ${Colors.yellow('build')}`);
console.log(' ⚙️', Colors.gray(' --local-base, -c'), ' Builds addon with local addon base.');
console.log(` ${Colors.yellow('serve')}`);
}
96 changes: 75 additions & 21 deletions cli/create-addon-structure.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import type { AddonType, IconType, LostConfig } from "../lib/common.ts";
import type { AddonType, LostConfig } from "../lib/common.ts";
import type { PluginProperty } from "../lib/plugin-props.ts";
import type { LostCategoryDefault } from "../lib/entities.ts";
import type { AddonScript } from "./get-addon-scripts.ts";
import type { AddonFile } from "./get-addon-files.ts";
import { BUILD_PATH } from "./paths.ts";
import { ADDON_BASE_URL, BUILD_PATH, LOCAL_ADDON_BASE_PATH } from "./paths.ts";
import type { AddonIcon } from "./get-addon-icon.ts";
import { Project } from "./cli-deps.ts";
import { path } from '../deps.ts';
import { LOGGER } from './misc.ts';

type AddonFiles = {
[K in AddonType]: [
readonly [K in AddonType]: [
`c3runtime/${K}.js`,
'c3runtime/type.js',
'instance.js',
Expand All @@ -36,7 +37,6 @@ const ADDON_FILES: AddonFiles = {
}

interface CreateAddonStructureOptions {
LIB_PATH: string;
CONFIG: LostConfig<'plugin' | 'behavior'>;
PLUGIN_PROPERTIES: PluginProperty[];
SCRIPTS: AddonScript[];
Expand All @@ -45,8 +45,8 @@ interface CreateAddonStructureOptions {
ICON: AddonIcon;
}

export async function createAddonStructure(options: CreateAddonStructureOptions) {
const {LIB_PATH, CONFIG, PLUGIN_PROPERTIES, SCRIPTS, FILES, ICON, CATEGORIES} = options;
export async function createAddonStructure(options: CreateAddonStructureOptions, localBase: boolean) {
const { CONFIG, PLUGIN_PROPERTIES, SCRIPTS, FILES, ICON, CATEGORIES } = options;
try {
await Deno.remove(BUILD_PATH, { recursive: true });
} catch (e) {
Expand All @@ -68,24 +68,77 @@ export async function createAddonStructure(options: CreateAddonStructureOptions)
})
};

await Deno.copyFile(ICON.path, `${BUILD_PATH}/${ICON.filename}`);

let instanceFileData = await transpileTsToJs(`${Deno.cwd()}/Addon/Instance.ts`) as string;
instanceFileData = instanceFileData.replace(/import\s+Config\s+from\s+["'](?:@config|\.\.\/lost\.config\.ts)["'];/, `const Config = ${JSON.stringify(CONFIG)};`);
await Deno.writeTextFile(`${BUILD_PATH}/c3runtime/instance.js`, instanceFileData);

ADDON_FILES[CONFIG.Type].forEach(async (file) => {
const baseAddonDir = path.resolve(LIB_PATH, `addon_base/${CONFIG.Type}`);
let data = await Deno.readTextFile(`${baseAddonDir}/${file}`);
data = data
.replace(/const\s+ADDON_ID\s*=\s*"";/, `const ADDON_ID = ${JSON.stringify(CONFIG.AddonId)};`)
.replace(/const\s+CONFIG\s*=\s*\{\};/, `const CONFIG = ${JSON.stringify(CONFIG)};`)
.replace(/const\s+PLUGIN_PROPERTIES\s*=\s*\{\};/, `const PLUGIN_PROPERTIES = ${JSON.stringify(PLUGIN_PROPERTIES)};`)
.replace(/const\s+REMOTE_SCRIPTS\s*=\s*\[\];/, `const REMOTE_SCRIPTS = ${JSON.stringify(CONFIG.RemoteScripts || [])};`)
.replace(/const\s+SCRIPTS\s*=\s*\[\];/, `const SCRIPTS = ${JSON.stringify(SCRIPTS)};`)
.replace(/const\s+FILES\s*=\s*\[\];/, `const FILES = ${JSON.stringify(FILES)};`)
await Deno.writeTextFile(path.resolve(BUILD_PATH, file), data);
})
if (!localBase) {
if (!ICON.isDefault) {
await Deno.copyFile(ICON.path, `${BUILD_PATH}/${ICON.filename}`);
} else {
const getIcon = await fetch(ICON.path);

if (!getIcon.ok) {
// failed to get default icon
LOGGER.Error('build', `Failed to download default icon from url: ${ICON.path}`)
Deno.exit();
} else {
const iconContent = await getIcon.text();
await Deno.writeTextFile(`${BUILD_PATH}/${ICON.filename}`, iconContent)
}
}

for await (const fileOrPath of ADDON_FILES[CONFIG.Type]) {
try {
const response = await fetch(`${ADDON_BASE_URL}/${CONFIG.Type}/${fileOrPath}`);

if (!response.ok) {
LOGGER.Error('build', `Failed to fetch ${fileOrPath}`, response.statusText);
Deno.exit();
}

let fileContent = await response.text();

fileContent = fileContent
.replace(/const\s+ADDON_ID\s*=\s*"";/, `const ADDON_ID = ${JSON.stringify(CONFIG.AddonId)};`)
.replace(/const\s+CONFIG\s*=\s*\{\};/, `const CONFIG = ${JSON.stringify(CONFIG)};`)
.replace(/const\s+PLUGIN_PROPERTIES\s*=\s*\{\};/, `const PLUGIN_PROPERTIES = ${JSON.stringify(PLUGIN_PROPERTIES)};`)
.replace(/const\s+REMOTE_SCRIPTS\s*=\s*\[\];/, `const REMOTE_SCRIPTS = ${JSON.stringify(CONFIG.RemoteScripts || [])};`)
.replace(/const\s+SCRIPTS\s*=\s*\[\];/, `const SCRIPTS = ${JSON.stringify(SCRIPTS)};`)
.replace(/const\s+FILES\s*=\s*\[\];/, `const FILES = ${JSON.stringify(FILES)};`)

await Deno.writeTextFile(path.resolve(BUILD_PATH, fileOrPath), fileContent);

} catch (error) {
LOGGER.Error('build', `Error processing ${fileOrPath}:`, error);
Deno.exit();
}
}
} else {
if (!ICON.isDefault) {
await Deno.copyFile(`${LOCAL_ADDON_BASE_PATH}/${ICON.filename}`, `${BUILD_PATH}/${ICON.filename}`);
} else {
const iconContent = await Deno.readTextFile(`${LOCAL_ADDON_BASE_PATH}/${ICON.filename}`);
await Deno.writeTextFile(`${BUILD_PATH}/${ICON.filename}`, iconContent);
}

for await (const fileOrPath of ADDON_FILES[CONFIG.Type]) {

let fileContent = await Deno.readTextFile(`${LOCAL_ADDON_BASE_PATH}/${CONFIG.Type}/${fileOrPath}`);

fileContent = fileContent
.replace(/const\s+ADDON_ID\s*=\s*"";/, `const ADDON_ID = ${JSON.stringify(CONFIG.AddonId)};`)
.replace(/const\s+CONFIG\s*=\s*\{\};/, `const CONFIG = ${JSON.stringify(CONFIG)};`)
.replace(/const\s+PLUGIN_PROPERTIES\s*=\s*\{\};/, `const PLUGIN_PROPERTIES = ${JSON.stringify(PLUGIN_PROPERTIES)};`)
.replace(/const\s+REMOTE_SCRIPTS\s*=\s*\[\];/, `const REMOTE_SCRIPTS = ${JSON.stringify(CONFIG.RemoteScripts || [])};`)
.replace(/const\s+SCRIPTS\s*=\s*\[\];/, `const SCRIPTS = ${JSON.stringify(SCRIPTS)};`)
.replace(/const\s+FILES\s*=\s*\[\];/, `const FILES = ${JSON.stringify(FILES)};`)
.replace(/const\s+ICON_NAME\s*=\s*"";/, `const ICON_NAME = ${JSON.stringify(ICON.filename)};`)
.replace(/const\s+ICON_TYPE\s*=\s*"";/, `const ICON_TYPE = ${JSON.stringify(ICON.type)};`)

await Deno.writeTextFile(path.resolve(BUILD_PATH, fileOrPath), fileContent);
}
}

const setializedEntities = serializeEntities(CATEGORIES);

Expand All @@ -95,6 +148,7 @@ export async function createAddonStructure(options: CreateAddonStructureOptions)
await Deno.writeTextFile(path.resolve(BUILD_PATH, 'c3runtime', 'conditions.js'), entities);
entities = `const ADDON_ID = ${JSON.stringify(CONFIG.AddonId)};\nconst C3 = globalThis.C3;\nC3.Plugins[ADDON_ID].Exps = ${setializedEntities.Expressions};`;
await Deno.writeTextFile(path.resolve(BUILD_PATH, 'c3runtime', 'expressions.js'), entities);

}

function serializeEntities(categories: LostCategoryDefault[]) {
Expand Down Expand Up @@ -148,7 +202,7 @@ async function transpileTsToJs(filePath: string): Promise<string | null> {
const project = new Project({
compilerOptions: {
target: 8,
module: 7
module: 7
}
});
const sourceFile = project.addSourceFileAtPath(filePath);
Expand Down
16 changes: 6 additions & 10 deletions cli/get-addon-icon.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@

import { path } from '../deps.ts';
import type { IconType } from "../lib/common.ts";
import { LOGGER, WarningMessage } from "./misc.ts";
import { ADDON_ICON_FOLDER_PATH } from "./paths.ts";
import { ADDON_DEFAULT_ICON_URL, ADDON_ICON_FOLDER_PATH } from "./paths.ts";

export interface AddonIcon {
filename: string;
path: string;
type: IconType;
isDefault?: true;
}

interface GetAddonIconOptions {
LIB_PATH: string;
}

export async function getAddonIcon(options: GetAddonIconOptions): Promise<AddonIcon> {
const { LIB_PATH } = options;
export async function getAddonIcon(): Promise<AddonIcon> {
LOGGER.Searching('Looking for addon icon in png/svg format')
for await (const entry of Deno.readDir(ADDON_ICON_FOLDER_PATH)) {
if (entry.isFile) {
Expand All @@ -34,7 +29,8 @@ export async function getAddonIcon(options: GetAddonIconOptions): Promise<AddonI
LOGGER.Warning(WarningMessage.ICON_NOT_DETECTED_OR_WRONG_FORMAT);
return {
filename: 'icon.svg',
path: path.resolve(LIB_PATH, 'addon_base', 'icon.svg'),
type: 'image/svg+xml'
path: ADDON_DEFAULT_ICON_URL,
type: 'image/svg+xml',
isDefault: true
};
}
11 changes: 6 additions & 5 deletions cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ import { serveAddon } from "./serve-addon.ts";

interface BuildOptions {
serve: boolean;
LIB_PATH: string;
localBase: boolean;
}

export async function buildAddon(options: BuildOptions) {
const startTime = performance.now();
const {serve, LIB_PATH} = options;
const { serve, localBase } = options;

LOGGER.Clear();
LOGGER.Process('Fetching addon files');
Expand All @@ -31,12 +31,13 @@ export async function buildAddon(options: BuildOptions) {
LOGGER.LogBetweenLines('📃', Colors.bold('Plugin properties count:'), Colors.bold(Colors.yellow(`${PLUGIN_PROPERTIES.length}`)))
const SCRIPTS = await getAddonScripts(CONFIG);
const FILES = await getAddonFiles(CONFIG);
const ICON = await getAddonIcon({ LIB_PATH });
const ICON = await getAddonIcon();
const CATEGORIES = await getCategories();
LOGGER.Line();
LOGGER.Process('Building addon');
LOGGER.Info(`${Colors.gray('Addon base:')} ${(localBase) ? 'local' : 'online'}`);

await createAddonStructure({LIB_PATH, CONFIG, PLUGIN_PROPERTIES, SCRIPTS, FILES, CATEGORIES, ICON});
await createAddonStructure({CONFIG, PLUGIN_PROPERTIES, SCRIPTS, FILES, CATEGORIES, ICON}, localBase);

await createAddonJSON({CONFIG, ICON, SCRIPTS, FILES});

Expand All @@ -53,5 +54,5 @@ export async function buildAddon(options: BuildOptions) {

const endTime = performance.now();
const elapsedTime = endTime - startTime;
LOGGER.Timer(` Addon build time: ${Colors.bold(Colors.yellow(String(elapsedTime.toFixed(2))))} ms`);
LOGGER.LogBetweenLines('⏱️', ` Addon build time: ${Colors.bold(Colors.yellow(String(elapsedTime.toFixed(2))))} ms!`);
}
6 changes: 5 additions & 1 deletion cli/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ export const ADDON_CATEGORIES_FOLDER_PATH = `${Deno.cwd()}/Addon/Categories`;

export const ADDON_ICON_FOLDER_PATH = `${Deno.cwd()}/Addon`;

//export const DEFAULT_ICON_PATH = path.join(__dirname, 'plugin_base', 'ico.svg');
export const LOCAL_ADDON_BASE_PATH = `${Deno.cwd()}/_base`;

export const ADDON_DEFAULT_ICON_URL = `https://raw.githubusercontent.com/lostinmind-dev/lost-c3/refs/heads/master/addon_base/icon.svg`

export const ADDON_BASE_URL = `https://raw.githubusercontent.com/lostinmind-dev/lost-c3/refs/heads/master/addon_base/`
3 changes: 2 additions & 1 deletion deno.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@lost-c3/lib",
"version": "1.1.11",
"version": "1.1.12",
"exports": {
".": "./mod.ts",
"./cli": "./cli.ts"
Expand Down Expand Up @@ -32,6 +32,7 @@
"cover.png"
],
"exclude": [
"addon_base",
".github",
"addon_base",
"./cli/src/",
Expand Down
52 changes: 2 additions & 50 deletions deps.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,2 @@
import * as path from 'jsr:@std/[email protected]';
export * as Colors from 'jsr:@std/[email protected]/colors';

export function getLibraryDirectory(): string {
// Получаем URL текущего модуля
const moduleUrl = new URL(import.meta.url);

console.log("Debug: Module URL:", moduleUrl.toString());

if (moduleUrl.protocol === "file:") {
// Если это файловая система, преобразуем URL в путь
const modulePath = path.fromFileUrl(moduleUrl);
console.log("Debug: File path:", modulePath);
return path.dirname(modulePath);
} else if (moduleUrl.protocol === "https:") {
// Если это HTTPS URL (например, при использовании через JSR)
const denoDir = Deno.env.get("DENO_DIR") || getDefaultDenoDir();
console.log("Debug: Deno Dir:", denoDir);

// Извлекаем относительный путь из URL
const relativePath = moduleUrl.pathname.split("/").slice(1).join("/");
console.log("Debug: Relative path:", relativePath);

// Формируем путь к кэшированной версии пакета
const cachedPath = path.join(denoDir, "deps", "https", "jsr.io", relativePath);
console.log("Debug: Cached path:", cachedPath);

return path.dirname(cachedPath);
}

console.error("Error: Unable to determine library directory");
console.error("Module URL:", moduleUrl.toString());
console.error("DENO_DIR:", Deno.env.get("DENO_DIR"));
console.error("Default Deno Dir:", getDefaultDenoDir());

throw new Error("Не удалось определить директорию библиотеки");
}

function getDefaultDenoDir(): string {
switch (Deno.build.os) {
case "windows":
return path.join(Deno.env.get("LOCALAPPDATA") || "", "deno");
case "darwin":
return path.join(Deno.env.get("HOME") || "", "Library", "Caches", "deno");
default: // linux and other unix systems
return path.join(Deno.env.get("XDG_CACHE_HOME") || path.join(Deno.env.get("HOME") || "", ".cache"), "deno");
}
}

export { path };
export * as path from 'jsr:@std/[email protected]';
export * as Colors from 'jsr:@std/[email protected]/colors';

0 comments on commit 6c18f58

Please sign in to comment.