@solcreek/adapter-next-core 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # @solcreek/adapter-next-core
2
+
3
+ Next.js-specific adapter utilities shared between:
4
+
5
+ - [`@solcreek/adapter-creek`](https://github.com/solcreek/adapter-creek) — Next.js → Cloudflare Workers
6
+ - [`@solcreek/adapter-creekd`](https://github.com/solcreek/adapter-creekd) — Next.js → [`creekd`](https://github.com/solcreek/creekd) self-host
7
+
8
+ These helpers used to live in `@solcreek/adapter-core` alongside framework-neutral types like `DeployManifestBase` and `findRepoRoot`. They moved out so non-Next adapters (e.g. [`@solcreek/svelte-adapter`](https://github.com/solcreek/svelte-adapter), future Vue / Solid adapters) can depend on a clean `adapter-core` without inheriting Next.js's transpilation / cacheHandler / config-mutation surface.
9
+
10
+ ## What's in here
11
+
12
+ | Export | Purpose |
13
+ |---|---|
14
+ | `applyBaseModifyConfig` | Shared `next.config` mutations every Next adapter needs: auto-transpile JSX-in-JS deps, monorepo `outputFileTracingRoot`, TS error suppression, `cacheHandler` wire-up. |
15
+ | `detectPackagesNeedingTranspile`, `collectEntryFiles`, `looksLikeJsxInJs` | Heuristic JSX-in-JS detection across the user's dep tree, used to seed `next.config.transpilePackages`. |
16
+ | `CacheHandler` (default export from `@solcreek/adapter-next-core/cache-handler`) | In-memory ISR / fetch-cache handler suitable for single-instance Next deployments. Adapters wire it in via `next.config.cacheHandler`. Tag-based stale-while-revalidate behaviour matches [opennextjs-cloudflare#1168](https://github.com/opennextjs/opennextjs-cloudflare/issues/1168). |
17
+
18
+ Persistent / cross-instance caches (KV, SQLite, Durable Objects) are out of scope here. Adapters that need one ship their own and point `cacheHandler` at it; this package's handler is the lightweight default.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pnpm add @solcreek/adapter-next-core
24
+ ```
25
+
26
+ Peer dependency: `next >= 15` (optional — only required if you use `applyBaseModifyConfig`).
27
+
28
+ ## Usage
29
+
30
+ ```ts
31
+ import type { NextAdapter } from "next";
32
+ import {
33
+ applyBaseModifyConfig,
34
+ type BaseModifyConfigOptions,
35
+ } from "@solcreek/adapter-next-core";
36
+
37
+ export function createAdapter(options: MyAdapterOptions): NextAdapter {
38
+ return {
39
+ name: "my-adapter",
40
+ modifyConfig(config, ctx) {
41
+ const baseConfig = applyBaseModifyConfig(config, ctx, {
42
+ logLabel: "My Adapter",
43
+ cacheHandlerPath: require.resolve("@solcreek/adapter-next-core/cache-handler"),
44
+ });
45
+ // ... target-specific mutations on top of baseConfig
46
+ return baseConfig;
47
+ },
48
+ // ...
49
+ };
50
+ }
51
+ ```
52
+
53
+ `./cache-handler` is a separate subpath export because `next.config.cacheHandler` requires a path-resolvable module specifier — Next loads the handler by `require(modulePath)`, not by JS import.
54
+
55
+ ## Relationship to `@solcreek/adapter-core`
56
+
57
+ `adapter-core` is intentionally framework-neutral after the split:
58
+
59
+ - `findRepoRoot` (monorepo workspace traversal) — still in `adapter-core` because it's not Next-specific
60
+ - `DeployManifestBase` (cross-target manifest shape) — still in `adapter-core`
61
+ - `CreekdDeployManifest` (creekd-specific manifest types) — moved to [`@solcreek/creekd-manifest`](https://www.npmjs.com/package/@solcreek/creekd-manifest)
62
+ - Next-specific helpers (this package's surface) — moved here
63
+
64
+ Layering: `adapter-next-core → adapter-core` (no cycle). Non-Next adapters depend only on `adapter-core`.
65
+
66
+ ## License
67
+
68
+ Apache-2.0
@@ -0,0 +1,33 @@
1
+ import type { NextAdapter } from "next";
2
+ type ModifyConfigFn = NonNullable<NextAdapter["modifyConfig"]>;
3
+ type NextConfig = Parameters<ModifyConfigFn>[0];
4
+ type ModifyConfigCtx = Parameters<ModifyConfigFn>[1];
5
+ /**
6
+ * Options for `applyBaseModifyConfig`. Adapters pass their package name
7
+ * so the auto-transpile log line credits the right tool, and the path
8
+ * to the cache handler they want Next.js to use (typically the one
9
+ * resolved from this package or a target-specific override).
10
+ */
11
+ export interface BaseModifyConfigOptions {
12
+ /** Display name in the log line, e.g. "Creek Adapter", "Creekd Adapter". */
13
+ logLabel?: string;
14
+ /** Absolute path to the cache handler module Next.js should load. */
15
+ cacheHandlerPath: string;
16
+ }
17
+ /**
18
+ * The portion of `NextAdapter.modifyConfig` that's identical across
19
+ * targets: pick the cache handler, auto-transpile JSX-in-JS deps,
20
+ * suppress TS errors (build-time only — type-check separately), set
21
+ * `outputFileTracingRoot` for monorepos.
22
+ *
23
+ * Caller wraps this in their own `modifyConfig` and adds whatever
24
+ * target-specific knobs they need. For CF Workers that's
25
+ * `cacheMaxMemorySize: 0` and `maxPostponedStateSize: "20mb"`; for
26
+ * creekd self-host that's `output: 'standalone'`. The base function
27
+ * stays neutral.
28
+ *
29
+ * Returns a new config object — does not mutate the input.
30
+ */
31
+ export declare function applyBaseModifyConfig(config: NextConfig, ctx: ModifyConfigCtx, opts: BaseModifyConfigOptions): NextConfig;
32
+ export {};
33
+ //# sourceMappingURL=base-config.d.ts.map
@@ -0,0 +1,89 @@
1
+ import { copyFileSync, existsSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import * as path from "node:path";
4
+ import { findRepoRoot } from "@solcreek/adapter-core";
5
+ import { detectPackagesNeedingTranspile } from "./transpile-detect.js";
6
+ /**
7
+ * The portion of `NextAdapter.modifyConfig` that's identical across
8
+ * targets: pick the cache handler, auto-transpile JSX-in-JS deps,
9
+ * suppress TS errors (build-time only — type-check separately), set
10
+ * `outputFileTracingRoot` for monorepos.
11
+ *
12
+ * Caller wraps this in their own `modifyConfig` and adds whatever
13
+ * target-specific knobs they need. For CF Workers that's
14
+ * `cacheMaxMemorySize: 0` and `maxPostponedStateSize: "20mb"`; for
15
+ * creekd self-host that's `output: 'standalone'`. The base function
16
+ * stays neutral.
17
+ *
18
+ * Returns a new config object — does not mutate the input.
19
+ */
20
+ export function applyBaseModifyConfig(config, ctx, opts) {
21
+ // Only the production-build phase needs the adapter's massaging.
22
+ // Dev / lint / typecheck phases pass through untouched.
23
+ if (ctx.phase !== "phase-production-build")
24
+ return config;
25
+ const projectDir = process.cwd();
26
+ const repoRoot = findRepoRoot(projectDir);
27
+ const isMonorepo = repoRoot !== projectDir;
28
+ const label = opts.logLabel ?? "Adapter";
29
+ // Resolve the cache handler the same way Node would resolve a require:
30
+ // walk up node_modules from projectDir until a package with the right
31
+ // name is found. This works under npm (hoisted), yarn (hoisted), AND
32
+ // pnpm (content-addressed store under .pnpm/), where the older
33
+ // hardcoded "<projectDir>/node_modules/@solcreek/adapter-core/..."
34
+ // path does NOT exist because pnpm only symlinks direct deps.
35
+ //
36
+ // Falls back to the dev-time path the adapter passed when the consumer
37
+ // tree doesn't have @solcreek/adapter-core resolvable (e.g. building
38
+ // inside the adapter monorepo itself).
39
+ let resolvedCacheHandlerPath = opts.cacheHandlerPath;
40
+ try {
41
+ const fromProject = createRequire(projectDir + "/_");
42
+ resolvedCacheHandlerPath = fromProject.resolve("@solcreek/adapter-core/cache-handler");
43
+ }
44
+ catch {
45
+ // Module not resolvable from this project — stick with the
46
+ // adapter-supplied fallback.
47
+ }
48
+ // Turbopack refuses `cacheHandler` paths outside the project tree —
49
+ // it relativizes the absolute path against the project root then joins
50
+ // to the filesystem root, which trips a "leaves the filesystem root"
51
+ // safety check (FileSystemPath::join). pnpm's realpath resolution
52
+ // routinely lands in a workspace sibling outside projectDir, so we
53
+ // copy the handler into the project as a self-contained .mjs. The
54
+ // file has no external imports, so a verbatim copy is correct.
55
+ const relToProject = path.relative(projectDir, resolvedCacheHandlerPath);
56
+ const isOutsideProject = !relToProject ||
57
+ relToProject.startsWith("..") ||
58
+ path.isAbsolute(relToProject);
59
+ if (isOutsideProject && existsSync(resolvedCacheHandlerPath)) {
60
+ const localPath = path.join(projectDir, ".solcreek-cache-handler.mjs");
61
+ try {
62
+ copyFileSync(resolvedCacheHandlerPath, localPath);
63
+ resolvedCacheHandlerPath = localPath;
64
+ }
65
+ catch (e) {
66
+ console.warn(` [${label}] Failed to mirror cache-handler into project (${e instanceof Error ? e.message : String(e)}); Turbopack builds may fail.`);
67
+ }
68
+ }
69
+ // Auto-add any direct dep that ships JSX in `.js` to transpilePackages.
70
+ const detected = detectPackagesNeedingTranspile(projectDir);
71
+ const existing = Array.isArray(config.transpilePackages)
72
+ ? config.transpilePackages
73
+ : [];
74
+ const transpilePackages = detected.length > 0 ? [...new Set([...existing, ...detected])] : existing;
75
+ if (detected.length > 0) {
76
+ console.log(` [${label}] auto-transpile: ${JSON.stringify(detected)} (JSX in .js entry)`);
77
+ }
78
+ return {
79
+ ...config,
80
+ cacheHandler: resolvedCacheHandlerPath,
81
+ // Skip TypeScript type checking during build — type-checking should
82
+ // be a separate step in CI / pre-deploy, not a hard gate on bundling.
83
+ typescript: { ...config.typescript, ignoreBuildErrors: true },
84
+ ...(transpilePackages.length > 0 && { transpilePackages }),
85
+ // Monorepo: set tracing root so Next.js traces deps from repo root.
86
+ ...(isMonorepo && { outputFileTracingRoot: repoRoot }),
87
+ };
88
+ }
89
+ //# sourceMappingURL=base-config.js.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * In-memory Next.js ISR cache handler.
3
+ *
4
+ * Implements the `cacheHandler` interface (get / set / revalidateTag /
5
+ * resetRequestCache) using a module-scoped Map. Single-instance only;
6
+ * cache state is lost on process restart.
7
+ *
8
+ * Stale-while-revalidate is supported via `tagInvalidatedAt` — when a
9
+ * tag is invalidated via revalidateTag(), subsequent get() calls
10
+ * return the existing value with `cacheState: "stale"` so Next.js can
11
+ * serve it while triggering a background re-render. This matches the
12
+ * behaviour opennextjs-cloudflare#1168 documented for self-host.
13
+ *
14
+ * Used by both @solcreek/adapter-creek and @solcreek/adapter-creekd
15
+ * as the default cacheHandler — adapters wire it into next.config via
16
+ * cacheHandler: require.resolve("@solcreek/adapter-core/cache-handler")
17
+ *
18
+ * Persistent / cross-instance caches are out of scope here; an
19
+ * adapter that needs one (e.g. CF Durable Objects, a SQLite-backed
20
+ * store) should ship its own and tell users to point cacheHandler at
21
+ * that instead.
22
+ */
23
+ export default class CacheHandler {
24
+ constructor(_ctx?: unknown);
25
+ get(key: string, _ctx?: {
26
+ kind?: string;
27
+ }): Promise<{
28
+ value: unknown;
29
+ lastModified: number;
30
+ age: number;
31
+ cacheState: "stale";
32
+ } | {
33
+ value: unknown;
34
+ lastModified: number;
35
+ age: number;
36
+ cacheState: "fresh";
37
+ } | null>;
38
+ set(key: string, data: unknown | null, ctx?: {
39
+ tags?: string[];
40
+ revalidate?: number | false;
41
+ }): Promise<void>;
42
+ revalidateTag(tag: string | string[]): Promise<void>;
43
+ resetRequestCache(): void;
44
+ }
45
+ //# sourceMappingURL=cache-handler.d.ts.map
@@ -0,0 +1,113 @@
1
+ /**
2
+ * In-memory Next.js ISR cache handler.
3
+ *
4
+ * Implements the `cacheHandler` interface (get / set / revalidateTag /
5
+ * resetRequestCache) using a module-scoped Map. Single-instance only;
6
+ * cache state is lost on process restart.
7
+ *
8
+ * Stale-while-revalidate is supported via `tagInvalidatedAt` — when a
9
+ * tag is invalidated via revalidateTag(), subsequent get() calls
10
+ * return the existing value with `cacheState: "stale"` so Next.js can
11
+ * serve it while triggering a background re-render. This matches the
12
+ * behaviour opennextjs-cloudflare#1168 documented for self-host.
13
+ *
14
+ * Used by both @solcreek/adapter-creek and @solcreek/adapter-creekd
15
+ * as the default cacheHandler — adapters wire it into next.config via
16
+ * cacheHandler: require.resolve("@solcreek/adapter-core/cache-handler")
17
+ *
18
+ * Persistent / cross-instance caches are out of scope here; an
19
+ * adapter that needs one (e.g. CF Durable Objects, a SQLite-backed
20
+ * store) should ship its own and tell users to point cacheHandler at
21
+ * that instead.
22
+ */
23
+ const cache = new Map();
24
+ const tagToKeys = new Map();
25
+ // When a tag is invalidated via revalidateTag(), we record the wall-clock
26
+ // timestamp here. Subsequent get() calls compare this against the entry's
27
+ // lastModified — if the tag was invalidated AFTER the entry was written,
28
+ // the entry is treated as stale (cacheState: "stale") rather than missing.
29
+ //
30
+ // This implements stale-while-revalidate semantics: Next.js receives the
31
+ // old value plus the stale signal and decides to serve it while triggering
32
+ // a background re-render. Aligned with opennextjs-cloudflare#1168.
33
+ const tagInvalidatedAt = new Map();
34
+ function isStaleByTags(entry) {
35
+ for (const tag of entry.tags) {
36
+ const invalidatedAt = tagInvalidatedAt.get(tag);
37
+ if (invalidatedAt !== undefined && invalidatedAt > entry.lastModified) {
38
+ return true;
39
+ }
40
+ }
41
+ return false;
42
+ }
43
+ export default class CacheHandler {
44
+ constructor(_ctx) {
45
+ // Context includes serverDistDir, dev, etc.
46
+ // Not needed for in-memory implementation.
47
+ }
48
+ async get(key, _ctx) {
49
+ const entry = cache.get(key);
50
+ if (!entry)
51
+ return null;
52
+ const age = (Date.now() - entry.lastModified) / 1000;
53
+ // Stale if either (a) any of its tags was invalidated since write, or
54
+ // (b) time-based revalidate has elapsed.
55
+ const staleByTag = isStaleByTags(entry);
56
+ const staleByTime = entry.revalidate !== undefined &&
57
+ entry.revalidate !== false &&
58
+ (entry.revalidate === 0 || age > entry.revalidate);
59
+ if (staleByTag || staleByTime) {
60
+ return {
61
+ value: entry.value,
62
+ lastModified: entry.lastModified,
63
+ age: Math.floor(age),
64
+ cacheState: "stale",
65
+ };
66
+ }
67
+ return {
68
+ value: entry.value,
69
+ lastModified: entry.lastModified,
70
+ age: Math.floor(age),
71
+ cacheState: "fresh",
72
+ };
73
+ }
74
+ async set(key, data, ctx) {
75
+ if (data === null) {
76
+ cache.delete(key);
77
+ return;
78
+ }
79
+ const tags = ctx?.tags ?? [];
80
+ const revalidate = typeof ctx?.revalidate === "number" ? ctx.revalidate : undefined;
81
+ cache.set(key, {
82
+ value: data,
83
+ lastModified: Date.now(),
84
+ tags,
85
+ revalidate,
86
+ });
87
+ // Index by tags for revalidateTag()
88
+ for (const tag of tags) {
89
+ let keys = tagToKeys.get(tag);
90
+ if (!keys) {
91
+ keys = new Set();
92
+ tagToKeys.set(tag, keys);
93
+ }
94
+ keys.add(key);
95
+ }
96
+ }
97
+ async revalidateTag(tag) {
98
+ const tags = Array.isArray(tag) ? tag : [tag];
99
+ const now = Date.now();
100
+ // Mark each tag as invalidated NOW. Existing entries become stale on
101
+ // the next get(); fresh writes (lastModified > now) are unaffected.
102
+ // We do NOT delete entries — Next.js wants to serve them as stale
103
+ // while it re-renders in the background.
104
+ for (const t of tags) {
105
+ tagInvalidatedAt.set(t, now);
106
+ }
107
+ }
108
+ resetRequestCache() {
109
+ // No per-request cache to reset in this implementation.
110
+ }
111
+ }
112
+ ;
113
+ //# sourceMappingURL=cache-handler.js.map
@@ -0,0 +1,3 @@
1
+ export { applyBaseModifyConfig, type BaseModifyConfigOptions, } from "./base-config.js";
2
+ export { collectEntryFiles, detectPackagesNeedingTranspile, looksLikeJsxInJs, } from "./transpile-detect.js";
3
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ // Package entry. Aggregates the Next.js-specific adapter utilities
2
+ // previously bundled into @solcreek/adapter-core:
3
+ //
4
+ // import {
5
+ // applyBaseModifyConfig,
6
+ // detectPackagesNeedingTranspile,
7
+ // } from "@solcreek/adapter-next-core";
8
+ //
9
+ // The CacheHandler ships as a subpath export (./cache-handler) —
10
+ // Next.js requires a path-resolvable module for
11
+ // `next.config.cacheHandler`, so hiding it behind a re-export from
12
+ // the package root would force every consumer to know the dist
13
+ // filename.
14
+ export { applyBaseModifyConfig, } from "./base-config.js";
15
+ export { collectEntryFiles, detectPackagesNeedingTranspile, looksLikeJsxInJs, } from "./transpile-detect.js";
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Detect direct dependencies whose `.js` entry files contain JSX.
3
+ *
4
+ * Turbopack (Next.js's default bundler since 15) has a regression where
5
+ * it fails to parse JSX inside `.js` files shipped by a workspace-linked
6
+ * or third-party package — the build exits with `Expected ';', got
7
+ * 'ident'`. The documented upstream fix is to add the offending package
8
+ * to `transpilePackages`; doing it here means user apps don't need to
9
+ * know.
10
+ *
11
+ * Scope: DIRECT deps only. Transitive deps are either already
12
+ * transpiled by their publisher (the common case) or reachable through
13
+ * the direct dep we pick up. Walking all of node_modules would be slow
14
+ * and catch unrelated packages.
15
+ *
16
+ * Detection: we locate each dep's `.js` entry file (via package.json's
17
+ * `main` or the conditional `exports` field) and heuristically look for
18
+ * JSX with a strong React signal. The double-condition keeps false
19
+ * positives low — a plain TS-generics function `function f<T>()`
20
+ * without React imports won't trigger. False positives cost a little
21
+ * build time; false negatives are the status quo (i.e. the bug
22
+ * resurfaces).
23
+ *
24
+ * @param projectDir absolute path to the user's Next.js project root
25
+ * @returns list of package names to add to `next.config.transpilePackages`
26
+ */
27
+ export declare function detectPackagesNeedingTranspile(projectDir: string): string[];
28
+ /**
29
+ * Pick the `.js` entry file(s) for a package. Only files that end in
30
+ * `.js` (and not `.mjs` / `.cjs`) are eligible — the others either
31
+ * indicate module-format-specific entries (where Turbopack's bug
32
+ * doesn't apply) or that the publisher already transpiled.
33
+ */
34
+ export declare function collectEntryFiles(pkgJson: Record<string, unknown>, pkgRoot: string): string[];
35
+ /**
36
+ * Heuristic: a `.js` file looks like it contains JSX if it has at least
37
+ * one JSX-ish token AND at least one React signal. Both conditions
38
+ * together keep false positives low.
39
+ */
40
+ export declare function looksLikeJsxInJs(content: string, filePath: string): boolean;
41
+ //# sourceMappingURL=transpile-detect.d.ts.map
@@ -0,0 +1,175 @@
1
+ import * as path from "node:path";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ /**
4
+ * Detect direct dependencies whose `.js` entry files contain JSX.
5
+ *
6
+ * Turbopack (Next.js's default bundler since 15) has a regression where
7
+ * it fails to parse JSX inside `.js` files shipped by a workspace-linked
8
+ * or third-party package — the build exits with `Expected ';', got
9
+ * 'ident'`. The documented upstream fix is to add the offending package
10
+ * to `transpilePackages`; doing it here means user apps don't need to
11
+ * know.
12
+ *
13
+ * Scope: DIRECT deps only. Transitive deps are either already
14
+ * transpiled by their publisher (the common case) or reachable through
15
+ * the direct dep we pick up. Walking all of node_modules would be slow
16
+ * and catch unrelated packages.
17
+ *
18
+ * Detection: we locate each dep's `.js` entry file (via package.json's
19
+ * `main` or the conditional `exports` field) and heuristically look for
20
+ * JSX with a strong React signal. The double-condition keeps false
21
+ * positives low — a plain TS-generics function `function f<T>()`
22
+ * without React imports won't trigger. False positives cost a little
23
+ * build time; false negatives are the status quo (i.e. the bug
24
+ * resurfaces).
25
+ *
26
+ * @param projectDir absolute path to the user's Next.js project root
27
+ * @returns list of package names to add to `next.config.transpilePackages`
28
+ */
29
+ export function detectPackagesNeedingTranspile(projectDir) {
30
+ let projectPkg;
31
+ try {
32
+ projectPkg = JSON.parse(readFileSync(path.join(projectDir, "package.json"), "utf-8"));
33
+ }
34
+ catch {
35
+ return [];
36
+ }
37
+ const directDeps = new Set();
38
+ for (const field of ["dependencies", "devDependencies", "peerDependencies"]) {
39
+ const map = projectPkg[field];
40
+ if (map && typeof map === "object") {
41
+ for (const name of Object.keys(map))
42
+ directDeps.add(name);
43
+ }
44
+ }
45
+ if (directDeps.size === 0)
46
+ return [];
47
+ // Don't ever try to transpile Next.js itself or the React runtimes —
48
+ // they're pre-bundled and transpilePackages on them would be an
49
+ // expensive no-op at best, a breakage at worst.
50
+ const SKIP = new Set([
51
+ "next",
52
+ "react",
53
+ "react-dom",
54
+ "react-server-dom-webpack",
55
+ "react-dom/server",
56
+ "scheduler",
57
+ "@next/routing",
58
+ "@next/swc",
59
+ "@solcreek/adapter-creek",
60
+ "@solcreek/adapter-creekd",
61
+ "@solcreek/adapter-core",
62
+ ]);
63
+ const needsTranspile = [];
64
+ for (const dep of directDeps) {
65
+ if (SKIP.has(dep))
66
+ continue;
67
+ // Ignore subpath-qualified entries that aren't real packages (shouldn't
68
+ // show up in dependencies, but be defensive).
69
+ if (dep.includes("/") && !dep.startsWith("@"))
70
+ continue;
71
+ // Locate the package root via direct node_modules path. Can't use
72
+ // `require.resolve(dep + '/package.json')` — Node's resolver honors
73
+ // the `exports` field and most packages don't expose `./package.json`.
74
+ // pnpm's flat node_modules layout hoists a symlink at
75
+ // `node_modules/<dep>` for every direct + hoisted dep, so this works
76
+ // across npm, yarn, pnpm.
77
+ const pkgRoot = path.join(projectDir, "node_modules", dep);
78
+ const pkgJsonPath = path.join(pkgRoot, "package.json");
79
+ let pkgJson;
80
+ try {
81
+ pkgJson = JSON.parse(readFileSync(pkgJsonPath, "utf-8"));
82
+ }
83
+ catch {
84
+ continue;
85
+ }
86
+ // Only `.js` entry files matter — `.mjs` / `.cjs` indicate the
87
+ // publisher already picked a module format Turbopack handles
88
+ // correctly.
89
+ const entryCandidates = collectEntryFiles(pkgJson, pkgRoot);
90
+ if (entryCandidates.length === 0)
91
+ continue;
92
+ for (const entry of entryCandidates) {
93
+ try {
94
+ const content = readFileSync(entry, "utf-8");
95
+ if (looksLikeJsxInJs(content, entry)) {
96
+ needsTranspile.push(dep);
97
+ break; // one hit is enough; move to next package
98
+ }
99
+ }
100
+ catch {
101
+ // Unreadable entry file — skip without failing the whole detect pass.
102
+ }
103
+ }
104
+ }
105
+ return needsTranspile;
106
+ }
107
+ /**
108
+ * Pick the `.js` entry file(s) for a package. Only files that end in
109
+ * `.js` (and not `.mjs` / `.cjs`) are eligible — the others either
110
+ * indicate module-format-specific entries (where Turbopack's bug
111
+ * doesn't apply) or that the publisher already transpiled.
112
+ */
113
+ export function collectEntryFiles(pkgJson, pkgRoot) {
114
+ const candidates = [];
115
+ const tryAdd = (rel) => {
116
+ if (typeof rel !== "string")
117
+ return;
118
+ if (!rel.endsWith(".js"))
119
+ return;
120
+ const abs = path.join(pkgRoot, rel.startsWith("./") ? rel.slice(2) : rel);
121
+ try {
122
+ if (statSync(abs).isFile())
123
+ candidates.push(abs);
124
+ }
125
+ catch {
126
+ // Entry declared but doesn't exist on disk — skip.
127
+ }
128
+ };
129
+ tryAdd(pkgJson.main);
130
+ // `exports` can be a string, or a nested conditional object. We walk
131
+ // the "." entry's import/require/default branches.
132
+ const exports_ = pkgJson.exports;
133
+ if (typeof exports_ === "string") {
134
+ tryAdd(exports_);
135
+ }
136
+ else if (exports_ && typeof exports_ === "object") {
137
+ const rootExport = exports_["."] ?? exports_;
138
+ if (typeof rootExport === "string") {
139
+ tryAdd(rootExport);
140
+ }
141
+ else if (rootExport && typeof rootExport === "object") {
142
+ for (const cond of ["default", "import", "require", "node", "browser"]) {
143
+ tryAdd(rootExport[cond]);
144
+ }
145
+ }
146
+ }
147
+ return [...new Set(candidates)];
148
+ }
149
+ /**
150
+ * Heuristic: a `.js` file looks like it contains JSX if it has at least
151
+ * one JSX-ish token AND at least one React signal. Both conditions
152
+ * together keep false positives low.
153
+ */
154
+ export function looksLikeJsxInJs(content, filePath) {
155
+ if (!filePath.endsWith(".js"))
156
+ return false;
157
+ const head = content.slice(0, 20_000); // cap scan cost
158
+ const JSX_HINTS = [
159
+ /return\s*\(\s*</, // return (<...
160
+ /return\s+<[A-Za-z]/, // return <Tag or <Component
161
+ /=>\s*<[A-Za-z]/, // arrow => <...
162
+ /\bcreateElement\s*\(/, // raw createElement
163
+ ];
164
+ const hasJsxHint = JSX_HINTS.some((re) => re.test(head));
165
+ if (!hasJsxHint)
166
+ return false;
167
+ const REACT_HINTS = [
168
+ /['"]use client['"]/,
169
+ /from\s+['"]react['"]/,
170
+ /require\s*\(\s*['"]react['"]\s*\)/,
171
+ /\bReact\.createElement\b/,
172
+ ];
173
+ return REACT_HINTS.some((re) => re.test(head));
174
+ }
175
+ //# sourceMappingURL=transpile-detect.js.map
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@solcreek/adapter-next-core",
3
+ "version": "0.1.0",
4
+ "description": "Next.js-specific adapter utilities shared by @solcreek/adapter-creek (CF Workers) and @solcreek/adapter-creekd (creekd self-host)",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./cache-handler": {
14
+ "default": "./dist/cache-handler.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "!dist/**/*.test.*",
20
+ "!dist/**/*.map"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "scripts": {
26
+ "build": "tsc",
27
+ "dev": "tsc --watch",
28
+ "typecheck": "tsc --noEmit",
29
+ "test": "vitest run",
30
+ "test:watch": "vitest",
31
+ "clean": "rm -rf dist"
32
+ },
33
+ "keywords": [
34
+ "creek",
35
+ "creekd",
36
+ "adapter",
37
+ "next",
38
+ "nextjs",
39
+ "cache-handler",
40
+ "self-host"
41
+ ],
42
+ "author": "SolCreek",
43
+ "license": "Apache-2.0",
44
+ "homepage": "https://creek.dev",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "https://github.com/solcreek/adapter-next-core.git"
48
+ },
49
+ "dependencies": {
50
+ "@solcreek/adapter-core": "^0.2.0"
51
+ },
52
+ "peerDependencies": {
53
+ "next": ">=15"
54
+ },
55
+ "peerDependenciesMeta": {
56
+ "next": {
57
+ "optional": true
58
+ }
59
+ },
60
+ "devDependencies": {
61
+ "@types/node": "^22.13.10",
62
+ "@types/react": "^19.2.15",
63
+ "next": "16.2.3",
64
+ "react": "19.2.6",
65
+ "react-dom": "19.2.6",
66
+ "typescript": "^5.8.2",
67
+ "vitest": "^4.1.2"
68
+ },
69
+ "packageManager": "pnpm@10.33.0"
70
+ }