zod-compiler 1.23.8 → 1.24.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/README.md +116 -12
- package/dist/runtime.d.ts +53 -0
- package/dist/runtime.js +55 -0
- package/dist/turbopack.d.ts +56 -0
- package/dist/turbopack.d.ts.map +1 -0
- package/dist/turbopack.js +200 -0
- package/dist/turbopack.js.map +1 -0
- package/dist/unplugin/dep-graph.d.ts +45 -2
- package/dist/unplugin/dep-graph.d.ts.map +1 -1
- package/dist/unplugin/dep-graph.js +42 -2
- package/dist/unplugin/dep-graph.js.map +1 -1
- package/dist/unplugin/edits.d.ts +13 -1
- package/dist/unplugin/edits.d.ts.map +1 -1
- package/dist/unplugin/edits.js +35 -1
- package/dist/unplugin/edits.js.map +1 -1
- package/dist/unplugin/hoist.d.ts.map +1 -1
- package/dist/unplugin/hoist.js +2 -26
- package/dist/unplugin/hoist.js.map +1 -1
- package/dist/unplugin/transform.d.ts.map +1 -1
- package/dist/unplugin/transform.js +38 -19
- package/dist/unplugin/transform.js.map +1 -1
- package/dist/unplugin/virtual.d.ts +28 -1
- package/dist/unplugin/virtual.d.ts.map +1 -1
- package/dist/unplugin/virtual.js +27 -1
- package/dist/unplugin/virtual.js.map +1 -1
- package/package.json +12 -1
|
@@ -4,7 +4,8 @@ import * as path$1 from "node:path";
|
|
|
4
4
|
import * as fs$1 from "node:fs";
|
|
5
5
|
//#region src/unplugin/dep-graph.ts
|
|
6
6
|
/**
|
|
7
|
-
* Static per-file dependency graphs for disk-cache invalidation
|
|
7
|
+
* Static per-file dependency graphs, for disk-cache invalidation and for the
|
|
8
|
+
* watch dependencies a loader host has to declare (see transformDependencies).
|
|
8
9
|
*
|
|
9
10
|
* The disk cache used to record `getFirstPartyModulePaths()` — the superset
|
|
10
11
|
* of EVERY first-party module the loader had executed so far — as each
|
|
@@ -247,7 +248,46 @@ function collectStaticDeps(entryFile) {
|
|
|
247
248
|
complete: true
|
|
248
249
|
};
|
|
249
250
|
}
|
|
251
|
+
/**
|
|
252
|
+
* Files whose contents can change what `id`'s transform produces — the set a
|
|
253
|
+
* host must declare as watch dependencies.
|
|
254
|
+
*
|
|
255
|
+
* Discovery EXECUTES the file's import graph, so a compiled validator reflects
|
|
256
|
+
* every constant, enum and helper that graph contributed. A host that keys its
|
|
257
|
+
* cache on `id`'s own content alone therefore serves a stale validator after an
|
|
258
|
+
* edit to any of them.
|
|
259
|
+
*
|
|
260
|
+
* Bundler plugins do not need this: their `watchChange` hook fires for every
|
|
261
|
+
* file in the project, so the plugin invalidates wholesale. Loader hosts
|
|
262
|
+
* (Turbopack, plain webpack loaders) have no such hook — their only lever is
|
|
263
|
+
* declaring dependencies per file, which is what this returns.
|
|
264
|
+
*
|
|
265
|
+
* The entry is always included, for the reason the disk cache records it too: a
|
|
266
|
+
* host keys on the content it PASSED, but discovery executed the file from disk.
|
|
267
|
+
*
|
|
268
|
+
* Deliberately NOT backed by `getFirstPartyModulePaths()` when the crawl comes
|
|
269
|
+
* up incomplete, unlike the disk cache's fallback. That superset is
|
|
270
|
+
* point-in-time, not cumulative — `invalidateModuleCache()` empties it — so
|
|
271
|
+
* after an unrelated file's discovery repopulates it, it describes THAT file's
|
|
272
|
+
* graph and can silently omit this one's. The disk cache survives that because
|
|
273
|
+
* `watchChange` invalidates wholesale and deferred entries flush against one
|
|
274
|
+
* end-of-build snapshot; a loader host has neither backstop, so a plausible but
|
|
275
|
+
* wrong list would go undetected. Reporting `complete: false` lets the caller
|
|
276
|
+
* do the sound thing instead.
|
|
277
|
+
*/
|
|
278
|
+
function transformDependencies(id) {
|
|
279
|
+
const entry = realpathOf(path$1.resolve(id));
|
|
280
|
+
const staticDeps = collectStaticDeps(entry);
|
|
281
|
+
if (!staticDeps.complete) return {
|
|
282
|
+
files: [entry],
|
|
283
|
+
complete: false
|
|
284
|
+
};
|
|
285
|
+
return {
|
|
286
|
+
files: [entry, ...staticDeps.deps.filter((d) => d !== entry)],
|
|
287
|
+
complete: true
|
|
288
|
+
};
|
|
289
|
+
}
|
|
250
290
|
//#endregion
|
|
251
|
-
export { collectStaticDeps, resetDepGraphMemo };
|
|
291
|
+
export { collectStaticDeps, resetDepGraphMemo, transformDependencies };
|
|
252
292
|
|
|
253
293
|
//# sourceMappingURL=dep-graph.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dep-graph.js","names":["path","fs"],"sources":["../../src/unplugin/dep-graph.ts"],"sourcesContent":["/**\n * Static per-file dependency graphs for disk-cache invalidation.\n *\n * The disk cache used to record `getFirstPartyModulePaths()` — the superset\n * of EVERY first-party module the loader had executed so far — as each\n * entry's dependency set. Supersets never serve stale results, but in a\n * large codebase every entry ends up recording the whole project (~1,900\n * deps, ~400KB JSON per entry in the field report), so ANY commit\n * invalidates essentially the entire cache and CI re-pays full discovery\n * every run.\n *\n * This module computes the file's ACTUAL import graph statically: scan\n * import/export/require specifiers, resolve them (relative paths with\n * extension probing, tsconfig path aliases via the loader's config, bare\n * specifiers through node resolution), and BFS across first-party files.\n * No file is executed. Type-only imports are included (over-approximation\n * only over-invalidates).\n *\n * Soundness rule: when anything cannot be analyzed — a non-literal dynamic\n * import, an unresolvable relative specifier — the crawl reports\n * `complete: false` and the caller falls back to the superset. A static\n * crawl may only replace the superset when it provably covers everything\n * the file can load.\n *\n * Cost discipline (this runs serialized on the bundler's main process, once\n * per discovery file, over closures that reach thousands of files):\n * - every existence probe uses `statSync(p, { throwIfNoEntry: false })` —\n * a thrown ENOENT pays V8 error-plus-stack construction, and a cold crawl\n * issues these probes by the million (the dominant cost in field samples);\n * - resolution is memoized at every level: realpath per path, createRequire\n * per directory, resolved specifier per (directory, specifier), and the\n * full edge list per file (mtime-validated) — repeat crawls over the\n * shared core graph are Map lookups plus one cheap stat per file;\n * - the BFS aborts the moment the graph becomes unanalyzable: the caller\n * discards an incomplete result for the superset anyway, so finishing the\n * crawl would be pure waste (and incomplete is the COMMON outcome on\n * large graphs — one dynamic import anywhere poisons the whole closure).\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { resolveTsconfigPathCandidates } from \"../loader.js\";\n\nexport interface StaticDeps {\n /** Absolute real paths of first-party files reachable from the entry. */\n deps: string[];\n /** False when the graph could not be fully analyzed — use the superset. */\n complete: boolean;\n}\n\nconst SOURCE_EXTENSIONS = [\".ts\", \".tsx\", \".mts\", \".cts\", \".js\", \".jsx\", \".mjs\", \".cjs\"];\nconst NODE_MODULES_SEGMENT = `${path.sep}node_modules${path.sep}`;\n/** Specifier schemes that never resolve to project files. */\n// oxlint-disable-next-line no-control-regex -- rollup-convention virtual module ids begin with NUL\nconst SKIP_SPECIFIER = /^(?:node:|data:|virtual:|\\u0000)/;\n/** Runaway guard — graphs larger than this fall back to the superset. */\nconst MAX_FILES = 10_000;\n\nconst INCOMPLETE: StaticDeps = { deps: [], complete: false };\n\n/**\n * Resolution-failure sentinel. A unique symbol rather than a string literal:\n * `\"incomplete\" | string` collapses to `string`, so the type system could\n * not distinguish a resolved path from the failure marker.\n */\nconst UNRESOLVED = Symbol(\"unresolved\");\n\ninterface FileNode {\n mtimeMs: number;\n /** Resolved first-party imports (absolute real paths), deduped. */\n edges: string[];\n /** Non-literal dynamic import/require or unresolvable specifier. */\n incomplete: boolean;\n}\n\n/**\n * Per-process memos. The file node memo is revalidated by mtime on every\n * visit; the resolution memos (specifier, realpath, require) depend on the\n * filesystem layout rather than file contents and are only dropped by\n * resetDepGraphMemo() — the same wholesale invalidation watch mode already\n * applies to the module cache (a memoized resolution can only go stale when\n * files appear/move, which fires watchChange).\n */\nconst nodeMemo = new Map<string, FileNode | null>();\nconst resolveMemo = new Map<string, string | null | typeof UNRESOLVED>();\nconst realpathMemo = new Map<string, string>();\nconst requireMemo = new Map<string, ReturnType<typeof createRequire>>();\n\n/** Reset the per-process dep-graph memos (watch-mode file changes). */\nexport function resetDepGraphMemo(): void {\n nodeMemo.clear();\n resolveMemo.clear();\n realpathMemo.clear();\n requireMemo.clear();\n}\n\nconst STATIC_SPECIFIER =\n /(?:\\bfrom\\s*|\\bimport\\s+|\\bimport\\s*\\(\\s*|\\brequire\\s*\\(\\s*)[\"']([^\"'\\n]+)[\"']/g;\n// No /g flag: `.test()` on a global regex resumes from lastIndex of the\n// PREVIOUS file's match, silently missing dynamic imports (a missed\n// detection records a falsely-complete dep set — stale cache).\nconst DYNAMIC_CALL = /\\b(?:import|require)\\s*\\(\\s*(?![\"'])[^)\\s]/;\n\n/** statSync that reports ENOENT as undefined instead of an exception. */\nfunction tryStat(p: string): fs.Stats | undefined {\n try {\n return fs.statSync(p, { throwIfNoEntry: false });\n } catch {\n // Non-ENOENT errors (ENOTDIR from probing `file.ts/index.ts`, EACCES):\n // treat as absent.\n return undefined;\n }\n}\n\nfunction tryFile(p: string): string | null {\n return tryStat(p)?.isFile() ? p : null;\n}\n\n/** Probe a path (possibly extensionless) to an existing file. */\nfunction probeFile(base: string): string | null {\n const hasExtension = path.extname(base) !== \"\";\n if (hasExtension) {\n if (tryFile(base)) return base;\n // Extensioned path that doesn't exist as-is: TS source referenced with a\n // .js specifier (nodenext style). Probe the extension-family swap before\n // the append/index probes — in nodenext codebases this is the common hit\n // and skips ~16 dead probes per import.\n if (/\\.[cm]?js$/.test(base)) {\n const hit =\n tryFile(base.replace(/\\.([cm]?)js$/, \".$1ts\")) ??\n tryFile(base.replace(/\\.[cm]?js$/, \".tsx\"));\n if (hit) return hit;\n }\n }\n for (const ext of SOURCE_EXTENSIONS) {\n const hit = tryFile(base + ext);\n if (hit) return hit;\n }\n for (const ext of SOURCE_EXTENSIONS) {\n const hit = tryFile(path.join(base, `index${ext}`));\n if (hit) return hit;\n }\n // Extensionless path that exists exactly (e.g. ./bin/cli).\n return hasExtension ? null : tryFile(base);\n}\n\nfunction realpathOf(p: string): string {\n let real = realpathMemo.get(p);\n if (real === undefined) {\n try {\n real = fs.realpathSync(p);\n } catch {\n real = p; // keep the unresolved path\n }\n realpathMemo.set(p, real);\n }\n return real;\n}\n\nfunction firstPartyOrNull(resolved: string): string | null {\n const real = realpathOf(resolved);\n return real.includes(NODE_MODULES_SEGMENT) ? null : real;\n}\n\n/** Node resolution is a function of the importing DIRECTORY, not the file. */\nfunction requireFor(dir: string): ReturnType<typeof createRequire> {\n let req = requireMemo.get(dir);\n if (req === undefined) {\n req = createRequire(path.join(dir, \"__zod_compiler_resolve__.js\"));\n requireMemo.set(dir, req);\n }\n return req;\n}\n\n/**\n * Resolve one specifier from a directory. Returns:\n * - an absolute path (first-party file to record + crawl)\n * - null when the dep is intentionally out of scope (node_modules, builtins)\n * - UNRESOLVED when resolution failed and the graph cannot be trusted\n */\nfunction resolveSpecifier(rawSpec: string, fromDir: string): string | null | typeof UNRESOLVED {\n if (SKIP_SPECIFIER.test(rawSpec)) return null;\n const memoKey = `${fromDir}\\0${rawSpec}`;\n const memoized = resolveMemo.get(memoKey);\n if (memoized !== undefined) return memoized;\n const result = resolveSpecifierUncached(rawSpec, fromDir);\n resolveMemo.set(memoKey, result);\n return result;\n}\n\nfunction resolveSpecifierUncached(\n rawSpec: string,\n fromDir: string,\n): string | null | typeof UNRESOLVED {\n // Vite-style resource queries (./logo.svg?url, ./shader.glsl?raw) resolve\n // to the underlying file.\n const q = rawSpec.indexOf(\"?\");\n const spec = q === -1 ? rawSpec : rawSpec.slice(0, q);\n if (spec === \"\") return null;\n\n if (spec.startsWith(\"./\") || spec.startsWith(\"../\")) {\n const hit = probeFile(path.resolve(fromDir, spec));\n return hit === null ? UNRESOLVED : firstPartyOrNull(hit);\n }\n\n const { candidates, authoritative } = resolveTsconfigPathCandidates(fromDir, spec);\n for (const candidate of candidates) {\n const hit = probeFile(candidate);\n if (hit !== null) {\n return firstPartyOrNull(hit);\n }\n }\n // An authoritative miss (explicit `paths` pattern matched, or the paths\n // config is present but uninterpretable) means the import cannot be\n // trusted. Implicit baseUrl candidates are proposed for EVERY bare\n // specifier (npm packages, `#` imports) and only mean \"try baseDir\n // first\" — a miss falls through to node resolution below.\n if (authoritative) return UNRESOLVED;\n\n // Bare specifier (package) or package.json \"imports\" (#...): node\n // resolution from the importing directory. node_modules results are out of\n // scope (zod's version is part of the cache key); symlinked workspace\n // packages realpath outside node_modules and are crawled as first-party.\n try {\n const resolved = requireFor(fromDir).resolve(spec);\n if (!path.isAbsolute(resolved)) return null; // node builtin\n return firstPartyOrNull(resolved);\n } catch {\n // Unresolvable from Node's algorithm. jiti may still resolve it (e.g.\n // ESM-only packages without CJS entries) — the file itself stays a dep\n // through the entry, but its subtree is unknown for bare packages.\n // Treat unresolvable BARE specifiers as out-of-scope third-party\n // (caught by the zod-version/plugin key when relevant) only when they\n // cannot be project files; '#' subpath imports stay strict.\n return spec.startsWith(\"#\") ? UNRESOLVED : null;\n }\n}\n\n/**\n * Scan + resolve one file into its edge list. Memoized by mtime, so the\n * shared core graph is read and resolved once per process — each entry's\n * closure walk after that is one cheap stat plus Map lookups per file.\n * Returns null for unreadable files.\n */\nfunction fileNode(filePath: string): FileNode | null {\n const stat = tryStat(filePath);\n if (stat === undefined || !stat.isFile()) {\n nodeMemo.set(filePath, null);\n return null;\n }\n const memo = nodeMemo.get(filePath);\n if (memo !== undefined && memo !== null && memo.mtimeMs === stat.mtimeMs) return memo;\n\n let source: string;\n try {\n source = fs.readFileSync(filePath, \"utf8\");\n } catch {\n nodeMemo.set(filePath, null);\n return null;\n }\n // String/comment contents can false-positive both patterns; extra\n // specifiers only add deps (safe), a false `incomplete` only falls back\n // to the superset (safe).\n let incomplete = DYNAMIC_CALL.test(source);\n const edges: string[] = [];\n const seen = new Set<string>();\n const dir = path.dirname(filePath);\n for (const m of source.matchAll(STATIC_SPECIFIER)) {\n const spec = m[1];\n if (!spec) continue;\n const resolved = resolveSpecifier(spec, dir);\n if (resolved === UNRESOLVED) {\n incomplete = true;\n } else if (resolved !== null && !seen.has(resolved)) {\n seen.add(resolved);\n edges.push(resolved);\n }\n }\n const node: FileNode = { mtimeMs: stat.mtimeMs, edges, incomplete };\n nodeMemo.set(filePath, node);\n return node;\n}\n\n/**\n * Compute the static first-party dependency closure of `entryFile`.\n * The entry itself is excluded (its content is part of the cache key).\n */\nexport function collectStaticDeps(entryFile: string): StaticDeps {\n const entry = firstPartyOrNull(path.resolve(entryFile));\n if (entry === null) return INCOMPLETE;\n\n const visited = new Set<string>([entry]);\n const queue: string[] = [entry];\n\n while (queue.length > 0) {\n if (visited.size > MAX_FILES) return INCOMPLETE;\n const file = queue.pop() as string;\n const node = fileNode(file);\n // Any unanalyzable node poisons the whole closure; the caller falls back\n // to the superset, so abort instead of crawling to exhaustion.\n if (node === null || node.incomplete) return INCOMPLETE;\n for (const dep of node.edges) {\n if (!visited.has(dep)) {\n visited.add(dep);\n queue.push(dep);\n }\n }\n }\n\n visited.delete(entry);\n return { deps: [...visited], complete: true };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAM,oBAAoB;CAAC;CAAO;CAAQ;CAAQ;CAAQ;CAAO;CAAQ;CAAQ;AAAM;AACvF,MAAM,uBAAuB,GAAGA,OAAK,IAAI,cAAcA,OAAK;;AAG5D,MAAM,iBAAiB;;AAEvB,MAAM,YAAY;AAElB,MAAM,aAAyB;CAAE,MAAM,CAAC;CAAG,UAAU;AAAM;;;;;;AAO3D,MAAM,aAAa,OAAO,YAAY;;;;;;;;;AAkBtC,MAAM,2BAAW,IAAI,IAA6B;AAClD,MAAM,8BAAc,IAAI,IAA+C;AACvE,MAAM,+BAAe,IAAI,IAAoB;AAC7C,MAAM,8BAAc,IAAI,IAA8C;;AAGtE,SAAgB,oBAA0B;CACxC,SAAS,MAAM;CACf,YAAY,MAAM;CAClB,aAAa,MAAM;CACnB,YAAY,MAAM;AACpB;AAEA,MAAM,mBACJ;AAIF,MAAM,eAAe;;AAGrB,SAAS,QAAQ,GAAiC;CAChD,IAAI;EACF,OAAOC,KAAG,SAAS,GAAG,EAAE,gBAAgB,MAAM,CAAC;CACjD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AAO;EAAG,UAAU;CAAK;AAC9C"}
|
|
1
|
+
{"version":3,"file":"dep-graph.js","names":["path","fs"],"sources":["../../src/unplugin/dep-graph.ts"],"sourcesContent":["/**\n * Static per-file dependency graphs, for disk-cache invalidation and for the\n * watch dependencies a loader host has to declare (see transformDependencies).\n *\n * The disk cache used to record `getFirstPartyModulePaths()` — the superset\n * of EVERY first-party module the loader had executed so far — as each\n * entry's dependency set. Supersets never serve stale results, but in a\n * large codebase every entry ends up recording the whole project (~1,900\n * deps, ~400KB JSON per entry in the field report), so ANY commit\n * invalidates essentially the entire cache and CI re-pays full discovery\n * every run.\n *\n * This module computes the file's ACTUAL import graph statically: scan\n * import/export/require specifiers, resolve them (relative paths with\n * extension probing, tsconfig path aliases via the loader's config, bare\n * specifiers through node resolution), and BFS across first-party files.\n * No file is executed. Type-only imports are included (over-approximation\n * only over-invalidates).\n *\n * Soundness rule: when anything cannot be analyzed — a non-literal dynamic\n * import, an unresolvable relative specifier — the crawl reports\n * `complete: false` and the caller falls back to the superset. A static\n * crawl may only replace the superset when it provably covers everything\n * the file can load.\n *\n * Cost discipline (this runs serialized on the bundler's main process, once\n * per discovery file, over closures that reach thousands of files):\n * - every existence probe uses `statSync(p, { throwIfNoEntry: false })` —\n * a thrown ENOENT pays V8 error-plus-stack construction, and a cold crawl\n * issues these probes by the million (the dominant cost in field samples);\n * - resolution is memoized at every level: realpath per path, createRequire\n * per directory, resolved specifier per (directory, specifier), and the\n * full edge list per file (mtime-validated) — repeat crawls over the\n * shared core graph are Map lookups plus one cheap stat per file;\n * - the BFS aborts the moment the graph becomes unanalyzable: the caller\n * discards an incomplete result for the superset anyway, so finishing the\n * crawl would be pure waste (and incomplete is the COMMON outcome on\n * large graphs — one dynamic import anywhere poisons the whole closure).\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { resolveTsconfigPathCandidates } from \"../loader.js\";\n\nexport interface StaticDeps {\n /** Absolute real paths of first-party files reachable from the entry. */\n deps: string[];\n /** False when the graph could not be fully analyzed — use the superset. */\n complete: boolean;\n}\n\nconst SOURCE_EXTENSIONS = [\".ts\", \".tsx\", \".mts\", \".cts\", \".js\", \".jsx\", \".mjs\", \".cjs\"];\nconst NODE_MODULES_SEGMENT = `${path.sep}node_modules${path.sep}`;\n/** Specifier schemes that never resolve to project files. */\n// oxlint-disable-next-line no-control-regex -- rollup-convention virtual module ids begin with NUL\nconst SKIP_SPECIFIER = /^(?:node:|data:|virtual:|\\u0000)/;\n/** Runaway guard — graphs larger than this fall back to the superset. */\nconst MAX_FILES = 10_000;\n\nconst INCOMPLETE: StaticDeps = { deps: [], complete: false };\n\n/**\n * Resolution-failure sentinel. A unique symbol rather than a string literal:\n * `\"incomplete\" | string` collapses to `string`, so the type system could\n * not distinguish a resolved path from the failure marker.\n */\nconst UNRESOLVED = Symbol(\"unresolved\");\n\ninterface FileNode {\n mtimeMs: number;\n /** Resolved first-party imports (absolute real paths), deduped. */\n edges: string[];\n /** Non-literal dynamic import/require or unresolvable specifier. */\n incomplete: boolean;\n}\n\n/**\n * Per-process memos. The file node memo is revalidated by mtime on every\n * visit; the resolution memos (specifier, realpath, require) depend on the\n * filesystem layout rather than file contents and are only dropped by\n * resetDepGraphMemo() — the same wholesale invalidation watch mode already\n * applies to the module cache (a memoized resolution can only go stale when\n * files appear/move, which fires watchChange).\n */\nconst nodeMemo = new Map<string, FileNode | null>();\nconst resolveMemo = new Map<string, string | null | typeof UNRESOLVED>();\nconst realpathMemo = new Map<string, string>();\nconst requireMemo = new Map<string, ReturnType<typeof createRequire>>();\n\n/** Reset the per-process dep-graph memos (watch-mode file changes). */\nexport function resetDepGraphMemo(): void {\n nodeMemo.clear();\n resolveMemo.clear();\n realpathMemo.clear();\n requireMemo.clear();\n}\n\nconst STATIC_SPECIFIER =\n /(?:\\bfrom\\s*|\\bimport\\s+|\\bimport\\s*\\(\\s*|\\brequire\\s*\\(\\s*)[\"']([^\"'\\n]+)[\"']/g;\n// No /g flag: `.test()` on a global regex resumes from lastIndex of the\n// PREVIOUS file's match, silently missing dynamic imports (a missed\n// detection records a falsely-complete dep set — stale cache).\nconst DYNAMIC_CALL = /\\b(?:import|require)\\s*\\(\\s*(?![\"'])[^)\\s]/;\n\n/** statSync that reports ENOENT as undefined instead of an exception. */\nfunction tryStat(p: string): fs.Stats | undefined {\n try {\n return fs.statSync(p, { throwIfNoEntry: false });\n } catch {\n // Non-ENOENT errors (ENOTDIR from probing `file.ts/index.ts`, EACCES):\n // treat as absent.\n return undefined;\n }\n}\n\nfunction tryFile(p: string): string | null {\n return tryStat(p)?.isFile() ? p : null;\n}\n\n/** Probe a path (possibly extensionless) to an existing file. */\nfunction probeFile(base: string): string | null {\n const hasExtension = path.extname(base) !== \"\";\n if (hasExtension) {\n if (tryFile(base)) return base;\n // Extensioned path that doesn't exist as-is: TS source referenced with a\n // .js specifier (nodenext style). Probe the extension-family swap before\n // the append/index probes — in nodenext codebases this is the common hit\n // and skips ~16 dead probes per import.\n if (/\\.[cm]?js$/.test(base)) {\n const hit =\n tryFile(base.replace(/\\.([cm]?)js$/, \".$1ts\")) ??\n tryFile(base.replace(/\\.[cm]?js$/, \".tsx\"));\n if (hit) return hit;\n }\n }\n for (const ext of SOURCE_EXTENSIONS) {\n const hit = tryFile(base + ext);\n if (hit) return hit;\n }\n for (const ext of SOURCE_EXTENSIONS) {\n const hit = tryFile(path.join(base, `index${ext}`));\n if (hit) return hit;\n }\n // Extensionless path that exists exactly (e.g. ./bin/cli).\n return hasExtension ? null : tryFile(base);\n}\n\nfunction realpathOf(p: string): string {\n let real = realpathMemo.get(p);\n if (real === undefined) {\n try {\n real = fs.realpathSync(p);\n } catch {\n real = p; // keep the unresolved path\n }\n realpathMemo.set(p, real);\n }\n return real;\n}\n\nfunction firstPartyOrNull(resolved: string): string | null {\n const real = realpathOf(resolved);\n return real.includes(NODE_MODULES_SEGMENT) ? null : real;\n}\n\n/** Node resolution is a function of the importing DIRECTORY, not the file. */\nfunction requireFor(dir: string): ReturnType<typeof createRequire> {\n let req = requireMemo.get(dir);\n if (req === undefined) {\n req = createRequire(path.join(dir, \"__zod_compiler_resolve__.js\"));\n requireMemo.set(dir, req);\n }\n return req;\n}\n\n/**\n * Resolve one specifier from a directory. Returns:\n * - an absolute path (first-party file to record + crawl)\n * - null when the dep is intentionally out of scope (node_modules, builtins)\n * - UNRESOLVED when resolution failed and the graph cannot be trusted\n */\nfunction resolveSpecifier(rawSpec: string, fromDir: string): string | null | typeof UNRESOLVED {\n if (SKIP_SPECIFIER.test(rawSpec)) return null;\n const memoKey = `${fromDir}\\0${rawSpec}`;\n const memoized = resolveMemo.get(memoKey);\n if (memoized !== undefined) return memoized;\n const result = resolveSpecifierUncached(rawSpec, fromDir);\n resolveMemo.set(memoKey, result);\n return result;\n}\n\nfunction resolveSpecifierUncached(\n rawSpec: string,\n fromDir: string,\n): string | null | typeof UNRESOLVED {\n // Vite-style resource queries (./logo.svg?url, ./shader.glsl?raw) resolve\n // to the underlying file.\n const q = rawSpec.indexOf(\"?\");\n const spec = q === -1 ? rawSpec : rawSpec.slice(0, q);\n if (spec === \"\") return null;\n\n if (spec.startsWith(\"./\") || spec.startsWith(\"../\")) {\n const hit = probeFile(path.resolve(fromDir, spec));\n return hit === null ? UNRESOLVED : firstPartyOrNull(hit);\n }\n\n const { candidates, authoritative } = resolveTsconfigPathCandidates(fromDir, spec);\n for (const candidate of candidates) {\n const hit = probeFile(candidate);\n if (hit !== null) {\n return firstPartyOrNull(hit);\n }\n }\n // An authoritative miss (explicit `paths` pattern matched, or the paths\n // config is present but uninterpretable) means the import cannot be\n // trusted. Implicit baseUrl candidates are proposed for EVERY bare\n // specifier (npm packages, `#` imports) and only mean \"try baseDir\n // first\" — a miss falls through to node resolution below.\n if (authoritative) return UNRESOLVED;\n\n // Bare specifier (package) or package.json \"imports\" (#...): node\n // resolution from the importing directory. node_modules results are out of\n // scope (zod's version is part of the cache key); symlinked workspace\n // packages realpath outside node_modules and are crawled as first-party.\n try {\n const resolved = requireFor(fromDir).resolve(spec);\n if (!path.isAbsolute(resolved)) return null; // node builtin\n return firstPartyOrNull(resolved);\n } catch {\n // Unresolvable from Node's algorithm. jiti may still resolve it (e.g.\n // ESM-only packages without CJS entries) — the file itself stays a dep\n // through the entry, but its subtree is unknown for bare packages.\n // Treat unresolvable BARE specifiers as out-of-scope third-party\n // (caught by the zod-version/plugin key when relevant) only when they\n // cannot be project files; '#' subpath imports stay strict.\n return spec.startsWith(\"#\") ? UNRESOLVED : null;\n }\n}\n\n/**\n * Scan + resolve one file into its edge list. Memoized by mtime, so the\n * shared core graph is read and resolved once per process — each entry's\n * closure walk after that is one cheap stat plus Map lookups per file.\n * Returns null for unreadable files.\n */\nfunction fileNode(filePath: string): FileNode | null {\n const stat = tryStat(filePath);\n if (stat === undefined || !stat.isFile()) {\n nodeMemo.set(filePath, null);\n return null;\n }\n const memo = nodeMemo.get(filePath);\n if (memo !== undefined && memo !== null && memo.mtimeMs === stat.mtimeMs) return memo;\n\n let source: string;\n try {\n source = fs.readFileSync(filePath, \"utf8\");\n } catch {\n nodeMemo.set(filePath, null);\n return null;\n }\n // String/comment contents can false-positive both patterns; extra\n // specifiers only add deps (safe), a false `incomplete` only falls back\n // to the superset (safe).\n let incomplete = DYNAMIC_CALL.test(source);\n const edges: string[] = [];\n const seen = new Set<string>();\n const dir = path.dirname(filePath);\n for (const m of source.matchAll(STATIC_SPECIFIER)) {\n const spec = m[1];\n if (!spec) continue;\n const resolved = resolveSpecifier(spec, dir);\n if (resolved === UNRESOLVED) {\n incomplete = true;\n } else if (resolved !== null && !seen.has(resolved)) {\n seen.add(resolved);\n edges.push(resolved);\n }\n }\n const node: FileNode = { mtimeMs: stat.mtimeMs, edges, incomplete };\n nodeMemo.set(filePath, node);\n return node;\n}\n\n/**\n * Compute the static first-party dependency closure of `entryFile`.\n * The entry itself is excluded (its content is part of the cache key).\n */\nexport function collectStaticDeps(entryFile: string): StaticDeps {\n const entry = firstPartyOrNull(path.resolve(entryFile));\n if (entry === null) return INCOMPLETE;\n\n const visited = new Set<string>([entry]);\n const queue: string[] = [entry];\n\n while (queue.length > 0) {\n if (visited.size > MAX_FILES) return INCOMPLETE;\n const file = queue.pop() as string;\n const node = fileNode(file);\n // Any unanalyzable node poisons the whole closure; the caller falls back\n // to the superset, so abort instead of crawling to exhaustion.\n if (node === null || node.incomplete) return INCOMPLETE;\n for (const dep of node.edges) {\n if (!visited.has(dep)) {\n visited.add(dep);\n queue.push(dep);\n }\n }\n }\n\n visited.delete(entry);\n return { deps: [...visited], complete: true };\n}\n\nexport interface TransformDependencies {\n /**\n * Files to declare as watch dependencies, entry first and deduped. Complete\n * only when `complete` is true — otherwise it is just the entry.\n */\n files: string[];\n /**\n * False when the import graph could not be fully analyzed. `files` is then\n * NOT sufficient, and the host has to reach for a coarser signal (a context\n * dependency over the project, or refusing to cache the result) instead of\n * trusting it.\n */\n complete: boolean;\n}\n\n/**\n * Files whose contents can change what `id`'s transform produces — the set a\n * host must declare as watch dependencies.\n *\n * Discovery EXECUTES the file's import graph, so a compiled validator reflects\n * every constant, enum and helper that graph contributed. A host that keys its\n * cache on `id`'s own content alone therefore serves a stale validator after an\n * edit to any of them.\n *\n * Bundler plugins do not need this: their `watchChange` hook fires for every\n * file in the project, so the plugin invalidates wholesale. Loader hosts\n * (Turbopack, plain webpack loaders) have no such hook — their only lever is\n * declaring dependencies per file, which is what this returns.\n *\n * The entry is always included, for the reason the disk cache records it too: a\n * host keys on the content it PASSED, but discovery executed the file from disk.\n *\n * Deliberately NOT backed by `getFirstPartyModulePaths()` when the crawl comes\n * up incomplete, unlike the disk cache's fallback. That superset is\n * point-in-time, not cumulative — `invalidateModuleCache()` empties it — so\n * after an unrelated file's discovery repopulates it, it describes THAT file's\n * graph and can silently omit this one's. The disk cache survives that because\n * `watchChange` invalidates wholesale and deferred entries flush against one\n * end-of-build snapshot; a loader host has neither backstop, so a plausible but\n * wrong list would go undetected. Reporting `complete: false` lets the caller\n * do the sound thing instead.\n */\nexport function transformDependencies(id: string): TransformDependencies {\n // realpath, matching how the crawl records every dep — otherwise a symlinked\n // or differently-cased spelling of the entry appears twice in one list.\n const entry = realpathOf(path.resolve(id));\n const staticDeps = collectStaticDeps(entry);\n if (!staticDeps.complete) return { files: [entry], complete: false };\n return { files: [entry, ...staticDeps.deps.filter((d) => d !== entry)], complete: true };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,MAAM,oBAAoB;CAAC;CAAO;CAAQ;CAAQ;CAAQ;CAAO;CAAQ;CAAQ;AAAM;AACvF,MAAM,uBAAuB,GAAGA,OAAK,IAAI,cAAcA,OAAK;;AAG5D,MAAM,iBAAiB;;AAEvB,MAAM,YAAY;AAElB,MAAM,aAAyB;CAAE,MAAM,CAAC;CAAG,UAAU;AAAM;;;;;;AAO3D,MAAM,aAAa,OAAO,YAAY;;;;;;;;;AAkBtC,MAAM,2BAAW,IAAI,IAA6B;AAClD,MAAM,8BAAc,IAAI,IAA+C;AACvE,MAAM,+BAAe,IAAI,IAAoB;AAC7C,MAAM,8BAAc,IAAI,IAA8C;;AAGtE,SAAgB,oBAA0B;CACxC,SAAS,MAAM;CACf,YAAY,MAAM;CAClB,aAAa,MAAM;CACnB,YAAY,MAAM;AACpB;AAEA,MAAM,mBACJ;AAIF,MAAM,eAAe;;AAGrB,SAAS,QAAQ,GAAiC;CAChD,IAAI;EACF,OAAOC,KAAG,SAAS,GAAG,EAAE,gBAAgB,MAAM,CAAC;CACjD,QAAQ;EAGN;CACF;AACF;AAEA,SAAS,QAAQ,GAA0B;CACzC,OAAO,QAAQ,CAAC,CAAC,EAAE,OAAO,IAAI,IAAI;AACpC;;AAGA,SAAS,UAAU,MAA6B;CAC9C,MAAM,eAAeD,OAAK,QAAQ,IAAI,MAAM;CAC5C,IAAI,cAAc;EAChB,IAAI,QAAQ,IAAI,GAAG,OAAO;EAK1B,IAAI,aAAa,KAAK,IAAI,GA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,OAAO,CAAC,OAAO,GAAG,WAAW,KAAK,QAAQ,MAAM,MAAM,KAAK,CAAC;EAAG,UAAU;CAAK;AACzF"}
|
package/dist/unplugin/edits.d.ts
CHANGED
|
@@ -22,6 +22,18 @@ interface Insertion {
|
|
|
22
22
|
offset: number;
|
|
23
23
|
text: string;
|
|
24
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* Offset after the shebang and the directive prologue ("use strict",
|
|
27
|
+
* "use client", "use server", ...) — where module-head insertions must go.
|
|
28
|
+
*
|
|
29
|
+
* A directive is only a directive while it is still part of the prologue, so
|
|
30
|
+
* anything prepended at offset 0 demotes it to a plain string expression.
|
|
31
|
+
* Bundlers that give directives meaning reject that outright: React Server
|
|
32
|
+
* Components builds fail with `The "use client" directive must be placed
|
|
33
|
+
* before other expressions`, which is how the generated runtime prologue used
|
|
34
|
+
* to break every Next.js file that exported a schema.
|
|
35
|
+
*/
|
|
36
|
+
declare function moduleHeadOffset(code: string): number;
|
|
25
37
|
/**
|
|
26
38
|
* Apply non-overlapping edits (any order) and an optional insertion to a
|
|
27
39
|
* string. Mirrors MagicString.overwrite + appendLeft semantics: an insertion
|
|
@@ -29,5 +41,5 @@ interface Insertion {
|
|
|
29
41
|
*/
|
|
30
42
|
declare function applyEdits(code: string, edits: readonly Edit[], insert?: Insertion): string;
|
|
31
43
|
//#endregion
|
|
32
|
-
export { Edit, Insertion, applyEdits };
|
|
44
|
+
export { Edit, Insertion, applyEdits, moduleHeadOffset };
|
|
33
45
|
//# sourceMappingURL=edits.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edits.d.ts","names":[],"sources":["../../src/unplugin/edits.ts"],"mappings":";;;;;;;;;;;UAWiB;;EAEf;;EAEA;;EAEA;;UAGe;;EAEf;EACA
|
|
1
|
+
{"version":3,"file":"edits.d.ts","names":[],"sources":["../../src/unplugin/edits.ts"],"mappings":";;;;;;;;;;;UAWiB;;EAEf;;EAEA;;EAEA;;UAGe;;EAEf;EACA;;;;;;;;;;;;;iBAcc,iBAAiB;;;;;;iBAwCjB,WAAW,cAAc,gBAAgB,QAAQ,SAAS"}
|
package/dist/unplugin/edits.js
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
1
|
//#region src/unplugin/edits.ts
|
|
2
2
|
/**
|
|
3
|
+
* Offset after the shebang and the directive prologue ("use strict",
|
|
4
|
+
* "use client", "use server", ...) — where module-head insertions must go.
|
|
5
|
+
*
|
|
6
|
+
* A directive is only a directive while it is still part of the prologue, so
|
|
7
|
+
* anything prepended at offset 0 demotes it to a plain string expression.
|
|
8
|
+
* Bundlers that give directives meaning reject that outright: React Server
|
|
9
|
+
* Components builds fail with `The "use client" directive must be placed
|
|
10
|
+
* before other expressions`, which is how the generated runtime prologue used
|
|
11
|
+
* to break every Next.js file that exported a schema.
|
|
12
|
+
*/
|
|
13
|
+
function moduleHeadOffset(code) {
|
|
14
|
+
let i = 0;
|
|
15
|
+
if (code.startsWith("#!")) {
|
|
16
|
+
const nl = code.indexOf("\n");
|
|
17
|
+
i = nl === -1 ? code.length : nl + 1;
|
|
18
|
+
}
|
|
19
|
+
while (true) {
|
|
20
|
+
while (i < code.length) {
|
|
21
|
+
const ch = code[i];
|
|
22
|
+
if (/\s/.test(ch)) i++;
|
|
23
|
+
else if (ch === "/" && code[i + 1] === "/") {
|
|
24
|
+
const nl = code.indexOf("\n", i);
|
|
25
|
+
i = nl === -1 ? code.length : nl + 1;
|
|
26
|
+
} else if (ch === "/" && code[i + 1] === "*") {
|
|
27
|
+
const end = code.indexOf("*/", i + 2);
|
|
28
|
+
i = end === -1 ? code.length : end + 2;
|
|
29
|
+
} else break;
|
|
30
|
+
}
|
|
31
|
+
const directive = code.slice(i).match(/^(["'])use [^"'\n\\]*\1(?=[^\S\n]*([;\n"']|$))\s*;?[^\S\n]*\n?/);
|
|
32
|
+
if (!directive) return i;
|
|
33
|
+
i += directive[0].length;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
3
37
|
* Apply non-overlapping edits (any order) and an optional insertion to a
|
|
4
38
|
* string. Mirrors MagicString.overwrite + appendLeft semantics: an insertion
|
|
5
39
|
* at an edit boundary lands before the edit's replacement.
|
|
@@ -22,6 +56,6 @@ function applyEdits(code, edits, insert) {
|
|
|
22
56
|
return result;
|
|
23
57
|
}
|
|
24
58
|
//#endregion
|
|
25
|
-
export { applyEdits };
|
|
59
|
+
export { applyEdits, moduleHeadOffset };
|
|
26
60
|
|
|
27
61
|
//# sourceMappingURL=edits.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edits.js","names":[],"sources":["../../src/unplugin/edits.ts"],"sourcesContent":["/**\n * Edit primitives shared by the transform pipeline stages.\n *\n * Every stage (hoist → hoisted-schema compile → rewrites → runtime inject)\n * describes its changes as non-overlapping `Edit` splices (plus at most one\n * insertion) against the STAGE INPUT. The same edit list is applied two\n * ways: `applyEdits()` produces the stage output string, and the pipeline\n * applies it to a MagicString to produce the stage's sourcemap — deriving\n * both from one list makes code/map divergence impossible.\n */\n\nexport interface Edit {\n /** Start offset in the stage-input string. */\n start: number;\n /** End offset (exclusive) in the stage-input string. */\n end: number;\n /** Replacement text. */\n text: string;\n}\n\nexport interface Insertion {\n /** Offset in the stage-input string to insert at. */\n offset: number;\n text: string;\n}\n\n/**\n * Apply non-overlapping edits (any order) and an optional insertion to a\n * string. Mirrors MagicString.overwrite + appendLeft semantics: an insertion\n * at an edit boundary lands before the edit's replacement.\n */\nexport function applyEdits(code: string, edits: readonly Edit[], insert?: Insertion): string {\n const ops: Array<Edit | (Insertion & { insertion: true })> = [...edits];\n if (insert) ops.push({ ...insert, insertion: true });\n ops.sort((a, b) => {\n const aStart = \"insertion\" in a ? a.offset : a.start;\n const bStart = \"insertion\" in b ? b.offset : b.start;\n if (aStart !== bStart) return bStart - aStart;\n // Same position: apply the insertion last so it ends up BEFORE the\n // replacement text in the output (appendLeft semantics).\n return \"insertion\" in a ? -1 : 1;\n });\n let result = code;\n for (const op of ops) {\n if (\"insertion\" in op) {\n result = result.slice(0, op.offset) + op.text + result.slice(op.offset);\n } else {\n result = result.slice(0, op.start) + op.text + result.slice(op.end);\n }\n }\n return result;\n}\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"edits.js","names":[],"sources":["../../src/unplugin/edits.ts"],"sourcesContent":["/**\n * Edit primitives shared by the transform pipeline stages.\n *\n * Every stage (hoist → hoisted-schema compile → rewrites → runtime inject)\n * describes its changes as non-overlapping `Edit` splices (plus at most one\n * insertion) against the STAGE INPUT. The same edit list is applied two\n * ways: `applyEdits()` produces the stage output string, and the pipeline\n * applies it to a MagicString to produce the stage's sourcemap — deriving\n * both from one list makes code/map divergence impossible.\n */\n\nexport interface Edit {\n /** Start offset in the stage-input string. */\n start: number;\n /** End offset (exclusive) in the stage-input string. */\n end: number;\n /** Replacement text. */\n text: string;\n}\n\nexport interface Insertion {\n /** Offset in the stage-input string to insert at. */\n offset: number;\n text: string;\n}\n\n/**\n * Offset after the shebang and the directive prologue (\"use strict\",\n * \"use client\", \"use server\", ...) — where module-head insertions must go.\n *\n * A directive is only a directive while it is still part of the prologue, so\n * anything prepended at offset 0 demotes it to a plain string expression.\n * Bundlers that give directives meaning reject that outright: React Server\n * Components builds fail with `The \"use client\" directive must be placed\n * before other expressions`, which is how the generated runtime prologue used\n * to break every Next.js file that exported a schema.\n */\nexport function moduleHeadOffset(code: string): number {\n let i = 0;\n if (code.startsWith(\"#!\")) {\n const nl = code.indexOf(\"\\n\");\n i = nl === -1 ? code.length : nl + 1;\n }\n while (true) {\n // Skip whitespace and comments between directives\n while (i < code.length) {\n const ch = code[i] as string;\n if (/\\s/.test(ch)) {\n i++;\n } else if (ch === \"/\" && code[i + 1] === \"/\") {\n const nl = code.indexOf(\"\\n\", i);\n i = nl === -1 ? code.length : nl + 1;\n } else if (ch === \"/\" && code[i + 1] === \"*\") {\n const end = code.indexOf(\"*/\", i + 2);\n i = end === -1 ? code.length : end + 2;\n } else {\n break;\n }\n }\n // The body excludes backslashes and the lookahead demands a statement\n // boundary, so the two shapes that merely START like a directive are left\n // alone: `\"use \\\"strict\\\"\";` (matching through the escape would land the\n // insertion mid-literal) and `\"use \" + mode;` (an expression statement,\n // where it would land on the `+`). Both would emit a syntax error.\n const directive = code\n .slice(i)\n .match(/^([\"'])use [^\"'\\n\\\\]*\\1(?=[^\\S\\n]*([;\\n\"']|$))\\s*;?[^\\S\\n]*\\n?/);\n if (!directive) return i;\n i += directive[0].length;\n }\n}\n\n/**\n * Apply non-overlapping edits (any order) and an optional insertion to a\n * string. Mirrors MagicString.overwrite + appendLeft semantics: an insertion\n * at an edit boundary lands before the edit's replacement.\n */\nexport function applyEdits(code: string, edits: readonly Edit[], insert?: Insertion): string {\n const ops: Array<Edit | (Insertion & { insertion: true })> = [...edits];\n if (insert) ops.push({ ...insert, insertion: true });\n ops.sort((a, b) => {\n const aStart = \"insertion\" in a ? a.offset : a.start;\n const bStart = \"insertion\" in b ? b.offset : b.start;\n if (aStart !== bStart) return bStart - aStart;\n // Same position: apply the insertion last so it ends up BEFORE the\n // replacement text in the output (appendLeft semantics).\n return \"insertion\" in a ? -1 : 1;\n });\n let result = code;\n for (const op of ops) {\n if (\"insertion\" in op) {\n result = result.slice(0, op.offset) + op.text + result.slice(op.offset);\n } else {\n result = result.slice(0, op.start) + op.text + result.slice(op.end);\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;AAqCA,SAAgB,iBAAiB,MAAsB;CACrD,IAAI,IAAI;CACR,IAAI,KAAK,WAAW,IAAI,GAAG;EACzB,MAAM,KAAK,KAAK,QAAQ,IAAI;EAC5B,IAAI,OAAO,KAAK,KAAK,SAAS,KAAK;CACrC;CACA,OAAO,MAAM;EAEX,OAAO,IAAI,KAAK,QAAQ;GACtB,MAAM,KAAK,KAAK;GAChB,IAAI,KAAK,KAAK,EAAE,GACd;QACK,IAAI,OAAO,OAAO,KAAK,IAAI,OAAO,KAAK;IAC5C,MAAM,KAAK,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EAEL,SAAS,YAAY;;;;;;;iBAQP,sBAAsB,eAAe;
|
|
1
|
+
{"version":3,"file":"hoist.d.ts","names":[],"sources":["../../src/unplugin/hoist.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA+Da,qBAAmB;;;;;;cAOnB,aAAW;;UAGP;;EAEf;;EAEA;;UAGQ;;EAER,KAAK;;EAEL,KAAK;;EAEL,SAAS,YAAY;;;;;;;iBAQP,sBAAsB,eAAe;UAw7BpC;;;;;;;EAOf,oBAAoB;;;;;;;;EAQpB;;;;;;;iBAQc,yBACd;EACG,WAAW;EAAa,cAAc;;;UAY1B;;EAEf;;EAEA;;UAGe;;EAEf;;EAEA,SAAS;;;;;;EAMT,OAAO;EACP,QAAQ;;;;;;iBAOM,gBAAgB,cAAc,UAAU;;;;;iBAQxC,oBAAoB,cAAc,UAAU,eAAe"}
|
package/dist/unplugin/hoist.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { applyEdits } from "./edits.js";
|
|
1
|
+
import { applyEdits, moduleHeadOffset } from "./edits.js";
|
|
2
2
|
import { Parser } from "acorn";
|
|
3
3
|
//#region src/unplugin/hoist.ts
|
|
4
4
|
/**
|
|
@@ -723,30 +723,6 @@ function analyzeCaptures(expr) {
|
|
|
723
723
|
impure
|
|
724
724
|
};
|
|
725
725
|
}
|
|
726
|
-
/** Offset after the shebang and directive prologue ("use client", ...). */
|
|
727
|
-
function insertionOffset(code) {
|
|
728
|
-
let i = 0;
|
|
729
|
-
if (code.startsWith("#!")) {
|
|
730
|
-
const nl = code.indexOf("\n");
|
|
731
|
-
i = nl === -1 ? code.length : nl + 1;
|
|
732
|
-
}
|
|
733
|
-
while (true) {
|
|
734
|
-
while (i < code.length) {
|
|
735
|
-
const ch = code[i];
|
|
736
|
-
if (/\s/.test(ch)) i++;
|
|
737
|
-
else if (ch === "/" && code[i + 1] === "/") {
|
|
738
|
-
const nl = code.indexOf("\n", i);
|
|
739
|
-
i = nl === -1 ? code.length : nl + 1;
|
|
740
|
-
} else if (ch === "/" && code[i + 1] === "*") {
|
|
741
|
-
const end = code.indexOf("*/", i + 2);
|
|
742
|
-
i = end === -1 ? code.length : end + 2;
|
|
743
|
-
} else break;
|
|
744
|
-
}
|
|
745
|
-
const directive = code.slice(i).match(/^(["'])use [^"'\n]*\1\s*;?[^\S\n]*\n?/);
|
|
746
|
-
if (!directive) return i;
|
|
747
|
-
i += directive[0].length;
|
|
748
|
-
}
|
|
749
|
-
}
|
|
750
726
|
/** Keywords that precede `( ... ) {` without binding anything. */
|
|
751
727
|
const NON_BINDING_KEYWORDS = "if|for|while|switch|return|typeof|await|yield|new|do|else|case|in|of|delete|void";
|
|
752
728
|
/**
|
|
@@ -998,7 +974,7 @@ function hoistZodSchemasMeta(code, options) {
|
|
|
998
974
|
text: h.name
|
|
999
975
|
}));
|
|
1000
976
|
const insert = {
|
|
1001
|
-
offset:
|
|
977
|
+
offset: moduleHeadOffset(code),
|
|
1002
978
|
text: `${decls}\n`
|
|
1003
979
|
};
|
|
1004
980
|
return {
|