@effected/bundler 0.4.1 → 0.5.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,9 +1,6 @@
1
+ import { existsLikeNode } from "../internal/exists.js";
1
2
  import { BUNDLE_MANIFEST_FILENAME, decodeManifestSource } from "@effected/manifest";
2
- import { Data, Effect, Layer } from "effect";
3
- import { existsSync, readFileSync, realpathSync } from "node:fs";
4
- import { join, resolve } from "node:path";
5
- import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
6
- import * as NodePath from "@effect/platform-node/NodePath";
3
+ import { Cause, Data, Effect, FileSystem, Path } from "effect";
7
4
  import { WorkspaceDiscovery, WorkspaceRootNotFoundError, Workspaces } from "@effected/workspaces";
8
5
 
9
6
  // src/meta/bundle-source.ts
@@ -25,82 +22,69 @@ var BundleManifestSourceError = class extends Data.TaggedError("BundleManifestSo
25
22
  * @internal
26
23
  */
27
24
  const RETIRED_MANIFEST_FILENAME = "tsdoctor.json";
28
- /** Bound once: the platform layer is stateless and layers memoize by reference. */
29
- const platform = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer);
30
25
  /** The canonical absolute form of a directory, so a relative or symlinked `cwd` compares equal to the discovered root. */
31
- function canonical(dir) {
32
- const absolute = resolve(dir);
33
- try {
34
- return realpathSync(absolute);
35
- } catch {
36
- return absolute;
37
- }
38
- }
39
- /** `Effect.runPromise` rejects with the failure itself or with a `FiberFailure` wrapping it; check both. */
40
- function isRootNotFound(cause) {
41
- if (cause instanceof WorkspaceRootNotFoundError) return true;
42
- return typeof cause === "object" && cause !== null && "_tag" in cause && cause._tag === "WorkspaceRootNotFoundError";
43
- }
26
+ const canonical = (dir) => Effect.gen(function* () {
27
+ const absolute = (yield* Path.Path).resolve(dir);
28
+ return yield* (yield* FileSystem.FileSystem).realPath(absolute).pipe(Effect.orElseSucceed(() => absolute));
29
+ });
44
30
  /**
45
31
  * The workspace root containing `cwd`, or the reason discovery failed. A package outside any
46
32
  * workspace is the `root: undefined` case with no failure. Mirrors the `WorkspaceDiscovery`
47
33
  * invocation in `changesets/next-versions.ts`.
48
34
  */
