@sparkelf/dsh-plus 0.2.2-alpha.2.29 → 0.2.2-alpha.2.30

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,12 +1,11 @@
1
- /** Materialize the Plus distribution's embedded patch set without Desktop. */
1
+ /** Materialize the Plus distribution's independent patch packages without Desktop. */
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync, } from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
- import { basename, dirname, isAbsolute, relative, resolve } from 'node:path';
5
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
6
6
  import { tmpdir } from 'node:os';
7
7
  import { satisfies, valid, validRange } from 'semver';
8
8
  import { parseDocument } from 'yaml';
9
- import { readPatchSet } from "./patch-set.js";
10
9
  const FORMAT_VERSION = 1;
11
10
  function isSelectedNpmPatch(patch) {
12
11
  return patch.target.kind === 'npm';
@@ -51,22 +50,7 @@ function requireStringArray(value, label) {
51
50
  }
52
51
  function resolveInstalledPackage(distributionDirectory, packageName) {
53
52
  const requireFromDistribution = createRequire(resolve(distributionDirectory, 'package.json'));
54
- let manifestPath;
55
- try {
56
- manifestPath = requireFromDistribution.resolve(packageName + '/package.json');
57
- }
58
- catch {
59
- // Some packages do not export `./package.json`; resolve the entry module instead and walk
60
- // up to the directory that holds the manifest.
61
- let directory = dirname(requireFromDistribution.resolve(packageName));
62
- while (!existsSync(resolve(directory, 'package.json'))) {
63
- const parent = dirname(directory);
64
- if (parent === directory)
65
- throw new Error(packageName + ' has no resolvable package manifest');
66
- directory = parent;
67
- }
68
- manifestPath = resolve(directory, 'package.json');
69
- }
53
+ const manifestPath = requireFromDistribution.resolve(packageName + '/package.json');
70
54
  const manifest = readJsonObject(manifestPath, packageName + ' manifest');
71
55
  return {
72
56
  name: packageName,
@@ -75,6 +59,48 @@ function resolveInstalledPackage(distributionDirectory, packageName) {
75
59
  manifest,
76
60
  };
77
61
  }
62
+ function resolvePatchFile(packageDirectory, declared) {
63
+ const absoluteFile = resolve(packageDirectory, declared);
64
+ const local = relative(packageDirectory, absoluteFile);
65
+ if (isAbsolute(local) || local === '..' || local.startsWith('../')) {
66
+ throw new Error('patch file must stay inside its patch package: ' + declared);
67
+ }
68
+ if (!existsSync(absoluteFile))
69
+ throw new Error('patch file does not exist: ' + absoluteFile);
70
+ return { relativeFile: local.replaceAll('\\', '/'), absoluteFile };
71
+ }
72
+ function parseVariant(value, index, patchPackage) {
73
+ const label = patchPackage.name + ' dshPatch.variants[' + String(index) + ']';
74
+ const variant = requireObject(value, label);
75
+ const target = requireObject(variant.target, label + '.target');
76
+ const kind = requireString(target.kind, label + '.target.kind');
77
+ const common = {
78
+ id: requireString(variant.id, label + '.id'),
79
+ dsh: requireRange(variant.dsh, label + '.dsh'),
80
+ file: requireString(variant.file, label + '.file'),
81
+ patchPackage,
82
+ };
83
+ if (kind === 'npm') {
84
+ return {
85
+ ...common,
86
+ target: {
87
+ kind,
88
+ name: requireString(target.name, label + '.target.name'),
89
+ range: requireRange(target.range, label + '.target.range'),
90
+ },
91
+ };
92
+ }
93
+ if (kind === 'dsh-source') {
94
+ return {
95
+ ...common,
96
+ target: {
97
+ kind,
98
+ baseRevision: requireString(target.baseRevision, label + '.target.baseRevision'),
99
+ },
100
+ };
101
+ }
102
+ throw new Error('unsupported patch target kind: ' + kind);
103
+ }
78
104
  function git(root, args, acceptFailure = false) {
79
105
  const result = spawnSync('git', args, { cwd: root, encoding: 'utf8' });
80
106
  if (result.status === 0)
@@ -122,6 +148,23 @@ function requireSourceBase(root, baseRevision) {
122
148
  }
123
149
  return checkoutRevision;
124
150
  }
151
+ function patchPackageVariants(distributionDirectory, names) {
152
+ const variants = [];
153
+ for (const name of names) {
154
+ const patchPackage = resolveInstalledPackage(distributionDirectory, name);
155
+ const declaration = requireObject(patchPackage.manifest.dshPatch, name + ' dshPatch');
156
+ if (declaration.formatVersion !== FORMAT_VERSION) {
157
+ throw new Error('unsupported dshPatch formatVersion in ' + name + ': ' + String(declaration.formatVersion));
158
+ }
159
+ if (!Array.isArray(declaration.variants) || declaration.variants.length === 0) {
160
+ throw new Error(name + ' dshPatch.variants must be a non-empty array');
161
+ }
162
+ for (const [index, value] of declaration.variants.entries()) {
163
+ variants.push(parseVariant(value, index, patchPackage));
164
+ }
165
+ }
166
+ return variants;
167
+ }
125
168
  // 先验证official source,再物化Plus声明的profile依赖,避免source不匹配时改动用户profile。
126
169
  function prepareSelection(distributionDirectory, profileDirectory, dshRoot) {
127
170
  const distributionManifest = readJsonObject(resolve(distributionDirectory, 'package.json'), 'Plus distribution manifest');
@@ -149,24 +192,31 @@ function prepareSelection(distributionDirectory, profileDirectory, dshRoot) {
149
192
  throw new Error('dshPlus.profile.allowBuilds.' + name + ' must be a boolean');
150
193
  allowBuilds[name] = allowed;
151
194
  }
152
- const patchSet = readPatchSet(distributionDirectory, distributionManifest);
195
+ const patchPackageNames = requireStringArray(plus.patchPackages, 'dshPlus.patchPackages');
153
196
  const dependencies = requireObject(distributionManifest.dependencies, 'Plus distribution dependencies');
154
197
  const dshManifest = readJsonObject(resolve(dshRoot, 'package.json'), 'DSH source manifest');
155
198
  const dshVersion = requireVersion(dshManifest.version, 'DSH source version');
156
199
  if (!satisfies(dshVersion, dshRange, { includePrerelease: true })) {
157
200
  throw new Error(distributionName + '@' + distributionVersion + ' requires DSH ' + dshRange + ', found ' + dshVersion);
158
201
  }
159
- const checkoutRevision = requireSourceBase(dshRoot, patchSet.sourceBaseRevision);
160
- const patchEntries = [...patchSet.entries, ...patchSet.thirdPartyPatches];
202
+ const checkoutRevision = requireSourceBase(dshRoot, baseRevision);
203
+ const groups = new Map();
204
+ for (const variant of patchPackageVariants(distributionDirectory, patchPackageNames)) {
205
+ const entries = groups.get(variant.id) ?? [];
206
+ entries.push(variant);
207
+ groups.set(variant.id, entries);
208
+ }
161
209
  const sourceStates = new Map();
162
- for (const item of patchEntries) {
163
- if (!satisfies(dshVersion, item.dsh, { includePrerelease: true })) {
164
- throw new Error('patch ' + item.id + ' declares DSH ' + item.dsh + ', found ' + dshVersion);
210
+ const orderedGroups = [...groups].sort(([left], [right]) => left.localeCompare(right));
211
+ for (const [, variants] of orderedGroups) {
212
+ for (const variant of variants) {
213
+ if (variant.target.kind !== 'dsh-source'
214
+ || variant.target.baseRevision !== baseRevision
215
+ || !satisfies(dshVersion, variant.dsh, { includePrerelease: true }))
216
+ continue;
217
+ const file = resolvePatchFile(variant.patchPackage.directory, variant.file);
218
+ sourceStates.set(file.absoluteFile, sourcePatchState(dshRoot, file.absoluteFile));
165
219
  }
166
- if (item.target.kind !== 'dsh-source')
167
- continue;
168
- const absoluteFile = resolve(distributionDirectory, item.file);
169
- sourceStates.set(absoluteFile, sourcePatchState(dshRoot, absoluteFile));
170
220
  }
171
221
  const pendingSourceFiles = [...sourceStates].flatMap(([file, state]) => state === 'pending' ? [file] : []);
172
222
  preflightSourcePatches(dshRoot, pendingSourceFiles);
@@ -177,38 +227,49 @@ function prepareSelection(distributionDirectory, profileDirectory, dshRoot) {
177
227
  return { name, version: installed.version };
178
228
  });
179
229
  const runtimePackages = [
180
- ...Object.keys(dependencies).sort().map((name) => {
230
+ ...Object.keys(dependencies).filter(name => !patchPackageNames.includes(name)).sort().map((name) => {
181
231
  const installed = resolveInstalledPackage(distributionDirectory, name);
182
232
  return { name, version: installed.version };
183
233
  }),
184
234
  ...profileDependencies,
185
235
  ].sort((left, right) => left.name.localeCompare(right.name));
186
236
  const selected = [];
187
- for (const item of patchEntries) {
188
- const absoluteFile = resolve(distributionDirectory, item.file);
189
- if (item.target.kind === 'dsh-source') {
190
- selected.push({
191
- id: item.id,
192
- scope: item.scope,
193
- file: item.file,
194
- absoluteFile,
195
- target: { kind: 'dsh-source', baseRevision: patchSet.sourceBaseRevision },
196
- alreadyApplied: sourceStates.get(absoluteFile) === 'applied',
197
- });
198
- continue;
199
- }
200
- const targetDirectory = item.target.name in profileDependencySpecs ? profileDirectory : distributionDirectory;
201
- const targetVersion = resolveInstalledPackage(targetDirectory, item.target.name).version;
202
- if (!satisfies(targetVersion, item.target.range, { includePrerelease: true })) {
203
- throw new Error('patch ' + item.id + ' targets ' + item.target.name + ' ' + item.target.range + ', found ' + targetVersion);
204
- }
205
- selected.push({
206
- id: item.id,
207
- scope: item.scope,
208
- file: item.file,
209
- absoluteFile,
210
- target: { kind: 'npm', name: item.target.name, version: targetVersion },
237
+ // 每个patch id必须在当前DSH、official base与installed npm graph上唯一命中,不能fallback到第二variant。
238
+ for (const [id, variants] of orderedGroups) {
239
+ const candidates = variants.flatMap((variant) => {
240
+ if (!satisfies(dshVersion, variant.dsh, { includePrerelease: true }))
241
+ return [];
242
+ const file = resolvePatchFile(variant.patchPackage.directory, variant.file);
243
+ if (variant.target.kind === 'dsh-source') {
244
+ if (variant.target.baseRevision !== baseRevision)
245
+ return [];
246
+ return [{
247
+ id,
248
+ patchPackage: { name: variant.patchPackage.name, version: variant.patchPackage.version },
249
+ file: file.relativeFile,
250
+ absoluteFile: file.absoluteFile,
251
+ target: { kind: 'dsh-source', baseRevision },
252
+ alreadyApplied: sourceStates.get(file.absoluteFile) === 'applied',
253
+ }];
254
+ }
255
+ const targetDirectory = variant.target.name in profileDependencySpecs ? profileDirectory : distributionDirectory;
256
+ const targetVersion = resolveInstalledPackage(targetDirectory, variant.target.name).version;
257
+ if (!satisfies(targetVersion, variant.target.range, { includePrerelease: true }))
258
+ return [];
259
+ return [{
260
+ id,
261
+ patchPackage: { name: variant.patchPackage.name, version: variant.patchPackage.version },
262
+ file: file.relativeFile,
263
+ absoluteFile: file.absoluteFile,
264
+ target: { kind: 'npm', name: variant.target.name, version: targetVersion },
265
+ }];
211
266
  });
267
+ const [candidate] = candidates;
268
+ if (candidate === undefined)
269
+ throw new Error('no compatible patch variant for ' + id + ' on DSH ' + dshVersion);
270
+ if (candidates.length > 1)
271
+ throw new Error('multiple compatible patch variants for ' + id + ' on DSH ' + dshVersion);
272
+ selected.push(candidate);
212
273
  }
213
274
  const lockPatches = selected.map((patch) => {
214
275
  if ('alreadyApplied' in patch) {
@@ -238,7 +299,7 @@ function materializePatchFiles(profileDirectory, patches) {
238
299
  const root = resolve(profileDirectory, '.dsh-plus', 'patches');
239
300
  rmSync(root, { recursive: true, force: true });
240
301
  const stablePatches = patches.map((patch) => {
241
- const destination = resolve(root, patch.scope, patch.id, basename(patch.file));
302
+ const destination = resolve(root, patch.patchPackage.name, patch.patchPackage.version, patch.file);
242
303
  mkdirSync(dirname(destination), { recursive: true });
243
304
  copyFileSync(patch.absoluteFile, destination);
244
305
  return { ...patch, absoluteFile: destination };
@@ -262,7 +323,7 @@ function materializePatchFiles(profileDirectory, patches) {
262
323
  continue;
263
324
  }
264
325
  // 成员或版本变化必须改变workspace路径,使pnpm重新应用新的组合payload。
265
- const members = group.map(patch => encodeURIComponent(patch.id)).join('+');
326
+ const members = group.map(patch => encodeURIComponent(patch.id + '@' + patch.patchPackage.version)).join('+');
266
327
  const destination = resolve(root, 'combined', encodeURIComponent(key), members + '.patch');
267
328
  mkdirSync(dirname(destination), { recursive: true });
268
329
  const contents = group.map((patch) => {
@@ -25,7 +25,6 @@ function parseStartOptions(argv) {
25
25
  let host = '127.0.0.1';
26
26
  let open = true;
27
27
  let foreground = false;
28
- let edition;
29
28
  let capabilities;
30
29
  for (let index = 0; index < argv.length; index += 1) {
31
30
  const token = argv[index];
@@ -53,14 +52,6 @@ function parseStartOptions(argv) {
53
52
  foreground = true;
54
53
  continue;
55
54
  }
56
- if (token === '--edition') {
57
- const value = argv[index + 1];
58
- if (value === undefined || value === '')
59
- throw new Error('--edition requires a value');
60
- edition = value;
61
- index += 1;
62
- continue;
63
- }
64
55
  if (token === '--capabilities') {
65
56
  const value = argv[index + 1];
66
57
  if (value === undefined)
@@ -82,7 +73,7 @@ function parseStartOptions(argv) {
82
73
  }
83
74
  throw new Error('unknown option: ' + String(token));
84
75
  }
85
- return { port, host, open, foreground, edition, capabilities };
76
+ return { port, host, open, foreground, capabilities };
86
77
  }
87
78
  /**
88
79
  * Resolve a stated capability selection.
@@ -166,54 +157,6 @@ function runForeground(entry, profileName, port, host, open) {
166
157
  const result = spawnSync(process.execPath, args, { stdio: 'inherit' });
167
158
  return result.status ?? 1;
168
159
  }
169
- /** Parse the install command's edition selection. */
170
- function parseInstallOptions(argv) {
171
- let edition;
172
- let profile;
173
- for (let index = 0; index < argv.length; index += 1) {
174
- const token = argv[index];
175
- if (token === '--edition') {
176
- const value = argv[index + 1];
177
- if (value === undefined || value === '')
178
- throw new Error('--edition requires a value');
179
- edition = value;
180
- index += 1;
181
- continue;
182
- }
183
- if (token === '--profile') {
184
- const value = argv[index + 1];
185
- if (value === undefined || value === '')
186
- throw new Error('--profile requires a value');
187
- profile = value;
188
- index += 1;
189
- continue;
190
- }
191
- throw new Error('unknown option: ' + String(token));
192
- }
193
- if (edition === undefined)
194
- throw new Error('install requires --edition personal or --edition team');
195
- return { edition, profile };
196
- }
197
- /**
198
- * Install one edition's package manifest into the profile.
199
- *
200
- * The profile's `package.json` is the install artifact; there is no separate standalone
201
- * package. A later `start` uses the same manifest, so changing the edition is a new
202
- * install rather than a second product.
203
- *
204
- * @param argv - arguments after `install`.
205
- * @returns the process exit code.
206
- */
207
- function install(argv) {
208
- const { edition, profile } = parseInstallOptions(argv);
209
- const base = resolvePaths(declarationAnchor());
210
- const paths = profile === undefined
211
- ? base
212
- : { ...base, profileName: profile, profileDirectory: join(base.home, 'profiles', profile) };
213
- ensureProfile(paths, installationRoot(), edition);
214
- console.log('Installed the ' + edition + ' edition into ' + paths.profileDirectory);
215
- return 0;
216
- }
217
160
  async function start(argv) {
218
161
  const options = parseStartOptions(argv);
219
162
  const anchor = installationAnchor();
@@ -259,12 +202,10 @@ async function start(argv) {
259
202
  }
260
203
  console.log('pnpm installed.');
261
204
  }
262
- const created = ensureProfile(paths, installationRoot(), options.edition);
205
+ const created = ensureProfile(paths, installationRoot());
263
206
  console.log(created
264
207
  ? 'Created the ' + paths.profileName + ' profile at ' + paths.profileDirectory
265
208
  : 'Using the existing ' + paths.profileName + ' profile');
266
- if (options.edition !== undefined)
267
- console.log('Edition: ' + options.edition);
268
209
  // The profile symlinks the consumer's packages, so a patch lands on the installed
269
210
  // copy the launcher loads. A reinstall restores the published bytes, which is why
270
211
  // this runs on every start rather than only when the profile was created.
@@ -640,30 +581,6 @@ async function doctor() {
640
581
  ? 'capabilities: ' + (actual.mounted.length === 0 ? '(none enabled)' : actual.mounted.join(', '))
641
582
  : 'capabilities disagree with ' + CAPABILITY_RECORD + ': ' + drifted.map(capability => capability.id).join(', ')
642
583
  + ' (run dsh-plus capabilities)');
643
- const profileManifestPath = join(paths.profileDirectory, 'package.json');
644
- if (existsSync(profileManifestPath)) {
645
- const profileManifest = JSON.parse(readFileSync(profileManifestPath, 'utf8'));
646
- const editionId = profileManifest.dsh?.profile?.plusEdition;
647
- if (editionId !== undefined) {
648
- const distribution = readDistributionProfile(paths.distributionDirectory);
649
- const edition = distribution.editions[editionId];
650
- if (edition === undefined) {
651
- check(false, 'edition "' + editionId + '" is not declared by this distribution');
652
- }
653
- else {
654
- const bundles = new Set(profileManifest.dsh?.profile?.bundles ?? []);
655
- const missingBundles = edition.bundles.filter(bundle => !bundles.has(bundle));
656
- const packageNames = Object.keys(edition.packages);
657
- const missingPackages = packageNames.filter(name => !existsSync(join(paths.profileDirectory, 'node_modules', ...name.split('/'), 'package.json')));
658
- check(missingBundles.length === 0, 'edition ' + editionId + ': ' + String(edition.bundles.length - missingBundles.length) + '/'
659
- + String(edition.bundles.length) + ' bundles mounted'
660
- + (missingBundles.length === 0 ? '' : ' (missing ' + missingBundles.join(', ') + ')'));
661
- check(missingPackages.length === 0, 'edition ' + editionId + ': ' + String(packageNames.length - missingPackages.length) + '/'
662
- + String(packageNames.length) + ' packages installed'
663
- + (missingPackages.length === 0 ? '' : ' (missing ' + missingPackages.join(', ') + ')'));
664
- }
665
- }
666
- }
667
584
  console.log(failures === 0 ? 'No problems found.' : String(failures) + ' problem(s) found.');
668
585
  return failures === 0 ? 0 : 1;
669
586
  }
@@ -671,7 +588,6 @@ const USAGE = [
671
588
  'Usage: dsh-plus <command> [options]',
672
589
  '',
673
590
  'Commands:',
674
- ' install install an edition package manifest into the profile',
675
591
  ' start start the server (first run creates the profile)',
676
592
  ' stop stop the server',
677
593
  ' status report whether the server is running',
@@ -684,11 +600,6 @@ const USAGE = [
684
600
  ' --host <h> interface to bind (default 127.0.0.1)',
685
601
  ' --no-open do not open a browser',
686
602
  ' --foreground run in this terminal instead of in the background',
687
- ' --edition <id> install the named edition manifest (personal or team)',
688
- '',
689
- 'install options:',
690
- ' --edition <id> package manifest to install (personal or team)',
691
- ' --profile <n> profile name to install into (default: this installation)',
692
603
  '',
693
604
  'capabilities options:',
694
605
  ' --enable <ids> enable the comma-separated capability ids',
@@ -711,8 +622,6 @@ export async function runStandaloneCli(argv) {
711
622
  console.log(USAGE);
712
623
  return 0;
713
624
  }
714
- if (command === 'install')
715
- return install(rest);
716
625
  if (command === 'start')
717
626
  return await start(rest);
718
627
  if (command === 'stop')
@@ -93,18 +93,12 @@ export declare function isWithin(candidate: string, parent: string, platform?: N
93
93
  */
94
94
  export declare function resolveDistributionDirectory(anchor: string): string;
95
95
  /** The reviewed bundle order and pins the installed distribution declares. */
96
- export interface EditionComposition {
97
- readonly label: string;
98
- readonly bundles: readonly string[];
99
- readonly packages: Readonly<Record<string, string>>;
100
- }
101
96
  export declare function readDistributionProfile(distributionDirectory: string): {
102
97
  readonly name: string;
103
98
  readonly bundles: readonly string[];
104
99
  readonly dependencies: Readonly<Record<string, string>>;
105
100
  readonly allowBuilds: Readonly<Record<string, boolean>>;
106
101
  readonly overrides: Readonly<Record<string, string>>;
107
- readonly editions: Readonly<Record<string, EditionComposition>>;
108
102
  readonly dshRange: string;
109
103
  readonly version: string;
110
104
  };
@@ -197,10 +191,9 @@ export declare function resolvePaths(anchor: string, env?: NodeJS.ProcessEnv): S
197
191
  *
198
192
  * @param paths - resolved standalone paths.
199
193
  * @param consumerDirectory - directory whose `node_modules` holds the installed packages.
200
- * @param edition - edition id whose package list to install, or undefined for the default.
201
194
  * @returns whether this call created the manifest.
202
195
  */
203
- export declare function ensureProfile(paths: StandalonePaths, consumerDirectory: string, edition?: string): boolean;
196
+ export declare function ensureProfile(paths: StandalonePaths, consumerDirectory: string): boolean;
204
197
  /**
205
198
  * Apply the reviewed npm-target patches to the profile's installed packages.
206
199
  *