@indent-com/nexus-sdk 0.0.0-stage → 0.1.1

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 (46) hide show
  1. package/dist/analyze.d.ts +26 -0
  2. package/dist/analyze.js +190 -0
  3. package/dist/build.d.ts +32 -0
  4. package/dist/build.js +141 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +21 -0
  7. package/dist/client.d.ts +18 -0
  8. package/dist/client.js +4 -0
  9. package/dist/contract.d.ts +7 -0
  10. package/dist/contract.js +1 -0
  11. package/dist/errors.d.ts +10 -0
  12. package/dist/errors.js +20 -0
  13. package/dist/helpers.d.ts +3 -0
  14. package/dist/helpers.js +43 -0
  15. package/dist/index.d.ts +199 -0
  16. package/dist/index.js +117 -0
  17. package/dist/manifest.d.ts +34 -0
  18. package/dist/react.d.ts +10 -0
  19. package/dist/react.js +7 -0
  20. package/dist/schema.d.ts +6 -0
  21. package/dist/schema.js +75 -0
  22. package/dist/store.d.ts +9 -0
  23. package/dist/store.js +118 -0
  24. package/dist/stubs.d.ts +1 -0
  25. package/dist/stubs.js +1 -0
  26. package/dist/vite.d.ts +7 -0
  27. package/dist/vite.js +56 -0
  28. package/package.json +68 -4
  29. package/template/.agents/skills/building-nexus-apps/SKILL.md +66 -0
  30. package/template/.agents/skills/building-nexus-apps/gotchas.md +40 -0
  31. package/template/.agents/skills/building-nexus-apps/local-testing.md +88 -0
  32. package/template/AGENTS.md +16 -0
  33. package/template/README.md +25 -0
  34. package/template/_gitignore +4 -0
  35. package/template/migrations/0001_notes.sql +5 -0
  36. package/template/package.json +24 -0
  37. package/template/pnpm-workspace.yaml +2 -0
  38. package/template/server/notes.ts +19 -0
  39. package/template/tsconfig.json +15 -0
  40. package/template/ui/index.html +12 -0
  41. package/template/ui/src/App.tsx +84 -0
  42. package/template/ui/src/components.tsx +44 -0
  43. package/template/ui/src/main.tsx +4 -0
  44. package/template/ui/src/style.css +5 -0
  45. package/template/ui/vite.config.mjs +4 -0
  46. package/README.md +0 -3
