@git.zone/tspublish 1.15.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,300 +0,0 @@
1
- import * as plugins from './plugins.js';
2
- import * as paths from './paths.js';
3
- import { logger, logInfo, logSuccess, logWarn, logError, logBuild, logPublish, logOngoing, logStart, logDone } from './logging.js';
4
-
5
- import { type ITsPublishJson, type ITsPublishModulePlan } from './interfaces/index.js';
6
- import type { TsPublish } from './classes.tspublish.js';
7
-
8
- export interface IPublishModuleOptions {
9
- monoRepoDir: string;
10
- packageSubFolder: string;
11
- packageSubFolderFullPath?: string;
12
- tsPublishJson?: ITsPublishJson;
13
- publishModDirFullPath?: string;
14
- name?: string;
15
- version?: string;
16
- dependencies?: { [key: string]: string };
17
- modulePlan?: ITsPublishModulePlan;
18
- }
19
-
20
- export interface IResolvedRegistry {
21
- url: string;
22
- accessLevel: string;
23
- }
24
-
25
- export class PublishModule {
26
- tsPublishRef: TsPublish;
27
- public options: IPublishModuleOptions;
28
- constructor(tsPublishRef: TsPublish, options: IPublishModuleOptions) {
29
- this.tsPublishRef = tsPublishRef;
30
- this.options = options;
31
- }
32
-
33
- public async init() {
34
- this.options.packageSubFolderFullPath = plugins.path.join(
35
- this.options.monoRepoDir,
36
- this.options.packageSubFolder
37
- );
38
-
39
- // check requirements
40
- if (!this.options.packageSubFolder.startsWith('ts')) {
41
- throw new Error('subFolder must start with "ts"');
42
- }
43
- const tspublishJsonPath = plugins.path.join(this.options.packageSubFolderFullPath, 'tspublish.json');
44
- const tspublishJsonContent = await plugins.smartfs.file(tspublishJsonPath).encoding('utf8').read();
45
- this.options.tsPublishJson = JSON.parse(tspublishJsonContent as string);
46
-
47
- // the package.json of the parent mono repo
48
- const packageJsonPath = plugins.path.join(this.options.monoRepoDir, 'package.json');
49
- const packageJsonContent = await plugins.smartfs.file(packageJsonPath).encoding('utf8').read();
50
- const monoRepoPackageJson = JSON.parse(packageJsonContent as string);
51
-
52
- this.options.modulePlan ??= (await this.tsPublishRef.plan(this.options.monoRepoDir)).modules
53
- .find((module) => module.folder === this.options.packageSubFolder);
54
- if (!this.options.modulePlan) throw new Error('Missing publish module plan.');
55
- this.options.dependencies = this.options.modulePlan.manifest.dependencies;
56
- this.options.name = this.options.name || this.options.tsPublishJson!.name;
57
- this.options.version = monoRepoPackageJson.version;
58
-
59
- // now that we have a name and version, lets check if there is already a package under the same name and version.
60
- const smartnpmInstance = new plugins.smartnpm.NpmRegistry({}); // TODO: pass in options
61
- let packageInfo: plugins.smartnpm.NpmPackage | undefined;
62
- try {
63
- packageInfo = await smartnpmInstance.getPackageInfo(this.options.name!);
64
- } catch (error) {
65
- logWarn(`Package ${this.options.name} does not yet seem to exist. Proceeding in 10 seconds...`);
66
- await plugins.smartdelay.delayFor(10000);
67
- }
68
- if (packageInfo) {
69
- const availableVersions = packageInfo.allVersions.map((versionArg) => versionArg.version);
70
- logInfo(`Available versions for ${this.options.name}: ${availableVersions.join(', ')}`);
71
- if (availableVersions.includes(this.options.version!)) {
72
- logError(
73
- `Package ${this.options.name} already exists with version ${this.options.version}`
74
- );
75
- throw new Error(`Package ${this.options.name} already exists with version ${this.options.version}.`);
76
- }
77
- }
78
- }
79
-
80
- public async getLatestVersionOfPackage(name: string) {
81
- const smartnpmInstance = new plugins.smartnpm.NpmRegistry({}); // TODO: pass in options
82
- const packageInfo = await smartnpmInstance.getPackageInfo(name);
83
- if (!packageInfo) {
84
- throw new Error(`package ${name} not found`);
85
- }
86
- return packageInfo.allVersions[0].version;
87
- }
88
-
89
- public async createTsconfigJson() {
90
- const tsconfigPath = plugins.path.join(paths.cwd, 'tsconfig.json');
91
- let originalTsConfig: any = null;
92
- if (await plugins.smartfs.file(tsconfigPath).exists()) {
93
- const tsconfigContent = await plugins.smartfs.file(tsconfigPath).encoding('utf8').read();
94
- originalTsConfig = JSON.parse(tsconfigContent as string);
95
- }
96
- if (originalTsConfig?.compilerOptions?.paths) {
97
- for (const path of Object.keys(originalTsConfig.compilerOptions.paths)) {
98
- originalTsConfig.compilerOptions.paths[
99
- path
100
- ][0] = `.${originalTsConfig.compilerOptions.paths[path][0]}`;
101
- }
102
- }
103
- const tsconfigJson = {
104
- compilerOptions: {
105
- experimentalDecorators: true,
106
- useDefineForClassFields: false,
107
- target: 'ES2022',
108
- module: 'NodeNext',
109
- moduleResolution: 'NodeNext',
110
- esModuleInterop: true,
111
- verbatimModuleSyntax: true,
112
- paths: originalTsConfig?.compilerOptions?.paths,
113
- },
114
- exclude: ['dist_*/**/*.d.ts'],
115
- };
116
- return JSON.stringify(tsconfigJson, null, 2);
117
- }
118
-
119
- public async createPackageJson() {
120
- if (!this.options.modulePlan) throw new Error('Publish module must be initialized first.');
121
- const rootManifest = JSON.parse(await plugins.fs.readFile(plugins.path.join(this.options.monoRepoDir, 'package.json'), 'utf8'));
122
- const buildVersion = rootManifest.devDependencies?.['@git.zone/tsbuild'] ?? rootManifest.dependencies?.['@git.zone/tsbuild'];
123
- if (typeof buildVersion !== 'string' || !buildVersion) throw new Error('Publishing requires a declared @git.zone/tsbuild version.');
124
- const packageJson = {
125
- ...this.options.modulePlan.manifest,
126
- scripts: {
127
- build: 'tsbuild tsfolders',
128
- },
129
- devDependencies: {
130
- '@git.zone/tsbuild': buildVersion,
131
- },
132
- };
133
- return JSON.stringify(packageJson, null, 2);
134
- }
135
-
136
- public async createPublishModuleDir() {
137
- logOngoing(`Creating publish directory for ${this.options.name}`);
138
- this.options.publishModDirFullPath = plugins.path.join(
139
- this.options.monoRepoDir,
140
- `dist_publish_${this.options.packageSubFolder}`
141
- );
142
-
143
- // Ensure empty directory
144
- const publishDir = plugins.smartfs.directory(this.options.publishModDirFullPath);
145
- if (await publishDir.exists()) {
146
- await publishDir.recursive().delete();
147
- }
148
- await publishDir.recursive().create();
149
-
150
- // package.json
151
- const packageJsonPath = plugins.path.join(this.options.publishModDirFullPath, 'package.json');
152
- await plugins.smartfs.file(packageJsonPath).encoding('utf8').write(await this.createPackageJson());
153
-
154
- // tsconfig.json
155
- const tsconfigJsonPath = plugins.path.join(this.options.publishModDirFullPath, 'tsconfig.json');
156
- await plugins.smartfs.file(tsconfigJsonPath).encoding('utf8').write(await this.createTsconfigJson());
157
-
158
- // ts subfolder, the folder that contains the source code and is being transpiled
159
- for (const folder of this.options.modulePlan!.folders) {
160
- await plugins.smartfs.directory(plugins.path.join(this.options.monoRepoDir, folder)).recursive()
161
- .copy(plugins.path.join(this.options.publishModDirFullPath, folder));
162
- }
163
- for (const path of this.options.modulePlan!.include) {
164
- await plugins.fs.cp(plugins.path.join(this.options.monoRepoDir, path), plugins.path.join(this.options.publishModDirFullPath, path), { recursive: true });
165
- }
166
-
167
- // readme
168
- const readmeSrc = plugins.path.join(this.options.packageSubFolderFullPath!, 'readme.md');
169
- const readmeDest = plugins.path.join(this.options.publishModDirFullPath, 'readme.md');
170
- await plugins.smartfs.file(readmeSrc).copy(readmeDest);
171
-
172
- // license
173
- const licenseSrc = plugins.path.join(this.options.monoRepoDir, this.options.modulePlan!.licenseFile);
174
- const licenseDest = plugins.path.join(this.options.publishModDirFullPath, this.options.modulePlan!.licenseFile);
175
- await plugins.smartfs.file(licenseSrc).copy(licenseDest);
176
-
177
- // cli stuff
178
- await this.createBinCliSetup();
179
- }
180
-
181
- public async build() {
182
- logBuild(`Building ${this.options.name}...`);
183
- const smartshellInstance = new plugins.smartshell.Smartshell({
184
- executor: 'bash',
185
- });
186
- await smartshellInstance.exec(`cd ${this.options.publishModDirFullPath} && pnpm run build`);
187
- logSuccess(`Build completed for ${this.options.name}`);
188
- }
189
-
190
- public async createBinCliSetup() {
191
- const binSetupApplies: boolean =
192
- !!this.options.tsPublishJson?.bin &&
193
- Array.isArray(this.options.tsPublishJson!.bin) &&
194
- this.options.tsPublishJson!.bin.length > 0;
195
- if (!binSetupApplies) return;
196
- const indexPath = `./dist_${this.options.packageSubFolder}/index.js`;
197
- const fileContent = `#!/usr/bin/env node\nprocess.env.CLI_CALL = 'true';\nconst cliTool = await import(${JSON.stringify(indexPath)});\nawait cliTool.runCli();\n`;
198
- const cliJsPath = plugins.path.join(this.options.publishModDirFullPath!, 'cli.js');
199
- await plugins.smartfs.file(cliJsPath).encoding('utf8').write(fileContent);
200
- }
201
-
202
- /**
203
- * Resolves the registries to publish to based on tspublish.json configuration.
204
- * Supports:
205
- * - "useBase": Use only registries from smartconfig.json
206
- * - "extendBase": Use base registries + additions, with exclusions via "-" prefix
207
- * - Explicit registries: Direct registry URLs in format "url:accessLevel"
208
- */
209
- private async resolveRegistries(): Promise<IResolvedRegistry[]> {
210
- const rawRegistries = this.options.tsPublishJson?.registries || [];
211
-
212
- // Empty → skip publishing
213
- if (rawRegistries.length === 0) {
214
- return [];
215
- }
216
-
217
- const hasUseBase = rawRegistries.includes('useBase');
218
- const hasExtendBase = rawRegistries.includes('extendBase');
219
-
220
- let baseRegistries: string[] = [];
221
- let baseAccessLevel = 'public';
222
-
223
- // Load base registries from smartconfig.json if needed
224
- if (hasUseBase || hasExtendBase) {
225
- const smartconfigInstance = new plugins.smartconfig.Smartconfig(this.options.monoRepoDir);
226
- const gitzoneConfig = smartconfigInstance.dataFor<any>('@git.zone/cli', {});
227
- baseRegistries = gitzoneConfig?.release?.targets?.npm?.registries ?? gitzoneConfig?.release?.registries ?? [];
228
- baseAccessLevel = gitzoneConfig?.release?.targets?.npm?.accessLevel ?? gitzoneConfig?.release?.accessLevel ?? 'public';
229
-
230
- if (baseRegistries.length === 0) {
231
- throw new Error(
232
- `useBase/extendBase specified in tspublish.json but no registries configured in smartconfig.json at @git.zone/cli.release.registries`
233
- );
234
- }
235
- }
236
-
237
- // useBase: Only base registries
238
- if (hasUseBase) {
239
- return baseRegistries.map((url) => ({ url, accessLevel: baseAccessLevel }));
240
- }
241
-
242
- // extendBase: Base registries + additions - exclusions
243
- if (hasExtendBase) {
244
- const exclusions = rawRegistries
245
- .filter((r) => r.startsWith('-'))
246
- .map((r) => r.slice(1)); // remove '-' prefix
247
-
248
- const additions = rawRegistries.filter((r) => r !== 'extendBase' && !r.startsWith('-'));
249
-
250
- // Filter out excluded base registries
251
- const result: IResolvedRegistry[] = baseRegistries
252
- .filter((url) => !exclusions.includes(url))
253
- .map((url) => ({ url, accessLevel: baseAccessLevel }));
254
-
255
- // Add explicit registries
256
- for (const addition of additions) {
257
- const parts = addition.split(':');
258
- const url = parts[0];
259
- const access = parts[1] || 'public';
260
- result.push({ url, accessLevel: access });
261
- }
262
-
263
- return result;
264
- }
265
-
266
- // Explicit registries only (original behavior)
267
- return rawRegistries.map((r) => {
268
- const parts = r.split(':');
269
- const url = parts[0];
270
- const access = parts[1] || 'public';
271
- return { url, accessLevel: access };
272
- });
273
- }
274
-
275
- public async publish() {
276
- const registries = await this.resolveRegistries();
277
-
278
- // Handle empty registries
279
- if (registries.length === 0) {
280
- logWarn(`No registries configured for ${this.options.name}. Skipping publish.`);
281
- return;
282
- }
283
-
284
- logPublish(`Publishing ${this.options.name} v${this.options.version} to ${registries.length} registry(ies)...`);
285
- const smartshellInstance = new plugins.smartshell.Smartshell({
286
- executor: 'bash',
287
- });
288
-
289
- for (const registry of registries) {
290
- const registryUrl = registry.url.startsWith('https://') ? registry.url : `https://${registry.url}`;
291
- logOngoing(`Publishing to ${registryUrl}...`);
292
- await smartshellInstance.exec(
293
- `cd ${this.options.publishModDirFullPath} && pnpm publish ${
294
- registry.accessLevel === 'public' ? '--access public' : ''
295
- } --no-git-checks --registry ${registryUrl}`
296
- );
297
- }
298
- logSuccess(`Successfully published ${this.options.name} v${this.options.version}!`);
299
- }
300
- }
package/ts/logging.ts DELETED
@@ -1,104 +0,0 @@
1
- import * as plugins from './plugins.js';
2
- import * as commitinfo from './00_commitinfo_data.js';
3
-
4
- export const logger = plugins.smartlog.Smartlog.createForCommitinfo(commitinfo.commitinfo);
5
- logger.enableConsole();
6
-
7
- // Color-coded log level indicators
8
- const logIcons = {
9
- info: plugins.consolecolor.coloredString('ℹ', 'cyan'),
10
- success: plugins.consolecolor.coloredString('✓', 'green'),
11
- warn: plugins.consolecolor.coloredString('⚠', 'orange'),
12
- error: plugins.consolecolor.coloredString('✖', 'red'),
13
- start: plugins.consolecolor.coloredString('▶', 'blue'),
14
- done: plugins.consolecolor.coloredString('✔', 'green'),
15
- package: plugins.consolecolor.coloredString('📦', 'blue'),
16
- build: plugins.consolecolor.coloredString('🔨', 'cyan'),
17
- publish: plugins.consolecolor.coloredString('🚀', 'green'),
18
- };
19
-
20
- // Helper function for info messages with color
21
- export const logInfo = (message: string, data?: any) => {
22
- const coloredMessage = `${logIcons.info} ${plugins.consolecolor.coloredString(message, 'cyan')}`;
23
- logger.log('info', coloredMessage, data);
24
- };
25
-
26
- // Helper function for success messages
27
- export const logSuccess = (message: string, data?: any) => {
28
- const coloredMessage = `${logIcons.success} ${plugins.consolecolor.coloredString(message, 'green')}`;
29
- logger.log('ok', coloredMessage, data);
30
- };
31
-
32
- // Helper function for warning messages
33
- export const logWarn = (message: string, data?: any) => {
34
- const coloredMessage = `${logIcons.warn} ${plugins.consolecolor.coloredString(message, 'orange')}`;
35
- logger.log('warn', coloredMessage, data);
36
- };
37
-
38
- // Helper function for error messages
39
- export const logError = (message: string, data?: any) => {
40
- const coloredMessage = `${logIcons.error} ${plugins.consolecolor.coloredString(message, 'red')}`;
41
- logger.log('error', coloredMessage, data);
42
- };
43
-
44
- // Helper function for start of operations
45
- export const logStart = (operation: string) => {
46
- const coloredMessage = `${logIcons.start} ${plugins.consolecolor.coloredString(`Starting ${operation}...`, 'blue')}`;
47
- logger.log('info', coloredMessage);
48
- };
49
-
50
- // Helper function for completion of operations
51
- export const logDone = (operation: string) => {
52
- const coloredMessage = `${logIcons.done} ${plugins.consolecolor.coloredString(`Completed ${operation}`, 'green')}`;
53
- logger.log('ok', coloredMessage);
54
- };
55
-
56
- // Helper function for package-related messages
57
- export const logPackage = (message: string, packageName: string) => {
58
- const coloredMessage = `${logIcons.package} ${message}: ${plugins.consolecolor.coloredString(packageName, 'blue', 'white')}`;
59
- logger.log('info', coloredMessage);
60
- };
61
-
62
- // Helper function for build-related messages
63
- export const logBuild = (message: string) => {
64
- const coloredMessage = `${logIcons.build} ${plugins.consolecolor.coloredString(message, 'cyan')}`;
65
- logger.log('info', coloredMessage);
66
- };
67
-
68
- // Helper function for publish-related messages
69
- export const logPublish = (message: string) => {
70
- const coloredMessage = `${logIcons.publish} ${plugins.consolecolor.coloredString(message, 'green')}`;
71
- logger.log('info', coloredMessage);
72
- };
73
-
74
- // Create a visual separator for different phases
75
- export const logSeparator = () => {
76
- const separator = plugins.consolecolor.coloredString('━'.repeat(60), 'cyan');
77
- console.log(separator);
78
- };
79
-
80
- // Create a header for major sections
81
- export const logHeader = (title: string) => {
82
- logSeparator();
83
- const header = plugins.consolecolor.coloredString(` ${title.toUpperCase()} `, 'white', 'blue');
84
- console.log(header);
85
- logSeparator();
86
- };
87
-
88
- // Helper for indicating ongoing operations
89
- export const logOngoing = (text: string) => {
90
- const spinnerIcon = plugins.consolecolor.coloredString('⟳', 'cyan');
91
- const coloredMessage = `${spinnerIcon} ${plugins.consolecolor.coloredString(text, 'cyan')}`;
92
- logger.log('info', coloredMessage);
93
- };
94
-
95
- // Progress indicator helper
96
- export const logProgress = (current: number, total: number, item: string) => {
97
- const percentage = Math.round((current / total) * 100);
98
- const progressBar = '█'.repeat(Math.floor(percentage / 5)) + '░'.repeat(20 - Math.floor(percentage / 5));
99
- const coloredProgress = plugins.consolecolor.coloredString(
100
- `[${progressBar}] ${percentage}% - ${item}`,
101
- percentage === 100 ? 'green' : 'blue'
102
- );
103
- logger.log('info', coloredProgress);
104
- };