@cedarjs/vite 7.1.0 → 7.1.1-next.469

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/buildApp.d.ts.map +1 -1
  2. package/dist/buildApp.js +32 -11
  3. package/dist/buildRouteHooks.d.ts +7 -13
  4. package/dist/buildRouteHooks.d.ts.map +1 -1
  5. package/dist/buildRouteHooks.js +5 -10
  6. package/dist/bundled/react-server-dom-webpack.server.js +2263 -29124
  7. package/dist/devFeServer.js +3 -3
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +4 -0
  11. package/dist/jobsDevMiddleware.d.ts.map +1 -1
  12. package/dist/jobsDevMiddleware.js +29 -2
  13. package/dist/lib/sandboxChildren.d.ts +58 -0
  14. package/dist/lib/sandboxChildren.d.ts.map +1 -0
  15. package/dist/lib/sandboxChildren.js +157 -0
  16. package/dist/plugins/vite-plugin-cedar-cell.d.ts +2 -1
  17. package/dist/plugins/vite-plugin-cedar-cell.d.ts.map +1 -1
  18. package/dist/plugins/vite-plugin-cedar-cell.js +30 -11
  19. package/dist/plugins/vite-plugin-cedar-parsed-scalars.d.ts +20 -0
  20. package/dist/plugins/vite-plugin-cedar-parsed-scalars.d.ts.map +1 -0
  21. package/dist/plugins/vite-plugin-cedar-parsed-scalars.js +60 -0
  22. package/dist/plugins/vite-plugin-cedar-sandbox-children.d.ts +20 -0
  23. package/dist/plugins/vite-plugin-cedar-sandbox-children.d.ts.map +1 -0
  24. package/dist/plugins/vite-plugin-cedar-sandbox-children.js +58 -0
  25. package/dist/plugins/vite-plugin-handler-als-wrapping.d.ts +2 -6
  26. package/dist/plugins/vite-plugin-handler-als-wrapping.d.ts.map +1 -1
  27. package/dist/plugins/vite-plugin-handler-als-wrapping.js +4 -7
  28. package/dist/rsc/rscBuildClient.d.ts +1 -1
  29. package/dist/rsc/rscBuildForServer.d.ts +1 -1
  30. package/dist/rsc/rscBuildForSsr.d.ts +1 -1
  31. package/dist/runFeServer.js +3 -3
  32. package/dist/streaming/streamHelpers.d.ts +6 -1
  33. package/dist/streaming/streamHelpers.d.ts.map +1 -1
  34. package/dist/streaming/streamHelpers.js +1 -1
  35. package/package.json +46 -44
