Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@
},
"dependencies": {
"@zenstackhq/common-helpers": "workspace:*",
"@zenstackhq/schema": "workspace:*",
"@zenstackhq/language": "workspace:*",
"@zenstackhq/orm": "workspace:*",
"@zenstackhq/schema": "workspace:*",
"@zenstackhq/sdk": "workspace:*",
"@zenstackhq/server": "workspace:*",
"chokidar": "^5.0.0",
Expand All @@ -56,7 +56,9 @@
"package-manager-detector": "^1.3.0",
"prisma": "catalog:",
"semver": "^7.7.2",
"ts-pattern": "catalog:"
"terminal-link": "^5.0.0",
"ts-pattern": "catalog:",
"zod": "catalog:"
},
"devDependencies": {
"@types/better-sqlite3": "catalog:",
Expand All @@ -72,9 +74,9 @@
"tmp": "catalog:"
},
"peerDependencies": {
"pg": "catalog:",
"better-sqlite3": "catalog:",
"mysql2": "catalog:"
"mysql2": "catalog:",
"pg": "catalog:"
},
"peerDependenciesMeta": {
"pg": {
Expand Down
68 changes: 68 additions & 0 deletions packages/cli/src/actions/action-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import fs from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
import { CliError } from '../cli-error';
import terminalLink from 'terminal-link';
import { z } from 'zod';

export function getSchemaFile(file?: string) {
if (file) {
Expand Down Expand Up @@ -216,3 +218,69 @@ export async function getZenStackPackages(

return result.filter((p) => !!p);
}

const FETCH_CLI_MAX_TIME = 1000;
const CLI_CONFIG_ENDPOINT = 'https://zenstack.dev/config/cli-v3.json';

const usageTipsSchema = z.object({
notifications: z.array(z.object({ title: z.string(), url: z.url().optional(), active: z.boolean() })),
});

/**
* Starts the usage tips fetch in the background. Returns a callback that, when invoked check if the fetch
* is complete. If not complete, it will wait until the max time is reached. After that, if fetch is still
* not complete, just return.
*/
export function startUsageTipsFetch() {
let fetchedData: z.infer<typeof usageTipsSchema> | undefined = undefined;
let fetchComplete = false;

const start = Date.now();
const controller = new AbortController();

fetch(CLI_CONFIG_ENDPOINT, {
headers: { accept: 'application/json' },
signal: controller.signal,
})
.then(async (res) => {
if (!res.ok) return;
const data = await res.json();
const parseResult = usageTipsSchema.safeParse(data);
if (parseResult.success) {
fetchedData = parseResult.data;
}
})
.catch(() => {
// noop
})
.finally(() => {
fetchComplete = true;
});

return async () => {
const elapsed = Date.now() - start;

if (!fetchComplete && elapsed < FETCH_CLI_MAX_TIME) {
// wait for the timeout
await new Promise((resolve) => setTimeout(resolve, FETCH_CLI_MAX_TIME - elapsed));
}

if (!fetchComplete) {
controller.abort();
return;
}

if (!fetchedData) return;

const activeItems = fetchedData.notifications.filter((item) => item.active);
// show a random active item
if (activeItems.length > 0) {
const item = activeItems[Math.floor(Math.random() * activeItems.length)]!;
if (item.url) {
console.log(terminalLink(item.title, item.url));
} else {
console.log(item.title);
}
}
};
}
20 changes: 16 additions & 4 deletions packages/cli/src/actions/generate.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
import { invariant, singleDebounce } from '@zenstackhq/common-helpers';
import { ZModelLanguageMetaData } from '@zenstackhq/language';
import { type AbstractDeclaration, isPlugin, LiteralExpr, Plugin, type Model } from '@zenstackhq/language/ast';
import { isPlugin, LiteralExpr, Plugin, type AbstractDeclaration, type Model } from '@zenstackhq/language/ast';
import { getLiteral, getLiteralArray } from '@zenstackhq/language/utils';
import { type CliPlugin } from '@zenstackhq/sdk';
import { watch } from 'chokidar';
import colors from 'colors';
import { createJiti } from 'jiti';
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { watch } from 'chokidar';
import ora, { type Ora } from 'ora';
import semver from 'semver';
import { CliError } from '../cli-error';
import * as corePlugins from '../plugins';
import { getOutputPath, getSchemaFile, getZenStackPackages, loadSchemaDocument } from './action-utils';
import semver from 'semver';
import {
getOutputPath,
getSchemaFile,
getZenStackPackages,
loadSchemaDocument,
startUsageTipsFetch,
} from './action-utils';

type Options = {
schema?: string;
Expand All @@ -24,6 +30,7 @@ type Options = {
liteOnly?: boolean;
generateModels?: boolean;
generateInput?: boolean;
tips?: boolean;
};

/**
Expand All @@ -35,8 +42,13 @@ export async function run(options: Options) {
} catch (err) {
console.warn(colors.yellow(`Failed to check for mismatched ZenStack packages: ${err}`));
}

const maybeShowUsageTips = options.tips && !options.silent && !options.watch ? startUsageTipsFetch() : undefined;

const model = await pureGenerate(options, false);

await maybeShowUsageTips?.();

if (options.watch) {
const logsEnabled = !options.silent;

Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,14 @@ function createProgram() {
);

const noVersionCheckOption = new Option('--no-version-check', 'do not check for new version');
const noTipsOption = new Option('--no-tips', 'do not show usage tips');

program
.command('generate')
.description('Run code generation plugins')
.addOption(schemaOption)
.addOption(noVersionCheckOption)
.addOption(noTipsOption)
.addOption(new Option('-o, --output <path>', 'default output directory for code generation'))
.addOption(new Option('-w, --watch', 'enable watch mode').default(false))
.addOption(
Expand Down
44 changes: 44 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion scripts/test-generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async function generate(schemaPath: string, options: string[]) {
const cliPath = path.join(_dirname, '../packages/cli/dist/index.js');
const RUNTIME = process.env.RUNTIME ?? 'node';
execSync(
`${RUNTIME} ${cliPath} generate --schema ${schemaPath} ${options.join(' ')} --generate-models=false --generate-input=false`,
`${RUNTIME} ${cliPath} generate --schema ${schemaPath} ${options.join(' ')} --generate-models=false --generate-input=false --no-version-check --no-tips`,
{
cwd: path.dirname(schemaPath),
},
Expand Down
Loading