49
- async function findWorkspaceRoot(cwd) {
50
- try {
51
- const packages = await Effect.runPromise(Effect.gen(function* () {
52
- return yield* (yield* WorkspaceDiscovery).listPackages();
53
- }).pipe(Effect.provide(Workspaces.layer({ cwd }).pipe(Layer.provide(platform)))));
54
- return { root: packages[0]?.isRootWorkspace ? packages[0].path : void 0 };
55
- } catch (cause) {
56
- if (isRootNotFound(cause)) return { root: void 0 };
57
- return {
58
- root: void 0,
59
- failure: cause instanceof Error ? cause.message : String(cause)
60
- };
61
- }
62
- }
63
- async function readSource(path) {
64
- if (!existsSync(path)) return void 0;
65
- let parsed;
66
- try {
67
- parsed = JSON.parse(readFileSync(path, "utf-8"));
68
- } catch (cause) {
69
- throw new BundleManifestSourceError({
35
+ const findWorkspaceRoot = (cwd) => Effect.flatMap(WorkspaceDiscovery, (discovery) => discovery.listPackages()).pipe(Effect.provide(Workspaces.layer({ cwd })), Effect.map((packages) => ({ root: packages[0]?.isRootWorkspace ? packages[0].path : void 0 })), Effect.catchCause((cause) => {
36
+ if (Cause.hasInterruptsOnly(cause)) return Effect.interrupt;
37
+ const error = Cause.squash(cause);
38
+ if (error instanceof WorkspaceRootNotFoundError) return Effect.succeed({ root: void 0 });
39
+ return Effect.succeed({
40
+ root: void 0,
41
+ failure: error instanceof Error ? error.message : String(error)
42
+ });
43
+ }));
44
+ const readSource = Effect.fnUntraced(function* (path) {
45
+ const fs = yield* FileSystem.FileSystem;
46
+ if (!(yield* existsLikeNode(path))) return void 0;
47
+ const text = yield* fs.readFileString(path);
48
+ const parsed = yield* Effect.try({
49
+ try: () => JSON.parse(text),
50
+ catch: (cause) => new BundleManifestSourceError({
70
51
  path,
71
52
  cause
72
- });
73
- }
74
- const result = await Effect.runPromise(Effect.result(decodeManifestSource(parsed, path)));
75
- if (result._tag === "Failure") throw new BundleManifestSourceError({
76
- path,
77
- cause: result.failure
53
+ })
78
54
  });
79
- return result.success;
80
- }
55
+ return yield* decodeManifestSource(parsed, path).pipe(Effect.mapError((cause) => new BundleManifestSourceError({
56
+ path,
57
+ cause
58
+ })));
59
+ });
81
60
  /**
82
61
  * Read the leaf (`<cwd>/bundle.json`) and project (`<workspaceRoot>/bundle.json`)
83
- * source tiers. Absence is normal; a present file that does not decode throws
62
+ * source tiers. Absence is normal; a present file that does not decode fails
84
63
  * {@link BundleManifestSourceError}. A package that IS the workspace root reads its file once, as the
85
64
  * leaf, and has no project tier.
86
65
  *
87
66
  * @public
88
67
  */
89
- async function loadBundleManifestSources(cwd) {
90
- const leafDir = canonical(cwd);
68
+ const loadBundleManifestSources = Effect.fnUntraced(function* (cwd) {
69
+ const { join } = yield* Path.Path;
70
+ const leafDir = yield* canonical(cwd);
91
71
  const tierDirs = [leafDir];
92
- const leaf = await readSource(join(leafDir, BUNDLE_MANIFEST_FILENAME));
93
- const { root, failure } = await findWorkspaceRoot(leafDir);
94
- const projectDir = root !== void 0 && canonical(root) !== leafDir ? root : void 0;
72
+ const leaf = yield* readSource(join(leafDir, BUNDLE_MANIFEST_FILENAME));
73
+ const { root, failure } = yield* findWorkspaceRoot(leafDir);
74
+ const projectDir = root !== void 0 && (yield* canonical(root)) !== leafDir ? root : void 0;
95
75
  if (projectDir !== void 0) tierDirs.push(projectDir);
96
- const project = projectDir !== void 0 ? await readSource(join(projectDir, BUNDLE_MANIFEST_FILENAME)) : void 0;
97
- const retiredSources = tierDirs.filter((dir) => !existsSync(join(dir, BUNDLE_MANIFEST_FILENAME))).map((dir) => join(dir, RETIRED_MANIFEST_FILENAME)).filter((path) => existsSync(path));
76
+ const project = projectDir !== void 0 ? yield* readSource(join(projectDir, BUNDLE_MANIFEST_FILENAME)) : void 0;
77
+ const retiredSources = [];
78
+ for (const dir of tierDirs) {
79
+ const retired = join(dir, RETIRED_MANIFEST_FILENAME);
80
+ if (!(yield* existsLikeNode(join(dir, BUNDLE_MANIFEST_FILENAME))) && (yield* existsLikeNode(retired))) retiredSources.push(retired);
81
+ }
98
82
  return {
99
83
  leaf,
100
84
  project,
101
85
  ...failure !== void 0 ? { discoveryFailure: failure } : {},
102
86
  ...retiredSources.length > 0 ? { retiredSources } : {}
103
87
  };
104
- }
88
+ });
105
89
 
106
90
  export { BundleManifestSourceError, RETIRED_MANIFEST_FILENAME, loadBundleManifestSources };
package/meta/generate.js CHANGED
@@ -8,9 +8,7 @@ import { scrubDeclarationMapsUnder } from "./scrub-declaration-maps.js";
8
8
  import { resolvePortableTsconfig } from "./tsconfig-resolver.js";
9
9
  import { writeTsdocConfig } from "./tsdoc-config.js";
10
10
  import { BUNDLE_MANIFEST_FILENAME, encodeBundleManifest } from "@effected/manifest";
11
- import { Effect } from "effect";
12
- import { copyFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
13
- import { join, resolve } from "node:path";
11
+ import { Cause, Effect, Exit, FileSystem, Path } from "effect";
14
12
 
15
13
  // src/meta/generate.ts
16
14
  function unscopedName(name) {
@@ -34,15 +32,28 @@ function manifestRepositoryOf(value) {
34
32
  * outMetaDir (`<unscoped>.api.json` + the final `package.json` + a portable `tsconfig.json`),
35
33
  * copying that trio into each localPaths dir. The api-extractor `tsdoc-metadata.json` is a
36
34
  * published-package artifact and is written into `dtsDir` (the built pkg/), not the meta bundle.
35
+ *
36
+ * Its own reads and writes go through `FileSystem` and `Path`; API Extractor reads the host disk. It fails with
37
+ * whatever failed: an API Extractor throw, a {@link BundleManifestEmitError}, an {@link OgGenerateError} or a
38
+ * `PlatformError`.
37
39
  * @public
38
40
  */
39
- async function generateMeta(options) {
41
+ const generateMeta = Effect.fnUntraced(function* (options) {
42
+ const fs = yield* FileSystem.FileSystem;
43
+ const { join, resolve } = yield* Path.Path;
44
+ /** `rmSync(path, { force: true })`: a missing path is not a failure. */
45
+ const removeForce = (path, recursive = false) => fs.remove(path, {
46
+ recursive,
47
+ force: true
48
+ }).pipe(Effect.catchIf((e) => e.reason._tag === "NotFound", () => Effect.void));
49
+ /** The failure an effect ended with, as a thrown value: a typed failure or a defect alike. */
50
+ const attempt = (effect) => Effect.map(Effect.exit(effect), (exit) => Exit.isSuccess(exit) ? void 0 : { error: Cause.squash(exit.cause) });
40
51
  const { cwd, packageName, tsconfigPath, dtsDir, entries, exportPaths, outMetaDir, localPaths, tsdoc, manifestTransform, onMessage, ci, onSuppressed } = options;
41
52
  const aeInputDir = options.aeInputDir ?? dtsDir;
42
53
  const splitDiagnostics = aeInputDir !== dtsDir;
43
- const tsdocConfigPath = writeTsdocConfig(cwd, tsdoc);
54
+ const tsdocConfigPath = yield* writeTsdocConfig(cwd, tsdoc);
44
55
  const packageJsonPath = join(cwd, "package.json");
45
- mkdirSync(outMetaDir, { recursive: true });
56
+ yield* fs.makeDirectory(outMetaDir, { recursive: true });
46
57
  const apiJsonFilename = `${unscopedName(packageName)}.api.json`;
47
58
  const tsdocMetadataPath = join(dtsDir, "tsdoc-metadata.json");
48
59
  const entryNames = Object.keys(entries);
@@ -65,12 +76,11 @@ async function generateMeta(options) {
65
76
  const specifier = exportPath === "." ? packageName : packageName + exportPath.slice(1);
66
77
  selfReferencePaths[specifier] = [join(aeInputDir, `${entries[name]}.d.ts`)];
67
78
  }
68
- scrubDeclarationMapsUnder(dtsDir);
69
- if (splitDiagnostics) scrubDeclarationMapsUnder(aeInputDir);
79
+ yield* scrubDeclarationMapsUnder(dtsDir);
80
+ if (splitDiagnostics) yield* scrubDeclarationMapsUnder(aeInputDir);
70
81
  for (const entryName of entryNames) {
71
82
  const modelEntryDts = join(dtsDir, `${entries[entryName]}.d.ts`);
72
- const safeEntry = entryName.replace(/[\\/]/g, "__");
73
- const perEntryApiJson = join(outMetaDir, `${safeEntry}.entry.api.json`);
83
+ const perEntryApiJson = join(outMetaDir, `${entryName.replace(/[\\/]/g, "__")}.entry.api.json`);
74
84
  intermediateApiJsons.push(perEntryApiJson);
75
85
  const isMain = exportPathFor(entryName) === ".";
76
86
  const captureRollupOnlyFatal = splitDiagnostics && onMessage !== void 0;
@@ -83,32 +93,27 @@ async function generateMeta(options) {
83
93
  const runAOnMessage = captureRollupOnlyFatal ? (entry) => {
84
94
  if (isCapturedFatal(entry)) rollupFatal.push(entry);
85
95
  } : () => {};
86
- let runAFailure;
87
- try {
88
- runApiExtractor({
89
- cwd,
90
- packageJsonPath,
91
- entryDtsPath: modelEntryDts,
92
- tsconfigPath,
93
- tsdocConfigPath,
94
- apiJsonPath: perEntryApiJson,
95
- ...isMain && !mainEntryDidTsdocMetadata ? { tsdocMetadataPath } : {},
96
- suppressWarnings: tsdoc.suppressWarnings,
97
- ...ci !== void 0 ? { ci } : {},
98
- ...splitDiagnostics ? {
99
- onMessage: runAOnMessage,
100
- ...captureRollupSuppressed ? { onSuppressed: (entry) => {
101
- rollupSuppressed.push(entry);
102
- } } : {}
103
- } : {
104
- ...onMessage !== void 0 ? { onMessage } : {},
105
- ...onSuppressed !== void 0 ? { onSuppressed } : {}
106
- }
107
- });
108
- } catch (err) {
109
- if (!splitDiagnostics) throw err;
110
- runAFailure = { error: err };
111
- }
96
+ const runAFailure = yield* attempt(runApiExtractor({
97
+ cwd,
98
+ packageJsonPath,
99
+ entryDtsPath: modelEntryDts,
100
+ tsconfigPath,
101
+ tsdocConfigPath,
102
+ apiJsonPath: perEntryApiJson,
103
+ ...isMain && !mainEntryDidTsdocMetadata ? { tsdocMetadataPath } : {},
104
+ suppressWarnings: tsdoc.suppressWarnings,
105
+ ...ci !== void 0 ? { ci } : {},
106
+ ...splitDiagnostics ? {
107
+ onMessage: runAOnMessage,
108
+ ...captureRollupSuppressed ? { onSuppressed: (entry) => {
109
+ rollupSuppressed.push(entry);
110
+ } } : {}
111
+ } : {
112
+ ...onMessage !== void 0 ? { onMessage } : {},
113
+ ...onSuppressed !== void 0 ? { onSuppressed } : {}
114
+ }
115
+ }));
116
+ if (runAFailure !== void 0 && !splitDiagnostics) return yield* Effect.fail(runAFailure.error);
112
117
  if (splitDiagnostics) {
113
118
  const runBOnMessage = captureRollupOnlyFatal && onMessage !== void 0 ? (entry) => {
114
119
  if (isCapturedFatal(entry) || entry.ciFatal === true) runBReported.add(diagnosticKey(entry));
@@ -122,31 +127,28 @@ async function generateMeta(options) {
122
127
  level: "error"
123
128
  });
124
129
  } : onMessage;
125
- try {
126
- runApiExtractor({
127
- cwd,
128
- packageJsonPath,
129
- entryDtsPath: join(aeInputDir, `${entries[entryName]}.d.ts`),
130
- tsconfigPath,
131
- tsdocConfigPath,
132
- apiJsonPath: perEntryApiJson,
133
- emitDocModel: false,
134
- selfReferencePaths,
135
- suppressWarnings: tsdoc.suppressWarnings,
136
- ...runBOnMessage !== void 0 ? { onMessage: runBOnMessage } : {},
137
- ...onSuppressed !== void 0 ? { onSuppressed: (entry) => {
138
- runBSuppressed.add(diagnosticKey(entry));
139
- onSuppressed(entry);
140
- } } : {}
141
- });
142
- } catch (err) {
143
- if (onMessage !== void 0) onMessage({
144
- source: "api-extractor",
145
- level: "warn",
146
- code: "diagnostics-harvest-failed",
147
- text: `Could not harvest per-module source locations for "${entryName}": ${String(err)}`
148
- });
149
- }
130
+ const runBFailure = yield* attempt(runApiExtractor({
131
+ cwd,
132
+ packageJsonPath,
133
+ entryDtsPath: join(aeInputDir, `${entries[entryName]}.d.ts`),
134
+ tsconfigPath,
135
+ tsdocConfigPath,
136
+ apiJsonPath: perEntryApiJson,
137
+ emitDocModel: false,
138
+ selfReferencePaths,
139
+ suppressWarnings: tsdoc.suppressWarnings,
140
+ ...runBOnMessage !== void 0 ? { onMessage: runBOnMessage } : {},
141
+ ...onSuppressed !== void 0 ? { onSuppressed: (entry) => {
142
+ runBSuppressed.add(diagnosticKey(entry));
143
+ onSuppressed(entry);
144
+ } } : {}
145
+ }));
146
+ if (runBFailure !== void 0 && onMessage !== void 0) onMessage({
147
+ source: "api-extractor",
148
+ level: "warn",
149
+ code: "diagnostics-harvest-failed",
150
+ text: `Could not harvest per-module source locations for "${entryName}": ${String(runBFailure.error)}`
151
+ });
150
152
  if (captureRollupOnlyFatal && onMessage !== void 0) for (const entry of rollupFatal) {
151
153
  if (runBReported.has(diagnosticKey(entry))) continue;
152
154
  onMessage(stripLocation(entry));
@@ -161,11 +163,11 @@ async function generateMeta(options) {
161
163
  continue;
162
164
  }
163
165
  if (isMain) mainEntryDidTsdocMetadata = true;
164
- perEntryModels.set(entryName, JSON.parse(readFileSync(perEntryApiJson, "utf-8")));
166
+ perEntryModels.set(entryName, JSON.parse(yield* fs.readFileString(perEntryApiJson)));
165
167
  }
166
168
  if (firstFailure !== void 0) {
167
- for (const intermediate of intermediateApiJsons) rmSync(intermediate, { force: true });
168
- throw firstFailure.error;
169
+ for (const intermediate of intermediateApiJsons) yield* removeForce(intermediate);
170
+ return yield* Effect.fail(firstFailure.error);
169
171
  }
170
172
  const finalModel = perEntryModels.size === 1 ? perEntryModels.values().next().value : mergeApiModels({
171
173
  perEntryModels,
@@ -173,21 +175,18 @@ async function generateMeta(options) {
173
175
  exportPaths
174
176
  });
175
177
  const apiJsonPath = join(outMetaDir, apiJsonFilename);
176
- writeFileSync(apiJsonPath, `${JSON.stringify(finalModel, null, 2)}\n`, "utf-8");
177
- for (const intermediate of intermediateApiJsons) rmSync(intermediate, { force: true });
178
+ yield* fs.writeFileString(apiJsonPath, `${JSON.stringify(finalModel, null, 2)}\n`);
179
+ for (const intermediate of intermediateApiJsons) yield* removeForce(intermediate);
178
180
  const bundlePackageJson = join(outMetaDir, "package.json");
179
- const builtPkg = JSON.parse(readFileSync(join(dtsDir, "package.json"), "utf-8"));
181
+ const builtPkg = JSON.parse(yield* fs.readFileString(join(dtsDir, "package.json")));
180
182
  const finalPkg = manifestTransform ? manifestTransform(builtPkg) : builtPkg;
181
- writeFileSync(bundlePackageJson, `${JSON.stringify(finalPkg, null, 2)}\n`, "utf-8");
183
+ yield* fs.writeFileString(bundlePackageJson, `${JSON.stringify(finalPkg, null, 2)}\n`);
182
184
  const bundleTsconfig = join(outMetaDir, "tsconfig.json");
183
- const portableTsconfig = resolvePortableTsconfig(cwd, tsconfigPath);
184
- writeFileSync(bundleTsconfig, `${JSON.stringify(portableTsconfig, null, 2)}\n`, "utf-8");
185
- rmSync(join(outMetaDir, BUNDLE_MANIFEST_FILENAME), { force: true });
186
- rmSync(join(outMetaDir, RETIRED_MANIFEST_FILENAME), { force: true });
187
- rmSync(join(outMetaDir, "og"), {
188
- recursive: true,
189
- force: true
190
- });
185
+ const portableTsconfig = yield* resolvePortableTsconfig(cwd, tsconfigPath);
186
+ yield* fs.writeFileString(bundleTsconfig, `${JSON.stringify(portableTsconfig, null, 2)}\n`);
187
+ yield* removeForce(join(outMetaDir, BUNDLE_MANIFEST_FILENAME));
188
+ yield* removeForce(join(outMetaDir, RETIRED_MANIFEST_FILENAME));
189
+ yield* removeForce(join(outMetaDir, "og"), true);
191
190
  let manifestPath;
192
191
  let generatedImageRelative;
193
192
  if (options.bundle !== void 0) {
@@ -204,7 +203,7 @@ async function generateMeta(options) {
204
203
  const generate = options.bundle.config?.openGraph?.generate;
205
204
  if (generate !== void 0) {
206
205
  const cacheSalt = resolveOgCacheSalt(generate, options.bundle.config?.openGraph?.cacheSalt);
207
- const generated = await writeGeneratedOgImage({
206
+ const generated = yield* writeGeneratedOgImage({
208
207
  generate,
209
208
  info: ogImageInfoOf({
210
209
  ...composeInput,
@@ -223,41 +222,33 @@ async function generateMeta(options) {
223
222
  const manifest = composeBundleManifest(composeInput);
224
223
  if (manifest !== void 0) {
225
224
  const path = join(outMetaDir, BUNDLE_MANIFEST_FILENAME);
226
- try {
227
- const encoded = await Effect.runPromise(encodeBundleManifest(manifest));
228
- writeFileSync(path, `${JSON.stringify(encoded, null, 2)}\n`, "utf-8");
229
- } catch (cause) {
230
- throw new BundleManifestEmitError({
231
- packageName,
232
- path,
233
- cause
234
- });
235
- }
225
+ yield* encodeBundleManifest(manifest).pipe(Effect.flatMap((encoded) => fs.writeFileString(path, `${JSON.stringify(encoded, null, 2)}\n`)), Effect.mapError((cause) => new BundleManifestEmitError({
226
+ packageName,
227
+ path,
228
+ cause
229
+ })));
236
230
  manifestPath = path;
237
231
  }
238
232
  }
239
233
  for (const localPath of localPaths) {
240
234
  const dest = resolve(cwd, localPath);
241
- mkdirSync(dest, { recursive: true });
242
- copyFileSync(apiJsonPath, join(dest, apiJsonFilename));
243
- copyFileSync(bundlePackageJson, join(dest, "package.json"));
244
- copyFileSync(bundleTsconfig, join(dest, "tsconfig.json"));
245
- if (manifestPath !== void 0) copyFileSync(manifestPath, join(dest, BUNDLE_MANIFEST_FILENAME));
246
- else rmSync(join(dest, BUNDLE_MANIFEST_FILENAME), { force: true });
247
- rmSync(join(dest, RETIRED_MANIFEST_FILENAME), { force: true });
248
- rmSync(join(dest, "og"), {
249
- recursive: true,
250
- force: true
251
- });
235
+ yield* fs.makeDirectory(dest, { recursive: true });
236
+ yield* fs.copyFile(apiJsonPath, join(dest, apiJsonFilename));
237
+ yield* fs.copyFile(bundlePackageJson, join(dest, "package.json"));
238
+ yield* fs.copyFile(bundleTsconfig, join(dest, "tsconfig.json"));
239
+ if (manifestPath !== void 0) yield* fs.copyFile(manifestPath, join(dest, BUNDLE_MANIFEST_FILENAME));
240
+ else yield* removeForce(join(dest, BUNDLE_MANIFEST_FILENAME));
241
+ yield* removeForce(join(dest, RETIRED_MANIFEST_FILENAME));
242
+ yield* removeForce(join(dest, "og"), true);
252
243
  if (generatedImageRelative !== void 0) {
253
- mkdirSync(join(dest, "og"), { recursive: true });
254
- copyFileSync(join(outMetaDir, generatedImageRelative), join(dest, generatedImageRelative));
244
+ yield* fs.makeDirectory(join(dest, "og"), { recursive: true });
245
+ yield* fs.copyFile(join(outMetaDir, generatedImageRelative), join(dest, generatedImageRelative));
255
246
  }
256
247
  }
257
248
  return {
258
249
  apiJsonPath,
259
250
  apiJsonFilename
260
251
  };
261
- }
252
+ });
262
253
 
263
254
  export { generateMeta };
package/meta/og-image.js CHANGED
@@ -1,9 +1,6 @@
1
1
  import { causeMessage } from "../internal/causeMessage.js";
2
- import { Data, Effect, Layer, Option, Predicate, Result, Schema } from "effect";
3
- import { mkdirSync, writeFileSync } from "node:fs";
4
- import { join } from "node:path";
2
+ import { Data, Effect, FileSystem, Layer, Option, Path, Predicate, Schema } from "effect";
5
3
  import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
6
- import * as NodeServices from "@effect/platform-node/NodeServices";
7
4
  import { ImageBackend, ImageCache, ImageCacheKey } from "@effected/images/cache";
8
5
 
9
6
  // src/meta/og-image.ts
@@ -98,40 +95,37 @@ function resolveOgCacheSalt(generate, cacheSalt) {
98
95
  *
99
96
  * @public
100
97
  */
101
- async function writeGeneratedOgImage(options) {
98
+ const writeGeneratedOgImage = (options) => {
102
99
  const { packageName } = options.info;
103
100
  const backend = options.cache === void 0 ? ImageBackend.layerNone : tolerantDirectory(options.cache.directory);
104
- const result = await Effect.gen(function* () {
105
- const key = yield* ImageCacheKey.fromParams(OgImageInfoKey, options.info, {
106
- salt: options.cache?.salt ?? "",
107
- namespace: "og"
108
- });
109
- return yield* (yield* ImageCache).getOrGenerate(key, () => Effect.tryPromise({
110
- try: () => options.generate(options.info),
111
- catch: (cause) => cause
112
- }), { accept: ACCEPT });
113
- }).pipe(Effect.provide(ImageCache.layer.pipe(Layer.provide(backend), Layer.provideMerge(Layer.merge(NodeServices.layer, NodeCrypto.layerDigest)))), Effect.result, Effect.runPromise);
114
- if (Result.isFailure(result)) throw new OgGenerateError({
115
- packageName,
116
- cause: result.failure
117
- });
118
- const { bytes, facts } = result.success;
119
- const relative = `og/${options.unscopedName}.${facts.extension}`;
120
- try {
121
- mkdirSync(join(options.outMetaDir, "og"), { recursive: true });
122
- writeFileSync(join(options.outMetaDir, relative), bytes);
123
- } catch (cause) {
124
- throw new OgGenerateError({
101
+ return Effect.gen(function* () {
102
+ const { bytes, facts } = yield* Effect.gen(function* () {
103
+ const key = yield* ImageCacheKey.fromParams(OgImageInfoKey, options.info, {
104
+ salt: options.cache?.salt ?? "",
105
+ namespace: "og"
106
+ });
107
+ return yield* (yield* ImageCache).getOrGenerate(key, () => Effect.tryPromise({
108
+ try: () => options.generate(options.info),
109
+ catch: (cause) => cause
110
+ }), { accept: ACCEPT });
111
+ }).pipe(Effect.provide(ImageCache.layer.pipe(Layer.provide(backend), Layer.provideMerge(NodeCrypto.layerDigest))), Effect.mapError((cause) => new OgGenerateError({
125
112
  packageName,
126
113
  cause
127
- });
128
- }
129
- return {
130
- path: relative,
131
- type: facts.mimeType,
132
- width: facts.width,
133
- height: facts.height
134
- };
135
- }
114
+ })));
115
+ const fs = yield* FileSystem.FileSystem;
116
+ const { join } = yield* Path.Path;
117
+ const relative = `og/${options.unscopedName}.${facts.extension}`;
118
+ yield* fs.makeDirectory(join(options.outMetaDir, "og"), { recursive: true }).pipe(Effect.andThen(fs.writeFile(join(options.outMetaDir, relative), bytes)), Effect.mapError((cause) => new OgGenerateError({
119
+ packageName,
120
+ cause
121
+ })));
122
+ return {
123
+ path: relative,
124
+ type: facts.mimeType,
125
+ width: facts.width,
126
+ height: facts.height
127
+ };
128
+ });
129
+ };
136
130
 
137
131
  export { OgGenerateError, resolveOgCacheSalt, resolveOgGenerator, writeGeneratedOgImage };
package/meta/og-satori.js CHANGED
@@ -6,10 +6,16 @@ import { readFile } from "node:fs/promises";
6
6
  // src/meta/og-satori.ts
7
7
  /**
8
8
  * The bundled Inter SemiBold face (SIL OFL 1.1; see `assets/LICENSE-Inter.txt`). Resolved
9
- * relative to THIS module: the built `meta/og-satori.js` reaches `assets/` at the package root, while
10
- * the source `src/meta/og-satori.ts` reaches it through `public/`, so both candidates are tried.
9
+ * relative to THIS module: the built `meta/og-satori.js` reaches `assets/` at the package root, the
10
+ * source `src/meta/og-satori.ts` reaches it through `public/`, and a package that inlines the bundler
11
+ * into a file at its own root, as `@effected/plugin` does, ships `assets/` beside that file, so all
12
+ * three candidates are tried.
11
13
  */
12
- const FONT_CANDIDATES = [new URL("../assets/Inter-SemiBold.ttf", import.meta.url), new URL("../../public/assets/Inter-SemiBold.ttf", import.meta.url)];
14
+ const FONT_CANDIDATES = [
15
+ new URL("../assets/Inter-SemiBold.ttf", import.meta.url),
16
+ new URL("../../public/assets/Inter-SemiBold.ttf", import.meta.url),
17
+ new URL("./assets/Inter-SemiBold.ttf", import.meta.url)
18
+ ];
13
19
  function fontPath() {
14
20
  for (const candidate of FONT_CANDIDATES) {
15
21
  const path = fileURLToPath(candidate);
@@ -111,7 +117,7 @@ const ogImage = { satori(options = {}) {
111
117
  };
112
118
  const cacheSalt = JSON.stringify({
113
119
  renderer: "@effected/bundler/og#satori",
114
- version: "0.4.1",
120
+ version: "0.5.0",
115
121
  satori: peerVersion("satori"),
116
122
  resvg: peerVersion("@resvg/resvg-js"),
117
123
  colors
package/meta/run-pass.js CHANGED
@@ -8,16 +8,24 @@ import { normalizeMetaOptions } from "./config.js";
8
8
  import { generateMeta } from "./generate.js";
9
9
  import { OgGenerateError } from "./og-image.js";
10
10
  import { rewriteMetaVersions } from "./optimistic.js";
11
- import { join } from "node:path";
11
+ import { Cause, Effect, Path } from "effect";
12
12
 
13
13
  // src/meta/run-pass.ts
14
14
  /**
15
15
  * Meta-pass orchestrator: derives export paths, filters bin/ entries, resolves optimistic
16
16
  * next-versions, and calls generateMeta once per publish group.
17
+ *
18
+ * The injected `generateMeta`, `resolveNextVersions` and `loadBundleManifestSources` stay promise-returning, and a
19
+ * rejection of one is a failure carrying the rejected value; the real ones are effects over `FileSystem` and `Path`.
17
20
  * @public
18
21
  */
19
- async function runMetaPass(o) {
20
- const gen = o.generateMeta ?? generateMeta;
22
+ const runMetaPass = Effect.fnUntraced(function* (o) {
23
+ const { join } = yield* Path.Path;
24
+ const fromPromise = (run) => Effect.tryPromise({
25
+ try: run,
26
+ catch: (e) => e
27
+ });
28
+ const gen = (options) => o.generateMeta !== void 0 ? fromPromise(() => o.generateMeta?.(options)) : generateMeta(options);
21
29
  const norm = normalizeMetaOptions(o.meta);
22
30
  const canonicalId = (o.groups.find((g) => g.name === o.packageName) ?? o.groups[0])?.id ?? "npm";
23
31
  const dtsBasenames = {};
@@ -28,23 +36,21 @@ async function runMetaPass(o) {
28
36
  }
29
37
  const exportPaths = deriveExportPaths(nonBinEntries, o.exportsMap);
30
38
  applySubdirMetaEntries(o.overrides, dtsBasenames, exportPaths);
31
- const resolveNext = o.resolveNextVersions ?? resolveNextVersions;
32
- const nextVersions = norm.optimistic ? await resolveNext(o.cwd) : void 0;
39
+ const resolveNext = o.resolveNextVersions;
40
+ const nextVersions = norm.optimistic ? resolveNext !== void 0 ? yield* fromPromise(() => resolveNext(o.cwd)) : yield* resolveNextVersions(o.cwd) : void 0;
33
41
  const manifestTransform = nextVersions ? (m) => rewriteMetaVersions(m, nextVersions.versions, o.packageName) : void 0;
34
- const loadSources = o.loadBundleManifestSources ?? loadBundleManifestSources;
35
- let sources;
36
- try {
37
- sources = await loadSources(o.cwd);
38
- } catch (err) {
39
- if (err instanceof BundleManifestSourceError) for (const g of o.groups) o.collector.recordError(g.id, {
42
+ const loadSources = o.loadBundleManifestSources;
43
+ const sources = yield* (loadSources !== void 0 ? fromPromise(() => loadSources(o.cwd)) : loadBundleManifestSources(o.cwd)).pipe(Effect.tapCause((cause) => Effect.sync(() => {
44
+ const err = Cause.squash(cause);
45
+ if (!(err instanceof BundleManifestSourceError)) return;
46
+ for (const g of o.groups) o.collector.recordError(g.id, {
40
47
  source: "meta",
41
48
  level: "error",
42
49
  code: "bundle-manifest-source-invalid",
43
50
  text: err.message,
44
51
  file: err.path
45
52
  });
46
- throw err;
47
- }
53
+ })));
48
54
  if (sources.discoveryFailure !== void 0) for (const g of o.groups) o.collector.recordWarning(g.id, {
49
55
  source: "meta",
50
56
  level: "warn",
@@ -63,30 +69,29 @@ async function runMetaPass(o) {
63
69
  name: t.id,
64
70
  registry: t.registry
65
71
  }));
66
- try {
67
- await gen({
68
- cwd: o.cwd,
69
- packageName: o.packageName,
70
- tsconfigPath: o.tsconfigPath,
71
- dtsDir: join(o.cwd, "dist", "prod", g.id, "pkg"),
72
- aeInputDir: declarationsDirFor(o.cwd, g.id),
73
- entries: dtsBasenames,
74
- exportPaths,
75
- outMetaDir: join(o.cwd, "dist", "prod", g.id, "meta"),
76
- localPaths: g.id === canonicalId ? norm.localPaths : [],
77
- tsdoc: norm.tsdoc,
78
- ...manifestTransform !== void 0 ? { manifestTransform } : {},
79
- ci: o.ci,
80
- bundle: {
81
- config: norm.bundle,
82
- leaf: sources.leaf,
83
- project: sources.project,
84
- targets
85
- },
86
- onMessage: (e) => e.level === "error" ? o.collector.recordError(g.id, e) : o.collector.recordWarning(g.id, e),
87
- onSuppressed: (e) => o.collector.recordSuppressed(g.id, e)
88
- });
89
- } catch (err) {
72
+ yield* gen({
73
+ cwd: o.cwd,
74
+ packageName: o.packageName,
75
+ tsconfigPath: o.tsconfigPath,
76
+ dtsDir: join(o.cwd, "dist", "prod", g.id, "pkg"),
77
+ aeInputDir: declarationsDirFor(o.cwd, g.id),
78
+ entries: dtsBasenames,
79
+ exportPaths,
80
+ outMetaDir: join(o.cwd, "dist", "prod", g.id, "meta"),
81
+ localPaths: g.id === canonicalId ? norm.localPaths : [],
82
+ tsdoc: norm.tsdoc,
83
+ ...manifestTransform !== void 0 ? { manifestTransform } : {},
84
+ ci: o.ci,
85
+ bundle: {
86
+ config: norm.bundle,
87
+ leaf: sources.leaf,
88
+ project: sources.project,
89
+ targets
90
+ },
91
+ onMessage: (e) => e.level === "error" ? o.collector.recordError(g.id, e) : o.collector.recordWarning(g.id, e),
92
+ onSuppressed: (e) => o.collector.recordSuppressed(g.id, e)
93
+ }).pipe(Effect.tapCause((cause) => Effect.sync(() => {
94
+ const err = Cause.squash(cause);
90
95
  if (err instanceof OgGenerateError) o.collector.recordError(g.id, {
91
96
  source: "meta",
92
97
  level: "error",
@@ -100,10 +105,9 @@ async function runMetaPass(o) {
100
105
  text: err.message,
101
106
  file: err.path
102
107
  });
103
- throw err;
104
- }
108
+ })));
105
109
  }
106
- }
110
+ });
107
111
  /**
108
112
  * For each `outSubdir` override, point its meta entry at the isolated sub-package barrel.
109
113
  *