@@ -25,7 +25,7 @@ async function createServer() {
25
25
  const rwPaths = getPaths();
26
26
  const rscEnabled = getConfig().experimental.rsc?.enabled ?? false;
27
27
  const serverStorage = createServerStorage();
28
- app.use("*", (req, _res, next) => {
28
+ app.use((req, _res, next) => {
29
29
  const fullUrl = getFullUrl(req, rscEnabled);
30
30
  const perReqStore = createPerRequestMap({
31
31
  // Convert express headers to fetch header
@@ -102,8 +102,8 @@ async function createServer() {
102
102
  },
103
103
  vite
104
104
  );
105
- app.get("*", createServerAdapter(routeHandler));
106
- app.post("*", handleWithMiddleware());
105
+ app.get("/{*splat}", createServerAdapter(routeHandler));
106
+ app.post("/{*splat}", handleWithMiddleware());
107
107
  const port = getConfig().web.port;
108
108
  console.log(`Started server on http://localhost:${port}`);
109
109
  return app.listen(port);
package/dist/index.d.ts CHANGED
@@ -19,6 +19,7 @@ export { cedarRemoveFromBundle } from './plugins/vite-plugin-cedar-remove-from-b
19
19
  export { cedarjsResolveCedarStyleImportsPlugin } from './plugins/vite-plugin-cedarjs-resolve-cedar-style-imports.js';
20
20
  export { cedarjsJobPathInjectorPlugin } from './plugins/vite-plugin-cedarjs-job-path-injector.js';
21
21
  export { cedarMockCellDataPlugin } from './plugins/vite-plugin-cedar-mock-cell-data.js';
22
+ export { cedarParsedScalarsPlugin } from './plugins/vite-plugin-cedar-parsed-scalars.js';
22
23
  export { cedarMergedConfig } from './plugins/vite-plugin-merged-config.js';
23
24
  export { cedarNetlifySkewProtectionPlugin } from './plugins/vite-plugin-cedar-netlify-skew-protection.js';
24
25
  export { cedarSwapApolloProvider } from './plugins/vite-plugin-swap-apollo-provider.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources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AE,MAAM,uDAAuD,CAAA;AACvG,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAA;AAChF,OAAO,EAAE,gBAAgB,EAAE,MAAM,8CAA8C,CAAA;AAC/E,OAAO,EAAE,4BAA4B,EAAE,MAAM,4DAA4D,CAAA;AACzG,OAAO,EAAE,2BAA2B,EAAE,MAAM,mDAAmD,CAAA;AAC/F,OAAO,EAAE,qBAAqB,EAAE,MAAM,mDAAmD,CAAA;AACzF,OAAO,EAAE,qCAAqC,EAAE,MAAM,8DAA8D,CAAA;AACpH,OAAO,EAAE,4BAA4B,EAAE,MAAM,oDAAoD,CAAA;AACjG,OAAO,EAAE,uBAAuB,EAAE,MAAM,+CAA+C,CAAA;AACvF,OAAO,EAAE,wBAAwB,EAAE,MAAM,+CAA+C,CAAA;AACxF,OAAO,EAAE,iBAAiB,EAAE,MAAM,wCAAwC,CAAA;AAC1E,OAAO,EAAE,gCAAgC,EAAE,MAAM,wDAAwD,CAAA;AACzG,OAAO,EAAE,uBAAuB,EAAE,MAAM,+CAA+C,CAAA;AACvF,OAAO,EAAE,0BAA0B,EAAE,MAAM,iDAAiD,CAAA;AAC5F,OAAO,EAAE,qBAAqB,EAAE,MAAM,oDAAoD,CAAA;AAE1F,KAAK,aAAa,GAAG;IACnB,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IACzB,KAAK,CAAC,EAAE,YAAY,GAAG,SAAS,CAAA;CACjC,CAAA;AAED;;GAEG;AACH,wBAAgB,KAAK,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,GAAE,aAAkB,GAAG,YAAY,EAAE,CAgDzE;AAED,8DAA8D;AAC9D,eAAe,KAAK,CAAA"}
package/dist/index.js CHANGED
@@ -20,6 +20,7 @@ import { cedarDataUriShim } from "./plugins/vite-plugin-cedar-data-uri-shim.js";
20
20
  import { cedarEntryInjectionPlugin } from "./plugins/vite-plugin-cedar-entry-injection.js";
21
21
  import { cedarHtmlEnvPlugin } from "./plugins/vite-plugin-cedar-html-env.js";
22
22
  import { cedarMockCellDataPlugin } from "./plugins/vite-plugin-cedar-mock-cell-data.js";
23
+ import { cedarParsedScalarsPlugin } from "./plugins/vite-plugin-cedar-parsed-scalars.js";
23
24
  import { cedarRemoveDevFatalErrorPage } from "./plugins/vite-plugin-cedar-remove-dev-fatal-error-page.js";
24
25
  import { cedarRemoveFromBundle } from "./plugins/vite-plugin-cedar-remove-from-bundle.js";
25
26
  import { cedarRoutesAutoLoaderPlugin } from "./plugins/vite-plugin-cedar-routes-auto-loader.js";
@@ -49,6 +50,7 @@ import { cedarRemoveFromBundle as cedarRemoveFromBundle2 } from "./plugins/vite-
49
50
  import { cedarjsResolveCedarStyleImportsPlugin as cedarjsResolveCedarStyleImportsPlugin2 } from "./plugins/vite-plugin-cedarjs-resolve-cedar-style-imports.js";
50
51
  import { cedarjsJobPathInjectorPlugin } from "./plugins/vite-plugin-cedarjs-job-path-injector.js";
51
52
  import { cedarMockCellDataPlugin as cedarMockCellDataPlugin2 } from "./plugins/vite-plugin-cedar-mock-cell-data.js";
53
+ import { cedarParsedScalarsPlugin as cedarParsedScalarsPlugin2 } from "./plugins/vite-plugin-cedar-parsed-scalars.js";
52
54
  import { cedarMergedConfig as cedarMergedConfig2 } from "./plugins/vite-plugin-merged-config.js";
53
55
  import { cedarNetlifySkewProtectionPlugin } from "./plugins/vite-plugin-cedar-netlify-skew-protection.js";
54
56
  import { cedarSwapApolloProvider as cedarSwapApolloProvider2 } from "./plugins/vite-plugin-swap-apollo-provider.js";
@@ -80,6 +82,7 @@ function cedar({ mode, babel } = {}) {
80
82
  cedarMergedConfig(),
81
83
  cedarjsResolveCedarStyleImportsPlugin(),
82
84
  cedarSwapApolloProvider(),
85
+ cedarParsedScalarsPlugin(),
83
86
  cedarCellTransform(),
84
87
  cedarRemoveFromBundle(),
85
88
  cedarRemoveDevFatalErrorPage(),
@@ -109,6 +112,7 @@ export {
109
112
  cedarMockCellDataPlugin2 as cedarMockCellDataPlugin,
110
113
  cedarNetlifySkewProtectionPlugin,
111
114
  cedarOtelWrappingPlugin,
115
+ cedarParsedScalarsPlugin2 as cedarParsedScalarsPlugin,
112
116
  cedarRemoveDevFatalErrorPage2 as cedarRemoveDevFatalErrorPage,
113
117
  cedarRemoveFromBundle2 as cedarRemoveFromBundle,
114
118
  cedarRoutesAutoLoaderPlugin2 as cedarRoutesAutoLoaderPlugin,
@@ -1 +1 @@
1
- {"version":3,"file":"jobsDevMiddleware.d.ts","sourceRoot":"","sources":["../src/jobsDevMiddleware.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAA;AAyEzC,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAC1B;AAKD,KAAK,eAAe,GAAG,IAAI,CAAC,aAAa,EAAE,eAAe,CAAC,CAAA;AAE3D;;;;;;;;GAQG;AACH,wBAAsB,mBAAmB,CACvC,UAAU,EAAE,eAAe,GAC1B,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CA8FhC"}
1
+ {"version":3,"file":"jobsDevMiddleware.d.ts","sourceRoot":"","sources":["../src/jobsDevMiddleware.ts"],"names":[],"mappings":"AAgCA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAA;AAsGzC,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAC1B;AAKD,KAAK,eAAe,GAAG,IAAI,CAAC,aAAa,EAAE,eAAe,CAAC,CAAA;AAE3D;;;;;;;;GAQG;AACH,wBAAsB,mBAAmB,CACvC,UAAU,EAAE,eAAe,GAC1B,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CA6GhC"}
@@ -1,8 +1,13 @@
1
+ import fs from "node:fs";
2
+ import { hostname } from "node:os";
3
+ import path from "node:path";
1
4
  import { pathToFileURL } from "node:url";
2
5
  import ansis from "ansis";
3
6
  import {
7
+ isJobModuleFile,
4
8
  JobNotFoundError,
5
9
  JobsLibNotFoundError,
10
+ jobsFromModules,
6
11
  setJobLoaderOverrides
7
12
  } from "@cedarjs/jobs";
8
13
  import { getPaths } from "@cedarjs/project-config";
@@ -40,10 +45,27 @@ async function loadJobViaVite(viteServer, { name: jobName, path: jobPath }) {
40
45
  }
41
46
  return mod[jobName];
42
47
  }
48
+ async function loadAllJobsViaVite(viteServer) {
49
+ const jobsDir = getPaths().api.jobs;
50
+ if (!fs.existsSync(jobsDir)) {
51
+ return [];
52
+ }
53
+ const files = fs.readdirSync(jobsDir, { recursive: true, encoding: "utf-8" }).filter(isJobModuleFile).sort();
54
+ const modules = [];
55
+ for (const file of files) {
56
+ modules.push(
57
+ await viteServer.ssrLoadModule(
58
+ pathToFileURL(path.join(jobsDir, file)).href
59
+ )
60
+ );
61
+ }
62
+ return jobsFromModules(modules);
63
+ }
43
64
  async function startJobsDevWorkers(viteServer) {
44
65
  setJobLoaderOverrides({
45
66
  loadJobsManager: () => loadJobsManagerViaVite(viteServer),
46
- loadJob: (computedProperties) => loadJobViaVite(viteServer, computedProperties)
67
+ loadJob: (computedProperties) => loadJobViaVite(viteServer, computedProperties),
68
+ loadAllJobs: () => loadAllJobsViaVite(viteServer)
47
69
  });
48
70
  let jobsManager;
49
71
  try {
@@ -61,12 +83,17 @@ async function startJobsDevWorkers(viteServer) {
61
83
  setJobLoaderOverrides(void 0);
62
84
  return null;
63
85
  }
86
+ try {
87
+ await jobsManager.syncSchedules();
88
+ } catch (e) {
89
+ logger.error("[CedarJS Jobs] Could not sync the declared schedules", e);
90
+ }
64
91
  logger.warn(
65
92
  `[CedarJS Jobs] Starting ${numWorkers.length} worker(s) in-process (Unified Dev)...`
66
93
  );
67
94
  const workers = numWorkers.map(([index, id]) => {
68
95
  const workerConfig = jobsManager.workers[index];
69
- const processName = `ud-jobs.${[workerConfig.queue].flat().join("-")}.${id}`;
96
+ const processName = `ud-jobs.${[workerConfig.queue].flat().join("-")}.${id} host:${hostname()} pid:${process.pid}`;
70
97
  return jobsManager.createWorker({
71
98
  index,
72
99
  clear: false,
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The folder in `api/dist/ud` a bundled API build puts every sandboxed
3
+ * child script in, as `<name>.child.js`, with a `node_modules` holding the
4
+ * packages they import. `findChildScript()` in `@cedarjs/api/sandbox`
5
+ * looks for `api/dist/ud/sandbox-children` from its caller's folder up.
6
+ */
7
+ export declare const SANDBOX_CHILDREN_DIR = "sandbox-children";
8
+ /**
9
+ * Every sandboxed child script in `apiSrc` (`**\/*.child.{ts,js,mts,mjs}`),
10
+ * as `{ 'sandbox-children/<name>.child': file }`, for a bundled build's
11
+ * `input`. Throws when two have the same name: in a bundle they all go in
12
+ * one folder, and `findChildScript()` finds them by name.
13
+ */
14
+ export declare function findSandboxChildScripts(apiSrc: string): Record<string, string>;
15
+ export interface SandboxChildImports {
16
+ /** The child script's source file, which its imports resolve from */
17
+ source: string;
18
+ /** What it imports: package names and Node builtins */
19
+ imports: string[];
20
+ }
21
+ /**
22
+ * Copies the packages the child scripts import, and everything those
23
+ * depend on, into `<childrenDir>/node_modules`, so the folder runs on its
24
+ * own wherever it's deployed: a serverless function's file tracing doesn't
25
+ * follow a child script (nothing imports it), and it would miss what
26
+ * native packages load at run time anyway (sharp's libvips).
27
+ *
28
+ * Follows each package's `dependencies`, and the `optionalDependencies`
29
+ * and `peerDependencies` that are installed, which is how native packages
30
+ * ship their platform's binaries (`@img/sharp-linux-x64`,
31
+ * `@img/sharp-libvips-linux-x64`).
32
+ *
33
+ * The copy keeps each package's choices, so it finds the same versions
34
+ * it does in the app: a dependency nested in a package's own
35
+ * `node_modules` is copied into the copy's `node_modules`; one beside it
36
+ * in a `node_modules` (pnpm's layout), or shadowed in the copy by another
37
+ * version, goes next to the dependent's copy; one in the app's own
38
+ * `node_modules` folders goes at the top. A package already reachable from
39
+ * the dependent's copy is reused. When two versions would still need the
40
+ * same place, it throws instead of letting one overwrite the other. So
41
+ * does a package or regular dependency that isn't installed: the child
42
+ * couldn't import it either.
43
+ */
44
+ export declare function vendorSandboxChildPackages(childrenDir: string, children: SandboxChildImports[]): void;
45
+ /**
46
+ * Copies the bundled build's sandboxed children (and their `node_modules`)
47
+ * into every Node function in a Vercel Build Output API folder
48
+ * (`.vercel/output/functions/*.func`), at the same path as in the app
49
+ * (`api/dist/ud/sandbox-children`). Each Vercel function is a single
50
+ * bundled file with nothing else from the app, and `findChildScript()`
51
+ * looks for the children from the function's folder up.
52
+ */
53
+ export declare function copySandboxChildrenIntoVercelFunctions({ appRoot, childrenDir, functionsDir, }: {
54
+ appRoot: string;
55
+ childrenDir: string;
56
+ functionsDir: string;
57
+ }): string[];
58
+ //# sourceMappingURL=sandboxChildren.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandboxChildren.d.ts","sourceRoot":"","sources":["../../src/lib/sandboxChildren.ts"],"names":[],"mappings":"AAMA;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,qBAAqB,CAAA;AAEtD;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,MAAM,GACb,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAyBxB;AA6CD,MAAM,WAAW,mBAAmB;IAClC,qEAAqE;IACrE,MAAM,EAAE,MAAM,CAAA;IACd,uDAAuD;IACvD,OAAO,EAAE,MAAM,EAAE,CAAA;CAClB;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,mBAAmB,EAAE,QA+GhC;AAgBD;;;;;;;GAOG;AACH,wBAAgB,sCAAsC,CAAC,EACrD,OAAO,EACP,WAAW,EACX,YAAY,GACb,EAAE;IACD,OAAO,EAAE,MAAM,CAAA;IACf,WAAW,EAAE,MAAM,CAAA;IACnB,YAAY,EAAE,MAAM,CAAA;CACrB,YAgCA"}
@@ -0,0 +1,157 @@
1
+ import fs from "node:fs";
2
+ import { isBuiltin } from "node:module";
3
+ import path from "node:path";
4
+ import fg from "fast-glob";
5
+ const SANDBOX_CHILDREN_DIR = "sandbox-children";
6
+ function findSandboxChildScripts(apiSrc) {
7
+ const files = fg.sync("**/*.child.{ts,js,mts,mjs}", {
8
+ cwd: apiSrc,
9
+ absolute: true,
10
+ ignore: ["**/node_modules/**", "**/__tests__/**"]
11
+ }).sort();
12
+ const entries = {};
13
+ for (const file of files) {
14
+ const name = path.basename(file).replace(/\.(ts|js|mts|mjs)$/, "");
15
+ const key = `${SANDBOX_CHILDREN_DIR}/${name}`;
16
+ if (entries[key]) {
17
+ throw new Error(
18
+ `Two sandboxed child scripts are named ${name}: ${path.relative(apiSrc, entries[key])} and ${path.relative(apiSrc, file)}. A bundled build puts every child script in one folder, so their names must be unique.`
19
+ );
20
+ }
21
+ entries[key] = path.normalize(file);
22
+ }
23
+ return entries;
24
+ }
25
+ const packageName = (specifier) => {
26
+ const parts = specifier.split("/");
27
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
28
+ };
29
+ const readPackageJson = (dir) => {
30
+ const parsed = JSON.parse(
31
+ fs.readFileSync(path.join(dir, "package.json"), "utf8")
32
+ );
33
+ return parsed && typeof parsed === "object" ? parsed : {};
34
+ };
35
+ const findPackage = (name, dir) => {
36
+ let current = dir;
37
+ for (; ; ) {
38
+ const candidate = path.join(current, "node_modules", name);
39
+ if (fs.existsSync(path.join(candidate, "package.json"))) {
40
+ return { realDir: fs.realpathSync(candidate), foundIn: current };
41
+ }
42
+ const parent = path.dirname(current);
43
+ if (parent === current) {
44
+ return null;
45
+ }
46
+ current = parent;
47
+ }
48
+ };
49
+ function vendorSandboxChildPackages(childrenDir, children) {
50
+ const copyOf = /* @__PURE__ */ new Map();
51
+ const occupied = /* @__PURE__ */ new Map();
52
+ const inNodeModules = (dir) => dir.split(path.sep).includes("node_modules");
53
+ const reachableFrom = (copy, name) => {
54
+ let dir = copy;
55
+ for (; ; ) {
56
+ const there = occupied.get(path.join(dir, "node_modules", name));
57
+ if (there || dir === childrenDir) {
58
+ return there?.realDir;
59
+ }
60
+ dir = path.dirname(dir);
61
+ }
62
+ };
63
+ const visit = (name, fromDir, dependentCopy, required, dependent) => {
64
+ const found = findPackage(name, fromDir);
65
+ if (!found) {
66
+ if (required) {
67
+ throw new Error(
68
+ `Can't find package "${name}", which ${dependent} imports, in a node_modules folder above ${fromDir}`
69
+ );
70
+ }
71
+ return;
72
+ }
73
+ const { realDir, foundIn } = found;
74
+ const reachable = reachableFrom(dependentCopy, name);
75
+ if (reachable === realDir) {
76
+ return;
77
+ }
78
+ const copiedFolder = copyOf.get(foundIn);
79
+ const besideDependent = path.join(dependentCopy, "node_modules", name);
80
+ const target = copiedFolder ? path.join(copiedFolder, "node_modules", name) : inNodeModules(foundIn) || reachable ? besideDependent : path.join(childrenDir, "node_modules", name);
81
+ const there = occupied.get(target);
82
+ if (there) {
83
+ throw new Error(
84
+ `Sandboxed child scripts need two versions of "${name}" in one place: ${there.realDir} (for ${there.neededBy}) and ${realDir} (for ${dependent}). Install a single version of it, or move the children so their imports resolve the same way.`
85
+ );
86
+ }
87
+ occupied.set(target, { realDir, neededBy: dependent });
88
+ if (!copyOf.has(realDir)) {
89
+ copyOf.set(realDir, target);
90
+ }
91
+ fs.cpSync(realDir, target, {
92
+ recursive: true,
93
+ dereference: true,
94
+ // Its own node_modules are copied as dependencies, when they're needed
95
+ filter: (src) => src !== path.join(realDir, "node_modules")
96
+ });
97
+ const pkg = readPackageJson(realDir);
98
+ const optional = /* @__PURE__ */ new Set([
99
+ ...Object.keys(pkg.optionalDependencies ?? {}),
100
+ ...Object.keys(pkg.peerDependencies ?? {})
101
+ ]);
102
+ for (const dep of Object.keys(pkg.dependencies ?? {})) {
103
+ visit(dep, realDir, target, !optional.has(dep), name);
104
+ }
105
+ for (const dep of optional) {
106
+ visit(dep, realDir, target, false, name);
107
+ }
108
+ };
109
+ for (const { source, imports } of children) {
110
+ for (const specifier of imports) {
111
+ if (isBuiltin(specifier) || specifier.startsWith("#")) {
112
+ continue;
113
+ }
114
+ visit(
115
+ packageName(specifier),
116
+ fs.realpathSync(path.dirname(source)),
117
+ childrenDir,
118
+ true,
119
+ path.basename(source)
120
+ );
121
+ }
122
+ }
123
+ }
124
+ const findVercelFunctionDirs = (dir) => fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
125
+ const entryPath = path.join(dir, entry.name);
126
+ return entry.name.endsWith(".func") ? [entryPath] : findVercelFunctionDirs(entryPath);
127
+ }) : [];
128
+ function copySandboxChildrenIntoVercelFunctions({
129
+ appRoot,
130
+ childrenDir,
131
+ functionsDir
132
+ }) {
133
+ const childrenDirInApp = path.relative(appRoot, childrenDir);
134
+ if (!fs.existsSync(childrenDir)) {
135
+ return [];
136
+ }
137
+ const functionDirs = findVercelFunctionDirs(functionsDir).filter((dir) => {
138
+ const config = path.join(dir, ".vc-config.json");
139
+ if (!fs.existsSync(config)) {
140
+ return false;
141
+ }
142
+ const parsed = JSON.parse(fs.readFileSync(config, "utf8"));
143
+ return !!parsed && typeof parsed === "object" && "runtime" in parsed && typeof parsed.runtime === "string" && parsed.runtime.startsWith("nodejs");
144
+ });
145
+ for (const dir of functionDirs) {
146
+ fs.cpSync(childrenDir, path.join(dir, childrenDirInApp), {
147
+ recursive: true
148
+ });
149
+ }
150
+ return functionDirs;
151
+ }
152
+ export {
153
+ SANDBOX_CHILDREN_DIR,
154
+ copySandboxChildrenIntoVercelFunctions,
155
+ findSandboxChildScripts,
156
+ vendorSandboxChildPackages
157
+ };
@@ -16,7 +16,8 @@ import type { Plugin } from 'vite';
16
16
  * export const QUERY = gql`...`
17
17
  * export const Loading = () => <div>Loading...</div>
18
18
  * export const Success = ({ data }) => <div>{data}</div>
19
- * export default createCell({ QUERY, Loading, Success, displayName: 'MyCell' })
19
+ * const MyCell = createCell({ QUERY, Loading, Success, displayName: 'MyCell' })
20
+ * export default MyCell
20
21
  * ```
21
22
  */
22
23
  export declare function cedarCellTransform(): Plugin;
@@ -1 +1 @@
1
- {"version":3,"file":"vite-plugin-cedar-cell.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-cedar-cell.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAqBlC;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAsK3C"}
1
+ {"version":3,"file":"vite-plugin-cedar-cell.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-cedar-cell.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAqBlC;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAsM3C"}
@@ -23,6 +23,7 @@ function cedarCellTransform() {
23
23
  if (!id.match(/Cell\.[jt]sx?$/)) {
24
24
  return null;
25
25
  }
26
+ const cellComponentName = parsePath(id).name;
26
27
  try {
27
28
  const ast = parse(code, {
28
29
  sourceType: "module",
@@ -111,20 +112,38 @@ function cedarCellTransform() {
111
112
  computed: false
112
113
  }
113
114
  ];
115
+ const cellVariableDeclaration = {
116
+ type: "VariableDeclaration",
117
+ kind: "const",
118
+ declarations: [
119
+ {
120
+ type: "VariableDeclarator",
121
+ id: {
122
+ type: "Identifier",
123
+ name: cellComponentName
124
+ },
125
+ init: {
126
+ type: "CallExpression",
127
+ callee: {
128
+ type: "Identifier",
129
+ name: createCellHookName
130
+ },
131
+ arguments: [
132
+ {
133
+ type: "ObjectExpression",
134
+ properties: objectProperties
135
+ }
136
+ ]
137
+ }
138
+ }
139
+ ]
140
+ };
141
+ path.node.body.push(cellVariableDeclaration);
114
142
  const exportDefaultDeclaration = {
115
143
  type: "ExportDefaultDeclaration",
116
144
  declaration: {
117
- type: "CallExpression",
118
- callee: {
119
- type: "Identifier",
120
- name: createCellHookName
121
- },
122
- arguments: [
123
- {
124
- type: "ObjectExpression",
125
- properties: objectProperties
126
- }
127
- ]
145
+ type: "Identifier",
146
+ name: cellComponentName
128
147
  }
129
148
  };
130
149
  path.node.body.push(exportDefaultDeclaration);
@@ -0,0 +1,20 @@
1
+ import type { Plugin } from 'vite';
2
+ /**
3
+ * Gives `CedarApolloProvider` the cache config for the scalars in
4
+ * `graphql.parsedScalars` in `cedar.toml`. Does nothing when no scalar is set
5
+ * to be parsed.
6
+ *
7
+ * The config comes from the project's generated GraphQL schema, so it is built
8
+ * into the virtual module `virtual:cedar-parsed-scalars` rather than into the
9
+ * provider, which is a published package that Vite pre-bundles in dev. The
10
+ * module puts the config on `globalThis.__CEDAR__PARSED_SCALARS`, where the
11
+ * provider reads it when it creates the cache, and `App` and the web test
12
+ * setup file import the module so that every entry point that renders the
13
+ * provider has it. The module is a
14
+ * dependency of the generated schema file, so a change to the schema reloads
15
+ * the app. The generated schema is only read, and `graphql` and its schema
16
+ * loader only imported, when the virtual module is actually resolved, so a
17
+ * project that doesn't use this setting doesn't pay for loading them.
18
+ */
19
+ export declare function cedarParsedScalarsPlugin(): Plugin | undefined;
20
+ //# sourceMappingURL=vite-plugin-cedar-parsed-scalars.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-plugin-cedar-parsed-scalars.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-cedar-parsed-scalars.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAclC;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,wBAAwB,IAAI,MAAM,GAAG,SAAS,CA4E7D"}
@@ -0,0 +1,60 @@
1
+ import { normalizePath } from "vite";
2
+ import { getParsedScalars, getPaths } from "@cedarjs/project-config";
3
+ const VIRTUAL_MODULE_ID = "virtual:cedar-parsed-scalars";
4
+ const RESOLVED_VIRTUAL_MODULE_ID = "\0" + VIRTUAL_MODULE_ID;
5
+ const APP_FILE_REGEXP = /web[\\/]src[\\/]App\.(ts|tsx|js|jsx)$/;
6
+ const VITEST_WEB_SETUP_FILE_REGEXP = /[\\/]vitest-web\.setup\.(ts|js)$/;
7
+ function cedarParsedScalarsPlugin() {
8
+ if (Object.keys(getParsedScalars()).length === 0) {
9
+ return void 0;
10
+ }
11
+ return {
12
+ name: "cedar-parsed-scalars",
13
+ resolveId(id) {
14
+ if (id === VIRTUAL_MODULE_ID) {
15
+ return RESOLVED_VIRTUAL_MODULE_ID;
16
+ }
17
+ return null;
18
+ },
19
+ async load(id) {
20
+ if (id !== RESOLVED_VIRTUAL_MODULE_ID) {
21
+ return null;
22
+ }
23
+ this.addWatchFile(getPaths().generated.schema);
24
+ const { loadParsedScalarsCacheConfig } = await import("@cedarjs/internal/dist/generate/parsedScalars.js");
25
+ const config = loadParsedScalarsCacheConfig();
26
+ return `globalThis.__CEDAR__PARSED_SCALARS = ${JSON.stringify(config)}`;
27
+ },
28
+ transform(code, id) {
29
+ if (!APP_FILE_REGEXP.test(id) && !VITEST_WEB_SETUP_FILE_REGEXP.test(id)) {
30
+ return null;
31
+ }
32
+ return `import '${VIRTUAL_MODULE_ID}'
33
+ ${code}`;
34
+ },
35
+ // `this.addWatchFile` in `load` only reruns the virtual module for a
36
+ // change to a file it has already watched. The schema doesn't exist yet
37
+ // on a clean `cedar dev` (the web server and `cedar-gen-watch` start
38
+ // concurrently), so its first appearance is a 'create' event on a path
39
+ // nothing has watched yet, and reaches here without an `addWatchFile`
40
+ // call ever having registered it. Reload the virtual module for exactly
41
+ // that file, on every event type, so the app picks up the first schema
42
+ // once `cedar-gen-watch` writes it, the same way it already does for a
43
+ // later edit.
44
+ hotUpdate(options) {
45
+ if (options.file !== normalizePath(getPaths().generated.schema)) {
46
+ return;
47
+ }
48
+ const moduleGraph = this.environment.moduleGraph;
49
+ const module = moduleGraph.getModuleById(RESOLVED_VIRTUAL_MODULE_ID);
50
+ if (!module) {
51
+ return;
52
+ }
53
+ moduleGraph.invalidateModule(module);
54
+ return [module];
55
+ }
56
+ };
57
+ }
58
+ export {
59
+ cedarParsedScalarsPlugin
60
+ };
@@ -0,0 +1,20 @@
1
+ import type { Plugin } from 'vite';
2
+ /**
3
+ * For the bundled API build (`cedar build --ud`): the sandboxed child
4
+ * scripts in api/src are extra entries of the build (see
5
+ * `findSandboxChildScripts()`), so each comes out as
6
+ * `sandbox-children/<name>.child.js`. This plugin checks that each child
7
+ * stands alone, importing only packages and Node builtins (it can read
8
+ * nothing of the app), and then copies the packages they import into
9
+ * `sandbox-children/node_modules`.
10
+ *
11
+ * `findChildScript()` from `@cedarjs/api/sandbox` finds the children there
12
+ * from code in the bundle.
13
+ */
14
+ export declare function cedarSandboxChildrenPlugin({ environment, children, }: {
15
+ /** The bundled build's environment */
16
+ environment: string;
17
+ /** The child scripts' entries: `{ 'sandbox-children/x.child': file }` */
18
+ children: Record<string, string>;
19
+ }): Plugin;
20
+ //# sourceMappingURL=vite-plugin-cedar-sandbox-children.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-plugin-cedar-sandbox-children.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-cedar-sandbox-children.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AASlC;;;;;;;;;;;GAWG;AACH,wBAAgB,0BAA0B,CAAC,EACzC,WAAW,EACX,QAAQ,GACT,EAAE;IACD,sCAAsC;IACtC,WAAW,EAAE,MAAM,CAAA;IACnB,yEAAyE;IACzE,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACjC,GAAG,MAAM,CAmDT"}
@@ -0,0 +1,58 @@
1
+ import path from "node:path";
2
+ import { normalizePath } from "vite";
3
+ import {
4
+ SANDBOX_CHILDREN_DIR,
5
+ vendorSandboxChildPackages
6
+ } from "../lib/sandboxChildren.js";
7
+ function cedarSandboxChildrenPlugin({
8
+ environment,
9
+ children
10
+ }) {
11
+ const sources = new Set(
12
+ Object.values(children).map((file) => normalizePath(file))
13
+ );
14
+ let imports = [];
15
+ return {
16
+ name: "cedar-sandbox-children",
17
+ apply: "build",
18
+ applyToEnvironment(env) {
19
+ return env.name === environment;
20
+ },
21
+ generateBundle(_options, bundle) {
22
+ imports = [];
23
+ for (const chunk of Object.values(bundle)) {
24
+ if (chunk.type !== "chunk" || !chunk.facadeModuleId) {
25
+ continue;
26
+ }
27
+ const source = normalizePath(chunk.facadeModuleId);
28
+ if (!sources.has(source)) {
29
+ continue;
30
+ }
31
+ const bundled = [...chunk.imports, ...chunk.dynamicImports].filter(
32
+ (id) => id in bundle
33
+ );
34
+ if (bundled.length > 0) {
35
+ this.error(
36
+ `${path.basename(source)} imports your app's own code (${bundled.join(", ")}). A sandboxed child script may import only packages and Node builtins: it runs in a process that can't read the rest of your app.`
37
+ );
38
+ }
39
+ imports.push({
40
+ source,
41
+ imports: [...chunk.imports, ...chunk.dynamicImports]
42
+ });
43
+ }
44
+ },
45
+ writeBundle(options) {
46
+ if (imports.length === 0 || !options.dir) {
47
+ return;
48
+ }
49
+ vendorSandboxChildPackages(
50
+ path.join(options.dir, SANDBOX_CHILDREN_DIR),
51
+ imports
52
+ );
53
+ }
54
+ };
55
+ }
56
+ export {
57
+ cedarSandboxChildrenPlugin
58
+ };
@@ -25,9 +25,7 @@ import type { Plugin } from 'vite';
25
25
  * This replaces `babel-plugin-handler-als-wrapping` for Vite builds.
26
26
  * The babel plugin is still used for Jest and prerender.
27
27
  */
28
- export declare function handlerAlsWrappingPlugin({ projectIsEsm, }?: {
29
- projectIsEsm?: boolean;
30
- }): Plugin;
28
+ export declare function handlerAlsWrappingPlugin(): Plugin;
31
29
  /**
32
30
  * Wraps the `handler` export of an API function file with an async context
33
31
  * store guard. Returns the transformed code, or `null` if the file does not
@@ -38,7 +36,5 @@ export declare function handlerAlsWrappingPlugin({ projectIsEsm, }?: {
38
36
  * function so it can be applied from build pipelines that don't go through
39
37
  * Vite's plugin pipeline (e.g. the legacy esbuild API build).
40
38
  */
41
- export declare function applyHandlerAlsWrapping(code: string, { projectIsEsm }?: {
42
- projectIsEsm?: boolean;
43
- }): string | null;
39
+ export declare function applyHandlerAlsWrapping(code: string): string | null;
44
40
  //# sourceMappingURL=vite-plugin-handler-als-wrapping.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"vite-plugin-handler-als-wrapping.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-handler-als-wrapping.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAKlC;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,wBAAwB,CAAC,EACvC,YAAoB,GACrB,GAAE;IACD,YAAY,CAAC,EAAE,OAAO,CAAA;CAClB,GAAG,MAAM,CAuBd;AAED;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,MAAM,EACZ,EAAE,YAAoB,EAAE,GAAE;IAAE,YAAY,CAAC,EAAE,OAAO,CAAA;CAAO,GACxD,MAAM,GAAG,IAAI,CAsDf"}
1
+ {"version":3,"file":"vite-plugin-handler-als-wrapping.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-handler-als-wrapping.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAKlC;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,wBAAwB,IAAI,MAAM,CAuBjD;AAED;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAkDnE"}