@@ -0,0 +1,26 @@
1
+ import type { JsonSchema } from "@indent-com/nexus-sdk/manifest";
2
+ import type { Kind } from "./contract.ts";
3
+ export type Entrypoint = {
4
+ name: string;
5
+ kind: Kind;
6
+ input: JsonSchema;
7
+ output: JsonSchema;
8
+ description: string;
9
+ perViewer: boolean;
10
+ error?: string;
11
+ };
12
+ export type Installation = {
13
+ service: string;
14
+ alias: string;
15
+ };
16
+ export type TypedStatement = {
17
+ sql: string;
18
+ row: JsonSchema;
19
+ };
20
+ export type Analysis = {
21
+ entrypoints: Entrypoint[];
22
+ installations: Installation[];
23
+ env: string[];
24
+ statements: TypedStatement[];
25
+ };
26
+ export declare function analyze(root: string): Analysis;
@@ -0,0 +1,190 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+ import ts from "typescript";
4
+ import { BuildError, toSchema } from "./schema.js";
5
+ const defaults = {
6
+ strict: true,
7
+ target: ts.ScriptTarget.ES2023,
8
+ module: ts.ModuleKind.ESNext,
9
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
10
+ jsx: ts.JsxEmit.ReactJSX,
11
+ skipLibCheck: true,
12
+ };
13
+ export function analyze(root) {
14
+ const server = join(root, "server");
15
+ const sources = existsSync(server)
16
+ ? readdirSync(server, { recursive: true, encoding: "utf8" })
17
+ .filter((file) => /\.tsx?$/.test(file) && !file.endsWith(".d.ts"))
18
+ .map((file) => join(server, file))
19
+ : [];
20
+ const ambient = readdirSync(root)
21
+ .filter((file) => file.endsWith(".d.ts"))
22
+ .map((file) => join(root, file));
23
+ const options = compilerOptions(root);
24
+ const program = ts.createProgram([...sources, ...ambient], options);
25
+ const checker = program.getTypeChecker();
26
+ const sdk = ts.resolveModuleName("@indent-com/nexus-sdk", join(server, "x.ts"), options, ts.sys)
27
+ .resolvedModule?.resolvedFileName;
28
+ const integrations = join(root, "integrations.d.ts");
29
+ const problems = [];
30
+ const entrypoints = [];
31
+ const installations = new Map();
32
+ const env = new Set();
33
+ const statements = new Map();
34
+ const where = (node) => {
35
+ const file = node.getSourceFile();
36
+ const { line } = file.getLineAndCharacterOfPosition(node.getStart());
37
+ return `${relative(root, file.fileName)}:${line + 1}`;
38
+ };
39
+ const problem = (node, message) => {
40
+ problems.push(`${where(node)}: ${message}`);
41
+ };
42
+ const exported = (callee) => {
43
+ const found = checker.getSymbolAtLocation(callee);
44
+ const symbol = found && found.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(found) : found;
45
+ const declared = symbol?.declarations?.[0]?.getSourceFile().fileName;
46
+ return declared === sdk ? symbol?.name : undefined;
47
+ };
48
+ const helper = (callee) => {
49
+ const name = exported(callee);
50
+ return name === "query" || name === "mutation" ? name : undefined;
51
+ };
52
+ const statement = (node) => {
53
+ const [row] = node.typeArguments ?? [];
54
+ if (row === undefined || exported(node.tag) !== "sql")
55
+ return;
56
+ const { template } = node;
57
+ const sql = ts.isNoSubstitutionTemplateLiteral(template)
58
+ ? template.text
59
+ : template.head.text + template.templateSpans.map((span) => `?${span.literal.text}`).join("");
60
+ try {
61
+ const schema = toSchema(checker, checker.getTypeFromTypeNode(row), `sql<${row.getText()}>`);
62
+ if (schema.type !== "object") {
63
+ throw new BuildError(`sql<${row.getText()}> must be an object type`);
64
+ }
65
+ statements.set(JSON.stringify([sql, schema]), { sql, row: schema });
66
+ }
67
+ catch (error) {
68
+ if (!(error instanceof BuildError))
69
+ throw error;
70
+ problem(node, error.message);
71
+ }
72
+ };
73
+ const entrypoint = (call, kind) => {
74
+ const declaration = call.parent;
75
+ const statement = declaration.parent?.parent;
76
+ const file = call.getSourceFile();
77
+ if (!ts.isVariableDeclaration(declaration) ||
78
+ !ts.isIdentifier(declaration.name) ||
79
+ declaration.initializer !== call ||
80
+ !(declaration.parent.flags & ts.NodeFlags.Const) ||
81
+ !ts.isVariableStatement(statement) ||
82
+ statement.parent !== file ||
83
+ !file.fileName.startsWith(`${server}/`) ||
84
+ !statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
85
+ return problem(call, `${kind} must make a top-level \`export const\` in server/`);
86
+ }
87
+ const module = relative(server, file.fileName).replace(/\.tsx?$/, "");
88
+ const name = `${module}/${declaration.name.text}`;
89
+ const doc = checker.getSymbolAtLocation(declaration.name)?.getDocumentationComment(checker);
90
+ const found = { name, kind, description: ts.displayPartsToString(doc) };
91
+ // A broken entrypoint fails only its own calls, so the rest of the app still runs.
92
+ const broken = (message) => entrypoints.push({
93
+ ...found,
94
+ input: { type: "object" },
95
+ output: {},
96
+ perViewer: false,
97
+ error: `${where(call)}: ${message}`,
98
+ });
99
+ const [fn] = checker.getTypeAtLocation(call.arguments[0]).getCallSignatures();
100
+ if (fn === undefined)
101
+ return broken(`${name} must take a function`);
102
+ const [input, context] = fn.parameters;
103
+ try {
104
+ const schema = input
105
+ ? toSchema(checker, checker.getTypeOfSymbol(input), `${name} input`)
106
+ : { type: "object", properties: {}, additionalProperties: false };
107
+ if (schema.type !== "object")
108
+ throw new BuildError(`${name} input must be an object type`);
109
+ const output = checker.getAwaitedType(fn.getReturnType()) ?? fn.getReturnType();
110
+ entrypoints.push({
111
+ ...found,
112
+ input: schema,
113
+ output: toSchema(checker, output, `${name} output`),
114
+ perViewer: kind === "query" && context !== undefined,
115
+ });
116
+ }
117
+ catch (error) {
118
+ if (!(error instanceof BuildError))
119
+ throw error;
120
+ broken(error.message);
121
+ }
122
+ };
123
+ const staticName = (access, object) => {
124
+ if (ts.isPropertyAccessExpression(access) && access.expression === object) {
125
+ return access.name.text;
126
+ }
127
+ if (ts.isElementAccessExpression(access) &&
128
+ access.expression === object &&
129
+ ts.isStringLiteralLike(access.argumentExpression)) {
130
+ return access.argumentExpression.text;
131
+ }
132
+ return undefined;
133
+ };
134
+ const reference = (node) => {
135
+ const parent = node.parent;
136
+ if (node.text === "process" && staticName(parent, node) === "env") {
137
+ const variable = staticName(parent.parent, parent);
138
+ if (variable === undefined)
139
+ problem(parent, "read process.env by name, as in process.env.TOKEN");
140
+ else
141
+ env.add(variable);
142
+ return;
143
+ }
144
+ const declared = checker.getSymbolAtLocation(node)?.valueDeclaration?.getSourceFile();
145
+ if (declared?.fileName !== integrations)
146
+ return;
147
+ const alias = staticName(parent, node);
148
+ if (alias === undefined && ts.isElementAccessExpression(parent)) {
149
+ problem(parent, `name the installation by its slug, as in ${node.text}["acme"]`);
150
+ }
151
+ else if (alias !== undefined && alias !== "me") {
152
+ installations.set(`${node.text}["${alias}"]`, { service: node.text, alias });
153
+ }
154
+ };
155
+ const visit = (node) => {
156
+ if (ts.isCallExpression(node)) {
157
+ const kind = helper(node.expression);
158
+ if (kind !== undefined)
159
+ entrypoint(node, kind);
160
+ }
161
+ if (ts.isTaggedTemplateExpression(node))
162
+ statement(node);
163
+ if (ts.isIdentifier(node))
164
+ reference(node);
165
+ ts.forEachChild(node, visit);
166
+ };
167
+ for (const file of program.getSourceFiles()) {
168
+ if (!file.isDeclarationFile && !program.isSourceFileFromExternalLibrary(file))
169
+ visit(file);
170
+ }
171
+ if (problems.length > 0)
172
+ throw new BuildError(problems.join("\n"));
173
+ return {
174
+ entrypoints,
175
+ installations: [...installations]
176
+ .sort(([a], [b]) => a.localeCompare(b))
177
+ .map(([, installation]) => installation),
178
+ env: [...env].sort(),
179
+ statements: [...statements]
180
+ .sort(([a], [b]) => a.localeCompare(b))
181
+ .map(([, typed]) => typed),
182
+ };
183
+ }
184
+ function compilerOptions(root) {
185
+ const file = join(root, "tsconfig.json");
186
+ if (!existsSync(file))
187
+ return defaults;
188
+ const { config } = ts.readConfigFile(file, ts.sys.readFile);
189
+ return ts.parseJsonConfigFileContent(config, ts.sys, root).options;
190
+ }
@@ -0,0 +1,32 @@
1
+ import type { IncomingMessage, Server, ServerResponse } from "node:http";
2
+ import { type Entrypoint, type Installation, type TypedStatement } from "./analyze.ts";
3
+ import { BuildError } from "./schema.ts";
4
+ export type { DbBridge, DbGlobal, DbStatement, Kind } from "./contract.ts";
5
+ export type { Entrypoint, Installation, TypedStatement };
6
+ export { BuildError };
7
+ export type Migration = {
8
+ file: string;
9
+ sha256: string;
10
+ };
11
+ export type AppManifest = {
12
+ sdk: string;
13
+ installations: Installation[];
14
+ env: string[];
15
+ entrypoints: Entrypoint[];
16
+ migrations: Migration[];
17
+ statements: TypedStatement[];
18
+ };
19
+ export type BuildOptions = {
20
+ ui?: boolean;
21
+ };
22
+ export type ServeOptions = {
23
+ entrypoints: () => readonly Entrypoint[];
24
+ server: Server;
25
+ };
26
+ export type UiServer = {
27
+ handle(request: IncomingMessage, response: ServerResponse): void;
28
+ reload(): void;
29
+ close(): Promise<void>;
30
+ };
31
+ export declare function build(dir: string, options?: BuildOptions): Promise<AppManifest>;
32
+ export declare function serve(dir: string, options: ServeOptions): Promise<UiServer>;
package/dist/build.js ADDED
@@ -0,0 +1,141 @@
1
+ import { createHash } from "node:crypto";
2
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync, } from "node:fs";
3
+ import { builtinModules } from "node:module";
4
+ import { join } from "node:path";
5
+ import esbuild from "esbuild";
6
+ import { build as buildUi, createServer } from "vite";
7
+ import { analyze } from "./analyze.js";
8
+ import { BuildError } from "./schema.js";
9
+ import { stubPrefix } from "./stubs.js";
10
+ import { nexus } from "./vite.js";
11
+ export { BuildError };
12
+ const sdk = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
13
+ export async function build(dir, options = {}) {
14
+ const root = realpathSync(dir);
15
+ const { entrypoints, installations, env, statements } = analyze(root);
16
+ const dist = join(root, "dist");
17
+ rmSync(dist, { recursive: true, force: true });
18
+ mkdirSync(dist);
19
+ for (const file of await bundle(root, entrypoints))
20
+ writeFileSync(file.path, file.contents);
21
+ const migrations = copyMigrations(root, dist);
22
+ if (options.ui !== false && existsSync(join(root, "ui", "index.html"))) {
23
+ await buildUi({
24
+ root: join(root, "ui"),
25
+ logLevel: "warn",
26
+ plugins: [nexus({ root, entrypoints: () => entrypoints })],
27
+ build: { outDir: join(dist, "ui"), emptyOutDir: true },
28
+ });
29
+ }
30
+ const manifest = { sdk, installations, env, entrypoints, migrations, statements };
31
+ writeFileSync(join(dist, "app_manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
32
+ return manifest;
33
+ }
34
+ export async function serve(dir, options) {
35
+ const root = realpathSync(dir);
36
+ const vite = await createServer({
37
+ root: join(root, "ui"),
38
+ appType: "spa",
39
+ plugins: [nexus({ root, entrypoints: options.entrypoints })],
40
+ server: { middlewareMode: true, hmr: { server: options.server } },
41
+ });
42
+ return {
43
+ handle: (request, response) => vite.middlewares(request, response),
44
+ reload() {
45
+ for (const module of vite.moduleGraph.idToModuleMap.values()) {
46
+ if (module.id?.startsWith(stubPrefix))
47
+ vite.moduleGraph.invalidateModule(module);
48
+ }
49
+ vite.ws.send({ type: "full-reload" });
50
+ },
51
+ close: () => vite.close(),
52
+ };
53
+ }
54
+ async function bundle(root, entrypoints) {
55
+ const contents = entrypoints
56
+ .map(({ name, kind, error }, index) => {
57
+ const at = name.lastIndexOf("/");
58
+ const as = JSON.stringify(name);
59
+ if (error !== undefined) {
60
+ const failure = JSON.stringify({ name: "BuildError", code: "build_failed" });
61
+ const fail = `throw Object.assign(new Error(${JSON.stringify(error)}), ${failure})`;
62
+ const fn = `Object.assign(async () => { ${fail}; }, { kind: ${JSON.stringify(kind)} })`;
63
+ return `const broken${index} = ${fn};\nexport { broken${index} as ${as} };`;
64
+ }
65
+ const from = JSON.stringify(`./server/${name.slice(0, at)}`);
66
+ return `export { ${name.slice(at + 1)} as ${as} } from ${from};`;
67
+ })
68
+ .join("\n");
69
+ const result = await esbuild.build({
70
+ stdin: { contents, resolveDir: root, sourcefile: "app.ts", loader: "ts" },
71
+ absWorkingDir: root,
72
+ bundle: true,
73
+ format: "esm",
74
+ platform: "neutral",
75
+ target: "es2023",
76
+ conditions: ["worker", "browser"],
77
+ mainFields: ["browser", "module", "main"],
78
+ plugins: [builtins],
79
+ metafile: true,
80
+ outfile: join(root, "dist", "app.mjs"),
81
+ sourcemap: "external",
82
+ sourcesContent: false,
83
+ write: false,
84
+ logLevel: "silent",
85
+ });
86
+ const missing = nodeImports(result.metafile);
87
+ if (missing.length > 0)
88
+ throw new BuildError(missing.join("\n"));
89
+ return result.outputFiles;
90
+ }
91
+ const builtins = {
92
+ name: "node-builtins",
93
+ setup(build) {
94
+ const filter = new RegExp(`^(node:.*|${builtinModules.join("|")})$`);
95
+ build.onResolve({ filter }, async ({ path, pluginData, ...args }) => {
96
+ if (pluginData === builtins)
97
+ return undefined;
98
+ const found = await build.resolve(path, { ...args, pluginData: builtins });
99
+ return found.errors.length === 0 ? found : { path, external: true };
100
+ });
101
+ },
102
+ };
103
+ function nodeImports({ inputs }) {
104
+ const imports = Object.values(inputs).flatMap(({ imports }) => imports);
105
+ const imported = new Set(imports.map(({ path }) => path));
106
+ const queue = Object.keys(inputs).filter((file) => !imported.has(file));
107
+ const parents = new Map();
108
+ for (const file of queue) {
109
+ for (const { path, external } of inputs[file]?.imports ?? []) {
110
+ if (external || parents.has(path))
111
+ continue;
112
+ parents.set(path, file);
113
+ queue.push(path);
114
+ }
115
+ }
116
+ return queue.flatMap((file) => (inputs[file]?.imports ?? [])
117
+ .filter(({ external }) => external)
118
+ .map(({ path }) => {
119
+ const chain = [path];
120
+ for (let at = file; at && parents.has(at); at = parents.get(at)) {
121
+ chain.unshift(at);
122
+ }
123
+ return `${path} is not in the server runtime, imported by ${chain.join(" → ")}`;
124
+ }));
125
+ }
126
+ function copyMigrations(root, dist) {
127
+ const from = join(root, "migrations");
128
+ if (!existsSync(from))
129
+ return [];
130
+ mkdirSync(join(dist, "migrations"));
131
+ return readdirSync(from)
132
+ .filter((file) => file.endsWith(".sql"))
133
+ .sort()
134
+ .map((file) => {
135
+ copyFileSync(join(from, file), join(dist, "migrations", file));
136
+ const sha256 = createHash("sha256")
137
+ .update(readFileSync(join(from, file)))
138
+ .digest("hex");
139
+ return { file, sha256 };
140
+ });
141
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import { join, resolve } from "node:path";
3
+ import { build } from "./build.js";
4
+ const [command, dir = "."] = process.argv.slice(2);
5
+ if (command !== "build") {
6
+ console.error("usage: nexus-sdk build [dir]");
7
+ process.exit(2);
8
+ }
9
+ try {
10
+ const manifest = await build(resolve(dir));
11
+ console.log(`built ${manifest.entrypoints.length} entrypoints into ${join(dir, "dist")}`);
12
+ const broken = manifest.entrypoints.flatMap(({ error }) => error ?? []);
13
+ for (const error of broken)
14
+ console.error(error);
15
+ if (broken.length > 0)
16
+ process.exitCode = 1;
17
+ }
18
+ catch (error) {
19
+ console.error(error instanceof Error ? error.message : error);
20
+ process.exitCode = 1;
21
+ }
@@ -0,0 +1,18 @@
1
+ import type { Query, ToolError } from "@indent-com/nexus-sdk";
2
+
3
+ export { ToolError } from "@indent-com/nexus-sdk";
4
+
5
+ /** Watches a query outside React. Call the result to stop watching. */
6
+ export function watch<I, O>(
7
+ query: Query<I, O>,
8
+ input: I,
9
+ listener: (reading: Reading<O>) => void,
10
+ ): () => void;
11
+
12
+ /** A query's latest result, and whether it is being refreshed. */
13
+ export type Reading<O> = {
14
+ data: O | undefined; // the latest result
15
+ at: string | null; // when it was fetched
16
+ refreshing: boolean; // a live call is running
17
+ error: ToolError | undefined; // the last refresh failed; data is from before it
18
+ };
package/dist/client.js ADDED
@@ -0,0 +1,4 @@
1
+ import { watch as watchQuery } from "./store.js";
2
+ export { ToolError } from "./errors.js";
3
+ export { stub } from "./store.js";
4
+ export const watch = watchQuery;
@@ -0,0 +1,7 @@
1
+ import type { Result, Statement } from "@indent-com/nexus-sdk";
2
+ export type Kind = "query" | "mutation";
3
+ export type DbStatement = Statement<unknown>;
4
+ export type DbBridge = (statements: DbStatement[]) => Promise<Result<unknown>[]>;
5
+ export type DbGlobal = {
6
+ __nexusDb?: DbBridge;
7
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import type * as Sdk from "@indent-com/nexus-sdk";
2
+ export declare class ToolError extends Error implements Sdk.ToolError {
3
+ readonly name = "ToolError";
4
+ readonly code: string;
5
+ readonly retryable: boolean;
6
+ readonly data: unknown;
7
+ readonly link: string | undefined;
8
+ constructor(code: string, message: string, options?: Sdk.ToolErrorOptions);
9
+ static [Symbol.hasInstance](value: unknown): boolean;
10
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,20 @@
1
+ export class ToolError extends Error {
2
+ name = "ToolError";
3
+ code;
4
+ retryable;
5
+ data;
6
+ link;
7
+ constructor(code, message, options = {}) {
8
+ super(message);
9
+ this.code = code;
10
+ this.retryable = options.retryable ?? false;
11
+ this.data = options.data;
12
+ this.link = options.link;
13
+ }
14
+ // The runtime throws plain errors named ToolError, so they match too.
15
+ static [Symbol.hasInstance](value) {
16
+ return (value instanceof Error &&
17
+ value.name === "ToolError" &&
18
+ typeof value.code === "string");
19
+ }
20
+ }
@@ -0,0 +1,3 @@
1
+ import type * as Sdk from "@indent-com/nexus-sdk";
2
+ export declare const paginate: typeof Sdk.paginate;
3
+ export declare const map: typeof Sdk.map;
@@ -0,0 +1,43 @@
1
+ export const paginate = async ({ page, items, next, limit }) => {
2
+ const found = [];
3
+ let cursor;
4
+ for (;;) {
5
+ const current = await page(cursor);
6
+ found.push(...items(current));
7
+ const following = next(current) || undefined;
8
+ if (limit !== undefined && found.length >= limit) {
9
+ if (following !== undefined || found.length > limit)
10
+ console.warn(`paginate stopped at ${limit} items, and more remain`);
11
+ return found.slice(0, limit);
12
+ }
13
+ if (following === undefined)
14
+ return found;
15
+ if (following === cursor)
16
+ throw new Error(`paginate got cursor ${cursor} twice`);
17
+ cursor = following;
18
+ }
19
+ };
20
+ export const map = async (items, fn, options = {}) => {
21
+ const { concurrency = 5 } = options;
22
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
23
+ throw new RangeError(`concurrency must be a positive integer, not ${concurrency}`);
24
+ }
25
+ const results = new Array(items.length);
26
+ let next = 0;
27
+ let failed = false;
28
+ const worker = async () => {
29
+ while (!failed && next < items.length) {
30
+ const index = next++;
31
+ try {
32
+ results[index] = await fn(items[index], index);
33
+ }
34
+ catch (error) {
35
+ failed = true;
36
+ throw error;
37
+ }
38
+ }
39
+ };
40
+ const workers = Math.min(concurrency, items.length);
41
+ await Promise.all(Array.from({ length: workers }, worker));
42
+ return results;
43
+ };