From 63098f3d59fa59a28d8f2089488e4e23e7be8120 Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Fri, 20 Oct 2023 13:23:54 +0200 Subject: [PATCH 01/12] add explicit type saefty for readObjectSync --- packages/core/src/configs/types.ts | 1 + packages/core/src/engines/index.ts | 31 ++++++----- packages/core/src/plugins/index.ts | 4 +- .../core/src/schema/configFiles/engine.ts | 1 + .../core/src/schema/configFiles/overrides.ts | 7 +++ .../core/src/schema/configFiles/project.ts | 10 ++-- .../core/src/schema/configFiles/template.ts | 31 +++++++++-- packages/core/src/schema/configFiles/types.ts | 4 ++ packages/core/src/system/fs.ts | 2 +- .../src/tasks/task.rnv.app.create.ts | 3 +- .../engine-core/src/tasks/task.rnv.new.ts | 54 ++++++++++--------- packages/engine-rn-electron/src/sdk.ts | 8 +-- packages/engine-rn-electron/src/types.ts | 5 ++ packages/sdk-apple/src/plistParser.ts | 7 +-- packages/sdk-apple/src/types.ts | 14 +++++ 15 files changed, 125 insertions(+), 57 deletions(-) create mode 100644 packages/core/src/schema/configFiles/overrides.ts create mode 100644 packages/engine-rn-electron/src/types.ts diff --git a/packages/core/src/configs/types.ts b/packages/core/src/configs/types.ts index 8ade1263ba..ddd01d8394 100644 --- a/packages/core/src/configs/types.ts +++ b/packages/core/src/configs/types.ts @@ -9,6 +9,7 @@ export type NpmPackageFile = { description?: string; 'release-it'?: Record; name?: string; + main?: string; }; export type NpmPackageFileKey = keyof NpmPackageFile; diff --git a/packages/core/src/engines/index.ts b/packages/core/src/engines/index.ts index 8cbb4ba51c..484e92c0e3 100644 --- a/packages/core/src/engines/index.ts +++ b/packages/core/src/engines/index.ts @@ -168,17 +168,18 @@ export const loadEnginePluginDeps = async (c: RnvContext, engineConfigs: Array { - const engineConfig = readObjectSync(ecf.configPath); + const engineConfig = readObjectSync(ecf.configPath); - if (engineConfig?.plugins) { + const engPlugins = engineConfig?.plugins; + if (engPlugins) { const projectPlugins = c.files.project.config?.plugins; // Comparing original config causes engine think that template is not extended with additional deps // const projectPlugins = c.files.project.config_original.plugins; if (projectPlugins) { - Object.keys(engineConfig?.plugins).forEach((k) => { + Object.keys(engPlugins).forEach((k) => { if (!projectPlugins[k]) { hasAddedPlugins = true; - originalProjectPlugins[k] = engineConfig?.plugins[k]; + originalProjectPlugins[k] = engPlugins[k]; addedPlugins[k] = addedPlugins[k] || []; addedPlugins[k].push(k); } @@ -216,9 +217,9 @@ export const loadEnginePackageDeps = async (c: RnvContext, engineConfigs: Array< // Check engine dependencies const addedDeps = []; engineConfigs.forEach((ecf) => { - const engineConfig = readObjectSync(ecf.configPath); + const engineConfig = readObjectSync(ecf.configPath); c.buildConfig.defaults?.supportedPlatforms?.forEach((platform) => { - const npm = engineConfig?.platforms?.[platform]?.npm; + const npm = engineConfig?.platforms?.[platform]?.npm || {}; if (npm) { if (npm.devDependencies) { const deps = c.files.project.package.devDependencies || {}; @@ -233,8 +234,10 @@ export const loadEnginePackageDeps = async (c: RnvContext, engineConfigs: Array< logInfo( `Engine ${ecf.key} requires npm devDependency ${k} for platform ${platform}. ADDING...DONE` ); - deps[k] = npm?.devDependencies[k]; - addedDeps.push(k); + if (npm.devDependencies?.[k]) { + deps[k] = npm.devDependencies[k]; + addedDeps.push(k); + } } } }); @@ -254,8 +257,10 @@ export const loadEnginePackageDeps = async (c: RnvContext, engineConfigs: Array< logInfo( `Engine ${ecf.key} requires npm dependency ${k} for platform ${platform}. ADDING...DONE` ); - deps[k] = npm?.dependencies[k]; - addedDeps.push(k); + if (npm.dependencies?.[k]) { + deps[k] = npm.dependencies[k]; + addedDeps.push(k); + } } } }); @@ -268,8 +273,10 @@ export const loadEnginePackageDeps = async (c: RnvContext, engineConfigs: Array< logInfo( `Engine ${ecf.key} requires npm optionalDependency ${k} for platform ${platform}. ADDING...DONE` ); - deps[k] = npm?.optionalDependencies[k]; - addedDeps.push(k); + if (npm.optionalDependencies?.[k]) { + deps[k] = npm.optionalDependencies[k]; + addedDeps.push(k); + } } }); c.files.project.package.optionalDependencies = deps; diff --git a/packages/core/src/plugins/index.ts b/packages/core/src/plugins/index.ts index 93ff981ae5..2674a305e1 100644 --- a/packages/core/src/plugins/index.ts +++ b/packages/core/src/plugins/index.ts @@ -24,7 +24,7 @@ import { inquirerPrompt } from '../api'; import { writeRenativeConfigFile } from '../configs/utils'; import { installPackageDependencies } from '../projects/npm'; import { OverridesOptions, ResolveOptions } from '../system/types'; -import { ConfigFilePlugin, ConfigFilePlugins } from '../schema/configFiles/types'; +import { ConfigFileOverrides, ConfigFilePlugin, ConfigFilePlugins } from '../schema/configFiles/types'; const _getPluginScope = (plugin: RenativeConfigPlugin | string): RnvPluginScope => { if (typeof plugin === 'string') { @@ -631,7 +631,7 @@ const _overridePlugin = (c: RnvContext, pluginsPath: string, dir: string) => { if (overridePath && !fsExistsSync(overridePath)) { overridePath = path.resolve(pluginsPath, dir, 'overrides.json'); } - const overrideConfig = overridePath ? readObjectSync(overridePath) : null; + const overrideConfig = overridePath ? readObjectSync(overridePath) : null; const overrides = overrideConfig?.overrides; if (overrides) { Object.keys(overrides).forEach((k) => { diff --git a/packages/core/src/schema/configFiles/engine.ts b/packages/core/src/schema/configFiles/engine.ts index 530d2794e5..b8bf70402c 100644 --- a/packages/core/src/schema/configFiles/engine.ts +++ b/packages/core/src/schema/configFiles/engine.ts @@ -44,6 +44,7 @@ const EnginePlatform = z.object({ dependencies: z.optional(NpmDep), devDependencies: z.optional(NpmDep), peerDependencies: z.optional(NpmDep), + optionalDependencies: z.optional(NpmDep), }) ), }); diff --git a/packages/core/src/schema/configFiles/overrides.ts b/packages/core/src/schema/configFiles/overrides.ts new file mode 100644 index 0000000000..0afec0f830 --- /dev/null +++ b/packages/core/src/schema/configFiles/overrides.ts @@ -0,0 +1,7 @@ +import { z } from 'zod'; + +export const RootOverridesSchema = z.object({ + overrides: z.object({}), +}); + +export type _RootOverridesSchemaType = z.infer; diff --git a/packages/core/src/schema/configFiles/project.ts b/packages/core/src/schema/configFiles/project.ts index 5730ddbf6b..8ae44590d4 100644 --- a/packages/core/src/schema/configFiles/project.ts +++ b/packages/core/src/schema/configFiles/project.ts @@ -26,7 +26,7 @@ const MonoRoot = z.string().describe('Define custom path to monorepo root where const Env = z.record(z.string(), z.any()).describe('Object containing injected env variables'); -const Defaults = z +export const DefaultsSchema = z .object({ ports: z.optional(Ports), supportedPlatforms: z.optional(SupportedPlatforms), @@ -148,7 +148,7 @@ const Permissions = z 'Permission definititions which can be used by app configs via `includedPermissions` and `excludedPermissions` to customize permissions for each app' ); -const Engines = z.record(z.string(), Engine).describe('List of engines available in this project'); +export const EnginesSchema = z.record(z.string(), Engine).describe('List of engines available in this project'); const EnableHookRebuild = z .boolean() @@ -223,14 +223,14 @@ const RootProjectBaseFragment = { projectName: ProjectName, isMonorepo: z.optional(IsMonoRepo), isTemplate: z.boolean().optional(), - defaults: z.optional(Defaults), + defaults: z.optional(DefaultsSchema), pipes: z.optional(Pipes), templates: Templates, currentTemplate: CurrentTemplate, crypto: z.optional(Crypto), paths: z.optional(Paths), permissions: z.optional(Permissions), - engines: z.optional(Engines), + engines: z.optional(EnginesSchema), custom: z.optional(Ext), enableHookRebuild: z.optional(EnableHookRebuild), monoRoot: z.optional(MonoRoot), @@ -247,7 +247,7 @@ const RootProjectBaseFragment = { "Enables the equivalent to passing --skipDependencyCheck parameter on every rnv run so you don't have to use it" ), isNew: z - .string() + .boolean() .optional() .describe('Marker indicating that this project has just been bootstrapped. this prop is managed by rnv'), }; diff --git a/packages/core/src/schema/configFiles/template.ts b/packages/core/src/schema/configFiles/template.ts index 1617a47596..91a92f5652 100644 --- a/packages/core/src/schema/configFiles/template.ts +++ b/packages/core/src/schema/configFiles/template.ts @@ -1,16 +1,39 @@ import { z } from 'zod'; +import { DefaultsSchema, EnginesSchema } from './project'; + +const BootstrapQuestionsSchema = z + .array( + z.object({ + options: z + .array( + z.object({ + title: z.string(), + value: z.object({}), + }) + ) + .optional(), + configProp: z + .object({ + prop: z.string(), + key: z.string(), + }) + .optional(), + type: z.string(), + title: z.string(), + }) + ) + .describe('Defines list of custom bootstrap questions'); export const RootTemplateSchema = z.object({ + defaults: z.optional(DefaultsSchema), + engines: z.optional(EnginesSchema), templateConfig: z .object({ includedPaths: z .array(z.string()) .describe('Defines list of all file/dir paths you want to include in template') .optional(), - bootstrapQuestions: z - .array(z.record(z.any())) - .describe('Defines list of custom bootstrap questions') - .optional(), + bootstrapQuestions: BootstrapQuestionsSchema, }) .describe('Used in `renative.template.json` allows you to define template behaviour.') .optional(), diff --git a/packages/core/src/schema/configFiles/types.ts b/packages/core/src/schema/configFiles/types.ts index 839c2ee192..480869c4c2 100644 --- a/packages/core/src/schema/configFiles/types.ts +++ b/packages/core/src/schema/configFiles/types.ts @@ -11,6 +11,7 @@ import { _RootTemplateSchemaType } from './template'; import { _RootTemplatesSchemaType } from './templates'; import { _RootWorkspacesSchemaType } from './workspaces'; import { _RootRuntimeSchemaType } from './runtime'; +import { _RootOverridesSchemaType } from './overrides'; // renative.json export type ConfigFileProject = _RootProjectSchemaType; @@ -50,3 +51,6 @@ export type ConfigFileIntegration = _RootIntegrationSchemaType; // renative.runtime.json export type ConfigFileRuntime = _RootRuntimeSchemaType; + +//overrides.json +export type ConfigFileOverrides = _RootOverridesSchemaType; diff --git a/packages/core/src/system/fs.ts b/packages/core/src/system/fs.ts index 7f1897e1a8..d07aab1277 100755 --- a/packages/core/src/system/fs.ts +++ b/packages/core/src/system/fs.ts @@ -490,7 +490,7 @@ export const writeObjectSync = (filePath: string, obj: string | object, spaces: return writeFileSync(filePath, obj, spaces, addNewLine); }; -export const readObjectSync = (filePath?: string, sanitize?: boolean, c?: RnvContext) => { +export const readObjectSync = (filePath?: string, sanitize?: boolean, c?: RnvContext) => { logDebug(`readObjectSync:${sanitize}:${filePath}`); if (!filePath) { logDebug('readObjectSync: filePath is undefined'); diff --git a/packages/engine-core/src/tasks/task.rnv.app.create.ts b/packages/engine-core/src/tasks/task.rnv.app.create.ts index c85e1ec427..ea83f9df7a 100644 --- a/packages/engine-core/src/tasks/task.rnv.app.create.ts +++ b/packages/engine-core/src/tasks/task.rnv.app.create.ts @@ -16,6 +16,7 @@ import { TASK_APP_CREATE, PARAMS, } from '@rnv/core'; +import { ConfigFileApp } from '@rnv/core/lib/schema/configFiles/types'; export const taskRnvAppCreate: RnvTaskFn = async (c) => { logTask('taskRnvAppCreate'); @@ -120,7 +121,7 @@ export const taskRnvAppCreate: RnvTaskFn = async (c) => { logInfo('Copying new app config...DONE'); const confObjPath = path.join(destPath, 'renative.json'); - const confObj = readObjectSync(confObjPath); + const confObj = readObjectSync(confObjPath) || {}; confObj.id = appConfigId; confObj.common = confObj.common || {}; diff --git a/packages/engine-core/src/tasks/task.rnv.new.ts b/packages/engine-core/src/tasks/task.rnv.new.ts index 105668f8d5..eb79d6cb18 100644 --- a/packages/engine-core/src/tasks/task.rnv.new.ts +++ b/packages/engine-core/src/tasks/task.rnv.new.ts @@ -35,7 +35,7 @@ import { PlatformKey, commandExistsSync, } from '@rnv/core'; -import { ConfigFileProject } from '@rnv/core/lib/schema/configFiles/types'; +import { ConfigFileProject, ConfigFileTemplate } from '@rnv/core/lib/schema/configFiles/types'; type NewProjectData = { appTitle?: string; @@ -83,7 +83,7 @@ type NewProjectData = { }; gitEnabled?: boolean; optionPlatforms: { - selectedOptions?: Array; + selectedOptions?: Array; }; confirmString?: string; defaultProjectName?: string; @@ -162,17 +162,7 @@ type QuestionResults = Record< } >; -type BootstrapQuestions = Array<{ - options: Array<{ - title: string; - }>; - configProp: { - prop: string; - key: string; - }; - type: string; - title: string; -}>; +type BootstrapQuestions = Required['templateConfig']['bootstrapQuestions']; const interactiveQuestion = async ( results: QuestionResults, @@ -182,7 +172,7 @@ const interactiveQuestion = async ( if (bootstrapQuestions?.length) { for (let i = 0; i < bootstrapQuestions.length; i++) { const q = bootstrapQuestions[i]; - const qKey = q.configProp.key; + const qKey = q?.configProp?.key || ''; // inquirer will nest them if they look like an object const qKeyClean = qKey.replace('.', '__'); @@ -496,11 +486,12 @@ export const taskRnvNew = async (c: RnvContext) => { } } - const renativeTemplateConfig = readObjectSync( - path.join(c.paths.project.dir, 'node_modules', selectedInputTemplate, RENATIVE_CONFIG_TEMPLATE_NAME) - ); + const renativeTemplateConfig = + readObjectSync( + path.join(c.paths.project.dir, 'node_modules', selectedInputTemplate, RENATIVE_CONFIG_TEMPLATE_NAME) + ) || {}; - const renativeConfig = readObjectSync( + const renativeConfig = readObjectSync( path.join(c.paths.project.dir, 'node_modules', selectedInputTemplate, RENATIVE_CONFIG_NAME) ); @@ -537,7 +528,7 @@ export const taskRnvNew = async (c: RnvContext) => { // INPUT: Custom Questions // ================================================== const renativeTemplateConfigExt = {}; - const bootstrapQuestions = renativeTemplateConfig?.templateConfig?.bootstrapQuestions; + const bootstrapQuestions = renativeTemplateConfig?.templateConfig?.bootstrapQuestions || []; const results: QuestionResults = {}; const providedAnswers: Record = {}; @@ -634,7 +625,7 @@ export const taskRnvNew = async (c: RnvContext) => { const templates: Record< string, { - version?: string; + version: string; } > = {}; @@ -643,6 +634,10 @@ export const taskRnvNew = async (c: RnvContext) => { chalk().grey ); + if (!data.optionTemplates.selectedVersion) { + return; + } + if (data.optionTemplates.selectedOption) { templates[data.optionTemplates.selectedOption] = { version: data.optionTemplates.selectedVersion, @@ -651,12 +646,17 @@ export const taskRnvNew = async (c: RnvContext) => { delete renativeTemplateConfig.templateConfig; + if (!data.optionTemplates.selectedOption) { + logError('Current template not selected!'); + return; + } + const config: ConfigFileProject = { platforms: {}, ...renativeTemplateConfig, ...renativeTemplateConfigExt, - projectName: data.projectName, - workspaceID: data.optionWorkspaces.selectedOption, + projectName: data.projectName || 'my-project', + workspaceID: data.optionWorkspaces.selectedOption || 'project description', // paths: { // appConfigsDir: './appConfigs', // entryDir: './', @@ -664,8 +664,9 @@ export const taskRnvNew = async (c: RnvContext) => { // platformBuildsDir: './platformBuilds', // }, defaults: { - title: data.appTitle, - id: data.appID, + // TODO: these need to move into NEW metadata + // title: data.appTitle, + // id: data.appID, supportedPlatforms: data.optionPlatforms.selectedOptions, }, engines: {}, @@ -689,7 +690,8 @@ export const taskRnvNew = async (c: RnvContext) => { } }); - if (renativeTemplateConfig.engines) { + const tplEngines = renativeTemplateConfig.engines; + if (tplEngines) { // Remove unused engines based on selected platforms supPlats.forEach((k) => { const selectedEngineId = @@ -697,7 +699,7 @@ export const taskRnvNew = async (c: RnvContext) => { if (selectedEngineId) { const selectedEngine = findEngineKeyById(c, selectedEngineId); if (selectedEngine?.key) { - engines[selectedEngine.key] = renativeTemplateConfig.engines[selectedEngine.key]; + engines[selectedEngine.key] = tplEngines[selectedEngine.key]; } } }); diff --git a/packages/engine-rn-electron/src/sdk.ts b/packages/engine-rn-electron/src/sdk.ts index 2e97b14230..3b13a6b635 100644 --- a/packages/engine-rn-electron/src/sdk.ts +++ b/packages/engine-rn-electron/src/sdk.ts @@ -40,6 +40,8 @@ import { LINUX, TASK_EXPORT, } from '@rnv/core'; +import { FileElectronPackage } from './types'; +import { NpmPackageFile } from '@rnv/core/lib/configs/types'; export const configureElectronProject = async (c: RnvContext, exitOnFail?: boolean) => { logTask('configureElectronProject'); @@ -99,7 +101,7 @@ const configureProject = (c: RnvContext, exitOnFail?: boolean) => return; } const pkgJson = path.join(engine.originalTemplatePlatformsDir!, platform, 'package.json'); - const packageJson = readObjectSync(pkgJson); + const packageJson = readObjectSync(pkgJson) || {}; packageJson.name = `${c.runtime.appId}-${platform}`; packageJson.productName = `${getAppTitle(c, platform)}`; @@ -223,7 +225,7 @@ const configureProject = (c: RnvContext, exitOnFail?: boolean) => // Fix `Cannot compute electron version from installed node modules - none of the possible electron modules are installed.` // See https://github.com/electron-userland/electron-builder/issues/3984#issuecomment-505307933 const enginePkgJson = path.join(engine.rootPath!, 'package.json'); - const enginePackageJson = readObjectSync(enginePkgJson); + const enginePackageJson = readObjectSync(enginePkgJson); let electronConfig = merge( { @@ -234,7 +236,7 @@ const configureProject = (c: RnvContext, exitOnFail?: boolean) => output: path.join(platformBuildDir, 'export'), }, files: ['!export/*'], - electronVersion: enginePackageJson.dependencies.electron, + electronVersion: enginePackageJson?.dependencies?.electron, }, macConfig ); diff --git a/packages/engine-rn-electron/src/types.ts b/packages/engine-rn-electron/src/types.ts new file mode 100644 index 0000000000..b3124d708b --- /dev/null +++ b/packages/engine-rn-electron/src/types.ts @@ -0,0 +1,5 @@ +import { NpmPackageFile } from '@rnv/core/lib/configs/types'; + +export type FileElectronPackage = NpmPackageFile & { + productName?: string; +}; diff --git a/packages/sdk-apple/src/plistParser.ts b/packages/sdk-apple/src/plistParser.ts index e53299d3f1..4c052e6194 100644 --- a/packages/sdk-apple/src/plistParser.ts +++ b/packages/sdk-apple/src/plistParser.ts @@ -24,7 +24,7 @@ import { RnvPlatform, } from '@rnv/core'; import { getAppFolderName } from './common'; -import { Context } from './types'; +import { Context, FilePlistJSON } from './types'; export const parseExportOptionsPlist = (c: Context, platform: RnvPlatform) => new Promise((resolve) => { @@ -93,7 +93,8 @@ export const parseInfoPlist = (c: Context, platform: RnvPlatform) => const plistPath = path.join(appFolder, `${appFolderName}/Info.plist`); // PLIST - let plistObj = readObjectSync(path.join(__dirname, `../supportFiles/info.plist.${platform}.json`)); + let plistObj = + readObjectSync(path.join(__dirname, `../supportFiles/info.plist.${platform}.json`)) || {}; plistObj.CFBundleDisplayName = getAppTitle(c, platform); plistObj.CFBundleShortVersionString = getAppVersion(c, platform); plistObj.CFBundleVersion = getAppVersionCode(c, platform); @@ -138,7 +139,7 @@ export const parseInfoPlist = (c: Context, platform: RnvPlatform) => // URL_SCHEMES (LEGACY) if (urlScheme) { logWarning('urlScheme is DEPRECATED. use "plist:{ CFBundleURLTypes: []}" object instead'); - plistObj.CFBundleURLTypes.push({ + plistObj.CFBundleURLTypes?.push({ CFBundleTypeRole: 'Editor', CFBundleURLName: urlScheme, CFBundleURLSchemes: [urlScheme], diff --git a/packages/sdk-apple/src/types.ts b/packages/sdk-apple/src/types.ts index e23857ce42..d7db6280ee 100644 --- a/packages/sdk-apple/src/types.ts +++ b/packages/sdk-apple/src/types.ts @@ -112,3 +112,17 @@ export type SwiftAppDelegateSubKey = keyof SwiftAppDelegate['application'] & export type SwiftAppDelegateKey = keyof SwiftAppDelegate; export type TemplateXcode = Required['templateXcode']>; + +export type FilePlistJSON = { + CFBundleDisplayName?: string; + CFBundleShortVersionString?: string; + CFBundleVersion?: string; + UIAppFonts?: string[]; + UISupportedInterfaceOrientations?: string[]; + 'UISupportedInterfaceOrientations~ipad'?: string[]; + CFBundleURLTypes?: Array<{ + CFBundleTypeRole: string; + CFBundleURLName: string; + CFBundleURLSchemes: string[]; + }>; +}; From 18a85ca90051ef58119a0b9460f2c4ad26d2c086 Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Fri, 20 Oct 2023 21:46:36 +0200 Subject: [PATCH 02/12] type-saefty for readObjectSync --- packages/core/src/configs/appConfigs.ts | 3 +- packages/core/src/doctor/index.ts | 16 +++++--- packages/core/src/projects/index.ts | 37 +++++++++++-------- packages/core/src/projects/package.ts | 10 +++-- .../core/src/schema/configFiles/overrides.ts | 2 +- .../core/src/schema/configFiles/template.ts | 11 ++++++ packages/core/src/system/fs.ts | 14 +++---- packages/core/src/templates/index.ts | 2 +- .../src/tasks/task.rnv.project.upgrade.ts | 10 +++-- packages/sdk-android/src/manifestParser.ts | 9 ++++- packages/sdk-android/src/types.ts | 9 +++++ packages/sdk-apple/src/plistParser.ts | 6 +-- 12 files changed, 85 insertions(+), 44 deletions(-) diff --git a/packages/core/src/configs/appConfigs.ts b/packages/core/src/configs/appConfigs.ts index a1a265a38e..b20cd15511 100644 --- a/packages/core/src/configs/appConfigs.ts +++ b/packages/core/src/configs/appConfigs.ts @@ -6,6 +6,7 @@ import { fsExistsSync, fsReaddirSync, fsLstatSync, readObjectSync } from '../sys import { logTask, logWarning } from '../logger'; import { RnvContext } from '../context/types'; +import { ConfigFileApp } from '../schema/configFiles/types'; const IGNORE_FOLDERS = ['.git']; @@ -25,7 +26,7 @@ export const listAppConfigsFoldersSync = (c: RnvContext, ignoreHiddenConfigs: bo const appConfig = path.join(appConfigDir, RENATIVE_CONFIG_NAME); if (fsExistsSync(appConfig)) { try { - const config = readObjectSync(appConfig); + const config = readObjectSync(appConfig); if (config?.hidden !== true) { appConfigsDirs.push(dir); } diff --git a/packages/core/src/doctor/index.ts b/packages/core/src/doctor/index.ts index 0a9cbcce20..e3802678e2 100644 --- a/packages/core/src/doctor/index.ts +++ b/packages/core/src/doctor/index.ts @@ -2,6 +2,7 @@ import { writeFileSync, readObjectSync } from '../system/fs'; import { PACKAGE_JSON_FILEDS } from '../constants'; import { chalk, logWarning } from '../logger'; import { RnvContext } from '../context/types'; +import { NpmPackageFile } from '../configs/types'; const getSortedObject = (obj: any) => { if (obj !== null && typeof obj === 'object' && !Array.isArray(obj)) { @@ -39,15 +40,18 @@ const checkForDuplicates = (arr: Array) => { const fixPackageJson = (c: RnvContext, pkgPath: string) => new Promise((resolve) => { const pth = pkgPath || c.paths.project.package; - const pp = readObjectSync(pth); - const output = fixPackageObject(pp); - writeFileSync(pth, output, 4); + const pp = readObjectSync(pth); + if (pp) { + const output = fixPackageObject(pp); + writeFileSync(pth, output, 4); + } + resolve(); }); -const fixPackageObject = (pp: Record) => { - const output: Record = {}; - const usedKeys: Record = {}; +const fixPackageObject = (pp: Record) => { + const output: Record = {}; + const usedKeys: Record = {}; PACKAGE_JSON_FILEDS.forEach((v) => { if (pp[v] !== null) { diff --git a/packages/core/src/projects/index.ts b/packages/core/src/projects/index.ts index 664ee50a95..908c1ecafd 100644 --- a/packages/core/src/projects/index.ts +++ b/packages/core/src/projects/index.ts @@ -37,7 +37,7 @@ import { ParseFontsCallback } from './types'; import { inquirerPrompt } from '../api'; import { upgradeProjectDependencies } from '../configs/configProject'; import { generateConfigPropInjects } from '../system/injectors'; -import { ConfigFileApp, ConfigFileProject } from '../schema/configFiles/types'; +import { ConfigFileApp, ConfigFileEngine, ConfigFileProject, ConfigFileTemplate } from '../schema/configFiles/types'; export const checkAndBootstrapIfRequired = async (c: RnvContext) => { logTask('checkAndBootstrapIfRequired'); @@ -54,7 +54,7 @@ export const checkAndBootstrapIfRequired = async (c: RnvContext) => { c.paths.template.dir = templatePath; c.paths.template.configTemplate = path.join(templatePath, RENATIVE_CONFIG_TEMPLATE_NAME); - const templateObj = readObjectSync(c.paths.template.configTemplate); + const templateObj = readObjectSync(c.paths.template.configTemplate); const appConfigPath = path.join(c.paths.project.appConfigsDir, c.program.appConfigID, 'renative.json'); //TODO: Investigate whether we really need to support this: supportedPlatforms inside appconfig const appConfigObj = readObjectSync(appConfigPath); @@ -74,18 +74,24 @@ export const checkAndBootstrapIfRequired = async (c: RnvContext) => { }); } + if (!templateObj) { + return; + } + const config = { ...templateObj, }; // Clean unused engines - Object.keys(config.engines).forEach((k) => { - if (!activeEngineKeys.includes(k)) { - delete config.engines[k]; - } - }); + if (config.engines) { + Object.keys(config.engines).forEach((k) => { + if (!activeEngineKeys.includes(k)) { + delete config.engines?.[k]; + } + }); + } - if (config.templateConfig.packageTemplate) { + if (config.templateConfig?.packageTemplate) { const pkgJson = config.templateConfig.packageTemplate; if (!pkgJson.devDependencies) pkgJson.devDependencies = {}; if (!pkgJson.dependencies) pkgJson.dependencies = {}; @@ -95,7 +101,7 @@ export const checkAndBootstrapIfRequired = async (c: RnvContext) => { Object.keys(pkgJson.devDependencies).forEach((devDepKey) => { if (activeEngineKeys.includes(devDepKey)) { installPromises.push( - executeAsync(`npx yarn add ${devDepKey}@${pkgJson.devDependencies[devDepKey]}`, { + executeAsync(`npx yarn add ${devDepKey}@${pkgJson.devDependencies?.[devDepKey]}`, { cwd: c.paths.project.dir, }) ); @@ -114,18 +120,19 @@ export const checkAndBootstrapIfRequired = async (c: RnvContext) => { aek, 'renative.engine.json' ); - const eConfig = readObjectSync(engineConfigPath); - if (eConfig.platforms) { + const eConfig = readObjectSync(engineConfigPath); + if (eConfig?.platforms) { supportedPlatforms.forEach((supPlat) => { - const engPlatNpm = eConfig.platforms[supPlat]?.npm; + const engPlatNpm = eConfig.platforms?.[supPlat]?.npm; if (engPlatNpm) { const engPlatDeps = engPlatNpm.dependencies; - pkgJson.dependencies = pkgJson.dependencies || {}; + const deps = pkgJson.dependencies || {}; + pkgJson.dependencies = deps; if (engPlatDeps) { Object.keys(engPlatDeps).forEach((engPlatDepKey) => { - if (!pkgJson.dependencies[engPlatDepKey]) { + if (!deps[engPlatDepKey]) { logInfo(`Installing active engine dependency ${engPlatDepKey}`); - pkgJson.dependencies[engPlatDepKey] = engPlatDeps[engPlatDepKey]; + deps[engPlatDepKey] = engPlatDeps[engPlatDepKey]; } }); } diff --git a/packages/core/src/projects/package.ts b/packages/core/src/projects/package.ts index f08b9af63d..bbb386a2d1 100644 --- a/packages/core/src/projects/package.ts +++ b/packages/core/src/projects/package.ts @@ -4,6 +4,7 @@ import { logTask, logWarning, logInfo } from '../logger'; import { RENATIVE_CONFIG_TEMPLATE_NAME } from '../constants'; import { RnvContext } from '../context/types'; +import { ConfigFileTemplate } from '../schema/configFiles/types'; const packageJsonIsValid = (c: RnvContext) => { if (!fsExistsSync(c.paths.project.package)) return false; @@ -37,7 +38,7 @@ export const checkAndCreateProjectPackage = async (c: RnvContext) => { ); } - const templateObj = readObjectSync(c.paths.template.configTemplate); + const templateObj = readObjectSync(c.paths.template.configTemplate); const pkgJson = templateObj?.templateConfig?.packageTemplate || {}; pkgJson.name = packageName; @@ -46,10 +47,13 @@ export const checkAndCreateProjectPackage = async (c: RnvContext) => { // No longer good option to assume same version // pkgJson.dependencies.renative = rnvVersion; pkgJson.devDependencies = pkgJson.devDependencies || {}; - pkgJson.devDependencies.rnv = rnvVersion; + if (rnvVersion) { + pkgJson.devDependencies.rnv = rnvVersion; + } if (templateName) { - pkgJson.devDependencies[templateName] = c.files.project.config?.templates[templateName]?.version; + pkgJson.devDependencies[templateName] = + c.files.project.config?.templates[templateName]?.version || 'latest'; } const pkgJsonStringClean = JSON.stringify(pkgJson, null, 2); fsWriteFileSync(c.paths.project.package, pkgJsonStringClean); diff --git a/packages/core/src/schema/configFiles/overrides.ts b/packages/core/src/schema/configFiles/overrides.ts index 0afec0f830..387f08c8fb 100644 --- a/packages/core/src/schema/configFiles/overrides.ts +++ b/packages/core/src/schema/configFiles/overrides.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; export const RootOverridesSchema = z.object({ - overrides: z.object({}), + overrides: z.record(z.string(), z.record(z.string(), z.string())), }); export type _RootOverridesSchemaType = z.infer; diff --git a/packages/core/src/schema/configFiles/template.ts b/packages/core/src/schema/configFiles/template.ts index 91a92f5652..dc5d652c18 100644 --- a/packages/core/src/schema/configFiles/template.ts +++ b/packages/core/src/schema/configFiles/template.ts @@ -1,6 +1,8 @@ import { z } from 'zod'; import { DefaultsSchema, EnginesSchema } from './project'; +const NpmDep = z.record(z.string(), z.string()); + const BootstrapQuestionsSchema = z .array( z.object({ @@ -34,6 +36,15 @@ export const RootTemplateSchema = z.object({ .describe('Defines list of all file/dir paths you want to include in template') .optional(), bootstrapQuestions: BootstrapQuestionsSchema, + packageTemplate: z.optional( + z.object({ + dependencies: z.optional(NpmDep), + devDependencies: z.optional(NpmDep), + peerDependencies: z.optional(NpmDep), + optionalDependencies: z.optional(NpmDep), + name: z.string().optional(), + }) + ), }) .describe('Used in `renative.template.json` allows you to define template behaviour.') .optional(), diff --git a/packages/core/src/system/fs.ts b/packages/core/src/system/fs.ts index d07aab1277..bd776cbdb4 100755 --- a/packages/core/src/system/fs.ts +++ b/packages/core/src/system/fs.ts @@ -12,6 +12,7 @@ import { getApi } from '../api/provider'; import { getContext } from '../context/provider'; import { matchRegEx } from './regEx'; import type { ConfigPropKey } from '../schema/types'; +import lGet from 'lodash.get'; export const fsWriteFileSync = (dest: string | undefined, data: string, options?: fs.WriteFileOptions) => { // if (dest && dest.includes('renative.json')) { @@ -559,20 +560,17 @@ export const getRealPath = (c: RnvContext, p: string | undefined, key = 'undefin }; const _refToValue = (c: RnvContext, ref: string, key: string) => { + // ref=> '$REF$:./my/path/to/file.json$...prop.subProp' const val = ref.replace('$REF$:', '').split('$...'); - + // val=> ['./my/path/to/file.json', 'prop.subProp'] const realPath = getRealPath(c, val[0], key); if (realPath && realPath.includes('.json') && val.length === 2) { if (fs.existsSync(realPath)) { const obj = readObjectSync(realPath); - - try { - const output = val[1].split('.').reduce((o, i) => o[i], obj); - return output; - } catch (e) { - logWarning(`_refToValue: ${e}`); - } + const valPath = val[1]; // valPath=> 'prop.subProp' + const output = lGet(obj, valPath); + return output; } else { logWarning(`_refToValue: ${chalk().white(realPath)} does not exist!`); } diff --git a/packages/core/src/templates/index.ts b/packages/core/src/templates/index.ts index de742f2952..73649a1d64 100644 --- a/packages/core/src/templates/index.ts +++ b/packages/core/src/templates/index.ts @@ -212,7 +212,7 @@ const _configureRenativeConfig = async (c: RnvContext) => { export const configureTemplateFiles = async (c: RnvContext) => { logTask('configureTemplateFiles'); - const templateConfig = readObjectSync(c.paths.template.configTemplate); + const templateConfig = readObjectSync(c.paths.template.configTemplate); const includedPaths = templateConfig?.templateConfig?.includedPaths; if (includedPaths) { diff --git a/packages/engine-core/src/tasks/task.rnv.project.upgrade.ts b/packages/engine-core/src/tasks/task.rnv.project.upgrade.ts index a28ce9873e..c4294c5315 100644 --- a/packages/engine-core/src/tasks/task.rnv.project.upgrade.ts +++ b/packages/engine-core/src/tasks/task.rnv.project.upgrade.ts @@ -16,6 +16,8 @@ import { readObjectSync, RnvTaskFn, } from '@rnv/core'; +import { NpmPackageFile } from '@rnv/core/lib/configs/types'; +import { ConfigFileProject } from '@rnv/core/lib/schema/configFiles/types'; export const taskRnvProjectUpgrade: RnvTaskFn = async (c, _parentTask, originTask) => { logTask('taskRnvProjectUpgrade'); @@ -53,13 +55,15 @@ export const taskRnvProjectUpgrade: RnvTaskFn = async (c, _parentTask, originTas let pkgFile; let rnvFile; if (fsExistsSync(pkgPath)) { - pkgFile = readObjectSync(pkgPath); + pkgFile = readObjectSync(pkgPath); } if (fsExistsSync(rnvPath)) { - rnvFile = readObjectSync(rnvPath); + rnvFile = readObjectSync(rnvPath); + } + if (pkgFile && rnvFile) { + upgradedPaths.push(...upgradeDependencies(pkgFile, pkgPath, rnvFile, rnvPath, selectedVersion)); } - upgradedPaths.push(...upgradeDependencies(pkgFile, pkgPath, rnvFile, rnvPath, selectedVersion)); } }); } diff --git a/packages/sdk-android/src/manifestParser.ts b/packages/sdk-android/src/manifestParser.ts index b01dcb06bc..8128c1e149 100644 --- a/packages/sdk-android/src/manifestParser.ts +++ b/packages/sdk-android/src/manifestParser.ts @@ -16,7 +16,7 @@ import { parsePlugins, AndroidManifestNode, } from '@rnv/core'; -import { Context } from './types'; +import { AndroidManifestJSON, Context } from './types'; const PROHIBITED_DUPLICATE_TAGS = ['intent-filter']; const SYSTEM_TAGS = ['tag', 'children']; @@ -165,7 +165,12 @@ export const parseAndroidManifestSync = (c: Context) => { try { const baseManifestFilePath = path.join(__dirname, `../supportFiles/AndroidManifest_${platform}.json`); - const baseManifestFile = readObjectSync(baseManifestFilePath); + const baseManifestFile = readObjectSync(baseManifestFilePath); + + if (!baseManifestFile) { + return; + } + baseManifestFile.package = getAppId(c, platform); const objArr = getConfigPropArray(c, c.platform, 'templateAndroid'); diff --git a/packages/sdk-android/src/types.ts b/packages/sdk-android/src/types.ts index 2b5b1511a4..37b55adf0c 100644 --- a/packages/sdk-android/src/types.ts +++ b/packages/sdk-android/src/types.ts @@ -76,3 +76,12 @@ export type AndroidDevice = { }; export type TemplateAndroid = Required['templateAndroid']>; + +export type AndroidManifestJSONNode = { + tag: string; + 'android:name': string; +}; +export type AndroidManifestJSON = { + package?: string; + children: AndroidManifestJSONNode[]; +}; diff --git a/packages/sdk-apple/src/plistParser.ts b/packages/sdk-apple/src/plistParser.ts index 4c052e6194..651f39b81b 100644 --- a/packages/sdk-apple/src/plistParser.ts +++ b/packages/sdk-apple/src/plistParser.ts @@ -109,14 +109,12 @@ export const parseInfoPlist = (c: Context, platform: RnvPlatform) => const pc = c.buildConfig.permissions[platPrem] || {}; if (includedPermissions?.length && includedPermissions[0] === '*') { Object.keys(pc).forEach((v) => { - const key = v; - plistObj[key] = pc[v].desc; + (plistObj as Record)[v] = pc[v].desc; }); } else if (includedPermissions?.forEach) { includedPermissions.forEach((v) => { if (pc[v]) { - const key = v; - plistObj[key] = pc[v].desc; + (plistObj as Record)[v] = pc[v].desc; } }); } else if (includedPermissions) { From defd958e0dc3ce35a147dc50495cf92f8ab28131 Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Sat, 21 Oct 2023 22:44:06 +0200 Subject: [PATCH 03/12] fix runtime defaults --- packages/core/src/common.ts | 15 +++-- packages/core/src/configs/index.ts | 6 +- packages/core/src/context/defaults.ts | 24 ++++++- packages/core/src/context/types.ts | 62 ++++++++++--------- .../engine-rn-web/src/tasks/task.rnv.run.ts | 34 +++++----- packages/sdk-apple/src/runner.ts | 4 +- packages/sdk-tizen/src/deviceManager.ts | 18 ++++-- packages/sdk-tizen/src/runner.ts | 3 +- 8 files changed, 101 insertions(+), 65 deletions(-) diff --git a/packages/core/src/common.ts b/packages/core/src/common.ts index a95c1a8cbd..f71ed311d0 100755 --- a/packages/core/src/common.ts +++ b/packages/core/src/common.ts @@ -21,7 +21,7 @@ export const getTimestampPathsConfig = (c: RnvContext, platform: RnvPlatform): T if (platform === 'web') { timestampBuildFiles = (getConfigProp(c, platform, 'timestampBuildFiles') || []).map((v) => path.join(pPath, v)); } - if (timestampBuildFiles?.length) { + if (timestampBuildFiles?.length && c.runtime.timestamp) { return { paths: timestampBuildFiles, timestamp: c.runtime.timestamp }; } return undefined; @@ -76,7 +76,7 @@ export const getDevServerHost = (c: RnvContext) => { const devServerHostOrig = getConfigProp(c, c.platform, 'devServerHost'); const devServerHostFixed = devServerHostOrig - ? getValidLocalhost(devServerHostOrig, c.runtime.localhost) + ? getValidLocalhost(devServerHostOrig, c.runtime.localhost || DEFAULTS.devServerHost) : DEFAULTS.devServerHost; return devServerHostFixed; @@ -286,7 +286,7 @@ export const _getConfigProp = ( let resultPlatforms; let scheme; - if (platformObj) { + if (platformObj && ps) { scheme = platformObj.buildSchemes?.[ps] || {}; resultPlatforms = getFlavouredProp(c, platformObj, baseKey); } else { @@ -295,11 +295,10 @@ export const _getConfigProp = ( const resultScheme = baseKey && scheme[baseKey]; const resultCommonRoot = getFlavouredProp(c, sourceObj.common || {}, baseKey); - const resultCommonScheme = getFlavouredProp( - c, - sourceObj.common?.buildSchemes?.[c.runtime.scheme] || {}, - baseKey - ); + const resultCommonScheme = + c.runtime.scheme && + getFlavouredProp(c, sourceObj.common?.buildSchemes?.[c.runtime.scheme] || {}, baseKey); + const resultCommon = resultCommonScheme || resultCommonRoot; let result = _getValueOrMergedObject(resultScheme, resultPlatforms, resultCommon); diff --git a/packages/core/src/configs/index.ts b/packages/core/src/configs/index.ts index dcecfaafa3..540f30e2d3 100644 --- a/packages/core/src/configs/index.ts +++ b/packages/core/src/configs/index.ts @@ -246,8 +246,10 @@ export const parseRenativeConfigs = async (c: RnvContext) => { // c.paths.appConfig, // path.join(c.paths.project.appConfigsDir, c.runtime.appId) // ); - generateContextPaths(c.paths.appConfig, c.runtime.appConfigDir); - _loadConfigFiles(c, c.files.appConfig, c.paths.appConfig, true); + if (c.runtime.appConfigDir) { + generateContextPaths(c.paths.appConfig, c.runtime.appConfigDir); + _loadConfigFiles(c, c.files.appConfig, c.paths.appConfig, true); + } } const workspaceAppConfigsDir = getRealPath(c, c.buildConfig.workspaceAppConfigsDir); diff --git a/packages/core/src/context/defaults.ts b/packages/core/src/context/defaults.ts index 92715dbc4e..e1a768459b 100644 --- a/packages/core/src/context/defaults.ts +++ b/packages/core/src/context/defaults.ts @@ -25,10 +25,32 @@ export const generateRnvConfigFileObj = () => { }; }; -const runtime: any = { +const runtime: RnvContext['runtime'] = { enginesByPlatform: {}, + missingEnginePlugins: {}, enginesByIndex: [], enginesById: {}, + supportedPlatforms: [], + availablePlatforms: [], + platform: null, + _skipNativeDepResolutions: false, + _skipPluginScopeWarnings: false, + bundleAssets: false, + disableReset: false, + hosted: false, + isFirstRunAfterNew: false, + hasAllEnginesRegistered: false, + isTargetTrue: false, + isWSConfirmed: false, + skipBuildHooks: false, + skipActiveServerCheck: false, + versionCheckCompleted: false, + requiresForcedTemplateApply: false, + forceBuildHookRebuild: false, + keepSessionActive: false, + requiresBootstrap: false, + port: 3000, + runtimeExtraProps: {}, }; export const generateContextDefaults = (): RnvContext => ({ diff --git a/packages/core/src/context/types.ts b/packages/core/src/context/types.ts index 3f922371d4..390dcbf654 100644 --- a/packages/core/src/context/types.ts +++ b/packages/core/src/context/types.ts @@ -86,55 +86,59 @@ export type RnvContextBuildConfig = Partial & { }; export type RnvContextRuntime = { - platform: RnvPlatform; - appId?: string; - appDir: string; enginesByPlatform: Record; enginesByIndex: Array; enginesById: Record; missingEnginePlugins: Record; - localhost: string; - scheme: string; - bundleAssets: boolean; - activeTemplate: string; - engine?: RnvEngine; - target: string; - isTargetTrue: boolean; supportedPlatforms: Array; - keepSessionActive: boolean; - platformBuildsProjectPath?: string; + runtimeExtraProps: Record; availablePlatforms: Array; - _platformBuildsSuffix?: string; - timestamp: number; - appConfigDir: string; + platform: RnvPlatform; + isTargetTrue: boolean; + bundleAssets: boolean; + keepSessionActive: boolean; hasAllEnginesRegistered: boolean; - skipPackageUpdate?: boolean; - selectedTemplate?: string; - runtimeExtraProps: Record; requiresBootstrap: boolean; - currentTemplate: string; - requiresForcedTemplateApply: boolean; forceBuildHookRebuild: boolean; disableReset: boolean; skipActiveServerCheck: boolean; - port: number; - rnvVersionRunner: string; - rnvVersionProject: string; + requiresForcedTemplateApply: boolean; + isWSConfirmed: boolean; + _skipNativeDepResolutions: boolean; versionCheckCompleted: boolean; - currentPlatform: RnvEnginePlatform; _skipPluginScopeWarnings: boolean; skipBuildHooks: boolean; isFirstRunAfterNew: boolean; - currentEngine: RnvEngine; hosted: boolean; - task: string; - selectedWorkspace: string; - isWSConfirmed: boolean; - _skipNativeDepResolutions: boolean; + port: number; + //OPTIONALS + engine?: RnvEngine; + currentPlatform?: RnvEnginePlatform; + currentEngine?: RnvEngine; + skipPackageUpdate?: boolean; + selectedTemplate?: string; + _platformBuildsSuffix?: string; + platformBuildsProjectPath?: string; targetUDID?: string; forceBundleAssets?: boolean; webpackTarget?: string; shouldOpenBrowser?: boolean; + appId?: string; + rnvVersionRunner?: string; + rnvVersionProject?: string; + localhost?: string; + scheme?: string; + appDir?: string; + activeTemplate?: string; + timestamp?: number; + appConfigDir?: string; + currentTemplate?: string; + task?: string; + selectedWorkspace?: string; + + //TOFIX + + target?: string; }; export type RuntimePropKey = keyof RnvContextRuntime; diff --git a/packages/engine-rn-web/src/tasks/task.rnv.run.ts b/packages/engine-rn-web/src/tasks/task.rnv.run.ts index d6834db3a5..83336c73c9 100644 --- a/packages/engine-rn-web/src/tasks/task.rnv.run.ts +++ b/packages/engine-rn-web/src/tasks/task.rnv.run.ts @@ -41,22 +41,24 @@ const _configureHostedIfRequired = async (c: RnvContext) => { logDebug('Running hosted build'); const ipAddress = c.program.hostIp || ip.address(); - writeCleanFile( - path.join(c.runtime.currentEngine.rootPath!, 'templates', 'appShell', 'index.html'), - path.join(getPlatformProjectDir(c)!, 'index.html'), - [ - { - pattern: '{{DEV_SERVER}}', - override: `http://${ipAddress}:${c.runtime.port}`, - }, - { - pattern: '{{APPSHELL_HTML_HEADER}}', - override: String(hostedShellHeaders || ''), - }, - ], - undefined, - c - ); + if (c.runtime.currentEngine?.rootPath) { + writeCleanFile( + path.join(c.runtime.currentEngine.rootPath, 'templates', 'appShell', 'index.html'), + path.join(getPlatformProjectDir(c)!, 'index.html'), + [ + { + pattern: '{{DEV_SERVER}}', + override: `http://${ipAddress}:${c.runtime.port}`, + }, + { + pattern: '{{APPSHELL_HTML_HEADER}}', + override: String(hostedShellHeaders || ''), + }, + ], + undefined, + c + ); + } } }; diff --git a/packages/sdk-apple/src/runner.ts b/packages/sdk-apple/src/runner.ts index e5714ffc29..ea18445f03 100644 --- a/packages/sdk-apple/src/runner.ts +++ b/packages/sdk-apple/src/runner.ts @@ -332,7 +332,7 @@ export const getDeviceToRunOn = async (c: Context) => { } } - const target = c.runtime.target.replace(/(\s+)/g, '\\$1'); + const target = c.runtime.target?.replace(/(\s+)/g, '\\$1'); p = `--simulator ${target}`; } @@ -534,7 +534,7 @@ const _setAutomaticSigning = async (c: Context) => { const cnf = c.files.appConfig.config; if (!cnf) return; - const scheme = cnf.platforms?.[c.platform]?.buildSchemes?.[c.runtime.scheme]; + const scheme = c.runtime.scheme && cnf.platforms?.[c.platform]?.buildSchemes?.[c.runtime.scheme]; if (scheme && 'provisioningStyle' in scheme) { scheme.provisioningStyle = 'Automatic'; writeFileSync(c.paths.appConfig.config, cnf); diff --git a/packages/sdk-tizen/src/deviceManager.ts b/packages/sdk-tizen/src/deviceManager.ts index 7ab07f0d77..64cf90a4fb 100644 --- a/packages/sdk-tizen/src/deviceManager.ts +++ b/packages/sdk-tizen/src/deviceManager.ts @@ -321,8 +321,12 @@ Please create one and then edit the default target from ${c.paths.workspace.dir} hasDevice = true; } catch (e) { if (typeof e === 'string' && e.includes('No device matching')) { - await launchTizenSimulator(c, target); - hasDevice = await _waitForEmulatorToBeReady(c, target); + if (target) { + await launchTizenSimulator(c, target); + hasDevice = await _waitForEmulatorToBeReady(c, target); + } else { + return Promise.reject('Not target specified. (-t)'); + } } } try { @@ -346,8 +350,12 @@ Please create one and then edit the default target from ${c.paths.workspace.dir} )}"` ); - await launchTizenSimulator(c, target); - hasDevice = await _waitForEmulatorToBeReady(c, target); + if (target) { + await launchTizenSimulator(c, target); + hasDevice = await _waitForEmulatorToBeReady(c, target); + } else { + return Promise.reject('Not target specified. (-t)'); + } } const toReturn = true; @@ -367,7 +375,7 @@ Please create one and then edit the default target from ${c.paths.workspace.dir} }; // Check if target is present or it's the default one - const isTargetSpecified = c.program.target; + const isTargetSpecified = !!target; // Check for running devices const devices = await _getRunningDevices(c); diff --git a/packages/sdk-tizen/src/runner.ts b/packages/sdk-tizen/src/runner.ts index 7f595e8328..3d1fe68b2b 100644 --- a/packages/sdk-tizen/src/runner.ts +++ b/packages/sdk-tizen/src/runner.ts @@ -62,7 +62,7 @@ const _runTizenSimOrDevice = async (c: RnvContext) => { return true; }; -export const runTizen = async (c: RnvContext, target: string) => { +export const runTizen = async (c: RnvContext, target?: string) => { logTask('runTizen', `target:${target}`); const { platform } = c; const { hosted } = c.program; @@ -128,7 +128,6 @@ export const buildTizenProject = async (c: RnvContext) => { await buildCoreWebpackProject(c); if (!c.program.hosted) { - const tOut = path.join(tDir, 'output'); const tIntermediate = path.join(tDir, 'intermediate'); const tBuild = path.join(tDir, 'build'); From cd04ff20f3c7417f800dccde09b693645aa7d5c6 Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Sun, 22 Oct 2023 00:49:32 +0200 Subject: [PATCH 04/12] type upgrades for fs & plugins --- packages/core/src/configs/buildConfig.ts | 7 +- packages/core/src/configs/index.ts | 2 +- packages/core/src/context/types.ts | 7 +- packages/core/src/plugins/index.ts | 2 +- packages/core/src/plugins/types.ts | 5 +- .../core/src/schema/plugins/fragments/base.ts | 1 + packages/core/src/system/fs.ts | 79 +++++++++++-------- packages/core/src/templates/index.ts | 46 +++++++---- 8 files changed, 87 insertions(+), 62 deletions(-) diff --git a/packages/core/src/configs/buildConfig.ts b/packages/core/src/configs/buildConfig.ts index 562f27ecf0..29288d8ac9 100644 --- a/packages/core/src/configs/buildConfig.ts +++ b/packages/core/src/configs/buildConfig.ts @@ -11,8 +11,7 @@ import { } from '../system/fs'; import { chalk, logTask, logWarning, logDebug } from '../logger'; import { getContext } from '../context/provider'; -import type { RnvContext } from '../context/types'; -import { ConfigFileBuildConfig } from '../schema/configFiles/buildConfig'; +import type { RnvContext, RnvContextBuildConfig } from '../context/types'; import { FileUtilsPropConfig } from '../system/types'; import { PlatformKey } from '../schema/types'; @@ -136,13 +135,13 @@ export const generateBuildConfig = (_c?: RnvContext) => { `generateBuildConfig:mergeOrder.length:${mergeOrder.length},cleanPaths.length:${cleanPaths.length},existsPaths.length:${existsPaths.length},existsFiles.length:${existsFiles.length}` ); - let out: ConfigFileBuildConfig = merge.all([...meta, ...existsFiles], { + let out: RnvContextBuildConfig = merge.all([...meta, ...existsFiles], { arrayMerge: _arrayMergeOverride, }); out = merge({}, out); out.pluginTemplates = pluginTemplates; - c.buildConfig = sanitizeDynamicRefs(c, out); + c.buildConfig = sanitizeDynamicRefs(c, out); const propConfig: FileUtilsPropConfig = { files: c.files, runtimeProps: c.runtime, diff --git a/packages/core/src/configs/index.ts b/packages/core/src/configs/index.ts index 540f30e2d3..d008b55459 100644 --- a/packages/core/src/configs/index.ts +++ b/packages/core/src/configs/index.ts @@ -45,7 +45,7 @@ export const loadFileExtended = ( } if (fsExistsSync(extendsPath)) { - const extendsFile = readObjectSync(extendsPath); + const extendsFile = readObjectSync(extendsPath) || {}; fileObj[key] = mergeObjects(c, extendsFile, fileObj[key], false, true); // CLEAN props which should not be inherited diff --git a/packages/core/src/context/types.ts b/packages/core/src/context/types.ts index 390dcbf654..0ca8c035f0 100644 --- a/packages/core/src/context/types.ts +++ b/packages/core/src/context/types.ts @@ -2,10 +2,10 @@ import type { ConfigProp, ConfigPropKey, PlatformKey } from '../schema/types'; import type { RnvEngine, RnvEnginePlatform } from '../engines/types'; import type { OverridesOptions } from '../system/types'; import type { RnvPlatform } from '../types'; -import { RnvPlugin } from '../plugins/types'; import { ConfigFileApp, ConfigFileLocal, + ConfigFilePlugin, ConfigFilePlugins, ConfigFilePrivate, ConfigFileProject, @@ -63,7 +63,7 @@ export interface RnvContext { isBuildHooksReady: boolean; supportedPlatforms: Array; runtimePropsInjects: OverridesOptions; - _renativePluginCache: Record; + _renativePluginCache: Record; cli: Record; buildHooks: Record Promise>; configPropsInjects: OverridesOptions; @@ -135,9 +135,6 @@ export type RnvContextRuntime = { currentTemplate?: string; task?: string; selectedWorkspace?: string; - - //TOFIX - target?: string; }; diff --git a/packages/core/src/plugins/index.ts b/packages/core/src/plugins/index.ts index 2674a305e1..dea1562a2e 100644 --- a/packages/core/src/plugins/index.ts +++ b/packages/core/src/plugins/index.ts @@ -122,7 +122,7 @@ const _getMergedPlugin = ( } }); } - const mergedObj = mergeObjects(c, parentPlugin, currentPlugin, true, true); + const mergedObj = mergeObjects(c, parentPlugin, currentPlugin, true, true); if (c._renativePluginCache[pluginKey]) { mergedObj.config = c._renativePluginCache[pluginKey]; } diff --git a/packages/core/src/plugins/types.ts b/packages/core/src/plugins/types.ts index 575693b77d..64f9f855ad 100644 --- a/packages/core/src/plugins/types.ts +++ b/packages/core/src/plugins/types.ts @@ -1,3 +1,4 @@ +import { ConfigFilePlugin } from '../schema/configFiles/types'; import { RenativeConfigPlugin, RenativeConfigPluginPlatform } from '../schema/types'; export type PluginCallback = (plugin: RnvPlugin, pluginPlat: RenativeConfigPluginPlatform, key: string) => void; @@ -27,7 +28,5 @@ export type RnvPlugin = RenativeConfigPlugin & { scope?: string; _scopes?: Array; _id?: string; - config?: { - fontSources: Array; - }; + config?: ConfigFilePlugin; }; diff --git a/packages/core/src/schema/plugins/fragments/base.ts b/packages/core/src/schema/plugins/fragments/base.ts index 74093c150d..de55f8e89d 100644 --- a/packages/core/src/schema/plugins/fragments/base.ts +++ b/packages/core/src/schema/plugins/fragments/base.ts @@ -70,4 +70,5 @@ export const PluginBaseFragment = { webpackConfig: z.optional(Webpack), //Should this be at root plugin??? // 'engine-rn-next': z.optional(Webpack), //Should this be at root plugin??? disablePluginTemplateOverrides: z.optional(DisablePluginTemplateOverrides), + fontSources: z.array(z.string()).optional(), }; diff --git a/packages/core/src/system/fs.ts b/packages/core/src/system/fs.ts index bd776cbdb4..5ffd796f2e 100755 --- a/packages/core/src/system/fs.ts +++ b/packages/core/src/system/fs.ts @@ -49,11 +49,11 @@ export const fsSymlinkSync = (arg1: fs.PathLike | undefined, arg2: fs.PathLike) fs.symlinkSync(arg1!, arg2); }; -export const fsReadFile = (arg1: fs.PathLike, arg2: any) => { +export const fsReadFile = (arg1: fs.PathLike, arg2: (err: unknown, data: Buffer) => void) => { fs.readFile(arg1, arg2); }; -export const fsReaddir = (arg1: fs.PathLike, arg2: any) => fs.readdir(arg1, arg2); +export const fsReaddir = (arg1: fs.PathLike, arg2: (err: unknown, files: string[]) => void) => fs.readdir(arg1, arg2); const _getSanitizedPath = (origPath: string, timestampPathsConfig?: TimestampPathsConfig) => { if (timestampPathsConfig?.paths?.length && timestampPathsConfig?.timestamp) { @@ -507,7 +507,7 @@ export const readObjectSync = (filePath?: string, sanitize?: boolean if (sanitize) { logDebug(`readObjectSync: will sanitize file at: ${filePath}`); if (c) { - obj = sanitizeDynamicRefs(c, obj); + obj = sanitizeDynamicRefs(c, obj); } if (obj._refs) { obj = sanitizeDynamicProps(obj, { @@ -586,26 +586,29 @@ export const arrayMerge = (destinationArray: Array, sourceArray: Array, sourceArray: Array) => sourceArray; -export const sanitizeDynamicRefs = (c: RnvContext, obj: any) => { +type DynaObj = Record | Array; +export const sanitizeDynamicRefs = (c: RnvContext, obj: T) => { if (!obj) return obj; if (Array.isArray(obj)) { obj.forEach((v) => { sanitizeDynamicRefs(c, v); }); return obj; - } - Object.keys(obj).forEach((key) => { - const val = obj[key]; - if (val) { - if (typeof val === 'string') { - if (val.startsWith('$REF$:')) { - obj[key] = _refToValue(c, val, key); + } else if (typeof obj === 'object') { + Object.keys(obj).forEach((key) => { + const val = obj[key as keyof T]; + if (val) { + if (typeof val === 'string') { + if (val.startsWith('$REF$:')) { + obj[key as keyof T] = _refToValue(c, val, key); + } + } else if (Array.isArray(val) || typeof val === 'object') { + sanitizeDynamicRefs(c, val as DynaObj); } - } else { - sanitizeDynamicRefs(c, val); } - } - }); + }); + } + return obj; }; @@ -626,7 +629,7 @@ export const resolvePackage = (text: string) => { return newText; }; -export const sanitizeDynamicProps = (obj: any, propConfig: FileUtilsPropConfig): any => { +export const sanitizeDynamicProps = (obj: T, propConfig: FileUtilsPropConfig): any => { if (!obj) { return obj; } @@ -641,10 +644,11 @@ export const sanitizeDynamicProps = (obj: any, propConfig: FileUtilsPropConfig): }); } else if (typeof obj === 'object') { Object.keys(obj).forEach((key) => { - const val = obj[key]; + const val = obj[key as keyof T]; + // TODO: evaluate if this is still needed // Some values are passed as keys so have to validate keys as well - const newKey = resolvePackage(key); - delete obj[key]; + const newKey = resolvePackage(key) as keyof T; + delete obj[key as keyof T]; obj[newKey] = val; if (val) { if (typeof val === 'string') { @@ -667,42 +671,49 @@ const BIND_CONFIG_PROPS = '{{configProps.'; const BIND_RUNTIME_PROPS = '{{runtimeProps.'; const BIND_ENV = '{{env.'; -const _bindStringVals = (obj: any, _val: string, newKey: string | number, propConfig: FileUtilsPropConfig) => { +const _bindStringVals = (obj: T, _val: string, newKey: K, propConfig: FileUtilsPropConfig) => { const { props = {}, configProps = {}, runtimeProps = {} } = propConfig; let val = _val; if (val.includes(BIND_FILES)) { const key = val.replace(BIND_FILES, '').replace('}}', ''); //TODO: this any not good - const nVal: any = key.split('.').reduce((o, i) => o?.[i], propConfig.files); - obj[newKey] = resolvePackage(nVal); + const nVal = lGet(propConfig, key); + obj[newKey] = resolvePackage(nVal) as T[K]; } else if (val.includes(BIND_PROPS)) { Object.keys(props).forEach((pk) => { val = val.replace(`${BIND_PROPS}${pk}}}`, props?.[pk]); - obj[newKey] = resolvePackage(val); + obj[newKey] = resolvePackage(val) as T[K]; }); } else if (val.includes(BIND_CONFIG_PROPS)) { Object.keys(configProps).forEach((pk2) => { val = val.replace(`${BIND_CONFIG_PROPS}${pk2}}}`, configProps[pk2]); - obj[newKey] = resolvePackage(val); + obj[newKey] = resolvePackage(val) as T[K]; }); } else if (val.includes(BIND_RUNTIME_PROPS)) { Object.keys(runtimeProps).forEach((pk3) => { val = val.replace(`${BIND_RUNTIME_PROPS}${pk3}}}`, runtimeProps[pk3]); - obj[newKey] = resolvePackage(val); + obj[newKey] = resolvePackage(val) as T[K]; }); } else if (val.includes(BIND_ENV)) { const key = val.replace(BIND_ENV, '').replace('}}', ''); - obj[newKey] = process.env[key]; + obj[newKey] = process.env[key] as T[K]; } }; -export const mergeObjects = (c: RnvContext, obj1: any, obj2: any, dynamicRefs = true, replaceArrays = false) => { - if (!obj2) return obj1; - if (!obj1) return obj2; +export const mergeObjects = ( + c: RnvContext, + obj1: Partial, + obj2: Partial, + dynamicRefs = true, + replaceArrays = false +) => { + if (!obj2) return obj1 as T1; + if (!obj1) return obj2 as T1; const obj = merge(obj1, obj2, { arrayMerge: replaceArrays ? _arrayMergeOverride : arrayMerge, }); - return dynamicRefs ? sanitizeDynamicRefs(c, obj) : obj; + const out = dynamicRefs ? sanitizeDynamicRefs(c, obj) : obj; + return out as T1; }; export const replaceHomeFolder = (p: string) => { @@ -727,8 +738,12 @@ export const getFileListSync = (dir: fs.PathLike) => { return results; }; -export const loadFile = (fileObj: any, pathObj: Record, key: string) => { - const pKey = `${key}Exists`; +export const loadFile = >( + fileObj: T, + pathObj: Partial>, + key: K +) => { + const pKey = `${key}Exists` as K; const pth = pathObj[key]; if (typeof pth === 'string' && !fsExistsSync(pth)) { diff --git a/packages/core/src/templates/index.ts b/packages/core/src/templates/index.ts index 73649a1d64..3d77b21221 100644 --- a/packages/core/src/templates/index.ts +++ b/packages/core/src/templates/index.ts @@ -24,7 +24,7 @@ import { RnvPlatform } from '../types'; import { listAppConfigsFoldersSync } from '../configs/appConfigs'; import { writeRenativeConfigFile } from '../configs/utils'; import { checkIfProjectAndNodeModulesExists } from '../projects/dependencyManager'; -import { ConfigFileApp, ConfigFileTemplate } from '../schema/configFiles/types'; +import { ConfigFileApp, ConfigFileProject, ConfigFileTemplate } from '../schema/configFiles/types'; import { PlatformKey } from '../schema/types'; const _cleanProjectTemplateSync = (c: RnvContext) => { @@ -188,22 +188,36 @@ const _configureRenativeConfig = async (c: RnvContext) => { logInfo( `Your ${c.paths.project.config} needs to be updated with ${c.paths.template.configTemplate}. UPDATING...DONE` ); - const mergedObj = mergeObjects(c, templateConfig, c.files.project.config_original, false, true); - // Do not override supportedPlatforms - mergedObj.defaults.supportedPlatforms = c.files.project.config_original?.defaults?.supportedPlatforms; - // Do not override engines - mergedObj.engines = c.files.project.config_original?.engines; - // Set current template - mergedObj.currentTemplate = c.runtime.currentTemplate; - if (mergedObj.isNew) { - c.runtime.isFirstRunAfterNew = true; + if (c.files.project.config_original && templateConfig) { + const mergedObj = mergeObjects( + c, + templateConfig, + c.files.project.config_original, + false, + true + ); + + // Do not override supportedPlatforms + mergedObj.defaults = mergedObj.defaults || {}; + mergedObj.defaults.supportedPlatforms = c.files.project.config_original?.defaults?.supportedPlatforms; + // Do not override engines + mergedObj.engines = c.files.project.config_original?.engines; + // Set current template + if (c.runtime.currentTemplate) { + mergedObj.currentTemplate = c.runtime.currentTemplate; + } + + if (mergedObj.isNew) { + c.runtime.isFirstRunAfterNew = true; + } + + // mergedObj.isNew = null; + delete mergedObj.isNew; + delete mergedObj.templateConfig; + // c.files.project.config = mergedObj; + writeRenativeConfigFile(c, c.paths.project.config, mergedObj); + loadFileExtended(c, c.files.project, c.paths.project, 'config'); } - // mergedObj.isNew = null; - delete mergedObj.isNew; - delete mergedObj.templateConfig; - // c.files.project.config = mergedObj; - writeRenativeConfigFile(c, c.paths.project.config, mergedObj); - loadFileExtended(c, c.files.project, c.paths.project, 'config'); } return true; From f1d917ff3cd650b29ddd857b482829784e5ec618 Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Sun, 22 Oct 2023 01:32:38 +0200 Subject: [PATCH 05/12] cleanup SDKs --- .../core/src/schema/configFiles/workspace.ts | 12 +++- packages/core/src/types.ts | 2 + .../global-config-template.json | 1 - packages/sdk-android/src/constants.ts | 11 ---- packages/sdk-android/src/installer.ts | 28 +++------ packages/sdk-tizen/src/constants.ts | 9 --- packages/sdk-tizen/src/installer.ts | 63 ++++--------------- packages/sdk-webos/src/constants.ts | 7 --- packages/sdk-webos/src/installer.ts | 52 +++------------ 9 files changed, 42 insertions(+), 143 deletions(-) diff --git a/packages/core/src/schema/configFiles/workspace.ts b/packages/core/src/schema/configFiles/workspace.ts index 8022a25bfa..b3049f4589 100644 --- a/packages/core/src/schema/configFiles/workspace.ts +++ b/packages/core/src/schema/configFiles/workspace.ts @@ -1,7 +1,15 @@ import { z } from 'zod'; import { DefaultTargets } from '../shared'; -export const SDKs = z.record(z.string(), z.string()).describe('Define your sdk configurations'); +const SDKsSchema = z + .object({ + ANDROID_SDK: z.string().optional(), + ANDROID_NDK: z.string().optional(), + TIZEN_SDK: z.string().optional(), + WEBOS_SDK: z.string().optional(), + KAIOS_SDK: z.string().optional(), + }) + .describe('Define your sdk configurations'); // ANDROID_SDK: '~/Library/Android/sdk', // ANDROID_NDK: '~/Library/Android/sdk/ndk-bundle', // TIZEN_SDK: '~/tizen-studio', @@ -12,7 +20,7 @@ export const SDKs = z.record(z.string(), z.string()).describe('Define your sdk c export const RootWorkspaceSchema = z.object({ defaultTargets: z.optional(DefaultTargets), - sdks: z.optional(SDKs), + sdks: z.optional(SDKsSchema), projectTemplates: z.record(z.string(), z.object({})), appConfigsPath: z .string() diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index b286c06968..67d73965c7 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -1,5 +1,7 @@ import type { PlatformKey } from './schema/types'; +export * from './schema/configFiles/types'; + export type RnvPlatform = PlatformKey | null; export type RnvPlatformWithAll = PlatformKey | 'all'; diff --git a/packages/rnv/coreTemplateFiles/global-config-template.json b/packages/rnv/coreTemplateFiles/global-config-template.json index 183e3f1fa0..c9a0cc8f30 100644 --- a/packages/rnv/coreTemplateFiles/global-config-template.json +++ b/packages/rnv/coreTemplateFiles/global-config-template.json @@ -2,7 +2,6 @@ "sdks": { "ANDROID_SDK": "/Users//Library/Android/sdk", "ANDROID_NDK": "/Users//Library/Android/sdk/ndk-bundle", - "IOS_SDK": "No need. Just install Xcode", "TIZEN_SDK": "/Users//tizen-studio", "WEBOS_SDK": "/Users//Library/webOS_TV_SDK", "KAIOS_SDK": "/Applications/Kaiosrt.app" diff --git a/packages/sdk-android/src/constants.ts b/packages/sdk-android/src/constants.ts index c7a5dcc732..e38364e239 100644 --- a/packages/sdk-android/src/constants.ts +++ b/packages/sdk-android/src/constants.ts @@ -1,15 +1,4 @@ -import { ANDROID, ANDROID_TV, ANDROID_WEAR, FIRE_TV } from '@rnv/core'; - export const CLI_ANDROID_EMULATOR = 'androidEmulator'; export const CLI_ANDROID_ADB = 'androidAdb'; export const CLI_ANDROID_AVDMANAGER = 'androidAvdManager'; export const CLI_ANDROID_SDKMANAGER = 'androidSdkManager'; - -export const ANDROID_SDK = 'ANDROID_SDK'; -export const ANDROID_NDK = 'ANDROID_NDK'; - -export const SDK_PLATFORMS: any = {}; -SDK_PLATFORMS[ANDROID] = ANDROID_SDK; -SDK_PLATFORMS[ANDROID_TV] = ANDROID_SDK; -SDK_PLATFORMS[FIRE_TV] = ANDROID_SDK; -SDK_PLATFORMS[ANDROID_WEAR] = ANDROID_SDK; diff --git a/packages/sdk-android/src/installer.ts b/packages/sdk-android/src/installer.ts index a446f9dccd..636018944d 100644 --- a/packages/sdk-android/src/installer.ts +++ b/packages/sdk-android/src/installer.ts @@ -20,17 +20,12 @@ import { generateBuildConfig, RnvContext, inquirerPrompt, + ConfigFileWorkspace, } from '@rnv/core'; -import { - CLI_ANDROID_EMULATOR, - CLI_ANDROID_ADB, - CLI_ANDROID_AVDMANAGER, - CLI_ANDROID_SDKMANAGER, - SDK_PLATFORMS, - ANDROID_SDK, - ANDROID_NDK, -} from './constants'; +import { CLI_ANDROID_EMULATOR, CLI_ANDROID_ADB, CLI_ANDROID_AVDMANAGER, CLI_ANDROID_SDKMANAGER } from './constants'; + +type SDKKey = keyof Required['sdks']; const SDK_LOCATIONS: Record> = { android: [ @@ -88,16 +83,13 @@ export const checkAndConfigureAndroidSdks = async (c: RnvContext) => { c.cli[CLI_ANDROID_SDKMANAGER] = sdkManagerPath; }; -const _getCurrentSdkPath = (c: RnvContext) => - c.platform ? c.buildConfig?.sdks?.[SDK_PLATFORMS[c.platform]] : undefined; +const _getCurrentSdkPath = (c: RnvContext) => (c.platform ? c.buildConfig?.sdks?.ANDROID_SDK : undefined); const _isSdkInstalled = (c: RnvContext) => { logTask('_isSdkInstalled'); if (!c.platform) return false; - if (!SDK_PLATFORMS[c.platform]) return true; - const sdkPath = _getCurrentSdkPath(c); return fsExistsSync(getRealPath(c, sdkPath)); @@ -121,7 +113,7 @@ const _findFolderWithFile = (dir: string, fileToFind: string) => { return foundDir; }; -const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: string, traverseUntilFoundFile?: string) => { +const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: SDKKey, traverseUntilFoundFile?: string) => { logTask('_attemptAutoFix'); if (c.program.hosted) { @@ -132,12 +124,12 @@ const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: strin let locations: Array = SDK_LOCATIONS[sdkPlatform]; // try common Android SDK env variables - if (sdkKey === ANDROID_SDK) { + if (sdkKey === 'ANDROID_SDK') { const { ANDROID_SDK_HOME, ANDROID_SDK_ROOT, ANDROID_HOME, ANDROID_SDK: ANDROID_SDK_ENV } = process.env; locations = locations.concat([ANDROID_SDK_HOME, ANDROID_SDK_ROOT, ANDROID_HOME, ANDROID_SDK_ENV]); } - if (sdkKey === ANDROID_NDK) { + if (sdkKey === 'ANDROID_NDK') { const { ANDROID_NDK_HOME } = process.env; locations.push(ANDROID_NDK_HOME); } @@ -202,8 +194,8 @@ export const checkAndroidSdk = async (c: RnvContext) => { case ANDROID_TV: case FIRE_TV: case ANDROID_WEAR: - await _attemptAutoFix(c, 'android', ANDROID_SDK); - return _attemptAutoFix(c, 'android-ndk', ANDROID_NDK, 'source.properties'); + await _attemptAutoFix(c, 'android', 'ANDROID_SDK'); + return _attemptAutoFix(c, 'android-ndk', 'ANDROID_NDK', 'source.properties'); default: return true; } diff --git a/packages/sdk-tizen/src/constants.ts b/packages/sdk-tizen/src/constants.ts index 5e76c41199..a1cea8867b 100644 --- a/packages/sdk-tizen/src/constants.ts +++ b/packages/sdk-tizen/src/constants.ts @@ -1,12 +1,3 @@ -import { TIZEN, TIZEN_MOBILE, TIZEN_WATCH } from '@rnv/core'; - export const CLI_TIZEN_EMULATOR = 'tizenEmulator'; export const CLI_TIZEN = 'tizen'; export const CLI_SDB_TIZEN = 'tizenSdb'; - -export const TIZEN_SDK = 'TIZEN_SDK'; - -export const SDK_PLATFORMS: any = {}; -SDK_PLATFORMS[TIZEN] = TIZEN_SDK; -SDK_PLATFORMS[TIZEN_WATCH] = TIZEN_SDK; -SDK_PLATFORMS[TIZEN_MOBILE] = TIZEN_SDK; diff --git a/packages/sdk-tizen/src/installer.ts b/packages/sdk-tizen/src/installer.ts index 5e98e876b2..817c331529 100644 --- a/packages/sdk-tizen/src/installer.ts +++ b/packages/sdk-tizen/src/installer.ts @@ -8,8 +8,6 @@ import { getRealPath, writeFileSync, fsExistsSync, - fsReaddirSync, - fsLstatSync, chalk, logTask, logWarning, @@ -20,16 +18,13 @@ import { RnvContext, inquirerPrompt, } from '@rnv/core'; -import { CLI_SDB_TIZEN, CLI_TIZEN, CLI_TIZEN_EMULATOR, SDK_PLATFORMS, TIZEN_SDK } from './constants'; - -const SDK_LOCATIONS: Record> = { - tizen: [ - path.join('usr/local/tizen-studio'), - path.join(USER_HOME_DIR, 'tizen-studio'), - path.join('C:\\tizen-studio'), - ], - webos: [path.join('/opt/webOS_TV_SDK'), path.join('C:\\webOS_TV_SDK')], -}; +import { CLI_SDB_TIZEN, CLI_TIZEN, CLI_TIZEN_EMULATOR } from './constants'; + +const SDK_LOCATIONS = [ + path.join('usr/local/tizen-studio'), + path.join(USER_HOME_DIR, 'tizen-studio'), + path.join('C:\\tizen-studio'), +]; const _logSdkWarning = (c: RnvContext) => { logWarning(`Your ${c.paths.workspace.config} is missing SDK configuration object`); @@ -50,40 +45,19 @@ export const checkAndConfigureTizenSdks = async (c: RnvContext) => { } }; -const _getCurrentSdkPath = (c: RnvContext) => - c.platform ? c.buildConfig?.sdks?.[SDK_PLATFORMS[c.platform]] : undefined; +const _getCurrentSdkPath = (c: RnvContext) => (c.platform ? c.buildConfig?.sdks?.TIZEN_SDK : undefined); const _isSdkInstalled = (c: RnvContext) => { logTask('_isSdkInstalled'); if (!c.platform) return false; - if (!SDK_PLATFORMS[c.platform]) return true; - const sdkPath = _getCurrentSdkPath(c); return fsExistsSync(getRealPath(c, sdkPath)); }; -const _findFolderWithFile = (dir: string, fileToFind: string) => { - const opt = path.join(dir, fileToFind); - if (fsExistsSync(opt)) { - return dir; - } - let foundDir; - fsReaddirSync(dir).forEach((subDirName) => { - // not a directory check - if (!fsLstatSync(subDirName).isDirectory()) return; - const subDir = path.join(dir, subDirName); - const foundSubDir = _findFolderWithFile(subDir, fileToFind); - if (foundSubDir) { - foundDir = foundSubDir; - } - }); - return foundDir; -}; - -const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: string, traverseUntilFoundFile?: string) => { +const _attemptAutoFix = async (c: RnvContext) => { logTask('_attemptAutoFix'); if (!c.files.workspace.config) return; @@ -93,18 +67,7 @@ const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: strin return true; } - const locations: Array = SDK_LOCATIONS[sdkPlatform]; - - let result = locations.find((v) => fsExistsSync(v)); - - if (result && traverseUntilFoundFile) { - const subResult = _findFolderWithFile(result, traverseUntilFoundFile); - if (subResult) { - result = subResult; - } else { - // result = null; - } - } + const result = SDK_LOCATIONS.find((v) => fsExistsSync(v)); if (result) { logSuccess(`Found existing ${c.platform} SDK location at ${chalk().white(result)}`); @@ -121,7 +84,7 @@ const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: strin if (confirmSdk) { try { if (!c.files.workspace.config?.sdks) c.files.workspace.config.sdks = {}; - c.files.workspace.config.sdks[sdkKey] = result; + c.files.workspace.config.sdks.TIZEN_SDK = result; //TODO: use config_original here? writeFileSync(c.paths.workspace.config, c.files.workspace.config); generateBuildConfig(c); @@ -134,7 +97,7 @@ const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: strin } } - logTask(`_attemptAutoFix: no sdks found. searched at: ${SDK_LOCATIONS[sdkPlatform].join(', ')}`); + logTask(`_attemptAutoFix: no sdks found. searched at: ${SDK_LOCATIONS.join(', ')}`); // const setupInstance = PlatformSetup(c); // await setupInstance.askToInstallSDK(sdkPlatform); @@ -155,7 +118,7 @@ export const checkTizenSdk = async (c: RnvContext) => { case TIZEN: case TIZEN_MOBILE: case TIZEN_WATCH: - return _attemptAutoFix(c, 'tizen', TIZEN_SDK); + return _attemptAutoFix(c); default: return true; } diff --git a/packages/sdk-webos/src/constants.ts b/packages/sdk-webos/src/constants.ts index 576d19197c..da3e01f222 100644 --- a/packages/sdk-webos/src/constants.ts +++ b/packages/sdk-webos/src/constants.ts @@ -1,5 +1,3 @@ -import { WEBOS } from '@rnv/core'; - export const CLI_WEBOS_ARES = 'webosAres'; export const CLI_WEBOS_ARES_PACKAGE = 'webosAresPackage'; export const CLI_WEBOS_ARES_INSTALL = 'webosAresInstall'; @@ -7,8 +5,3 @@ export const CLI_WEBOS_ARES_LAUNCH = 'webosAresLaunch'; export const CLI_WEBOS_ARES_SETUP_DEVICE = 'webosAresSetup'; export const CLI_WEBOS_ARES_DEVICE_INFO = 'webosAresDeviceInfo'; export const CLI_WEBOS_ARES_NOVACOM = 'webosAresNovacom'; - -export const WEBOS_SDK = 'WEBOS_SDK'; - -export const SDK_PLATFORMS: any = {}; -SDK_PLATFORMS[WEBOS] = WEBOS_SDK; diff --git a/packages/sdk-webos/src/installer.ts b/packages/sdk-webos/src/installer.ts index 1639213be6..667f78b07d 100644 --- a/packages/sdk-webos/src/installer.ts +++ b/packages/sdk-webos/src/installer.ts @@ -5,8 +5,6 @@ import { getRealPath, writeFileSync, fsExistsSync, - fsReaddirSync, - fsLstatSync, chalk, logTask, logWarning, @@ -26,13 +24,9 @@ import { CLI_WEBOS_ARES_NOVACOM, CLI_WEBOS_ARES_SETUP_DEVICE, CLI_WEBOS_ARES_DEVICE_INFO, - WEBOS_SDK, - SDK_PLATFORMS, } from './constants'; -const SDK_LOCATIONS: Record> = { - webos: [path.join('/opt/webOS_TV_SDK'), path.join('C:\\webOS_TV_SDK')], -}; +const SDK_LOCATIONS = [path.join('/opt/webOS_TV_SDK'), path.join('C:\\webOS_TV_SDK')]; const _logSdkWarning = (c: RnvContext) => { logWarning(`Your ${c.paths.workspace.config} is missing SDK configuration object`); @@ -72,40 +66,19 @@ export const checkAndConfigureWebosSdks = async (c: RnvContext) => { } }; -const _getCurrentSdkPath = (c: RnvContext) => - c.platform ? c.buildConfig?.sdks?.[SDK_PLATFORMS[c.platform]] : undefined; +const _getCurrentSdkPath = (c: RnvContext) => (c.platform ? c.buildConfig?.sdks?.WEBOS_SDK : undefined); const _isSdkInstalled = (c: RnvContext) => { logTask('_isSdkInstalled'); if (!c.platform) return; - if (!SDK_PLATFORMS[c.platform]) return true; - const sdkPath = _getCurrentSdkPath(c); return fsExistsSync(getRealPath(c, sdkPath)); }; -const _findFolderWithFile = (dir: string, fileToFind: string) => { - const opt = path.join(dir, fileToFind); - if (fsExistsSync(opt)) { - return dir; - } - let foundDir; - fsReaddirSync(dir).forEach((subDirName) => { - // not a directory check - if (!fsLstatSync(subDirName).isDirectory()) return; - const subDir = path.join(dir, subDirName); - const foundSubDir = _findFolderWithFile(subDir, fileToFind); - if (foundSubDir) { - foundDir = foundSubDir; - } - }); - return foundDir; -}; - -const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: string, traverseUntilFoundFile?: string) => { +const _attemptAutoFix = async (c: RnvContext) => { logTask('_attemptAutoFix'); if (c.program.hosted) { @@ -113,18 +86,7 @@ const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: strin return true; } - const locations: Array = SDK_LOCATIONS[sdkPlatform]; - - let result = locations.find((v) => fsExistsSync(v)); - - if (result && traverseUntilFoundFile) { - const subResult = _findFolderWithFile(result, traverseUntilFoundFile); - if (subResult) { - result = subResult; - } else { - // result = null; - } - } + const result = SDK_LOCATIONS.find((v) => fsExistsSync(v)); if (result) { logSuccess(`Found existing ${c.platform} SDK location at ${chalk().white(result)}`); @@ -143,7 +105,7 @@ const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: strin if (!cnf) return false; try { if (!cnf.sdks) cnf.sdks = {}; - cnf.sdks[sdkKey] = result; + cnf.sdks.WEBOS_SDK = result; writeFileSync(c.paths.workspace.config, cnf); generateBuildConfig(c); await checkAndConfigureWebosSdks(c); @@ -155,7 +117,7 @@ const _attemptAutoFix = async (c: RnvContext, sdkPlatform: string, sdkKey: strin } } - logTask(`_attemptAutoFix: no sdks found. searched at: ${SDK_LOCATIONS[sdkPlatform].join(', ')}`); + logTask(`_attemptAutoFix: no sdks found. searched at: ${SDK_LOCATIONS.join(', ')}`); // const setupInstance = PlatformSetup(c); // await setupInstance.askToInstallSDK(sdkPlatform); @@ -174,7 +136,7 @@ export const checkWebosSdk = async (c: RnvContext) => { switch (c.platform) { case WEBOS: - return _attemptAutoFix(c, 'webos', WEBOS_SDK); + return _attemptAutoFix(c); default: return true; } From 00741e52a31e603516e6a67dee932ebc0821f5b4 Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Sun, 22 Oct 2023 02:00:03 +0200 Subject: [PATCH 06/12] further type safety enhancements --- packages/core/src/plugins/index.ts | 25 ++++++++++++------- .../core/src/schema/plugins/fragments/base.ts | 2 +- packages/core/src/system/fs.ts | 6 ++--- packages/core/src/system/types.ts | 6 ++--- packages/core/src/tasks/index.ts | 11 +++++--- 5 files changed, 30 insertions(+), 20 deletions(-) diff --git a/packages/core/src/plugins/index.ts b/packages/core/src/plugins/index.ts index dea1562a2e..134f7bc0ff 100644 --- a/packages/core/src/plugins/index.ts +++ b/packages/core/src/plugins/index.ts @@ -25,6 +25,7 @@ import { writeRenativeConfigFile } from '../configs/utils'; import { installPackageDependencies } from '../projects/npm'; import { OverridesOptions, ResolveOptions } from '../system/types'; import { ConfigFileOverrides, ConfigFilePlugin, ConfigFilePlugins } from '../schema/configFiles/types'; +import { NpmPackageFile } from '../configs/types'; const _getPluginScope = (plugin: RenativeConfigPlugin | string): RnvPluginScope => { if (typeof plugin === 'string') { @@ -143,7 +144,7 @@ const _getMergedPlugin = ( : sanitizeDynamicProps(obj, { files: c.files, runtimeProps: c.runtime, - props: obj.props, + props: obj.props || {}, configProps: c.injectableConfigProps, }); @@ -166,7 +167,7 @@ export const configurePlugins = async (c: RnvContext) => { } const isTemplate = c.files.project.config?.isTemplate; - const newDeps: Record = {}; + const newDeps: Record = {}; const newDevDeps: Record = {}; const { dependencies, devDependencies } = c.files.project.package; const ovMsg = isTemplate ? 'This is template. NO ACTION' : 'package.json will be overriden'; @@ -227,7 +228,9 @@ ${ovMsg}` ); hasPackageChanged = true; - newDeps[k] = plugin.version; + if (plugin.version) { + newDeps[k] = plugin.version; + } } } @@ -243,16 +246,20 @@ ${ovMsg}` |- ${npmKey}@${chalk().red(npmDep)}`); } else if (!dependencies[npmKey]) { logInfo(`Plugin ${chalk().white(k)} requires npm dependency ${chalk().white(npmKey)}. ${ovMsg}`); - newDeps[npmKey] = npmDep; - hasPackageChanged = true; + if (npmDep) { + newDeps[npmKey] = npmDep; + hasPackageChanged = true; + } } else if (dependencies[npmKey] !== npmDep) { logWarning( `Plugin ${chalk().white(k)} npm dependency ${chalk().white(npmKey)} mismatch (${chalk().red( dependencies[npmKey] )}) => (${chalk().green(npmDep)}) .${ovMsg}` ); - newDeps[npmKey] = npmDep; - hasPackageChanged = true; + if (npmDep) { + newDeps[npmKey] = npmDep; + hasPackageChanged = true; + } } }); } @@ -269,8 +276,8 @@ ${ovMsg}` return true; }; -const _updatePackage = (c: RnvContext, override: any) => { - const newPackage: any = merge(c.files.project.package, override); +const _updatePackage = (c: RnvContext, override: Partial) => { + const newPackage: NpmPackageFile = merge(c.files.project.package, override); writeRenativeConfigFile(c, c.paths.project.package, newPackage); c.files.project.package = newPackage; c._requiresNpmInstall = true; diff --git a/packages/core/src/schema/plugins/fragments/base.ts b/packages/core/src/schema/plugins/fragments/base.ts index de55f8e89d..af970534b7 100644 --- a/packages/core/src/schema/plugins/fragments/base.ts +++ b/packages/core/src/schema/plugins/fragments/base.ts @@ -4,7 +4,7 @@ import { z } from 'zod'; const Enabled = z.boolean().default(true).describe('Marks plugin enabled or disabled'); const Disabled = z.boolean().default(false).describe('Marks plugin disabled'); -const Props = z.record(z.string(), z.any()).describe('Custom props passed to plugin'); +const Props = z.record(z.string(), z.string()).describe('Custom props passed to plugin'); const Version = z.string().describe('Version of plugin. Typically package version'); const Source = z .string() diff --git a/packages/core/src/system/fs.ts b/packages/core/src/system/fs.ts index 5ffd796f2e..f1b4674611 100755 --- a/packages/core/src/system/fs.ts +++ b/packages/core/src/system/fs.ts @@ -629,7 +629,7 @@ export const resolvePackage = (text: string) => { return newText; }; -export const sanitizeDynamicProps = (obj: T, propConfig: FileUtilsPropConfig): any => { +export const sanitizeDynamicProps = (obj: T, propConfig: FileUtilsPropConfig): T => { if (!obj) { return obj; } @@ -659,7 +659,7 @@ export const sanitizeDynamicProps = (obj: T, propConfig: FileUtilsP } }); } else if (typeof obj === 'string') { - return resolvePackage(obj); + return resolvePackage(obj) as T; } return obj; @@ -740,7 +740,7 @@ export const getFileListSync = (dir: fs.PathLike) => { export const loadFile = >( fileObj: T, - pathObj: Partial>, + pathObj: Partial>, key: K ) => { const pKey = `${key}Exists` as K; diff --git a/packages/core/src/system/types.ts b/packages/core/src/system/types.ts index c390fbc14a..9021c8d4d8 100644 --- a/packages/core/src/system/types.ts +++ b/packages/core/src/system/types.ts @@ -47,7 +47,7 @@ export type RnvCLI = Record; export type FileUtilsPropConfig = { props: Record; - configProps?: Record; - runtimeProps?: Record; - files?: Record; + configProps?: Record | undefined; + runtimeProps?: Record | undefined; + files?: Record | undefined; }; diff --git a/packages/core/src/tasks/index.ts b/packages/core/src/tasks/index.ts index 6d242ab794..6ae065db82 100644 --- a/packages/core/src/tasks/index.ts +++ b/packages/core/src/tasks/index.ts @@ -341,7 +341,9 @@ export const executeOrSkipTask = async (c: RnvContext, task: string, parentTask: return executeTask(c, TASK_CONFIGURE_SOFT, parentTask, originTask); }; -const ACCEPTED_CONDITIONS = ['platform', 'target', 'appId', 'scheme']; +const ACCEPTED_CONDITIONS = ['platform', 'target', 'appId', 'scheme'] as const; + +type ACKey = typeof ACCEPTED_CONDITIONS[number]; const _logSkip = (task: string) => { logInfo(`Original RNV task ${chalk().white(task)} marked to ignore. SKIPPING...`); @@ -368,9 +370,10 @@ export const shouldSkipTask = (c: RnvContext, taskKey: string, originTaskKey?: s let conditionsToMatch = conditions.length; conditions.forEach((con: string) => { const conArr = con.split('='); - if (ACCEPTED_CONDITIONS.includes(conArr[0])) { - const rt: any = c.runtime; - if (rt[conArr[0]] === conArr[1]) { + const conKey = conArr[0] as ACKey; + if (ACCEPTED_CONDITIONS.includes(conKey)) { + const rt = c.runtime; + if (rt[conKey] === conArr[1]) { conditionsToMatch--; } } else { From 38e07dd0c4a0ce3e68a801c0c61e84bafbc2062e Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Sun, 22 Oct 2023 03:21:46 +0200 Subject: [PATCH 07/12] kill any hunt --- packages/core/src/context/types.ts | 2 +- .../platforms/fragments/templateAndroid.ts | 20 ---- .../fragments/templateAndroidBase.ts | 30 +++++ packages/core/src/schema/validators.ts | 2 +- .../engine-core/src/tasks/task.rnv.new.ts | 4 +- .../src/tasks/task.rnv.ftp.deploy.ts | 23 ++-- packages/rnv/src/runner.ts | 5 +- packages/sdk-android/src/ejector.ts | 6 +- packages/sdk-android/src/gradleParser.ts | 4 +- packages/sdk-android/src/kotlinParser.ts | 110 ++++++++---------- 10 files changed, 103 insertions(+), 103 deletions(-) diff --git a/packages/core/src/context/types.ts b/packages/core/src/context/types.ts index 0ca8c035f0..d2a6e77f53 100644 --- a/packages/core/src/context/types.ts +++ b/packages/core/src/context/types.ts @@ -26,7 +26,7 @@ export type CreateContextOptions = { RNV_HOME_DIR?: string; }; -type RnvContextProgram = ParamKeys & { +export type RnvContextProgram = ParamKeys & { args: string[]; rawArgs: string[]; option: (cmd: string, desc: string) => void; diff --git a/packages/core/src/schema/platforms/fragments/templateAndroid.ts b/packages/core/src/schema/platforms/fragments/templateAndroid.ts index f8d16c5dcc..c08e070a24 100644 --- a/packages/core/src/schema/platforms/fragments/templateAndroid.ts +++ b/packages/core/src/schema/platforms/fragments/templateAndroid.ts @@ -7,26 +7,6 @@ export const TemplateAndroidFragment = { ...TemplateAndroidBaseFragment, settings_gradle: z.optional(z.object({})), gradle_wrapper_properties: z.optional(z.object({})), - MainActivity_java: z.optional( - z.object({ - onCreate: z - .string({}) - .optional() - .default('super.onCreate(savedInstanceState)') - .describe('Overrides super.onCreate method handler of MainActivity.java'), - }) - ), - MainApplication_java: z.optional( - z - .object({ - // onCreate: z - // .string({}) - // .optional() - // .default('super.onCreate(savedInstanceState)') - // .describe('Overrides super.onCreate method handler of MainActivity.java'), - }) - .describe('Allows you to configure behaviour of MainActivity') - ), SplashActivity_java: z.optional(z.object({})), styles_xml: z.optional(z.object({})), colors_xml: z.optional(z.object({})), diff --git a/packages/core/src/schema/platforms/fragments/templateAndroidBase.ts b/packages/core/src/schema/platforms/fragments/templateAndroidBase.ts index bf894f770b..3ec3dbea8d 100644 --- a/packages/core/src/schema/platforms/fragments/templateAndroidBase.ts +++ b/packages/core/src/schema/platforms/fragments/templateAndroidBase.ts @@ -90,6 +90,36 @@ export const TemplateAndroidBaseFragment = { ), }) ), + MainActivity_java: z.optional( + z.object({ + onCreate: z + .string({}) + .optional() + .default('super.onCreate(savedInstanceState)') + .describe('Overrides super.onCreate method handler of MainActivity.java'), + imports: z.array(z.string()).optional(), + methods: z.array(z.string()).optional(), + createMethods: z.array(z.string()).optional(), + resultMethods: z.array(z.string()).optional(), + }) + ), + MainApplication_java: z.optional( + z + .object({ + imports: z.array(z.string()).optional(), + methods: z.array(z.string()).optional(), + createMethods: z.array(z.string()).optional(), + packages: z.array(z.string()).optional(), + packageParams: z.array(z.string()).optional(), + + // onCreate: z + // .string({}) + // .optional() + // .default('super.onCreate(savedInstanceState)') + // .describe('Overrides super.onCreate method handler of MainActivity.java'), + }) + .describe('Allows you to configure behaviour of MainActivity') + ), }; // .describe('Allows more advanced modifications to Android based project template'); diff --git a/packages/core/src/schema/validators.ts b/packages/core/src/schema/validators.ts index f1dae966a4..905570753b 100644 --- a/packages/core/src/schema/validators.ts +++ b/packages/core/src/schema/validators.ts @@ -1,5 +1,5 @@ import { RootProjectSchema } from './configFiles/project'; -export const validateRenativeProjectSchema = (inputJson: any) => { +export const validateRenativeProjectSchema = (inputJson: unknown) => { return RootProjectSchema.safeParse(inputJson); }; diff --git a/packages/engine-core/src/tasks/task.rnv.new.ts b/packages/engine-core/src/tasks/task.rnv.new.ts index eb79d6cb18..affd1b2680 100644 --- a/packages/engine-core/src/tasks/task.rnv.new.ts +++ b/packages/engine-core/src/tasks/task.rnv.new.ts @@ -153,11 +153,13 @@ const _prepareProjectOverview = (c: RnvContext, data: NewProjectData) => { data.confirmString = str; }; +type ConfigProp = Required['templateConfig']['bootstrapQuestions'][number]['configProp']; + type QuestionResults = Record< string, { answer: string; - configProp: any; + configProp: ConfigProp; value: any; } >; diff --git a/packages/integration-ftp/src/tasks/task.rnv.ftp.deploy.ts b/packages/integration-ftp/src/tasks/task.rnv.ftp.deploy.ts index b4c3c23bf7..d526cfbf89 100644 --- a/packages/integration-ftp/src/tasks/task.rnv.ftp.deploy.ts +++ b/packages/integration-ftp/src/tasks/task.rnv.ftp.deploy.ts @@ -30,24 +30,27 @@ const _deployToFtp = (c: RnvContext, platform: RnvPlatform) => promise = _createEnvFtpConfig(envPath); } else { promise = new Promise((resolve2) => { - fsReadFile(envPath, (err: any, data: any) => { + fsReadFile(envPath, (err: unknown, data) => { if (err) return reject(err); resolve2(data.toString()); }); }); } promise - .then((envContent: any) => { + .then((envContent) => { let matches = 0; const targetMatches = 2; - envContent - .split('\n') - .map((line: string) => line.split('=')) - .forEach(([key]: any) => { - if (['RNV_DEPLOY_WEB_FTP_SERVER', 'RNV_DEPLOY_WEB_FTP_USER'].indexOf(key) > -1) { - matches++; - } - }); + if (typeof envContent === 'string') { + envContent + .split('\n') + .map((line: string) => line.split('=')) + .forEach(([key]: any) => { + if (['RNV_DEPLOY_WEB_FTP_SERVER', 'RNV_DEPLOY_WEB_FTP_USER'].indexOf(key) > -1) { + matches++; + } + }); + } + let envPromise; if (matches >= targetMatches) { envPromise = Promise.resolve(); diff --git a/packages/rnv/src/runner.ts b/packages/rnv/src/runner.ts index 2b9eeea2e1..161b45068f 100644 --- a/packages/rnv/src/runner.ts +++ b/packages/rnv/src/runner.ts @@ -3,6 +3,7 @@ import { RnvApiLogger, RnvApiPrompt, RnvApiSpinner, + RnvContextProgram, createRnvApi, createRnvContext, doResolve, @@ -26,8 +27,8 @@ export const executeRnv = async ({ }: { cmd: string; subCmd: string; - process: any; - program: any; + process: NodeJS.Process; + program: RnvContextProgram; spinner: RnvApiSpinner; prompt: RnvApiPrompt; logger: RnvApiLogger; diff --git a/packages/sdk-android/src/ejector.ts b/packages/sdk-android/src/ejector.ts index eacdee70f1..f57fbda054 100644 --- a/packages/sdk-android/src/ejector.ts +++ b/packages/sdk-android/src/ejector.ts @@ -113,7 +113,7 @@ export const ejectGradleProject = async (c: RnvContext) => { const afterEvaluateFix: Array<{ match: string; replace: string }> = []; - parsePlugins(c, c.platform, (_plugin: any, pluginPlat: any, key: string) => { + parsePlugins(c, c.platform, (_plugin, pluginPlat, key: string) => { const pluginPath = doResolvePath(key); if (!pluginPath) return; @@ -131,8 +131,8 @@ export const ejectGradleProject = async (c: RnvContext) => { ]; // const excludeFolders = ['node_modules', 'android']; - if (pluginPlat.afterEvaluate) { - pluginPlat.afterEvaluate.forEach((v: any) => { + if (pluginPlat.templateAndroid?.app_build_gradle?.afterEvaluate) { + pluginPlat.templateAndroid?.app_build_gradle?.afterEvaluate.forEach((v) => { afterEvaluateFix.push({ match: v.replace('{{PLUGIN_ROOT}}', pluginPath), replace: v.replace('{{PLUGIN_ROOT}}', `../../node_modules/${key}`), diff --git a/packages/sdk-android/src/gradleParser.ts b/packages/sdk-android/src/gradleParser.ts index 795eaef05c..cd2bea3373 100644 --- a/packages/sdk-android/src/gradleParser.ts +++ b/packages/sdk-android/src/gradleParser.ts @@ -664,9 +664,9 @@ export const injectPluginGradleSync = ( } }; -export const parseAndroidConfigObject = (c: RnvContext, obj?: any, key = '') => { +export const parseAndroidConfigObject = (c: RnvContext, obj?: RenativeConfigPluginPlatform, key = '') => { // APP/BUILD.GRADLE - const templateAndroid = getConfigProp(c, obj, 'templateAndroid'); + const templateAndroid = getConfigProp(c, c.platform, 'templateAndroid'); const appBuildGradle = templateAndroid?.app_build_gradle; if (appBuildGradle) { diff --git a/packages/sdk-android/src/kotlinParser.ts b/packages/sdk-android/src/kotlinParser.ts index 8fc149c2d2..e39eef2e86 100644 --- a/packages/sdk-android/src/kotlinParser.ts +++ b/packages/sdk-android/src/kotlinParser.ts @@ -1,5 +1,8 @@ import { OverridesOptions, + PlatformKey, + RenativeConfigPluginPlatform, + RnvContext, addSystemInjects, getAppFolder, getAppId, @@ -8,14 +11,13 @@ import { getEntryFile, getGetJsBundleFile, getIP, - logWarning, writeCleanFile, } from '@rnv/core'; import { mkdirSync } from 'fs'; import path from 'path'; import { Context } from './types'; -const JS_BUNDLE_DEFAULTS: any = { +const JS_BUNDLE_DEFAULTS: Partial> = { // Android Wear does not support webview required for connecting to packager. this is hack to prevent RN connectiing to running bundler androidwear: '"assets://index.androidwear.bundle"', }; @@ -116,7 +118,7 @@ export const parseMainApplicationSync = (c: Context) => { ); }; -export const parseMainActivitySync = (c: any) => { +export const parseMainActivitySync = (c: RnvContext) => { const appFolder = getAppFolder(c); const { platform } = c; @@ -210,9 +212,16 @@ export const parseSplashActivitySync = (c: Context) => { ); }; -export const injectPluginKotlinSync = (c: any, plugin: any, key: any, pkg: any) => { - if (plugin.activityImports instanceof Array) { - plugin.activityImports.forEach((activityImport: any) => { +export const injectPluginKotlinSync = ( + c: RnvContext, + plugin: RenativeConfigPluginPlatform, + key: string, + pkg: string | undefined +) => { + const templ = plugin.templateAndroid; + const mainActivity = templ?.MainActivity_java; + if (mainActivity?.imports) { + mainActivity.imports.forEach((activityImport) => { // Avoid duplicate imports if (c.payload.pluginConfigAndroid.pluginActivityImports.indexOf(activityImport) === -1) { c.payload.pluginConfigAndroid.pluginActivityImports += `import ${activityImport}\n`; @@ -220,93 +229,68 @@ export const injectPluginKotlinSync = (c: any, plugin: any, key: any, pkg: any) }); } - if (plugin.activityMethods instanceof Array) { + if (mainActivity?.methods) { c.payload.pluginConfigAndroid.pluginActivityMethods += '\n'; - c.payload.pluginConfigAndroid.pluginActivityMethods += `${plugin.activityMethods.join('\n ')}`; + c.payload.pluginConfigAndroid.pluginActivityMethods += `${mainActivity.methods.join('\n ')}`; } - const { mainActivity } = plugin; if (mainActivity) { - if (mainActivity.createMethods instanceof Array) { + if (mainActivity.createMethods) { c.payload.pluginConfigAndroid.pluginActivityCreateMethods += '\n'; c.payload.pluginConfigAndroid.pluginActivityCreateMethods += `${mainActivity.createMethods.join('\n ')}`; } - if (mainActivity.resultMethods instanceof Array) { + if (mainActivity.resultMethods) { c.payload.pluginConfigAndroid.pluginActivityResultMethods += '\n'; c.payload.pluginConfigAndroid.pluginActivityResultMethods += `${mainActivity.resultMethods.join('\n ')}`; } + } - if (mainActivity.imports instanceof Array) { - mainActivity.imports.forEach((v: any) => { - c.payload.pluginConfigAndroid.pluginActivityImports += `import ${v}\n`; - }); - } + _injectPackage(c, plugin, pkg); - if (mainActivity.methods instanceof Array) { - c.payload.pluginConfigAndroid.pluginActivityMethods += '\n'; - c.payload.pluginConfigAndroid.pluginActivityMethods += `${mainActivity.methods.join('\n ')}`; - } - } + const mainApplication = templ?.MainApplication_java; - if (plugin.imports) { - plugin.imports.forEach((v: any) => { - c.payload.pluginConfigAndroid.pluginApplicationImports += `import ${v}\n`; + if (mainApplication?.packages) { + mainApplication.packages.forEach((v) => { + _injectPackage(c, plugin, v); }); } - _injectPackage(c, plugin, pkg); - - if (plugin.MainApplication) { - if (plugin.MainApplication.packages) { - plugin.MainApplication.packages.forEach((v: any) => { - _injectPackage(c, plugin, v); - }); - } + if (mainApplication?.createMethods) { + c.payload.pluginConfigAndroid.pluginApplicationCreateMethods += '\n'; + c.payload.pluginConfigAndroid.pluginApplicationCreateMethods += `${mainApplication.createMethods.join( + '\n ' + )}`; } - const { mainApplication } = plugin; - if (mainApplication) { - if (mainApplication.createMethods instanceof Array) { - c.payload.pluginConfigAndroid.pluginApplicationCreateMethods += '\n'; - c.payload.pluginConfigAndroid.pluginApplicationCreateMethods += `${mainApplication.createMethods.join( - '\n ' - )}`; - } - - if (mainApplication.imports instanceof Array) { - mainApplication.imports.forEach((v: any) => { - c.payload.pluginConfigAndroid.pluginApplicationImports += `import ${v}\n`; - }); - } - - if (mainApplication.methods instanceof Array) { - c.payload.pluginConfigAndroid.pluginApplicationMethods += '\n'; - c.payload.pluginConfigAndroid.pluginApplicationMethods += `${mainApplication.methods.join('\n ')}`; - } + if (mainApplication?.imports) { + mainApplication.imports.forEach((v) => { + c.payload.pluginConfigAndroid.pluginApplicationImports += `import ${v}\n`; + }); } - if (plugin.mainApplicationMethods) { - logWarning( - `Plugin ${key} in ${c.paths.project.config} is using DEPRECATED "${c.platform}": { MainApplicationMethods }. Use "${c.platform}": { "mainApplication": { "methods": []}} instead` - ); - c.payload.pluginConfigAndroid.pluginApplicationMethods += `\n${plugin.mainApplicationMethods}\n`; + if (mainApplication?.methods) { + c.payload.pluginConfigAndroid.pluginApplicationMethods += '\n'; + c.payload.pluginConfigAndroid.pluginApplicationMethods += `${mainApplication.methods.join('\n ')}`; } }; -const _injectPackage = (c: any, plugin: any, pkg: any) => { +const _injectPackage = (c: RnvContext, plugin: RenativeConfigPluginPlatform, pkg: string | undefined) => { if (pkg) { c.payload.pluginConfigAndroid.pluginApplicationImports += `import ${pkg}\n`; } let packageParams = ''; - if (plugin.packageParams) { - packageParams = plugin.packageParams.join(','); + const mainApplication = plugin.templateAndroid?.MainApplication_java; + if (mainApplication?.packageParams) { + packageParams = mainApplication.packageParams.join(','); } - const className = _extractClassName(pkg); - if (className) { - c.payload.pluginConfigAndroid.pluginPackages += `${className}(${packageParams}),\n`; + if (pkg) { + const className = _extractClassName(pkg); + if (className) { + c.payload.pluginConfigAndroid.pluginPackages += `${className}(${packageParams}),\n`; + } } }; -const _extractClassName = (pkg: any) => (pkg ? pkg.split('.').pop() : null); +const _extractClassName = (pkg: string) => (pkg ? pkg.split('.').pop() : null); From 4cc279a8bad19ffd58c759b8314342ccf15f2b74 Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Sun, 22 Oct 2023 04:06:35 +0200 Subject: [PATCH 08/12] type fixes --- .../src/schema/platforms/fragments/ios.ts | 2 +- .../fragments/templateAndroidBase.ts | 5 +- packages/core/src/schema/types.ts | 4 +- packages/sdk-android/src/manifestParser.ts | 56 ++++++++++++------- packages/sdk-android/src/types.ts | 16 +++--- packages/sdk-apple/src/runner.ts | 3 +- packages/sdk-apple/src/types.ts | 8 +-- packages/sdk-apple/src/xcodeParser.ts | 2 +- 8 files changed, 60 insertions(+), 36 deletions(-) diff --git a/packages/core/src/schema/platforms/fragments/ios.ts b/packages/core/src/schema/platforms/fragments/ios.ts index 335b2404c3..d2031bd3c4 100644 --- a/packages/core/src/schema/platforms/fragments/ios.ts +++ b/packages/core/src/schema/platforms/fragments/ios.ts @@ -53,7 +53,7 @@ export const PlatformiOSFragment = { .describe('Allows you to pass launch arguments to active scheme') .optional(), provisionProfileSpecifier: z.string().optional(), - provisionProfileSpecifiers: z.array(z.string()).optional(), + provisionProfileSpecifiers: z.record(z.string(), z.string()).optional(), allowProvisioningUpdates: z.boolean().optional(), provisioningProfiles: z.optional(provisioningProfiles), codeSignIdentities: z.optional(z.record(z.string(), z.string())), diff --git a/packages/core/src/schema/platforms/fragments/templateAndroidBase.ts b/packages/core/src/schema/platforms/fragments/templateAndroidBase.ts index 3ec3dbea8d..d11f47e887 100644 --- a/packages/core/src/schema/platforms/fragments/templateAndroidBase.ts +++ b/packages/core/src/schema/platforms/fragments/templateAndroidBase.ts @@ -61,7 +61,8 @@ const ManifestChildWithChildren: z.ZodType<_ManifestChildType> = ManifestChildBa children: z.lazy(() => ManifestChildWithChildren.array()), }); -const AndroidManifest = z.object({ +const AndroidManifest = ManifestChildBase.extend({ + package: z.string().optional(), children: z.array(ManifestChildWithChildren), }).describe(`Allows you to directly manipulate \`AndroidManifest.xml\` via json override mechanism Injects / Overrides values in AndroidManifest.xml file of generated android based project @@ -124,3 +125,5 @@ export const TemplateAndroidBaseFragment = { // .describe('Allows more advanced modifications to Android based project template'); export type _ManifestChildWithChildrenType = z.infer; + +export type _AndroidManifestType = z.infer; diff --git a/packages/core/src/schema/types.ts b/packages/core/src/schema/types.ts index be8520a3a7..f5f6b55b52 100644 --- a/packages/core/src/schema/types.ts +++ b/packages/core/src/schema/types.ts @@ -5,7 +5,7 @@ import type { _MergedPlatformObjectType } from './platforms'; import type { _RootAppBaseSchemalType } from './configFiles/app'; import type { _RootProjectBaseSchemaType } from './configFiles/project'; -import type { _ManifestChildWithChildrenType } from './platforms/fragments/templateAndroidBase'; +import type { _AndroidManifestType, _ManifestChildWithChildrenType } from './platforms/fragments/templateAndroidBase'; import type { _MergedPlatformPrivateObjectType } from './configFiles/private'; import { ConfigFileBuildConfig } from './configFiles/buildConfig'; @@ -40,6 +40,8 @@ export type RenativeConfigAppDelegateMethod = _AppDelegateMethodType; export type AndroidManifestNode = _ManifestChildWithChildrenType; +export type AndroidManifest = _AndroidManifestType; + // export type ManifestNode = _ManifestChildType; // export const test = (test: _ConfigRootMerged) => { diff --git a/packages/sdk-android/src/manifestParser.ts b/packages/sdk-android/src/manifestParser.ts index 8128c1e149..ba55ff31c7 100644 --- a/packages/sdk-android/src/manifestParser.ts +++ b/packages/sdk-android/src/manifestParser.ts @@ -15,32 +15,38 @@ import { writeCleanFile, parsePlugins, AndroidManifestNode, + AndroidManifest, } from '@rnv/core'; -import { AndroidManifestJSON, Context } from './types'; +import { Context } from './types'; const PROHIBITED_DUPLICATE_TAGS = ['intent-filter']; const SYSTEM_TAGS = ['tag', 'children']; -const _findChildNode = (tag: string, name: string, node: any) => { +const _findChildNode = (tag: string, name: string, node: AndroidManifestNode) => { if (!node) { logWarning('_findChildNode: Node is undefined'); return; } if (!name && !PROHIBITED_DUPLICATE_TAGS.includes(tag)) return null; // Can't determine reused child nodes without unique name identifier - for (let i = 0; i < node.children.length; i++) { - const ch = node.children[i]; - if (ch.tag === tag) { - if (ch['android:name'] === name || PROHIBITED_DUPLICATE_TAGS.includes(tag)) { - return ch; + if (node.children) { + for (let i = 0; i < node.children.length; i++) { + const ch = node.children?.[i]; + if (ch && ch.tag === tag) { + if (ch['android:name'] === name || PROHIBITED_DUPLICATE_TAGS.includes(tag)) { + return ch; + } } } } + return null; }; -const _convertToXML = (manifestObj: any) => _parseNode(manifestObj, 0); +const _convertToXML = (manifestObj: AndroidManifestNode) => _parseNode(manifestObj, 0); -const _parseNode = (n: any, level: number) => { +type NodeKey = keyof AndroidManifestNode; + +const _parseNode = (n: AndroidManifestNode, level: number) => { let output = ''; let space = ''; for (let i = 0; i < level; i++) { @@ -63,12 +69,13 @@ const _parseNode = (n: any, level: number) => { output += `${space}<${n.tag}${endLine}`; Object.keys(n).forEach((k) => { if (!SYSTEM_TAGS.includes(k)) { - output += `${isSingleLine ? '' : `${space} `}${k}="${n[k]}"${endLine}`; + output += `${isSingleLine ? '' : `${space} `}${k}="${n[k as NodeKey]}"${endLine}`; } }); - } else { - output += `${space}<${n.tag}`; } + // else { + // output += `${space}<${n.tag}`; + // } if (n.children && n.children.length) { if (isSingleLine) { output += '>\n'; @@ -77,7 +84,7 @@ const _parseNode = (n: any, level: number) => { } const nextLevel = level + 1; - n.children.forEach((v: any) => { + n.children.forEach((v) => { output += _parseNode(v, nextLevel); }); output += `${space}\n`; @@ -87,7 +94,10 @@ const _parseNode = (n: any, level: number) => { return output; }; -const _mergeNodeParameters = (node: any, nodeParamsExt: any) => { +const _mergeNodeParameters = ( + node: AndroidManifestNode | undefined, + nodeParamsExt: AndroidManifestNode | undefined +) => { if (!nodeParamsExt) { logWarning('_mergeNodeParameters: nodeParamsExt value is null'); return; @@ -98,11 +108,17 @@ const _mergeNodeParameters = (node: any, nodeParamsExt: any) => { } Object.keys(nodeParamsExt).forEach((k) => { - if (!SYSTEM_TAGS.includes(k)) node[k] = nodeParamsExt[k]; + const key = k as NodeKey; + const val = nodeParamsExt[key]; + + if (val && !SYSTEM_TAGS.includes(k)) { + //TODO: fix this + (node as Record)[key] = val; + } }); }; -const _mergeNodeChildren = (node: any, nodeChildrenExt: Array = []) => { +const _mergeNodeChildren = (node: AndroidManifestNode, nodeChildrenExt: Array = []) => { // console.log('_mergeNodeChildren', node, 'OVERRIDE', nodeChildrenExt); if (!node) { logWarning('_mergeNodeChildren: Node is undefined'); @@ -119,7 +135,7 @@ const _mergeNodeChildren = (node: any, nodeChildrenExt: Array { @@ -165,7 +181,7 @@ export const parseAndroidManifestSync = (c: Context) => { try { const baseManifestFilePath = path.join(__dirname, `../supportFiles/AndroidManifest_${platform}.json`); - const baseManifestFile = readObjectSync(baseManifestFilePath); + const baseManifestFile = readObjectSync(baseManifestFilePath); if (!baseManifestFile) { return; @@ -208,6 +224,7 @@ export const parseAndroidManifestSync = (c: Context) => { Object.keys(pc).forEach((k) => { if (!(excludedPermissions && excludedPermissions.includes(k))) { const key = pc[k].key || k; + baseManifestFile.children = baseManifestFile.children || []; baseManifestFile.children.push({ tag: 'uses-permission', 'android:name': key, @@ -218,6 +235,7 @@ export const parseAndroidManifestSync = (c: Context) => { includedPermissions.forEach((v) => { if (pc[v]) { const key = pc[v].key || v; + baseManifestFile.children = baseManifestFile.children || []; baseManifestFile.children.push({ tag: 'uses-permission', 'android:name': key, diff --git a/packages/sdk-android/src/types.ts b/packages/sdk-android/src/types.ts index 37b55adf0c..ce0a7f789f 100644 --- a/packages/sdk-android/src/types.ts +++ b/packages/sdk-android/src/types.ts @@ -77,11 +77,11 @@ export type AndroidDevice = { export type TemplateAndroid = Required['templateAndroid']>; -export type AndroidManifestJSONNode = { - tag: string; - 'android:name': string; -}; -export type AndroidManifestJSON = { - package?: string; - children: AndroidManifestJSONNode[]; -}; +// export type AndroidManifestJSONNode = { +// tag: string; +// 'android:name': string; +// children?: AndroidManifestJSONNode[]; +// }; +// export type AndroidManifestJSON = AndroidManifestJSONNode & { +// package?: string; +// }; diff --git a/packages/sdk-apple/src/runner.ts b/packages/sdk-apple/src/runner.ts index ea18445f03..ebeb33ff54 100644 --- a/packages/sdk-apple/src/runner.ts +++ b/packages/sdk-apple/src/runner.ts @@ -463,7 +463,8 @@ and we will try to help! } }; -const _handleMissingTeam = async (c: Context, e: any) => { +const _handleMissingTeam = async (c: Context, e: unknown) => { + if (typeof e !== 'string') return; const isDevelopmentTeamMissing = e.includes('requires a development team. Select a development team'); if (isDevelopmentTeamMissing) { const loc = `./appConfigs/${c.runtime.appId}/renative.json:{ "platforms": { "${c.platform}": { "teamID": "....."`; diff --git a/packages/sdk-apple/src/types.ts b/packages/sdk-apple/src/types.ts index d7db6280ee..c261e99b75 100644 --- a/packages/sdk-apple/src/types.ts +++ b/packages/sdk-apple/src/types.ts @@ -54,14 +54,14 @@ export type Payload = { runScheme?: string; provisioningStyle?: string; deploymentTarget?: string; - provisionProfileSpecifier?: any; - provisionProfileSpecifiers?: any; + provisionProfileSpecifier?: string; + provisionProfileSpecifiers?: Record; excludedArchs?: Array; codeSignIdentity?: string; codeSignIdentities?: Record; systemCapabilities?: Record; - teamID?: any; - appId?: any; + teamID?: string; + appId?: string; }; }; diff --git a/packages/sdk-apple/src/xcodeParser.ts b/packages/sdk-apple/src/xcodeParser.ts index 5ef456279a..1c9a3b27fb 100644 --- a/packages/sdk-apple/src/xcodeParser.ts +++ b/packages/sdk-apple/src/xcodeParser.ts @@ -33,7 +33,7 @@ export const parseXcodeProject = async (c: Context) => { c.payload.xcodeProj.deploymentTarget = getConfigProp(c, platform, 'deploymentTarget', '14.0'); c.payload.xcodeProj.provisionProfileSpecifier = c.program.provisionProfileSpecifier || getConfigProp(c, platform, 'provisionProfileSpecifier'); - c.payload.xcodeProj.provisionProfileSpecifiers = getConfigProp(c, platform, 'provisionProfileSpecifiers'); + c.payload.xcodeProj.provisionProfileSpecifiers = getConfigProp(c, platform, 'provisionProfileSpecifiers') || {}; c.payload.xcodeProj.codeSignIdentity = c.program.codeSignIdentity || getConfigProp(c, platform, 'codeSignIdentity', 'iPhone Developer'); From f1975b3c6d567f862477d4b7247e8d7d9714c152 Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Sun, 22 Oct 2023 04:24:41 +0200 Subject: [PATCH 09/12] fix more types --- packages/engine-rn-electron/src/sdk.ts | 5 ++++- .../src/tasks/task.rnv.crypto.updateProfiles.ts | 2 +- packages/sdk-android/src/runner.ts | 12 ++++++------ packages/sdk-apple/src/runner.ts | 2 +- packages/sdk-kaios/src/constants.ts | 7 ------- packages/sdk-kaios/src/deviceManager.ts | 3 +-- packages/sdk-react-native/src/common.ts | 8 ++++++-- packages/sdk-react-native/src/iosRunner.ts | 8 ++++++-- packages/sdk-tizen/src/deviceManager.ts | 14 ++++++++++---- packages/sdk-webos/src/deviceManager.ts | 8 ++++++-- packages/sdk-webpack/src/index.ts | 4 ++-- 11 files changed, 43 insertions(+), 30 deletions(-) diff --git a/packages/engine-rn-electron/src/sdk.ts b/packages/engine-rn-electron/src/sdk.ts index 3b13a6b635..98da1d1a8b 100644 --- a/packages/engine-rn-electron/src/sdk.ts +++ b/packages/engine-rn-electron/src/sdk.ts @@ -207,7 +207,10 @@ const configureProject = (c: RnvContext, exitOnFail?: boolean) => ); } - const macConfig: any = {}; + const macConfig: { + mac?: Record; + mas?: Record; + } = {}; if (platform === MACOS) { macConfig.mac = { entitlements: path.join(platformProjectDir, 'entitlements.mac.plist'), diff --git a/packages/engine-rn/src/tasks/task.rnv.crypto.updateProfiles.ts b/packages/engine-rn/src/tasks/task.rnv.crypto.updateProfiles.ts index 2f176990aa..cadec92fb9 100644 --- a/packages/engine-rn/src/tasks/task.rnv.crypto.updateProfiles.ts +++ b/packages/engine-rn/src/tasks/task.rnv.crypto.updateProfiles.ts @@ -18,7 +18,7 @@ const _updateProfile = (c: RnvContext, v: string) => logTask(`_updateProfile:${v}`, chalk().grey); updateProfile(c) .then(() => resolve()) - .catch((e: any) => reject(e)); + .catch((e) => reject(e)); }); const _updateProfiles = (c: RnvContext) => { diff --git a/packages/sdk-android/src/runner.ts b/packages/sdk-android/src/runner.ts index eeee1d83fd..5b42c62130 100644 --- a/packages/sdk-android/src/runner.ts +++ b/packages/sdk-android/src/runner.ts @@ -94,8 +94,8 @@ export const runAndroid = async (c: Context) => { return Promise.reject(e); } - const activeDevices = devicesAndEmulators.filter((d: any) => d.isActive); - const inactiveDevices = devicesAndEmulators.filter((d: any) => !d.isActive); + const activeDevices = devicesAndEmulators.filter((d) => d.isActive); + const inactiveDevices = devicesAndEmulators.filter((d) => !d.isActive); const askWhereToRun = async () => { if (activeDevices.length === 0 && inactiveDevices.length > 0) { @@ -123,7 +123,7 @@ export const runAndroid = async (c: Context) => { choices, }); if (response.chosenEmulator) { - const dev = activeDevices.find((d: any) => d.name === response.chosenEmulator); + const dev = activeDevices.find((d) => d.name === response.chosenEmulator); await runReactNativeAndroid(c, platform, dev); } } else { @@ -136,7 +136,7 @@ export const runAndroid = async (c: Context) => { if (target) { // a target is provided logDebug('Target provided', target); - const foundDevice = devicesAndEmulators.find((d: any) => d.udid.includes(target) || d.name.includes(target)); + const foundDevice = devicesAndEmulators.find((d) => d.udid.includes(target) || d.name.includes(target)); if (foundDevice) { if (foundDevice.isActive) { await runReactNativeAndroid(c, platform, foundDevice); @@ -157,7 +157,7 @@ export const runAndroid = async (c: Context) => { // neither a target nor an active device is found, revert to default target if available logDebug('Default target used', defaultTarget); const foundDevice = devicesAndEmulators.find( - (d: any) => d.udid.includes(defaultTarget) || d.name.includes(defaultTarget) + (d) => d.udid.includes(defaultTarget) || d.name.includes(defaultTarget) ); if (!foundDevice) { logDebug('Target not provided, asking where to run'); @@ -482,7 +482,7 @@ export const configureProject = async (c: Context) => { // FONTS const includedFonts = getConfigProp(c, c.platform, 'includedFonts') || []; - parseFonts(c, (font: any, dir: any) => { + parseFonts(c, (font: string, dir: string) => { if (font.includes('.ttf') || font.includes('.otf')) { const key = font.split('.')[0]; diff --git a/packages/sdk-apple/src/runner.ts b/packages/sdk-apple/src/runner.ts index ebeb33ff54..de0f4624f3 100644 --- a/packages/sdk-apple/src/runner.ts +++ b/packages/sdk-apple/src/runner.ts @@ -491,7 +491,7 @@ Type in your Apple Team ID to be used (will be saved to ${c.paths.appConfig?.con } }; -const _handleProvisioningIssues = async (c: Context, e: any, msg: string) => { +const _handleProvisioningIssues = async (c: Context, e: unknown, msg: string) => { const provisioningStyle = c.program.provisioningStyle || getConfigProp(c, c.platform, 'provisioningStyle'); const appFolderName = getAppFolderName(c, c.platform); // Sometimes xcodebuild reports Automatic signing is disabled but it could be keychain not accepted by user const isProvAutomatic = provisioningStyle === 'Automatic'; diff --git a/packages/sdk-kaios/src/constants.ts b/packages/sdk-kaios/src/constants.ts index 18f57360c5..b8ca689090 100644 --- a/packages/sdk-kaios/src/constants.ts +++ b/packages/sdk-kaios/src/constants.ts @@ -1,8 +1 @@ -import { KAIOS } from '@rnv/core'; - export const CLI_KAIOS_EMULATOR = 'tizenEmulator'; - -export const KAIOS_SDK = 'KAIOS_SDK'; - -export const SDK_PLATFORMS: any = {}; -SDK_PLATFORMS[KAIOS] = KAIOS_SDK; diff --git a/packages/sdk-kaios/src/deviceManager.ts b/packages/sdk-kaios/src/deviceManager.ts index b9165e9dcc..cb3c6ac232 100644 --- a/packages/sdk-kaios/src/deviceManager.ts +++ b/packages/sdk-kaios/src/deviceManager.ts @@ -1,5 +1,4 @@ import { fsExistsSync, getRealPath, chalk, logTask, RnvError, RnvContext } from '@rnv/core'; -import { KAIOS_SDK } from './constants'; const childProcess = require('child_process'); @@ -9,7 +8,7 @@ export const launchKaiOSSimulator = (c: RnvContext) => if (!c.buildConfig?.sdks?.KAIOS_SDK) { reject( - `${KAIOS_SDK} is not configured in your ${ + `KAIOS_SDK is not configured in your ${ c.paths.workspace.config } file. Make sure you add location to your Kaiosrt App path similar to: ${chalk().white.bold( '"KAIOS_SDK": "/Applications/Kaiosrt.app"' diff --git a/packages/sdk-react-native/src/common.ts b/packages/sdk-react-native/src/common.ts index a7862ae1bd..99930b55a9 100644 --- a/packages/sdk-react-native/src/common.ts +++ b/packages/sdk-react-native/src/common.ts @@ -94,9 +94,13 @@ const poll = (fn: () => Promise, timeout = 10000, interval = 1000) => { spinner.fail("Can't connect to bundler. Try restarting it."); reject("Can't connect to bundler. Try restarting it."); } - } catch (e: any) { + } catch (e: unknown) { spinner.fail("Can't connect to bundler. Try restarting it."); - reject(e); + if (typeof e === 'string') { + reject(e); + } else if (e instanceof Error) { + reject(e.message); + } } }; diff --git a/packages/sdk-react-native/src/iosRunner.ts b/packages/sdk-react-native/src/iosRunner.ts index 2a0a472bd9..c43f3a09dc 100644 --- a/packages/sdk-react-native/src/iosRunner.ts +++ b/packages/sdk-react-native/src/iosRunner.ts @@ -70,7 +70,11 @@ export const runReactNativeIOS = async ( env, printableEnvKeys: ['RNV_REACT_NATIVE_PATH', 'RNV_APP_ID', 'RNV_PROJECT_ROOT', 'RNV_APP_BUILD_DIR'], }); - } catch (e: any) { - return Promise.reject(e); + } catch (e) { + if (typeof e === 'string') { + return Promise.reject(e); + } else if (e instanceof Error) { + return Promise.reject(e.message); + } } }; diff --git a/packages/sdk-tizen/src/deviceManager.ts b/packages/sdk-tizen/src/deviceManager.ts index 64cf90a4fb..f5f9813558 100644 --- a/packages/sdk-tizen/src/deviceManager.ts +++ b/packages/sdk-tizen/src/deviceManager.ts @@ -116,8 +116,14 @@ const _getDeviceID = async (c: RnvContext, target: string) => { let connectResponse: string; try { connectResponse = await execCLI(c, CLI_SDB_TIZEN, `connect ${target}`); - } catch (e: any) { - connectResponse = e; + } catch (e) { + if (typeof e === 'string') { + connectResponse = e; + } else if (e instanceof Error) { + connectResponse = e.message; + } else { + connectResponse = 'Unknown error'; + } } if (connectResponse.includes('EPERM')) { throw new Error( @@ -336,13 +342,13 @@ Please create one and then edit the default target from ${c.paths.workspace.dir} ); fsRenameSync(path.join(tOut, wgt), path.join(tOut, wgtClean)); } - } catch (err: any) { + } catch (err) { logError(err); } try { await execCLI(c, CLI_TIZEN, `install -- ${tOut} -n ${wgtClean} -t ${deviceID}`); hasDevice = true; - } catch (err: any) { + } catch (err) { logError(err); logWarning( `There is no emulator or device connected! Let's try to launch it. "${chalk().white.bold( diff --git a/packages/sdk-webos/src/deviceManager.ts b/packages/sdk-webos/src/deviceManager.ts index bcd48c4e6b..02a4fdd275 100644 --- a/packages/sdk-webos/src/deviceManager.ts +++ b/packages/sdk-webos/src/deviceManager.ts @@ -79,8 +79,12 @@ const parseDevices = (c: RnvContext, devicesResponse: string): Promise { +const _runRemoteDebuggerChii = async (c: RnvContext, obj: { remoteDebuggerActive: boolean }) => { const { debugIp } = c.program; try { await commandExists('chii'); @@ -111,7 +111,7 @@ Debugger running at: ${debugUrl}`); return true; }; -const _runRemoteDebuggerWeinre = async (c: RnvContext, obj: any) => { +const _runRemoteDebuggerWeinre = async (c: RnvContext, obj: { remoteDebuggerActive: boolean }) => { const { debugIp } = c.program; try { await commandExists('weinre'); From 49bbd31043bfdfe79a04ce108005616b0fd20726 Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Sun, 22 Oct 2023 21:29:14 +0200 Subject: [PATCH 10/12] device manager fixes , ts coverage --- packages/core/src/api/types.ts | 2 +- packages/core/src/common.ts | 3 +- packages/core/src/system/fs.ts | 2 +- packages/sdk-android/src/deviceManager.ts | 47 ++++++++++++++++------- 4 files changed, 38 insertions(+), 16 deletions(-) diff --git a/packages/core/src/api/types.ts b/packages/core/src/api/types.ts index 218eda0baa..25ee130cbf 100644 --- a/packages/core/src/api/types.ts +++ b/packages/core/src/api/types.ts @@ -118,6 +118,6 @@ export type PromptRenderFn = (i: number, obj: any, mapping: any, defaultVal: str export type GetConfigPropFn = ( c: RnvContext, platform: RnvPlatform, - key: ConfigPropKey, + key: T, defaultVal?: ConfigProp[T] ) => ConfigProp[T]; diff --git a/packages/core/src/common.ts b/packages/core/src/common.ts index f71ed311d0..d69b969a42 100755 --- a/packages/core/src/common.ts +++ b/packages/core/src/common.ts @@ -14,6 +14,7 @@ import { inquirerPrompt } from './api'; import { RnvPlatform } from './types'; import { DEFAULTS } from './schema/defaults'; import { ConfigFileBuildConfig } from './schema/configFiles/buildConfig'; +import { GetConfigPropFn } from './api/types'; export const getTimestampPathsConfig = (c: RnvContext, platform: RnvPlatform): TimestampPathsConfig | undefined => { let timestampBuildFiles: Array = []; @@ -250,7 +251,7 @@ const _getValueOrMergedObject = (resultScheme: object, resultPlatforms: object, return resultCommon; }; -export const getConfigProp = ( +export const getConfigProp: GetConfigPropFn = ( c: RnvContext, platform: RnvPlatform, key: T, diff --git a/packages/core/src/system/fs.ts b/packages/core/src/system/fs.ts index f1b4674611..26f800c175 100755 --- a/packages/core/src/system/fs.ts +++ b/packages/core/src/system/fs.ts @@ -150,7 +150,7 @@ export const writeCleanFile = ( if (occurences) { occurences.forEach((occ) => { const val = occ.replace('{{configProps.', '').replace('}}', '') as ConfigPropKey; - const configVal = api.getConfigProp(c, c.platform, val, ''); + const configVal = api.getConfigProp(c, c.platform, val) || ''; pFileClean = pFileClean.replace(occ, configVal); }); } diff --git a/packages/sdk-android/src/deviceManager.ts b/packages/sdk-android/src/deviceManager.ts index a0bcac47b7..13768f98de 100644 --- a/packages/sdk-android/src/deviceManager.ts +++ b/packages/sdk-android/src/deviceManager.ts @@ -39,14 +39,14 @@ const currentDeviceProps: Record> = {}; export const composeDevicesString = (devices: Array) => { logTask('composeDevicesString', `numDevices:${devices ? devices.length : null}`); const devicesArray: Array = []; - devices.forEach((v, i) => devicesArray.push(_getDeviceString(v, i))); + devices.forEach((v, i) => devicesArray.push(_getDeviceAsString(v, i))); return `\n${devicesArray.join('')}`; }; export const composeDevicesArray = (devices: Array) => { logTask('composeDevicesString', `numDevices:${devices ? devices.length : null}`); - const devicesArray: Array = []; - devices.forEach((v) => devicesArray.push(_getDeviceString(v, null))); + const devicesArray: Array = []; + devices.forEach((v) => devicesArray.push(_getDeviceAsObject(v))); return devicesArray; }; @@ -116,9 +116,11 @@ export const listAndroidTargets = async (c: RnvContext) => { return devices; }; -//Fuck it, I just any this return until complete refactor -const _getDeviceString = (device: AndroidDevice, i: number | null): any => { - const { isTV, isTablet, name, udid, isDevice, isActive, avdConfig, isWear, arch } = device; +type DeviceInfo = { key: string; name: string; value: string; icon: string }; + +const getDeviceIcon = (device: AndroidDevice) => { + const { isTV, isTablet, udid, avdConfig, isWear } = device; + let deviceIcon = ''; if (isTablet) deviceIcon = 'Tablet 💊 '; if (isTV) deviceIcon = 'TV 📺 '; @@ -126,18 +128,32 @@ const _getDeviceString = (device: AndroidDevice, i: number | null): any => { if (!deviceIcon && (udid !== 'unknown' || avdConfig)) { deviceIcon = 'Phone 📱 '; } + return deviceIcon; +}; + +//Fuck it, I just any this return until complete refactor +const _getDeviceAsString = (device: AndroidDevice, i: number): string => { + const { name, udid, isDevice, isActive, arch } = device; + const deviceIcon = getDeviceIcon(device); const deviceString = `${chalk().white(name)} | ${deviceIcon} | arch: ${arch} | udid: ${chalk().grey(udid)}${ isDevice ? chalk().red(' (device)') : '' } ${isActive ? chalk().magenta(' (active)') : ''}`; - if (i === null) { - return { key: name, name: deviceString, value: name, icon: deviceIcon }; - } - return ` [${i + 1}]> ${deviceString}\n`; }; +const _getDeviceAsObject = (device: AndroidDevice): DeviceInfo => { + const { name, udid, isDevice, isActive, arch } = device; + const deviceIcon = getDeviceIcon(device); + + const deviceString = `${chalk().white(name)} | ${deviceIcon} | arch: ${arch} | udid: ${chalk().grey(udid)}${ + isDevice ? chalk().red(' (device)') : '' + } ${isActive ? chalk().magenta(' (active)') : ''}`; + + return { key: name, name: deviceString, value: name, icon: deviceIcon }; +}; + export const resetAdb = async (c: RnvContext, forceRun?: boolean, ranBefore?: boolean) => { if (!c.program.resetAdb && !forceRun) return; try { @@ -162,8 +178,8 @@ export const getAndroidTargets = async (c: RnvContext, skipDevices: boolean, ski await new Promise((r) => setTimeout(r, 1000)); try { - let devicesResult: any; - let avdResult: any; + let devicesResult: string | undefined; + let avdResult: string | undefined; if (!skipDevices) { devicesResult = await execCLI(c, CLI_ANDROID_ADB, 'devices -l'); @@ -399,7 +415,12 @@ export const connectToWifiDevice = async (c: RnvContext, target: string) => { return false; }; -const _parseDevicesResult = async (c: RnvContext, devicesString: string, avdsString: string, deviceOnly: boolean) => { +const _parseDevicesResult = async ( + c: RnvContext, + devicesString: string | undefined, + avdsString: string | undefined, + deviceOnly: boolean +) => { logDebug(`_parseDevicesResult:${devicesString}:${avdsString}:${deviceOnly}`); const devices: Array = []; const { skipTargetCheck } = c.program; From 969049dc27a1c321ae733ff83c5ac47edf5f1b5c Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Mon, 23 Oct 2023 07:11:01 +0200 Subject: [PATCH 11/12] update interfaces --- packages/core/src/api/defaults.ts | 1 + packages/core/src/common.ts | 28 +++++++++---------- packages/core/src/system/exec.ts | 12 ++++---- packages/core/src/system/types.ts | 4 +-- .../engine-core/src/tasks/task.rnv.new.ts | 5 ++-- .../tasks/task.rnv.crypto.updateProfiles.ts | 2 +- packages/sdk-android/src/deviceManager.ts | 4 +-- .../sdk-react-native/src/androidRunner.ts | 9 ++++-- 8 files changed, 34 insertions(+), 31 deletions(-) diff --git a/packages/core/src/api/defaults.ts b/packages/core/src/api/defaults.ts index e198d718a1..eb4d9adc2d 100644 --- a/packages/core/src/api/defaults.ts +++ b/packages/core/src/api/defaults.ts @@ -15,6 +15,7 @@ const spinner: any = () => ({ succeed: () => { //NOOP }, + text: '', }); const logger: any = {}; diff --git a/packages/core/src/common.ts b/packages/core/src/common.ts index d69b969a42..b17299e14b 100755 --- a/packages/core/src/common.ts +++ b/packages/core/src/common.ts @@ -9,7 +9,7 @@ import { chalk, logError, logTask, logWarning } from './logger'; import { getValidLocalhost } from './utils/utils'; import { RnvContext } from './context/types'; import { OverridesOptions, TimestampPathsConfig } from './system/types'; -import { ConfigProp, ConfigPropKey } from './schema/types'; +import { ConfigProp, ConfigPropKey, PlatformKey } from './schema/types'; import { inquirerPrompt } from './api'; import { RnvPlatform } from './types'; import { DEFAULTS } from './schema/defaults'; @@ -264,13 +264,11 @@ export const getConfigProp: GetConfigPropFn = ( return _getConfigProp(c, platform, key, defaultVal, c.buildConfig); }; -type PlatformGeneric = - | { - buildSchemes?: Record; - } - | undefined; - -// type PlatformGeneric = any; +type Plat = Required['platforms']>[PlatformKey]; +type PlatPropKey = keyof Plat; +type BuildSchemePropKey = keyof Required['buildSchemes'][string]; +type CommonPropKey = keyof ConfigFileBuildConfig['common']; +type BuildConfigPropKey = keyof ConfigFileBuildConfig; export const _getConfigProp = ( c: RnvContext, @@ -281,30 +279,30 @@ export const _getConfigProp = ( ): ConfigProp[T] => { if (!sourceObj || !platform) return undefined; - const platformObj: PlatformGeneric = sourceObj.platforms?.[platform]; + const platformObj = sourceObj.platforms?.[platform]; const ps = c.runtime.scheme; - const baseKey = key; + // const baseKey = key as PlatPropKey; let resultPlatforms; let scheme; if (platformObj && ps) { scheme = platformObj.buildSchemes?.[ps] || {}; - resultPlatforms = getFlavouredProp(c, platformObj, baseKey); + resultPlatforms = getFlavouredProp(c, platformObj, key as PlatPropKey); } else { scheme = {}; } - const resultScheme = baseKey && scheme[baseKey]; - const resultCommonRoot = getFlavouredProp(c, sourceObj.common || {}, baseKey); + const resultScheme = key && scheme[key as BuildSchemePropKey]; + const resultCommonRoot = getFlavouredProp(c, sourceObj.common || {}, key as CommonPropKey); const resultCommonScheme = c.runtime.scheme && - getFlavouredProp(c, sourceObj.common?.buildSchemes?.[c.runtime.scheme] || {}, baseKey); + getFlavouredProp(c, sourceObj.common?.buildSchemes?.[c.runtime.scheme] || {}, key as BuildSchemePropKey); const resultCommon = resultCommonScheme || resultCommonRoot; let result = _getValueOrMergedObject(resultScheme, resultPlatforms, resultCommon); if (result === undefined) { - result = getFlavouredProp(c, sourceObj, baseKey); + result = getFlavouredProp(c, sourceObj, key as BuildConfigPropKey); } if (result === undefined) result = defaultVal; // default the value only if it's not specified in any of the files. i.e. undefined diff --git a/packages/core/src/system/exec.ts b/packages/core/src/system/exec.ts index 7ab9a455b0..116d29601f 100755 --- a/packages/core/src/system/exec.ts +++ b/packages/core/src/system/exec.ts @@ -8,7 +8,7 @@ import { chalk, logDebug, logRaw, logError } from '../logger'; import { fsExistsSync } from './fs'; import { replaceOverridesInString } from '../utils/utils'; import { RnvContext } from '../context/types'; -import { ExecCallback, ExecCallback2, ExecOptions } from './types'; +import { ExecCallback, ExecOptions } from './types'; import { getContext } from '../context/provider'; import { getApi } from '../api/provider'; @@ -405,7 +405,7 @@ export const parseErrorMessage = (text: string, maxErrorLength = 800) => { const isUsingWindows = process.platform === 'win32'; -const fileNotExists = (commandName: string, callback: ExecCallback) => { +const fileNotExists = (commandName: string, callback: (isError: boolean) => void) => { access(commandName, constants.F_OK, (err) => { callback(!err); }); @@ -420,7 +420,7 @@ const fileNotExistsSync = (commandName: string) => { } }; -const localExecutable = (commandName: string, callback?: ExecCallback2) => { +const localExecutable = (commandName: string, callback?: ExecCallback) => { access(commandName, constants.F_OK | constants.X_OK, (err) => { callback && callback(null, !err); }); @@ -435,7 +435,7 @@ const localExecutableSync = (commandName: string) => { } }; -const commandExistsUnix = (commandName: string, cleanedCommandName: string, callback?: ExecCallback2) => { +const commandExistsUnix = (commandName: string, cleanedCommandName: string, callback?: ExecCallback) => { fileNotExists(commandName, (isFile: boolean) => { if (!isFile) { exec( @@ -451,7 +451,7 @@ const commandExistsUnix = (commandName: string, cleanedCommandName: string, call }); }; -const commandExistsWindows = (commandName: string, cleanedCommandName: string, callback?: ExecCallback2) => { +const commandExistsWindows = (commandName: string, cleanedCommandName: string, callback?: ExecCallback) => { if (/[\x00-\x1f<>:"|?*]/.test(commandName)) { callback && callback(null, false); return; @@ -514,7 +514,7 @@ if (isUsingWindows) { }; } -const commandExists = (commandName: string, callback?: ExecCallback2) => { +const commandExists = (commandName: string, callback?: ExecCallback) => { const cleanedCommandName = cleanInput(commandName); if (!callback && typeof Promise !== 'undefined') { return new Promise((resolve, reject) => { diff --git a/packages/core/src/system/types.ts b/packages/core/src/system/types.ts index 9021c8d4d8..09962b20db 100644 --- a/packages/core/src/system/types.ts +++ b/packages/core/src/system/types.ts @@ -29,9 +29,7 @@ export type ExecOptions = { printableEnvKeys?: Array; }; -export type ExecCallback = (isError: boolean) => void; - -export type ExecCallback2 = (result: any, isError: boolean) => void; +export type ExecCallback = (result: unknown, isError: boolean) => void; export type OverridesOptions = Array<{ pattern: string; diff --git a/packages/engine-core/src/tasks/task.rnv.new.ts b/packages/engine-core/src/tasks/task.rnv.new.ts index affd1b2680..15b168b499 100644 --- a/packages/engine-core/src/tasks/task.rnv.new.ts +++ b/packages/engine-core/src/tasks/task.rnv.new.ts @@ -34,6 +34,7 @@ import { inquirerPrompt, PlatformKey, commandExistsSync, + PromptParams, } from '@rnv/core'; import { ConfigFileProject, ConfigFileTemplate } from '@rnv/core/lib/schema/configFiles/types'; @@ -160,7 +161,7 @@ type QuestionResults = Record< { answer: string; configProp: ConfigProp; - value: any; + value: string; } >; @@ -201,7 +202,7 @@ const interactiveQuestion = async ( value, }; } else { - const inqQuestion: any = { + const inqQuestion: PromptParams = { name: qKeyClean, type: q.type, message: q.title, diff --git a/packages/engine-rn-tvos/src/tasks/task.rnv.crypto.updateProfiles.ts b/packages/engine-rn-tvos/src/tasks/task.rnv.crypto.updateProfiles.ts index 598b5fc7c6..4fcc04a138 100644 --- a/packages/engine-rn-tvos/src/tasks/task.rnv.crypto.updateProfiles.ts +++ b/packages/engine-rn-tvos/src/tasks/task.rnv.crypto.updateProfiles.ts @@ -18,7 +18,7 @@ const _updateProfile = (c: RnvContext, v: string) => logTask(`_updateProfile:${v}`, chalk().grey); updateProfile(c) .then(() => resolve()) - .catch((e: any) => reject(e)); + .catch((e) => reject(e)); }); const _updateProfiles = (c: RnvContext) => { diff --git a/packages/sdk-android/src/deviceManager.ts b/packages/sdk-android/src/deviceManager.ts index 13768f98de..1dc71fe42e 100644 --- a/packages/sdk-android/src/deviceManager.ts +++ b/packages/sdk-android/src/deviceManager.ts @@ -619,12 +619,12 @@ const waitForEmulatorToBeReady = (c: RnvContext, emulator: string) => }); export const checkForActiveEmulator = (c: RnvContext) => - new Promise((resolve, reject) => { + new Promise((resolve, reject) => { logTask('checkForActiveEmulator'); const { platform } = c; if (!platform) { - resolve(false); + resolve(undefined); return; } diff --git a/packages/sdk-react-native/src/androidRunner.ts b/packages/sdk-react-native/src/androidRunner.ts index a150ad229f..b8f91cf79e 100644 --- a/packages/sdk-react-native/src/androidRunner.ts +++ b/packages/sdk-react-native/src/androidRunner.ts @@ -13,6 +13,7 @@ import { ANDROID_WEAR, RnvContext, DEFAULTS, + RnvPlatform, } from '@rnv/core'; export const packageReactNativeAndroid = async (c: RnvContext) => { @@ -75,13 +76,17 @@ export const packageReactNativeAndroid = async (c: RnvContext) => { } }; -export const runReactNativeAndroid = async (c: RnvContext, platform: any, device: any) => { +export const runReactNativeAndroid = async ( + c: RnvContext, + platform: RnvPlatform, + device: { udid?: string } | undefined +) => { logTask('_runGradleApp'); const signingConfig = getConfigProp(c, platform, 'signingConfig', 'Debug'); const appFolder = getAppFolder(c); - const { udid } = device; + const udid = device?.udid; let command = `npx react-native run-android --mode=${signingConfig} --no-packager`; From 8ab220429cd3da3c937216198fb02ccce2fdc3e1 Mon Sep 17 00:00:00 2001 From: Pavel Jacko Date: Mon, 23 Oct 2023 07:44:28 +0200 Subject: [PATCH 12/12] regen json schema, fix fs file binding --- package.json | 2 +- packages/core/jsonSchema/rnv.app.json | 117 ++++++++++-- packages/core/jsonSchema/rnv.engine.json | 3 + packages/core/jsonSchema/rnv.global.json | 19 +- packages/core/jsonSchema/rnv.plugin.json | 102 ++++++++++- packages/core/jsonSchema/rnv.plugins.json | 102 ++++++++++- packages/core/jsonSchema/rnv.project.json | 119 +++++++++++-- packages/core/jsonSchema/rnv.template.json | 196 ++++++++++++++++++++- packages/core/src/system/fs.ts | 3 +- 9 files changed, 615 insertions(+), 48 deletions(-) diff --git a/package.json b/package.json index 2e4a644294..dd896c5680 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,7 @@ "bootstrap-clean": "rimraf -I ./node_modules; npx lerna clean --yes && yarn bootstrap", "build": "lerna run build", "report-circular": "npx madge --circular --extensions ts --exclude '\\.(d.ts)$' ./packages", - "report-ts-coverage": "typescript-coverage-report -p ./packages/core/tsconfig.json -t 99 -i lib", + "report-ts-coverage": "typescript-coverage-report -p ./packages/core/tsconfig.json -t 99", "report-jest": "jest --coverage", "compile": "npx lerna run compile", "deploy:canary": "yarn pre-publish && npx lerna publish from-package --dist-tag canary && git push origin HEAD", diff --git a/packages/core/jsonSchema/rnv.app.json b/packages/core/jsonSchema/rnv.app.json index 843094b301..a88c161d17 100644 --- a/packages/core/jsonSchema/rnv.app.json +++ b/packages/core/jsonSchema/rnv.app.json @@ -621,19 +621,31 @@ "AndroidManifest_xml": { "type": "object", "properties": { + "tag": { + "type": "string" + }, + "android:name": { + "type": "string" + }, + "android:required": { + "type": "boolean" + }, + "package": { + "type": "string" + }, "children": { "type": "array", "items": { "type": "object", "properties": { "tag": { - "type": "string" + "$ref": "#/definitions/rnv.app/properties/platforms/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/tag" }, "android:name": { - "type": "string" + "$ref": "#/definitions/rnv.app/properties/platforms/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/android:name" }, "android:required": { - "type": "boolean" + "$ref": "#/definitions/rnv.app/properties/platforms/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/android:required" }, "children": { "type": "array", @@ -652,6 +664,8 @@ } }, "required": [ + "tag", + "android:name", "children" ], "additionalProperties": false, @@ -662,16 +676,6 @@ "properties": {}, "additionalProperties": false }, - "settings_gradle": { - "type": "object", - "properties": {}, - "additionalProperties": false - }, - "gradle_wrapper_properties": { - "type": "object", - "properties": {}, - "additionalProperties": false - }, "MainActivity_java": { "type": "object", "properties": { @@ -679,16 +683,81 @@ "type": "string", "default": "super.onCreate(savedInstanceState)", "description": "Overrides super.onCreate method handler of MainActivity.java" + }, + "imports": { + "type": "array", + "items": { + "type": "string" + } + }, + "methods": { + "type": "array", + "items": { + "type": "string" + } + }, + "createMethods": { + "type": "array", + "items": { + "type": "string" + } + }, + "resultMethods": { + "type": "array", + "items": { + "type": "string" + } } }, "additionalProperties": false }, "MainApplication_java": { "type": "object", - "properties": {}, + "properties": { + "imports": { + "type": "array", + "items": { + "type": "string" + } + }, + "methods": { + "type": "array", + "items": { + "type": "string" + } + }, + "createMethods": { + "type": "array", + "items": { + "type": "string" + } + }, + "packages": { + "type": "array", + "items": { + "type": "string" + } + }, + "packageParams": { + "type": "array", + "items": { + "type": "string" + } + } + }, "additionalProperties": false, "description": "Allows you to configure behaviour of MainActivity" }, + "settings_gradle": { + "type": "object", + "properties": {}, + "additionalProperties": false + }, + "gradle_wrapper_properties": { + "type": "object", + "properties": {}, + "additionalProperties": false + }, "SplashActivity_java": { "type": "object", "properties": {}, @@ -1062,8 +1131,8 @@ "type": "string" }, "provisionProfileSpecifiers": { - "type": "array", - "items": { + "type": "object", + "additionalProperties": { "type": "string" } }, @@ -3108,7 +3177,9 @@ }, "props": { "type": "object", - "additionalProperties": {}, + "additionalProperties": { + "type": "string" + }, "description": "Custom props passed to plugin" }, "version": { @@ -3211,6 +3282,12 @@ "type": "boolean", "description": "Disables plugin overrides for selected plugin" }, + "fontSources": { + "type": "array", + "items": { + "type": "string" + } + }, "android": { "type": "object", "properties": { @@ -3286,6 +3363,12 @@ } }, "additionalProperties": false + }, + "MainActivity_java": { + "$ref": "#/definitions/rnv.app/properties/platforms/properties/android/properties/templateAndroid/properties/MainActivity_java" + }, + "MainApplication_java": { + "$ref": "#/definitions/rnv.app/properties/platforms/properties/android/properties/templateAndroid/properties/MainApplication_java" } }, "additionalProperties": false diff --git a/packages/core/jsonSchema/rnv.engine.json b/packages/core/jsonSchema/rnv.engine.json index 62d7c65cb5..b4b987ee09 100644 --- a/packages/core/jsonSchema/rnv.engine.json +++ b/packages/core/jsonSchema/rnv.engine.json @@ -53,6 +53,9 @@ }, "peerDependencies": { "$ref": "#/definitions/rnv.engine/properties/platforms/additionalProperties/properties/npm/properties/dependencies" + }, + "optionalDependencies": { + "$ref": "#/definitions/rnv.engine/properties/platforms/additionalProperties/properties/npm/properties/dependencies" } }, "additionalProperties": false diff --git a/packages/core/jsonSchema/rnv.global.json b/packages/core/jsonSchema/rnv.global.json index 736c89c17b..fa268306af 100644 --- a/packages/core/jsonSchema/rnv.global.json +++ b/packages/core/jsonSchema/rnv.global.json @@ -35,9 +35,24 @@ }, "sdks": { "type": "object", - "additionalProperties": { - "type": "string" + "properties": { + "ANDROID_SDK": { + "type": "string" + }, + "ANDROID_NDK": { + "type": "string" + }, + "TIZEN_SDK": { + "type": "string" + }, + "WEBOS_SDK": { + "type": "string" + }, + "KAIOS_SDK": { + "type": "string" + } }, + "additionalProperties": false, "description": "Define your sdk configurations" }, "projectTemplates": { diff --git a/packages/core/jsonSchema/rnv.plugin.json b/packages/core/jsonSchema/rnv.plugin.json index d87733c2d6..ab7ed57b07 100644 --- a/packages/core/jsonSchema/rnv.plugin.json +++ b/packages/core/jsonSchema/rnv.plugin.json @@ -16,7 +16,9 @@ }, "props": { "type": "object", - "additionalProperties": {}, + "additionalProperties": { + "type": "string" + }, "description": "Custom props passed to plugin" }, "version": { @@ -119,6 +121,12 @@ "type": "boolean", "description": "Disables plugin overrides for selected plugin" }, + "fontSources": { + "type": "array", + "items": { + "type": "string" + } + }, "android": { "type": "object", "properties": { @@ -294,19 +302,31 @@ "AndroidManifest_xml": { "type": "object", "properties": { + "tag": { + "type": "string" + }, + "android:name": { + "type": "string" + }, + "android:required": { + "type": "boolean" + }, + "package": { + "type": "string" + }, "children": { "type": "array", "items": { "type": "object", "properties": { "tag": { - "type": "string" + "$ref": "#/definitions/rnv.plugin/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/tag" }, "android:name": { - "type": "string" + "$ref": "#/definitions/rnv.plugin/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/android:name" }, "android:required": { - "type": "boolean" + "$ref": "#/definitions/rnv.plugin/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/android:required" }, "children": { "type": "array", @@ -325,6 +345,8 @@ } }, "required": [ + "tag", + "android:name", "children" ], "additionalProperties": false, @@ -358,6 +380,78 @@ } }, "additionalProperties": false + }, + "MainActivity_java": { + "type": "object", + "properties": { + "onCreate": { + "type": "string", + "default": "super.onCreate(savedInstanceState)", + "description": "Overrides super.onCreate method handler of MainActivity.java" + }, + "imports": { + "type": "array", + "items": { + "type": "string" + } + }, + "methods": { + "type": "array", + "items": { + "type": "string" + } + }, + "createMethods": { + "type": "array", + "items": { + "type": "string" + } + }, + "resultMethods": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "MainApplication_java": { + "type": "object", + "properties": { + "imports": { + "type": "array", + "items": { + "type": "string" + } + }, + "methods": { + "type": "array", + "items": { + "type": "string" + } + }, + "createMethods": { + "type": "array", + "items": { + "type": "string" + } + }, + "packages": { + "type": "array", + "items": { + "type": "string" + } + }, + "packageParams": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false, + "description": "Allows you to configure behaviour of MainActivity" } }, "additionalProperties": false diff --git a/packages/core/jsonSchema/rnv.plugins.json b/packages/core/jsonSchema/rnv.plugins.json index 193e67ae9a..5540864ec0 100644 --- a/packages/core/jsonSchema/rnv.plugins.json +++ b/packages/core/jsonSchema/rnv.plugins.json @@ -24,7 +24,9 @@ }, "props": { "type": "object", - "additionalProperties": {}, + "additionalProperties": { + "type": "string" + }, "description": "Custom props passed to plugin" }, "version": { @@ -127,6 +129,12 @@ "type": "boolean", "description": "Disables plugin overrides for selected plugin" }, + "fontSources": { + "type": "array", + "items": { + "type": "string" + } + }, "android": { "type": "object", "properties": { @@ -302,19 +310,31 @@ "AndroidManifest_xml": { "type": "object", "properties": { + "tag": { + "type": "string" + }, + "android:name": { + "type": "string" + }, + "android:required": { + "type": "boolean" + }, + "package": { + "type": "string" + }, "children": { "type": "array", "items": { "type": "object", "properties": { "tag": { - "type": "string" + "$ref": "#/definitions/rnv.plugins/properties/pluginTemplates/additionalProperties/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/tag" }, "android:name": { - "type": "string" + "$ref": "#/definitions/rnv.plugins/properties/pluginTemplates/additionalProperties/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/android:name" }, "android:required": { - "type": "boolean" + "$ref": "#/definitions/rnv.plugins/properties/pluginTemplates/additionalProperties/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/android:required" }, "children": { "type": "array", @@ -333,6 +353,8 @@ } }, "required": [ + "tag", + "android:name", "children" ], "additionalProperties": false, @@ -366,6 +388,78 @@ } }, "additionalProperties": false + }, + "MainActivity_java": { + "type": "object", + "properties": { + "onCreate": { + "type": "string", + "default": "super.onCreate(savedInstanceState)", + "description": "Overrides super.onCreate method handler of MainActivity.java" + }, + "imports": { + "type": "array", + "items": { + "type": "string" + } + }, + "methods": { + "type": "array", + "items": { + "type": "string" + } + }, + "createMethods": { + "type": "array", + "items": { + "type": "string" + } + }, + "resultMethods": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "MainApplication_java": { + "type": "object", + "properties": { + "imports": { + "type": "array", + "items": { + "type": "string" + } + }, + "methods": { + "type": "array", + "items": { + "type": "string" + } + }, + "createMethods": { + "type": "array", + "items": { + "type": "string" + } + }, + "packages": { + "type": "array", + "items": { + "type": "string" + } + }, + "packageParams": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false, + "description": "Allows you to configure behaviour of MainActivity" } }, "additionalProperties": false diff --git a/packages/core/jsonSchema/rnv.project.json b/packages/core/jsonSchema/rnv.project.json index 9f8c065f02..48cc538083 100644 --- a/packages/core/jsonSchema/rnv.project.json +++ b/packages/core/jsonSchema/rnv.project.json @@ -422,7 +422,7 @@ "description": "Enables the equivalent to passing --skipDependencyCheck parameter on every rnv run so you don't have to use it" }, "isNew": { - "type": "string", + "type": "boolean", "description": "Marker indicating that this project has just been bootstrapped. this prop is managed by rnv" }, "common": { @@ -1000,19 +1000,31 @@ "AndroidManifest_xml": { "type": "object", "properties": { + "tag": { + "type": "string" + }, + "android:name": { + "type": "string" + }, + "android:required": { + "type": "boolean" + }, + "package": { + "type": "string" + }, "children": { "type": "array", "items": { "type": "object", "properties": { "tag": { - "type": "string" + "$ref": "#/definitions/rnv.project/properties/platforms/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/tag" }, "android:name": { - "type": "string" + "$ref": "#/definitions/rnv.project/properties/platforms/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/android:name" }, "android:required": { - "type": "boolean" + "$ref": "#/definitions/rnv.project/properties/platforms/properties/android/properties/templateAndroid/properties/AndroidManifest_xml/properties/android:required" }, "children": { "type": "array", @@ -1031,6 +1043,8 @@ } }, "required": [ + "tag", + "android:name", "children" ], "additionalProperties": false, @@ -1041,16 +1055,6 @@ "properties": {}, "additionalProperties": false }, - "settings_gradle": { - "type": "object", - "properties": {}, - "additionalProperties": false - }, - "gradle_wrapper_properties": { - "type": "object", - "properties": {}, - "additionalProperties": false - }, "MainActivity_java": { "type": "object", "properties": { @@ -1058,16 +1062,81 @@ "type": "string", "default": "super.onCreate(savedInstanceState)", "description": "Overrides super.onCreate method handler of MainActivity.java" + }, + "imports": { + "type": "array", + "items": { + "type": "string" + } + }, + "methods": { + "type": "array", + "items": { + "type": "string" + } + }, + "createMethods": { + "type": "array", + "items": { + "type": "string" + } + }, + "resultMethods": { + "type": "array", + "items": { + "type": "string" + } } }, "additionalProperties": false }, "MainApplication_java": { "type": "object", - "properties": {}, + "properties": { + "imports": { + "type": "array", + "items": { + "type": "string" + } + }, + "methods": { + "type": "array", + "items": { + "type": "string" + } + }, + "createMethods": { + "type": "array", + "items": { + "type": "string" + } + }, + "packages": { + "type": "array", + "items": { + "type": "string" + } + }, + "packageParams": { + "type": "array", + "items": { + "type": "string" + } + } + }, "additionalProperties": false, "description": "Allows you to configure behaviour of MainActivity" }, + "settings_gradle": { + "type": "object", + "properties": {}, + "additionalProperties": false + }, + "gradle_wrapper_properties": { + "type": "object", + "properties": {}, + "additionalProperties": false + }, "SplashActivity_java": { "type": "object", "properties": {}, @@ -1441,8 +1510,8 @@ "type": "string" }, "provisionProfileSpecifiers": { - "type": "array", - "items": { + "type": "object", + "additionalProperties": { "type": "string" } }, @@ -3487,7 +3556,9 @@ }, "props": { "type": "object", - "additionalProperties": {}, + "additionalProperties": { + "type": "string" + }, "description": "Custom props passed to plugin" }, "version": { @@ -3590,6 +3661,12 @@ "type": "boolean", "description": "Disables plugin overrides for selected plugin" }, + "fontSources": { + "type": "array", + "items": { + "type": "string" + } + }, "android": { "type": "object", "properties": { @@ -3665,6 +3742,12 @@ } }, "additionalProperties": false + }, + "MainActivity_java": { + "$ref": "#/definitions/rnv.project/properties/platforms/properties/android/properties/templateAndroid/properties/MainActivity_java" + }, + "MainApplication_java": { + "$ref": "#/definitions/rnv.project/properties/platforms/properties/android/properties/templateAndroid/properties/MainApplication_java" } }, "additionalProperties": false diff --git a/packages/core/jsonSchema/rnv.template.json b/packages/core/jsonSchema/rnv.template.json index 484b58088d..1dedceda7f 100644 --- a/packages/core/jsonSchema/rnv.template.json +++ b/packages/core/jsonSchema/rnv.template.json @@ -4,6 +4,124 @@ "rnv.template": { "type": "object", "properties": { + "defaults": { + "type": "object", + "properties": { + "ports": { + "type": "object", + "additionalProperties": { + "type": "number" + }, + "propertyNames": { + "enum": [ + "ios", + "android", + "firetv", + "androidtv", + "androidwear", + "web", + "webtv", + "tizen", + "tizenmobile", + "tvos", + "webos", + "macos", + "windows", + "linux", + "tizenwatch", + "kaios", + "chromecast", + "xbox" + ] + }, + "description": "Allows you to assign custom port per each supported platform specific to this project. this is useful if you foten switch between multiple projects and do not want to experience constant port conflicts" + }, + "supportedPlatforms": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "ios", + "android", + "firetv", + "androidtv", + "androidwear", + "web", + "webtv", + "tizen", + "tizenmobile", + "tvos", + "webos", + "macos", + "windows", + "linux", + "tizenwatch", + "kaios", + "chromecast", + "xbox" + ] + }, + "description": "Array list of all supported platforms in current project" + }, + "portOffset": { + "type": "number", + "description": "Offset each port default value by increment" + }, + "defaultCommandSchemes": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "enum": [ + "run", + "export", + "build" + ] + }, + "description": "List of default schemes for each rnv command. This is useful if you want to avoid specifying `-s ...` every time your run rnv command. bu default rnv uses `-s debug`. NOTE: you can only use schemes you defined in `buildSchemes`" + }, + "targets": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "enum": [ + "ios", + "android", + "firetv", + "androidtv", + "androidwear", + "web", + "webtv", + "tizen", + "tizenmobile", + "tvos", + "webos", + "macos", + "windows", + "linux", + "tizenwatch", + "kaios", + "chromecast", + "xbox" + ] + }, + "description": "Override of default targets specific to this project" + } + }, + "additionalProperties": false, + "description": "Default system config for this project" + }, + "engines": { + "type": "object", + "additionalProperties": { + "type": "string", + "const": "source:rnv" + }, + "description": "List of engines available in this project" + }, "templateConfig": { "type": "object", "properties": { @@ -18,11 +136,87 @@ "type": "array", "items": { "type": "object", - "additionalProperties": {} + "properties": { + "options": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "value": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "title", + "value" + ], + "additionalProperties": false + } + }, + "configProp": { + "type": "object", + "properties": { + "prop": { + "type": "string" + }, + "key": { + "type": "string" + } + }, + "required": [ + "prop", + "key" + ], + "additionalProperties": false + }, + "type": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "type", + "title" + ], + "additionalProperties": false }, "description": "Defines list of custom bootstrap questions" + }, + "packageTemplate": { + "type": "object", + "properties": { + "dependencies": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "devDependencies": { + "$ref": "#/definitions/rnv.template/properties/templateConfig/properties/packageTemplate/properties/dependencies" + }, + "peerDependencies": { + "$ref": "#/definitions/rnv.template/properties/templateConfig/properties/packageTemplate/properties/dependencies" + }, + "optionalDependencies": { + "$ref": "#/definitions/rnv.template/properties/templateConfig/properties/packageTemplate/properties/dependencies" + }, + "name": { + "type": "string" + } + }, + "additionalProperties": false } }, + "required": [ + "bootstrapQuestions" + ], "additionalProperties": false, "description": "Used in `renative.template.json` allows you to define template behaviour." }, diff --git a/packages/core/src/system/fs.ts b/packages/core/src/system/fs.ts index 26f800c175..9d5cf500a9 100755 --- a/packages/core/src/system/fs.ts +++ b/packages/core/src/system/fs.ts @@ -677,7 +677,8 @@ const _bindStringVals = (obj: T, _val: string, newKey: K, if (val.includes(BIND_FILES)) { const key = val.replace(BIND_FILES, '').replace('}}', ''); //TODO: this any not good - const nVal = lGet(propConfig, key); + + const nVal = lGet(propConfig.files, key); obj[newKey] = resolvePackage(nVal) as T[K]; } else if (val.includes(BIND_PROPS)) { Object.keys(props).forEach((pk) => {