@awsless/ts-file-cache 0.0.16 → 0.0.17

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.
package/README.MD CHANGED
@@ -4,6 +4,9 @@
4
4
  Attempt to create a hash from an js/ts file and all it's dependecies.
5
5
  The goal is to generate a new hash when ever the file or it's dependecies change.
6
6
 
7
+ Supports pnpm (`pnpm-lock.yaml`) and bun (`bun.lock`) workspaces.
8
+ The lock file is auto-detected by walking up from the search path.
9
+
7
10
  ```ts
8
11
 
9
12
  const workspace = await loadWorkspace('.')
@@ -17,7 +20,3 @@ const workspace = await loadWorkspace('.')
17
20
  const hash = await generateFolderHash(workspace, "./src")
18
21
 
19
22
  ```
20
-
21
- ## Known issue's
22
-
23
- - When we walk the AST tree with the "swc-walk" package it could fail in some code bases. Right now we just silently fail which could lead to an incorrect cache key.
package/dist/index.cjs CHANGED
@@ -25,7 +25,8 @@ __export(index_exports, {
25
25
  loadWorkspace: () => loadWorkspace
26
26
  });
27
27
  module.exports = __toCommonJS(index_exports);
28
- var import_promises4 = require("fs/promises");
28
+ var import_promises5 = require("fs/promises");
29
+ var import_path8 = require("path");
29
30
 
30
31
  // src/hash.ts
31
32
  var import_crypto = require("crypto");
@@ -37,10 +38,31 @@ var import_path3 = require("path");
37
38
  var import_core = require("@swc/core");
38
39
  var import_path = require("path");
39
40
  var import_swc_walk = require("swc-walk");
41
+ var import_baseVisitor = require("swc-walk/baseVisitor");
42
+ var PatchedBaseVisitor = class extends import_baseVisitor.BaseVisitor {
43
+ FunctionBody(node, state, callback) {
44
+ for (const statement of node.stmts) {
45
+ callback(statement, state);
46
+ }
47
+ }
48
+ };
49
+ var baseVisitor = new PatchedBaseVisitor();
50
+ var parseOptions = (file) => {
51
+ if (file.endsWith(".tsx")) {
52
+ return { syntax: "typescript", tsx: true, decorators: true };
53
+ }
54
+ if (file.endsWith(".ts") || file.endsWith(".mts") || file.endsWith(".cts")) {
55
+ return { syntax: "typescript", decorators: true };
56
+ }
57
+ return { syntax: "ecmascript", jsx: true, decorators: true };
58
+ };
40
59
  var findImports = async (file, code) => {
41
- const ast = await (0, import_core.parse)(code, {
42
- syntax: "typescript"
43
- });
60
+ let ast;
61
+ try {
62
+ ast = await (0, import_core.parse)(code, parseOptions(file));
63
+ } catch (error) {
64
+ throw new Error(`Failed to parse: ${file}`, { cause: error });
65
+ }
44
66
  const importing = /* @__PURE__ */ new Set();
45
67
  try {
46
68
  (0, import_swc_walk.simple)(ast, {
@@ -62,10 +84,15 @@ var findImports = async (file, code) => {
62
84
  importing.add(first.expression.value);
63
85
  }
64
86
  }
87
+ },
88
+ TsImportEqualsDeclaration(node) {
89
+ if (node.moduleRef.type === "TsExternalModuleReference") {
90
+ importing.add(node.moduleRef.expression.value);
91
+ }
65
92
  }
66
- });
67
- } catch (_) {
68
- return [];
93
+ }, baseVisitor);
94
+ } catch (error) {
95
+ throw new Error(`Failed to walk the AST of: ${file}`, { cause: error });
69
96
  }
70
97
  return [...importing].map((importee) => {
71
98
  if (importee.startsWith(".")) {
@@ -95,15 +122,29 @@ var findFile = async (files) => {
95
122
  }
96
123
  throw new Error(`No such file: ${files.join(", ")}`);
97
124
  };
125
+ var alternateExtensions = {
126
+ ".js": [".ts", ".tsx"],
127
+ ".mjs": [".mts"],
128
+ ".cjs": [".cts"],
129
+ ".jsx": [".tsx"]
130
+ };
98
131
  var resolveModuleImportFile = (file, allowedExtensions) => {
99
- if (file.endsWith(".js") && allowedExtensions.includes("js") && allowedExtensions.includes("ts")) {
100
- return findFile([file, file.substring(0, file.length - 3) + ".ts"]);
132
+ const extension = (0, import_path2.extname)(file);
133
+ const alternates = alternateExtensions[extension];
134
+ if (alternates) {
135
+ const candidates = [file];
136
+ for (const alternate of alternates) {
137
+ if (allowedExtensions.includes(alternate.substring(1))) {
138
+ candidates.push(file.substring(0, file.length - extension.length) + alternate);
139
+ }
140
+ }
141
+ return findFile(candidates);
101
142
  }
102
143
  if (!(0, import_path2.basename)(file).includes(".")) {
103
144
  return findFile([
104
145
  file,
105
- ...allowedExtensions.map((exp) => `${file}.${exp}`),
106
- ...allowedExtensions.map((exp) => (0, import_path2.join)(file, `/index.${exp}`))
146
+ ...allowedExtensions.map((ext) => `${file}.${ext}`),
147
+ ...allowedExtensions.map((ext) => (0, import_path2.join)(file, `index.${ext}`))
107
148
  ]);
108
149
  }
109
150
  return file;
@@ -126,7 +167,7 @@ var generateRecursiveFileHashes = async (workspace, file, sourceFile, allowedExt
126
167
  } catch (error) {
127
168
  throw new Error(`Can't find imported file: "${file}" inside the source: "${sourceFile}"`);
128
169
  }
129
- const relFile = (0, import_path3.relative)(workspace.cwd, file);
170
+ const relFile = (0, import_path3.relative)(workspace.cwd, file).split(import_path3.sep).join("/");
130
171
  if (hashes.has(relFile)) {
131
172
  return;
132
173
  }
@@ -152,7 +193,7 @@ var generateRecursiveFileHashes = async (workspace, file, sourceFile, allowedExt
152
193
  if (dependency.type === "package") {
153
194
  hashes.set(module2, Buffer.from(`${module2}:${dependency.version}`, "utf8"));
154
195
  } else {
155
- const localPackage = workspace.packages[module2];
196
+ const localPackage = workspace.packages[dependency.link];
156
197
  if (!localPackage) {
157
198
  throw new Error(`Can't find the local workspace package for: ${file}`);
158
199
  }
@@ -175,8 +216,13 @@ var generateRecursiveFileHashes = async (workspace, file, sourceFile, allowedExt
175
216
  throw new Error(`Can't find the dependency version for: ${file} inside the source: ${sourceFile}`);
176
217
  };
177
218
  var mergeHashes = (hashes) => {
178
- const merge = Buffer.concat(Array.from(hashes.values()).sort());
179
- return (0, import_crypto.createHash)("sha1").update(merge).digest("hex");
219
+ const names = Array.from(hashes.keys()).sort();
220
+ const merged = (0, import_crypto.createHash)("sha1");
221
+ for (const name of names) {
222
+ merged.update(name);
223
+ merged.update(hashes.get(name));
224
+ }
225
+ return merged.digest("hex");
180
226
  };
181
227
  var getPackageName = (importee) => {
182
228
  const parts = importee.split("/");
@@ -190,45 +236,31 @@ var getPackageName = (importee) => {
190
236
  throw new Error(`Malformed importee: ${importee}`);
191
237
  };
192
238
  var findDependency = (workspace, module2, source) => {
193
- const pkg = Object.values(workspace.packages).filter((p) => source.startsWith(p.path)).sort((a, b) => b.path.split("/").length - a.path.split("/").length).find((p) => p.dependencies[module2]);
239
+ const pkg = Object.values(workspace.packages).filter((p) => source === p.path || source.startsWith(p.path + import_path3.sep)).sort((a, b) => b.path.split(import_path3.sep).length - a.path.split(import_path3.sep).length).find((p) => p.dependencies[module2]);
194
240
  if (!pkg) {
195
241
  return;
196
242
  }
197
243
  return pkg.dependencies[module2];
198
244
  };
199
245
 
200
- // src/index.ts
246
+ // src/package-manager/index.ts
247
+ var import_promises4 = require("fs/promises");
248
+ var import_path7 = require("path");
249
+
250
+ // src/package-manager/bun.ts
201
251
  var import_path5 = require("path");
202
252
 
203
- // src/package-manager/pnpm.ts
253
+ // src/package-manager/importer.ts
204
254
  var import_promises3 = require("fs/promises");
205
255
  var import_path4 = require("path");
206
- var import_yaml = require("yaml");
207
- var pnpm = async (search) => {
208
- const [cwd, lockFile] = await findLockFile(search);
209
- const data = (0, import_yaml.parse)(lockFile);
256
+ var buildPackages = async (cwd, importers) => {
210
257
  const packages = {};
211
258
  await Promise.all(
212
- Object.entries(data.importers).map(async ([path, importee]) => {
213
- const deps = { ...importee.devDependencies, ...importee.dependencies };
214
- const dependencies = {};
259
+ Object.entries(importers).map(async ([path, dependencies]) => {
215
260
  const packageJson = await (0, import_promises3.readFile)((0, import_path4.join)(cwd, path, "package.json"), "utf8");
216
261
  const packageData = JSON.parse(packageJson);
217
- for (const [name, entry2] of Object.entries(deps)) {
218
- if (entry2.version.startsWith("link:")) {
219
- dependencies[name] = {
220
- type: "workspace",
221
- link: (0, import_path4.join)(cwd, path, entry2.version.substring(5))
222
- };
223
- } else {
224
- dependencies[name] = {
225
- type: "package",
226
- version: entry2.version
227
- };
228
- }
229
- }
230
262
  const entry = packageData.module ?? packageData.main;
231
- packages[packageData.name] = {
263
+ packages[(0, import_path4.join)(cwd, path)] = {
232
264
  name: packageData.name,
233
265
  path: (0, import_path4.join)(cwd, path),
234
266
  main: entry ? (0, import_path4.join)(cwd, path, entry) : void 0,
@@ -236,25 +268,180 @@ var pnpm = async (search) => {
236
268
  };
237
269
  })
238
270
  );
271
+ return packages;
272
+ };
273
+
274
+ // src/package-manager/bun.ts
275
+ var bun = async (cwd, lockFile) => {
276
+ const data = parseJsonc(lockFile);
277
+ const resolvedVersions = {};
278
+ for (const [key, entry] of Object.entries(data.packages ?? {})) {
279
+ const resolution = entry[0];
280
+ const at = resolution.lastIndexOf("@");
281
+ const version = resolution.substring(at + 1);
282
+ if (!version.startsWith("workspace:")) {
283
+ resolvedVersions[key] = version;
284
+ }
285
+ }
286
+ const workspacePaths = {};
287
+ for (const [path, workspace] of Object.entries(data.workspaces)) {
288
+ if (workspace.name) {
289
+ workspacePaths[workspace.name] = path;
290
+ }
291
+ }
292
+ const importers = {};
293
+ for (const [path, workspace] of Object.entries(data.workspaces)) {
294
+ const deps = { ...workspace.devDependencies, ...workspace.optionalDependencies, ...workspace.dependencies };
295
+ const dependencies = {};
296
+ for (const [name, specifier] of Object.entries(deps)) {
297
+ if (specifier.startsWith("workspace:")) {
298
+ const target = specifier.substring(10);
299
+ const workspacePath = workspacePaths[name];
300
+ if (workspacePath !== void 0) {
301
+ dependencies[name] = {
302
+ type: "workspace",
303
+ link: (0, import_path5.join)(cwd, workspacePath)
304
+ };
305
+ } else {
306
+ dependencies[name] = {
307
+ type: "workspace",
308
+ link: (0, import_path5.join)(cwd, path, target)
309
+ };
310
+ }
311
+ continue;
312
+ }
313
+ const version = resolvedVersions[name] ?? resolvedVersions[`${workspace.name}/${name}`];
314
+ if (version) {
315
+ dependencies[name] = {
316
+ type: "package",
317
+ version
318
+ };
319
+ } else {
320
+ dependencies[name] = {
321
+ type: "package",
322
+ version: specifier
323
+ };
324
+ }
325
+ }
326
+ importers[path] = dependencies;
327
+ }
328
+ const packages = await buildPackages(cwd, importers);
239
329
  return {
240
330
  cwd,
241
331
  packages
242
332
  };
243
333
  };
244
- var findLockFile = async (path, level = 5) => {
334
+ var parseJsonc = (text) => {
335
+ try {
336
+ return JSON.parse(text);
337
+ } catch (_) {
338
+ return JSON.parse(stripJsoncSyntax(text));
339
+ }
340
+ };
341
+ var stripJsoncSyntax = (text) => {
342
+ let result = "";
343
+ let index = 0;
344
+ while (index < text.length) {
345
+ const char = text[index];
346
+ if (char === '"') {
347
+ result += char;
348
+ index++;
349
+ while (index < text.length) {
350
+ const stringChar = text[index];
351
+ result += stringChar;
352
+ index++;
353
+ if (stringChar === "\\") {
354
+ result += text[index] ?? "";
355
+ index++;
356
+ continue;
357
+ }
358
+ if (stringChar === '"') {
359
+ break;
360
+ }
361
+ }
362
+ continue;
363
+ }
364
+ if (char === "/" && text[index + 1] === "/") {
365
+ while (index < text.length && text[index] !== "\n") {
366
+ index++;
367
+ }
368
+ continue;
369
+ }
370
+ if (char === "/" && text[index + 1] === "*") {
371
+ index += 2;
372
+ while (index < text.length && !(text[index] === "*" && text[index + 1] === "/")) {
373
+ index++;
374
+ }
375
+ index += 2;
376
+ continue;
377
+ }
378
+ if (char === ",") {
379
+ let ahead = index + 1;
380
+ while (ahead < text.length && /\s/.test(text[ahead])) {
381
+ ahead++;
382
+ }
383
+ if (text[ahead] === "}" || text[ahead] === "]") {
384
+ index++;
385
+ continue;
386
+ }
387
+ }
388
+ result += char;
389
+ index++;
390
+ }
391
+ return result;
392
+ };
393
+
394
+ // src/package-manager/pnpm.ts
395
+ var import_path6 = require("path");
396
+ var import_yaml = require("yaml");
397
+ var pnpm = async (cwd, lockFile) => {
398
+ const data = (0, import_yaml.parse)(lockFile);
399
+ const importers = {};
400
+ for (const [path, importee] of Object.entries(data.importers)) {
401
+ const deps = { ...importee.devDependencies, ...importee.optionalDependencies, ...importee.dependencies };
402
+ const dependencies = {};
403
+ for (const [name, entry] of Object.entries(deps)) {
404
+ if (entry.version.startsWith("link:")) {
405
+ dependencies[name] = {
406
+ type: "workspace",
407
+ link: (0, import_path6.join)(cwd, path, entry.version.substring(5))
408
+ };
409
+ } else {
410
+ dependencies[name] = {
411
+ type: "package",
412
+ version: entry.version
413
+ };
414
+ }
415
+ }
416
+ importers[path] = dependencies;
417
+ }
418
+ const packages = await buildPackages(cwd, importers);
419
+ return {
420
+ cwd,
421
+ packages
422
+ };
423
+ };
424
+
425
+ // src/package-manager/index.ts
426
+ var parsers = {
427
+ "pnpm-lock.yaml": pnpm,
428
+ "bun.lock": bun
429
+ };
430
+ var loadPackageManager = async (search, level = 5) => {
245
431
  if (!level) {
246
- throw new TypeError("No pnpm lock file found");
432
+ throw new TypeError("No pnpm or bun lock file found");
247
433
  }
248
- const file = (0, import_path4.join)(path, "pnpm-lock.yaml");
249
- const exists = await fileExist(file);
250
- if (exists) {
251
- return [path, await (0, import_promises3.readFile)(file, "utf8")];
434
+ for (const [lockFileName, parser] of Object.entries(parsers)) {
435
+ const file = (0, import_path7.join)(search, lockFileName);
436
+ if (await fileExist(file)) {
437
+ return parser(search, await (0, import_promises4.readFile)(file, "utf8"));
438
+ }
252
439
  }
253
- return findLockFile((0, import_path4.normalize)((0, import_path4.join)(path, "..")), level - 1);
440
+ return loadPackageManager((0, import_path7.normalize)((0, import_path7.join)(search, "..")), level - 1);
254
441
  };
255
442
  var fileExist = async (file) => {
256
443
  try {
257
- const stat2 = await (0, import_promises3.lstat)(file);
444
+ const stat2 = await (0, import_promises4.lstat)(file);
258
445
  if (stat2.isFile()) {
259
446
  return true;
260
447
  }
@@ -265,11 +452,7 @@ var fileExist = async (file) => {
265
452
 
266
453
  // src/index.ts
267
454
  var loadWorkspace = async (search) => {
268
- const { cwd, packages } = await pnpm(toAbsolute(search));
269
- return {
270
- cwd,
271
- packages
272
- };
455
+ return loadPackageManager(toAbsolute(search));
273
456
  };
274
457
  var defaultOptions = {
275
458
  extensions: ["js", "mjs", "jsx", "ts", "mts", "tsx"]
@@ -284,10 +467,11 @@ var generateFileHash = async (workspace, file, opts = {}) => {
284
467
  var generateFolderHash = async (workspace, folder, opts = {}) => {
285
468
  const options = { ...defaultOptions, ...opts };
286
469
  const hashes = /* @__PURE__ */ new Map();
287
- const files = await (0, import_promises4.readdir)(folder, { recursive: true, withFileTypes: true });
470
+ const absoluteFolder = toAbsolute(folder);
471
+ const files = await (0, import_promises5.readdir)(absoluteFolder, { recursive: true, withFileTypes: true });
288
472
  for (const file of files) {
289
- if (file.isFile() && options.extensions.includes((0, import_path5.extname)(file.name).substring(1))) {
290
- const f = (0, import_path5.resolve)(file.parentPath, file.name);
473
+ if (file.isFile() && options.extensions.includes((0, import_path8.extname)(file.name).substring(1))) {
474
+ const f = (0, import_path8.resolve)(file.parentPath, file.name);
291
475
  await generateRecursiveFileHashes(workspace, f, f, options.extensions, hashes);
292
476
  }
293
477
  }
package/dist/index.js CHANGED
@@ -1,20 +1,42 @@
1
1
  // src/index.ts
2
2
  import { readdir } from "fs/promises";
3
+ import { extname as extname2, resolve as resolve2 } from "path";
3
4
 
4
5
  // src/hash.ts
5
6
  import { createHash } from "crypto";
6
7
  import { readFile } from "fs/promises";
7
8
  import { builtinModules } from "module";
8
- import { relative } from "path";
9
+ import { relative, sep } from "path";
9
10
 
10
11
  // src/import.ts
11
12
  import { parse } from "@swc/core";
12
13
  import { dirname, resolve } from "path";
13
14
  import { simple } from "swc-walk";
15
+ import { BaseVisitor } from "swc-walk/baseVisitor";
16
+ var PatchedBaseVisitor = class extends BaseVisitor {
17
+ FunctionBody(node, state, callback) {
18
+ for (const statement of node.stmts) {
19
+ callback(statement, state);
20
+ }
21
+ }
22
+ };
23
+ var baseVisitor = new PatchedBaseVisitor();
24
+ var parseOptions = (file) => {
25
+ if (file.endsWith(".tsx")) {
26
+ return { syntax: "typescript", tsx: true, decorators: true };
27
+ }
28
+ if (file.endsWith(".ts") || file.endsWith(".mts") || file.endsWith(".cts")) {
29
+ return { syntax: "typescript", decorators: true };
30
+ }
31
+ return { syntax: "ecmascript", jsx: true, decorators: true };
32
+ };
14
33
  var findImports = async (file, code) => {
15
- const ast = await parse(code, {
16
- syntax: "typescript"
17
- });
34
+ let ast;
35
+ try {
36
+ ast = await parse(code, parseOptions(file));
37
+ } catch (error) {
38
+ throw new Error(`Failed to parse: ${file}`, { cause: error });
39
+ }
18
40
  const importing = /* @__PURE__ */ new Set();
19
41
  try {
20
42
  simple(ast, {
@@ -36,10 +58,15 @@ var findImports = async (file, code) => {
36
58
  importing.add(first.expression.value);
37
59
  }
38
60
  }
61
+ },
62
+ TsImportEqualsDeclaration(node) {
63
+ if (node.moduleRef.type === "TsExternalModuleReference") {
64
+ importing.add(node.moduleRef.expression.value);
65
+ }
39
66
  }
40
- });
41
- } catch (_) {
42
- return [];
67
+ }, baseVisitor);
68
+ } catch (error) {
69
+ throw new Error(`Failed to walk the AST of: ${file}`, { cause: error });
43
70
  }
44
71
  return [...importing].map((importee) => {
45
72
  if (importee.startsWith(".")) {
@@ -55,7 +82,7 @@ var findImports = async (file, code) => {
55
82
 
56
83
  // src/module.ts
57
84
  import { stat } from "fs/promises";
58
- import { basename, isAbsolute, join } from "path";
85
+ import { basename, extname, isAbsolute, join } from "path";
59
86
  var findFile = async (files) => {
60
87
  for (const file of files) {
61
88
  try {
@@ -69,15 +96,29 @@ var findFile = async (files) => {
69
96
  }
70
97
  throw new Error(`No such file: ${files.join(", ")}`);
71
98
  };
99
+ var alternateExtensions = {
100
+ ".js": [".ts", ".tsx"],
101
+ ".mjs": [".mts"],
102
+ ".cjs": [".cts"],
103
+ ".jsx": [".tsx"]
104
+ };
72
105
  var resolveModuleImportFile = (file, allowedExtensions) => {
73
- if (file.endsWith(".js") && allowedExtensions.includes("js") && allowedExtensions.includes("ts")) {
74
- return findFile([file, file.substring(0, file.length - 3) + ".ts"]);
106
+ const extension = extname(file);
107
+ const alternates = alternateExtensions[extension];
108
+ if (alternates) {
109
+ const candidates = [file];
110
+ for (const alternate of alternates) {
111
+ if (allowedExtensions.includes(alternate.substring(1))) {
112
+ candidates.push(file.substring(0, file.length - extension.length) + alternate);
113
+ }
114
+ }
115
+ return findFile(candidates);
75
116
  }
76
117
  if (!basename(file).includes(".")) {
77
118
  return findFile([
78
119
  file,
79
- ...allowedExtensions.map((exp) => `${file}.${exp}`),
80
- ...allowedExtensions.map((exp) => join(file, `/index.${exp}`))
120
+ ...allowedExtensions.map((ext) => `${file}.${ext}`),
121
+ ...allowedExtensions.map((ext) => join(file, `index.${ext}`))
81
122
  ]);
82
123
  }
83
124
  return file;
@@ -100,7 +141,7 @@ var generateRecursiveFileHashes = async (workspace, file, sourceFile, allowedExt
100
141
  } catch (error) {
101
142
  throw new Error(`Can't find imported file: "${file}" inside the source: "${sourceFile}"`);
102
143
  }
103
- const relFile = relative(workspace.cwd, file);
144
+ const relFile = relative(workspace.cwd, file).split(sep).join("/");
104
145
  if (hashes.has(relFile)) {
105
146
  return;
106
147
  }
@@ -126,7 +167,7 @@ var generateRecursiveFileHashes = async (workspace, file, sourceFile, allowedExt
126
167
  if (dependency.type === "package") {
127
168
  hashes.set(module, Buffer.from(`${module}:${dependency.version}`, "utf8"));
128
169
  } else {
129
- const localPackage = workspace.packages[module];
170
+ const localPackage = workspace.packages[dependency.link];
130
171
  if (!localPackage) {
131
172
  throw new Error(`Can't find the local workspace package for: ${file}`);
132
173
  }
@@ -149,8 +190,13 @@ var generateRecursiveFileHashes = async (workspace, file, sourceFile, allowedExt
149
190
  throw new Error(`Can't find the dependency version for: ${file} inside the source: ${sourceFile}`);
150
191
  };
151
192
  var mergeHashes = (hashes) => {
152
- const merge = Buffer.concat(Array.from(hashes.values()).sort());
153
- return createHash("sha1").update(merge).digest("hex");
193
+ const names = Array.from(hashes.keys()).sort();
194
+ const merged = createHash("sha1");
195
+ for (const name of names) {
196
+ merged.update(name);
197
+ merged.update(hashes.get(name));
198
+ }
199
+ return merged.digest("hex");
154
200
  };
155
201
  var getPackageName = (importee) => {
156
202
  const parts = importee.split("/");
@@ -164,45 +210,31 @@ var getPackageName = (importee) => {
164
210
  throw new Error(`Malformed importee: ${importee}`);
165
211
  };
166
212
  var findDependency = (workspace, module, source) => {
167
- const pkg = Object.values(workspace.packages).filter((p) => source.startsWith(p.path)).sort((a, b) => b.path.split("/").length - a.path.split("/").length).find((p) => p.dependencies[module]);
213
+ const pkg = Object.values(workspace.packages).filter((p) => source === p.path || source.startsWith(p.path + sep)).sort((a, b) => b.path.split(sep).length - a.path.split(sep).length).find((p) => p.dependencies[module]);
168
214
  if (!pkg) {
169
215
  return;
170
216
  }
171
217
  return pkg.dependencies[module];
172
218
  };
173
219
 
174
- // src/index.ts
175
- import { extname, resolve as resolve2 } from "path";
220
+ // src/package-manager/index.ts
221
+ import { lstat, readFile as readFile3 } from "fs/promises";
222
+ import { join as join5, normalize } from "path";
176
223
 
177
- // src/package-manager/pnpm.ts
178
- import { lstat, readFile as readFile2 } from "fs/promises";
179
- import { join as join2, normalize } from "path";
180
- import { parse as parse2 } from "yaml";
181
- var pnpm = async (search) => {
182
- const [cwd, lockFile] = await findLockFile(search);
183
- const data = parse2(lockFile);
224
+ // src/package-manager/bun.ts
225
+ import { join as join3 } from "path";
226
+
227
+ // src/package-manager/importer.ts
228
+ import { readFile as readFile2 } from "fs/promises";
229
+ import { join as join2 } from "path";
230
+ var buildPackages = async (cwd, importers) => {
184
231
  const packages = {};
185
232
  await Promise.all(
186
- Object.entries(data.importers).map(async ([path, importee]) => {
187
- const deps = { ...importee.devDependencies, ...importee.dependencies };
188
- const dependencies = {};
233
+ Object.entries(importers).map(async ([path, dependencies]) => {
189
234
  const packageJson = await readFile2(join2(cwd, path, "package.json"), "utf8");
190
235
  const packageData = JSON.parse(packageJson);
191
- for (const [name, entry2] of Object.entries(deps)) {
192
- if (entry2.version.startsWith("link:")) {
193
- dependencies[name] = {
194
- type: "workspace",
195
- link: join2(cwd, path, entry2.version.substring(5))
196
- };
197
- } else {
198
- dependencies[name] = {
199
- type: "package",
200
- version: entry2.version
201
- };
202
- }
203
- }
204
236
  const entry = packageData.module ?? packageData.main;
205
- packages[packageData.name] = {
237
+ packages[join2(cwd, path)] = {
206
238
  name: packageData.name,
207
239
  path: join2(cwd, path),
208
240
  main: entry ? join2(cwd, path, entry) : void 0,
@@ -210,21 +242,176 @@ var pnpm = async (search) => {
210
242
  };
211
243
  })
212
244
  );
245
+ return packages;
246
+ };
247
+
248
+ // src/package-manager/bun.ts
249
+ var bun = async (cwd, lockFile) => {
250
+ const data = parseJsonc(lockFile);
251
+ const resolvedVersions = {};
252
+ for (const [key, entry] of Object.entries(data.packages ?? {})) {
253
+ const resolution = entry[0];
254
+ const at = resolution.lastIndexOf("@");
255
+ const version = resolution.substring(at + 1);
256
+ if (!version.startsWith("workspace:")) {
257
+ resolvedVersions[key] = version;
258
+ }
259
+ }
260
+ const workspacePaths = {};
261
+ for (const [path, workspace] of Object.entries(data.workspaces)) {
262
+ if (workspace.name) {
263
+ workspacePaths[workspace.name] = path;
264
+ }
265
+ }
266
+ const importers = {};
267
+ for (const [path, workspace] of Object.entries(data.workspaces)) {
268
+ const deps = { ...workspace.devDependencies, ...workspace.optionalDependencies, ...workspace.dependencies };
269
+ const dependencies = {};
270
+ for (const [name, specifier] of Object.entries(deps)) {
271
+ if (specifier.startsWith("workspace:")) {
272
+ const target = specifier.substring(10);
273
+ const workspacePath = workspacePaths[name];
274
+ if (workspacePath !== void 0) {
275
+ dependencies[name] = {
276
+ type: "workspace",
277
+ link: join3(cwd, workspacePath)
278
+ };
279
+ } else {
280
+ dependencies[name] = {
281
+ type: "workspace",
282
+ link: join3(cwd, path, target)
283
+ };
284
+ }
285
+ continue;
286
+ }
287
+ const version = resolvedVersions[name] ?? resolvedVersions[`${workspace.name}/${name}`];
288
+ if (version) {
289
+ dependencies[name] = {
290
+ type: "package",
291
+ version
292
+ };
293
+ } else {
294
+ dependencies[name] = {
295
+ type: "package",
296
+ version: specifier
297
+ };
298
+ }
299
+ }
300
+ importers[path] = dependencies;
301
+ }
302
+ const packages = await buildPackages(cwd, importers);
303
+ return {
304
+ cwd,
305
+ packages
306
+ };
307
+ };
308
+ var parseJsonc = (text) => {
309
+ try {
310
+ return JSON.parse(text);
311
+ } catch (_) {
312
+ return JSON.parse(stripJsoncSyntax(text));
313
+ }
314
+ };
315
+ var stripJsoncSyntax = (text) => {
316
+ let result = "";
317
+ let index = 0;
318
+ while (index < text.length) {
319
+ const char = text[index];
320
+ if (char === '"') {
321
+ result += char;
322
+ index++;
323
+ while (index < text.length) {
324
+ const stringChar = text[index];
325
+ result += stringChar;
326
+ index++;
327
+ if (stringChar === "\\") {
328
+ result += text[index] ?? "";
329
+ index++;
330
+ continue;
331
+ }
332
+ if (stringChar === '"') {
333
+ break;
334
+ }
335
+ }
336
+ continue;
337
+ }
338
+ if (char === "/" && text[index + 1] === "/") {
339
+ while (index < text.length && text[index] !== "\n") {
340
+ index++;
341
+ }
342
+ continue;
343
+ }
344
+ if (char === "/" && text[index + 1] === "*") {
345
+ index += 2;
346
+ while (index < text.length && !(text[index] === "*" && text[index + 1] === "/")) {
347
+ index++;
348
+ }
349
+ index += 2;
350
+ continue;
351
+ }
352
+ if (char === ",") {
353
+ let ahead = index + 1;
354
+ while (ahead < text.length && /\s/.test(text[ahead])) {
355
+ ahead++;
356
+ }
357
+ if (text[ahead] === "}" || text[ahead] === "]") {
358
+ index++;
359
+ continue;
360
+ }
361
+ }
362
+ result += char;
363
+ index++;
364
+ }
365
+ return result;
366
+ };
367
+
368
+ // src/package-manager/pnpm.ts
369
+ import { join as join4 } from "path";
370
+ import { parse as parse2 } from "yaml";
371
+ var pnpm = async (cwd, lockFile) => {
372
+ const data = parse2(lockFile);
373
+ const importers = {};
374
+ for (const [path, importee] of Object.entries(data.importers)) {
375
+ const deps = { ...importee.devDependencies, ...importee.optionalDependencies, ...importee.dependencies };
376
+ const dependencies = {};
377
+ for (const [name, entry] of Object.entries(deps)) {
378
+ if (entry.version.startsWith("link:")) {
379
+ dependencies[name] = {
380
+ type: "workspace",
381
+ link: join4(cwd, path, entry.version.substring(5))
382
+ };
383
+ } else {
384
+ dependencies[name] = {
385
+ type: "package",
386
+ version: entry.version
387
+ };
388
+ }
389
+ }
390
+ importers[path] = dependencies;
391
+ }
392
+ const packages = await buildPackages(cwd, importers);
213
393
  return {
214
394
  cwd,
215
395
  packages
216
396
  };
217
397
  };
218
- var findLockFile = async (path, level = 5) => {
398
+
399
+ // src/package-manager/index.ts
400
+ var parsers = {
401
+ "pnpm-lock.yaml": pnpm,
402
+ "bun.lock": bun
403
+ };
404
+ var loadPackageManager = async (search, level = 5) => {
219
405
  if (!level) {
220
- throw new TypeError("No pnpm lock file found");
406
+ throw new TypeError("No pnpm or bun lock file found");
221
407
  }
222
- const file = join2(path, "pnpm-lock.yaml");
223
- const exists = await fileExist(file);
224
- if (exists) {
225
- return [path, await readFile2(file, "utf8")];
408
+ for (const [lockFileName, parser] of Object.entries(parsers)) {
409
+ const file = join5(search, lockFileName);
410
+ if (await fileExist(file)) {
411
+ return parser(search, await readFile3(file, "utf8"));
412
+ }
226
413
  }
227
- return findLockFile(normalize(join2(path, "..")), level - 1);
414
+ return loadPackageManager(normalize(join5(search, "..")), level - 1);
228
415
  };
229
416
  var fileExist = async (file) => {
230
417
  try {
@@ -239,11 +426,7 @@ var fileExist = async (file) => {
239
426
 
240
427
  // src/index.ts
241
428
  var loadWorkspace = async (search) => {
242
- const { cwd, packages } = await pnpm(toAbsolute(search));
243
- return {
244
- cwd,
245
- packages
246
- };
429
+ return loadPackageManager(toAbsolute(search));
247
430
  };
248
431
  var defaultOptions = {
249
432
  extensions: ["js", "mjs", "jsx", "ts", "mts", "tsx"]
@@ -258,9 +441,10 @@ var generateFileHash = async (workspace, file, opts = {}) => {
258
441
  var generateFolderHash = async (workspace, folder, opts = {}) => {
259
442
  const options = { ...defaultOptions, ...opts };
260
443
  const hashes = /* @__PURE__ */ new Map();
261
- const files = await readdir(folder, { recursive: true, withFileTypes: true });
444
+ const absoluteFolder = toAbsolute(folder);
445
+ const files = await readdir(absoluteFolder, { recursive: true, withFileTypes: true });
262
446
  for (const file of files) {
263
- if (file.isFile() && options.extensions.includes(extname(file.name).substring(1))) {
447
+ if (file.isFile() && options.extensions.includes(extname2(file.name).substring(1))) {
264
448
  const f = resolve2(file.parentPath, file.name);
265
449
  await generateRecursiveFileHashes(workspace, f, f, options.extensions, hashes);
266
450
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awsless/ts-file-cache",
3
- "version": "0.0.16",
3
+ "version": "0.0.17",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -24,9 +24,9 @@
24
24
  }
25
25
  },
26
26
  "dependencies": {
27
- "@swc/core": "^1.10.18",
28
- "swc-walk": "1.0.0-rc.2",
29
- "yaml": "^2.5.0"
27
+ "@swc/core": "^1.16.0",
28
+ "swc-walk": "3.0.0-rc.0",
29
+ "yaml": "^2.9.0"
30
30
  },
31
31
  "scripts": {
32
32
  "test": "pnpm code test",