next-action-plus 1.0.1 → 2.0.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.
Files changed (94) hide show
  1. package/README.md +862 -280
  2. package/dist/auth/authjs.d.ts +23 -0
  3. package/dist/auth/authjs.js +18 -0
  4. package/dist/auth/better-auth.d.ts +34 -0
  5. package/dist/auth/better-auth.js +17 -0
  6. package/dist/auth/clerk.d.ts +20 -0
  7. package/dist/auth/clerk.js +17 -0
  8. package/dist/auth/iron-session.d.ts +21 -0
  9. package/dist/auth/iron-session.js +18 -0
  10. package/dist/auth/kinde.d.ts +25 -0
  11. package/dist/auth/kinde.js +19 -0
  12. package/dist/auth/supabase.d.ts +29 -0
  13. package/dist/auth/supabase.js +17 -0
  14. package/dist/auth/workos.d.ts +25 -0
  15. package/dist/auth/workos.js +17 -0
  16. package/dist/authorize/casl.d.ts +14 -0
  17. package/dist/authorize/casl.js +10 -0
  18. package/dist/authorize/cerbos.d.ts +26 -0
  19. package/dist/authorize/cerbos.js +10 -0
  20. package/dist/authorize/openfga.d.ts +20 -0
  21. package/dist/authorize/openfga.js +10 -0
  22. package/dist/authorize/oso.d.ts +20 -0
  23. package/dist/authorize/oso.js +10 -0
  24. package/dist/authorize/permit.d.ts +14 -0
  25. package/dist/authorize/permit.js +10 -0
  26. package/dist/authorize.d.ts +11 -0
  27. package/dist/authorize.js +2 -0
  28. package/dist/chunk-2INYDUJR.js +16 -0
  29. package/dist/chunk-A55FM7D6.js +53 -0
  30. package/dist/chunk-GFGIJNSY.js +19 -0
  31. package/dist/chunk-IFAKJ72B.js +16 -0
  32. package/dist/codemod/bin.js +169 -0
  33. package/dist/concurrency/lock/memory.d.ts +5 -0
  34. package/dist/concurrency/lock/memory.js +1 -0
  35. package/dist/concurrency/lock/postgres.d.ts +9 -0
  36. package/dist/concurrency/lock/postgres.js +45 -0
  37. package/dist/concurrency/lock/redis.d.ts +9 -0
  38. package/dist/concurrency/lock/redis.js +30 -0
  39. package/dist/concurrency.d.ts +21 -0
  40. package/dist/concurrency.js +48 -0
  41. package/dist/conformance.d.ts +29 -0
  42. package/dist/conformance.js +139 -0
  43. package/dist/gate.d.ts +17 -0
  44. package/dist/gate.js +2 -0
  45. package/dist/i18n/next-intl.d.ts +12 -0
  46. package/dist/i18n/next-intl.js +11 -0
  47. package/dist/idempotency.d.ts +12 -0
  48. package/dist/idempotency.js +28 -0
  49. package/dist/index-BSA9a_EW.d.ts +22 -0
  50. package/dist/index-C3Ra6AYj.d.ts +37 -0
  51. package/dist/index-CZFS0TSh.d.ts +53 -0
  52. package/dist/index-CuAEDv-H.d.ts +64 -0
  53. package/dist/index-DJ2Ox9am.d.ts +31 -0
  54. package/dist/index-DV3R2g7H.d.ts +41 -0
  55. package/dist/index.d.ts +196 -192
  56. package/dist/index.js +189 -276
  57. package/dist/kv/memory.d.ts +5 -0
  58. package/dist/kv/memory.js +27 -0
  59. package/dist/kv/redis.d.ts +9 -0
  60. package/dist/kv/redis.js +23 -0
  61. package/dist/queue/bullmq.d.ts +18 -0
  62. package/dist/queue/bullmq.js +14 -0
  63. package/dist/queue/inngest.d.ts +18 -0
  64. package/dist/queue/inngest.js +14 -0
  65. package/dist/queue/qstash.d.ts +19 -0
  66. package/dist/queue/qstash.js +14 -0
  67. package/dist/queue/trigger.d.ts +16 -0
  68. package/dist/queue/trigger.js +11 -0
  69. package/dist/rate/limit/arcjet.d.ts +19 -0
  70. package/dist/rate/limit/arcjet.js +15 -0
  71. package/dist/rate/limit/unkey.d.ts +25 -0
  72. package/dist/rate/limit/unkey.js +14 -0
  73. package/dist/rate/limit/upstash.d.ts +18 -0
  74. package/dist/rate/limit/upstash.js +15 -0
  75. package/dist/rate/limit.d.ts +12 -0
  76. package/dist/rate/limit.js +17 -0
  77. package/dist/react.d.ts +40 -0
  78. package/dist/react.js +110 -0
  79. package/dist/security/origin.d.ts +11 -0
  80. package/dist/security/origin.js +21 -0
  81. package/dist/security/redact.d.ts +9 -0
  82. package/dist/security/redact.js +15 -0
  83. package/dist/security/secret.d.ts +6 -0
  84. package/dist/security/secret.js +13 -0
  85. package/dist/spec.d.ts +6 -0
  86. package/dist/spec.js +1 -0
  87. package/dist/telemetry/otel.d.ts +11 -0
  88. package/dist/telemetry/otel.js +25 -0
  89. package/dist/telemetry/pino.d.ts +12 -0
  90. package/dist/telemetry/pino.js +18 -0
  91. package/dist/telemetry/sentry.d.ts +16 -0
  92. package/dist/telemetry/sentry.js +11 -0
  93. package/package.json +325 -72
  94. package/dist/index.js.map +0 -1
@@ -0,0 +1,169 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/codemod/v2.ts
4
+ import ts from "typescript";
5
+ var REMOVED = ["ActionPlus", "ActionPlusError", "ActionPlusValidationError", "isActionPlusError", "isActionPlusValidationError", "schemaAvailable"];
6
+ var codemodV2 = (props) => {
7
+ const { project: project2, write: write2 } = props;
8
+ const configPath = ts.findConfigFile(project2, ts.sys.fileExists, "tsconfig.json");
9
+ if (!configPath) throw new Error(`next-action-plus codemod: no tsconfig.json found in ${project2}`);
10
+ const config = ts.getParsedCommandLineOfConfigFile(configPath, {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: (diagnostic) => console.error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")) });
11
+ if (!config) throw new Error(`next-action-plus codemod: cannot read ${configPath}`);
12
+ const program = ts.createProgram({ rootNames: config.fileNames, options: config.options });
13
+ const checker = program.getTypeChecker();
14
+ const resolved = ts.resolveModuleName("next-action-plus", configPath, config.options, ts.sys).resolvedModule?.resolvedFileName;
15
+ if (!resolved) throw new Error("next-action-plus codemod: next-action-plus is not installed in this project (run the codemod before upgrading to v2)");
16
+ const packageRoot = resolved.slice(0, resolved.lastIndexOf("/") + 1);
17
+ const fromPackage = (node) => {
18
+ const found = checker.getSymbolAtLocation(node);
19
+ const symbol = found && found.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(found) : found;
20
+ return !!symbol?.declarations?.some((declaration) => declaration.getSourceFile().fileName.startsWith(packageRoot));
21
+ };
22
+ const report2 = { files: [], todos: [], clashes: [] };
23
+ for (const source of program.getSourceFiles()) {
24
+ if (source.isDeclarationFile || source.fileName.includes("/node_modules/") || !source.fileName.startsWith(config.options.rootDir ?? project2)) continue;
25
+ const changes = [];
26
+ const line = (node) => source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
27
+ const todo = (node, message) => {
28
+ const statement = ts.findAncestor(node, (ancestor) => ts.isStatement(ancestor) && ts.isSourceFile(ancestor.parent)) ?? node;
29
+ const start = statement.getStart(source);
30
+ const indent = source.text.slice(source.text.lastIndexOf("\n", start - 1) + 1, start);
31
+ const comment = `// TODO(next-action-plus v2): ${message}`;
32
+ if (source.text.slice(0, start).trimEnd().endsWith(comment)) return;
33
+ if (!changes.some((change) => change.start === start && change.text.includes(message))) changes.push({ start, end: start, text: `${comment}
34
+ ${indent}` });
35
+ report2.todos.push({ file: source.fileName, line: line(node), message });
36
+ };
37
+ const handlerRename = (handler) => {
38
+ const parameter = handler.parameters[0];
39
+ if (!parameter) return;
40
+ const hasLocalInput = (() => {
41
+ let isFound = false;
42
+ const visit2 = (node) => {
43
+ if ((ts.isVariableDeclaration(node) || ts.isParameter(node) || ts.isBindingElement(node)) && ts.isIdentifier(node.name) && node.name.text === "input") isFound = true;
44
+ ts.forEachChild(node, visit2);
45
+ };
46
+ visit2(handler.body);
47
+ return isFound;
48
+ })();
49
+ if (ts.isObjectBindingPattern(parameter.name)) {
50
+ for (const element of parameter.name.elements) {
51
+ const key = element.propertyName ?? element.name;
52
+ if (!ts.isIdentifier(key) || key.text !== "parsedInput") continue;
53
+ if (element.propertyName) {
54
+ changes.push({ start: key.getStart(source), end: key.getEnd(), text: "input" });
55
+ continue;
56
+ }
57
+ if (hasLocalInput) {
58
+ changes.push({ start: key.getStart(source), end: key.getEnd(), text: "input: parsedInput" });
59
+ report2.clashes.push({ file: source.fileName, line: line(element) });
60
+ continue;
61
+ }
62
+ const binding = checker.getSymbolAtLocation(element.name);
63
+ changes.push({ start: key.getStart(source), end: key.getEnd(), text: "input" });
64
+ const visit2 = (node) => {
65
+ if (ts.isIdentifier(node) && node.text === "parsedInput" && node !== element.name && checker.getSymbolAtLocation(node) === binding) {
66
+ const isShorthand = ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node;
67
+ changes.push({ start: node.getStart(source), end: node.getEnd(), text: isShorthand ? "parsedInput: input" : "input" });
68
+ }
69
+ if (ts.isShorthandPropertyAssignment(node) && node.name.text === "parsedInput" && checker.getShorthandAssignmentValueSymbol(node) === binding) {
70
+ changes.push({ start: node.name.getStart(source), end: node.name.getEnd(), text: "parsedInput: input" });
71
+ return;
72
+ }
73
+ ts.forEachChild(node, visit2);
74
+ };
75
+ visit2(handler.body);
76
+ }
77
+ }
78
+ if (ts.isIdentifier(parameter.name)) {
79
+ const binding = checker.getSymbolAtLocation(parameter.name);
80
+ const visit2 = (node) => {
81
+ if (ts.isPropertyAccessExpression(node) && node.name.text === "parsedInput" && ts.isIdentifier(node.expression) && checker.getSymbolAtLocation(node.expression) === binding) changes.push({ start: node.name.getStart(source), end: node.name.getEnd(), text: "input" });
82
+ ts.forEachChild(node, visit2);
83
+ };
84
+ visit2(handler.body);
85
+ }
86
+ };
87
+ const visit = (node) => {
88
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && node.moduleSpecifier.text === "next-action-plus" && node.importClause?.namedBindings && ts.isNamedImports(node.importClause.namedBindings)) {
89
+ const removed = [];
90
+ for (const element of node.importClause.namedBindings.elements) {
91
+ const name = (element.propertyName ?? element.name).text;
92
+ if (name === "createActionPlus") changes.push({ start: (element.propertyName ?? element.name).getStart(source), end: (element.propertyName ?? element.name).getEnd(), text: "actionCreate" });
93
+ else if (REMOVED.includes(name) || name.startsWith("TActionPlus") || ["TMiddlewareFn", "TInfer", "TInferIn", "TFormDataInput", "TGenericSchema", "TGenericSchemaAsync", "TStandardSchemaV1"].includes(name)) removed.push(name);
94
+ }
95
+ if (removed.length) todo(node, `${removed.join(", ")} no longer exist(s) in v2. Errors: use errorGet({ error, code }) and TError; schemas: TSchema, TSchemaInput, TSchemaOutput; middleware: TMiddleware.`);
96
+ }
97
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && fromPackage(node.expression) && checker.getSymbolAtLocation(node.expression)?.getName() !== "actionCreate") {
98
+ const aliased = checker.getSymbolAtLocation(node.expression);
99
+ const original = aliased && aliased.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(aliased).getName() : aliased?.getName();
100
+ if (original === "createActionPlus") {
101
+ const isAlias = node.expression.text !== "createActionPlus";
102
+ if (!isAlias) changes.push({ start: node.expression.getStart(source), end: node.expression.getEnd(), text: "actionCreate" });
103
+ const [options] = node.arguments;
104
+ const kept = [];
105
+ if (options && ts.isObjectLiteralExpression(options)) {
106
+ for (const property of options.properties) {
107
+ const name = property.name && ts.isIdentifier(property.name) ? property.name.text : void 0;
108
+ if (name === "logger" && ts.isPropertyAssignment(property)) kept.push(`log: ${property.initializer.getText(source)}`);
109
+ else if (ts.isShorthandPropertyAssignment(property) && name === "logger") kept.push("log: logger");
110
+ else {
111
+ kept.push(property.getText(source));
112
+ if (name && ["onError", "formatError", "formatValidationError", "includeInputInErrorDetails"].includes(name)) todo(node, `the v1 option "${name}" was removed: use a middleware (.use) that reads next()'s result, or a response contract (response: ...).`);
113
+ }
114
+ }
115
+ } else if (options) todo(node, "createActionPlus options passed as a variable: rename `logger` to `log` and add `gate: { required: false }, limit: false` to keep v1 behavior.");
116
+ const text2 = `{ gate: { required: false }, limit: false${kept.length ? `, ${kept.join(", ")}` : ""} }`;
117
+ if (!options) changes.push({ start: node.arguments.pos, end: node.arguments.end, text: text2 });
118
+ else if (ts.isObjectLiteralExpression(options)) changes.push({ start: options.getStart(source), end: options.getEnd(), text: text2 });
119
+ }
120
+ }
121
+ if (ts.isIdentifier(node) && node.text === "createActionPlus" && !ts.isImportSpecifier(node.parent) && !(ts.isCallExpression(node.parent) && node.parent.expression === node) && fromPackage(node)) changes.push({ start: node.getStart(source), end: node.getEnd(), text: "actionCreate" });
122
+ if (ts.isPropertyAccessExpression(node) && fromPackage(node.name)) {
123
+ if (node.name.text === "schema") changes.push({ start: node.name.getStart(source), end: node.name.getEnd(), text: "input" });
124
+ if (node.name.text === "action" && ts.isCallExpression(node.parent) && node.parent.expression === node) {
125
+ const [handler] = node.parent.arguments;
126
+ if (handler && (ts.isArrowFunction(handler) || ts.isFunctionExpression(handler))) handlerRename(handler);
127
+ else if (handler) todo(node, "the action handler is not an inline function: rename `parsedInput` to `input` in it by hand.");
128
+ }
129
+ }
130
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.getText(source) === "Object.getPrototypeOf" && node.arguments[0]) {
131
+ const type = checker.getTypeAtLocation(node.arguments[0]);
132
+ if (type.getSymbol()?.declarations?.some((declaration) => declaration.getSourceFile().fileName.startsWith(packageRoot))) todo(node, "v2 has no ActionPlus class to patch. Replace this with a middleware on the client: actionClient = actionCreate(...).use(async props => { const result = await props.next(); /* result.ok, result.data | result.error, result.input */ return result; })");
133
+ }
134
+ ts.forEachChild(node, visit);
135
+ };
136
+ visit(source);
137
+ if (!changes.length) continue;
138
+ const unique = changes.filter((change, index) => changes.findIndex((other) => other.start === change.start && other.end === change.end && other.text === change.text) === index).sort((a, b) => b.start - a.start || b.end - a.end);
139
+ let text = source.text;
140
+ for (const change of unique) text = text.slice(0, change.start) + change.text + text.slice(change.end);
141
+ report2.files.push({ file: source.fileName, changes: unique.length, before: source.text, after: text });
142
+ if (write2) ts.sys.writeFile(source.fileName, text);
143
+ }
144
+ return report2;
145
+ };
146
+
147
+ // src/codemod/bin.ts
148
+ var [command, version, ...rest] = process.argv.slice(2);
149
+ if (command !== "codemod" || version !== "v2") {
150
+ console.log("Usage: npx next-action-plus codemod v2 [project path] [--write]\n\nRun it while v1 is still installed, then upgrade to v2. Without --write it only prints what would change.");
151
+ process.exit(command ? 1 : 0);
152
+ }
153
+ var write = rest.includes("--write");
154
+ var project = rest.find((argument) => !argument.startsWith("--")) ?? process.cwd();
155
+ var report = codemodV2({ project, write });
156
+ for (const file of report.files) {
157
+ console.log(`
158
+ ${write ? "changed" : "would change"} ${file.file} (${file.changes} edits)`);
159
+ if (!write) {
160
+ const before = file.before.split("\n");
161
+ file.after.split("\n").forEach((line, index) => line !== before[index] && console.log(` ${index + 1}: ${line.trim()}`));
162
+ }
163
+ }
164
+ for (const clash of report.clashes) console.log(`
165
+ note ${clash.file}:${clash.line} the handler already has a local \`input\`, so it now reads \`{ input: parsedInput }\``);
166
+ for (const todo of report.todos) console.log(`
167
+ TODO ${todo.file}:${todo.line} ${todo.message}`);
168
+ console.log(`
169
+ ${report.files.length} files, ${report.files.reduce((sum, file) => sum + file.changes, 0)} edits, ${report.todos.length} TODOs${write ? "" : " (dry run: add --write to apply)"}`);
@@ -0,0 +1,5 @@
1
+ import { T as TLock } from '../../index-C3Ra6AYj.js';
2
+
3
+ declare const lockMemory: () => TLock;
4
+
5
+ export { lockMemory };
@@ -0,0 +1 @@
1
+ export { lockMemory } from '../../chunk-A55FM7D6.js';
@@ -0,0 +1,9 @@
1
+ import { b as TPostgresClient, T as TLock } from '../../index-C3Ra6AYj.js';
2
+
3
+ declare const lockPostgres: (props: Readonly<{
4
+ client: TPostgresClient;
5
+ table?: string;
6
+ pollMs?: number;
7
+ }>) => TLock;
8
+
9
+ export { lockPostgres };
@@ -0,0 +1,45 @@
1
+ // src/concurrency/lock/postgres.ts
2
+ var lockPostgres = (props) => {
3
+ const { client } = props;
4
+ const table = props.table ?? "next_action_plus_lock";
5
+ if (!/^[a-z_][a-z0-9_]*$/i.test(table)) throw new Error(`next-action-plus: invalid lock table name "${table}"`);
6
+ const pollMs = props.pollMs ?? 50;
7
+ let ready;
8
+ const query = async (text, values) => {
9
+ ready ??= client.query({ text: `CREATE TABLE IF NOT EXISTS ${table} (key text PRIMARY KEY, token bigint NOT NULL DEFAULT 0, holder bigint, expires_at timestamptz, generation bigint NOT NULL DEFAULT 0)`, values: [] });
10
+ await ready;
11
+ return (await client.query({ text, values })).rows;
12
+ };
13
+ return {
14
+ name: "postgres",
15
+ version: 1,
16
+ acquire: async (acquireProps) => {
17
+ const { key, leaseMs, waitMs } = acquireProps;
18
+ const deadline = Date.now() + waitMs;
19
+ for (; ; ) {
20
+ const rows = await query(
21
+ `INSERT INTO ${table} (key, token, holder, expires_at) VALUES ($1, 1, 1, now() + $2::bigint * interval '1 millisecond')
22
+ ON CONFLICT (key) DO UPDATE SET token = ${table}.token + 1, holder = ${table}.token + 1, expires_at = EXCLUDED.expires_at
23
+ WHERE ${table}.holder IS NULL OR ${table}.expires_at <= now() RETURNING holder`,
24
+ [key, leaseMs]
25
+ );
26
+ const token = rows[0] ? Number(rows[0].holder) : 0;
27
+ if (token > 0) {
28
+ return {
29
+ token,
30
+ release: async () => void await query(`UPDATE ${table} SET holder = NULL WHERE key = $1 AND holder = $2`, [key, token]),
31
+ extend: async (extendProps) => (await query(`UPDATE ${table} SET expires_at = now() + $3::bigint * interval '1 millisecond' WHERE key = $1 AND holder = $2 AND expires_at > now() RETURNING key`, [key, token, extendProps.ms])).length === 1
32
+ };
33
+ }
34
+ if (Date.now() >= deadline) return null;
35
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollMs, Math.max(1, deadline - Date.now()))));
36
+ }
37
+ },
38
+ generation: async (generationProps) => {
39
+ const rows = generationProps.bump ? await query(`INSERT INTO ${table} (key, generation) VALUES ($1, 1) ON CONFLICT (key) DO UPDATE SET generation = ${table}.generation + 1 RETURNING generation`, [generationProps.key]) : await query(`SELECT generation FROM ${table} WHERE key = $1`, [generationProps.key]);
40
+ return rows[0] ? Number(rows[0].generation) : 0;
41
+ }
42
+ };
43
+ };
44
+
45
+ export { lockPostgres };
@@ -0,0 +1,9 @@
1
+ import { c as TRedisClient, T as TLock } from '../../index-C3Ra6AYj.js';
2
+
3
+ declare const lockRedis: (props: Readonly<{
4
+ client: TRedisClient;
5
+ prefix?: string;
6
+ pollMs?: number;
7
+ }>) => TLock;
8
+
9
+ export { lockRedis };
@@ -0,0 +1,30 @@
1
+ // src/concurrency/lock/redis.ts
2
+ var lockRedis = (props) => {
3
+ const { client } = props;
4
+ const prefix = props.prefix ?? "nap:";
5
+ const pollMs = props.pollMs ?? 50;
6
+ return {
7
+ name: "redis",
8
+ version: 1,
9
+ acquire: async (acquireProps) => {
10
+ const { key, leaseMs, waitMs } = acquireProps;
11
+ const keys = [`${prefix}lock:${key}`, `${prefix}token:${key}`];
12
+ const deadline = Date.now() + waitMs;
13
+ for (; ; ) {
14
+ const token = Number(await client.eval({ script: "if redis.call('EXISTS', KEYS[1]) == 1 then return 0 end local t = redis.call('INCR', KEYS[2]) redis.call('SET', KEYS[1], t, 'PX', ARGV[1]) return t", keys, args: [leaseMs] }));
15
+ if (token > 0) {
16
+ return {
17
+ token,
18
+ release: async () => void await client.eval({ script: "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0", keys: [keys[0]], args: [token] }),
19
+ extend: async (extendProps) => Number(await client.eval({ script: "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[1], ARGV[2]) end return 0", keys: [keys[0]], args: [token, extendProps.ms] })) === 1
20
+ };
21
+ }
22
+ if (Date.now() >= deadline) return null;
23
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollMs, Math.max(1, deadline - Date.now()))));
24
+ }
25
+ },
26
+ generation: async (generationProps) => Number(await client.eval({ script: generationProps.bump ? "return redis.call('INCR', KEYS[1])" : "return tonumber(redis.call('GET', KEYS[1]) or '0')", keys: [`${prefix}generation:${generationProps.key}`], args: [] }))
27
+ };
28
+ };
29
+
30
+ export { lockRedis };
@@ -0,0 +1,21 @@
1
+ import { T as TLock } from './index-C3Ra6AYj.js';
2
+ import { d as TPlugin } from './index-DV3R2g7H.js';
3
+ import { b as TPluginRead, c as TPluginShape } from './index-CZFS0TSh.js';
4
+ import './index-CuAEDv-H.js';
5
+
6
+ declare const concurrencyCreate: <Ctx extends object = object>(props: Readonly<{
7
+ strategy: "parallel" | "queue" | "drop" | "latest" | "keepLatest" | "dedupe";
8
+ key: TPluginRead<string, TPluginShape<Ctx>>;
9
+ lock?: TLock;
10
+ leaseMs?: number;
11
+ waitMs?: number;
12
+ timeoutMs?: number;
13
+ pollMs?: number;
14
+ }>) => TPlugin<TPluginShape<Ctx>, {
15
+ concurrency: {
16
+ signal: AbortSignal;
17
+ token: number;
18
+ };
19
+ }>;
20
+
21
+ export { concurrencyCreate };
@@ -0,0 +1,48 @@
1
+ import { lockMemory } from './chunk-A55FM7D6.js';
2
+ import { errorCreate } from './chunk-IFAKJ72B.js';
3
+
4
+ // src/concurrency/create.ts
5
+ var concurrencyCreate = (props) => {
6
+ const { strategy, key, timeoutMs } = props;
7
+ const lock = props.lock ?? lockMemory();
8
+ const leaseMs = props.leaseMs ?? 3e4;
9
+ const waitMs = props.waitMs ?? 3e4;
10
+ const pollMs = props.pollMs ?? 100;
11
+ const inflight = /* @__PURE__ */ new Map();
12
+ return {
13
+ name: `concurrency:${strategy}`,
14
+ version: 1,
15
+ run: async (call) => {
16
+ const name = `concurrency:${await key({ input: call.input, args: call.args, ctx: call.ctx, meta: call.meta })}`;
17
+ const controller = new AbortController();
18
+ const timers = [];
19
+ const run = (token) => call.next({ ctx: { concurrency: { signal: controller.signal, token } } });
20
+ if (timeoutMs) timers.push(setTimeout(() => controller.abort(errorCreate({ code: "TIMEOUT", message: `Timed out after ${timeoutMs}ms` })), timeoutMs));
21
+ let lease = null;
22
+ try {
23
+ if (strategy === "parallel") return await run(0);
24
+ if (strategy === "dedupe") {
25
+ const shared = inflight.get(name) ?? run(0).finally(() => inflight.delete(name));
26
+ inflight.set(name, shared);
27
+ return await shared;
28
+ }
29
+ const token = strategy === "latest" || strategy === "keepLatest" ? await lock.generation({ key: name, bump: true }) : 0;
30
+ if (strategy === "latest") {
31
+ timers.push(setInterval(() => void lock.generation({ key: name }).then((current) => current !== token && controller.abort(errorCreate({ code: "SUPERSEDED", message: "A newer call replaced this one" }))), pollMs));
32
+ return await run(token);
33
+ }
34
+ lease = await lock.acquire({ key: name, leaseMs, waitMs: strategy === "drop" ? 0 : waitMs });
35
+ if (!lease) throw errorCreate(strategy === "drop" ? { code: "DROPPED", message: "Already running, this call was dropped" } : { code: "LOCK_TIMEOUT", message: `Still busy after ${waitMs}ms` });
36
+ if (strategy === "keepLatest" && await lock.generation({ key: name }) !== token) throw errorCreate({ code: "SUPERSEDED", message: "A newer call is waiting, this one was skipped" });
37
+ const held = lease;
38
+ timers.push(setInterval(() => void held.extend({ ms: leaseMs }).then((isHeld) => isHeld || controller.abort(errorCreate({ code: "LOCK_TIMEOUT", message: "Lost the lock while running" }))), Math.max(10, Math.floor(leaseMs / 2))));
39
+ return await run(strategy === "keepLatest" ? token : held.token);
40
+ } finally {
41
+ for (const timer of timers) clearInterval(timer);
42
+ await lease?.release();
43
+ }
44
+ }
45
+ };
46
+ };
47
+
48
+ export { concurrencyCreate };
@@ -0,0 +1,29 @@
1
+ import { T as TKv } from './index-BSA9a_EW.js';
2
+ import { T as TLock } from './index-C3Ra6AYj.js';
3
+ import { d as TPlugin } from './index-DV3R2g7H.js';
4
+ import { T as TResponse } from './index-DJ2Ox9am.js';
5
+ import './index-CuAEDv-H.js';
6
+
7
+ declare const conformanceKv: (props: Readonly<{
8
+ kv: () => TKv | Promise<TKv>;
9
+ }>) => void;
10
+
11
+ declare const conformanceLock: (props: Readonly<{
12
+ lock: () => TLock | Promise<TLock>;
13
+ }>) => void;
14
+
15
+ declare const conformancePlugin: (props: Readonly<{
16
+ plugin: TPlugin<any, any, any, any>;
17
+ calls: Array<{
18
+ input?: unknown;
19
+ args?: unknown[];
20
+ ctx?: object;
21
+ meta?: object;
22
+ }>;
23
+ }>) => void;
24
+
25
+ declare const conformanceResponse: (props: Readonly<{
26
+ response: TResponse;
27
+ }>) => void;
28
+
29
+ export { conformanceKv, conformanceLock, conformancePlugin, conformanceResponse };
@@ -0,0 +1,139 @@
1
+ import { errorGet, errorCreate } from './chunk-IFAKJ72B.js';
2
+ import { describe, it, expect } from 'vitest';
3
+
4
+ var conformanceKv = (props) => {
5
+ const { kv } = props;
6
+ const unique = () => `conformance:${crypto.randomUUID()}`;
7
+ describe("kv contract v1", () => {
8
+ it("missing keys read as undefined", async () => {
9
+ expect(await (await kv()).get({ key: unique() })).toBeUndefined();
10
+ });
11
+ it.each([0, false, "", null, "text", { nested: [1, { a: true }] }])("round-trips %j", async (value) => {
12
+ const current = await kv();
13
+ const key = unique();
14
+ await current.set({ key, value });
15
+ expect(await current.get({ key })).toEqual(value);
16
+ });
17
+ it("expires after ttlMs", async () => {
18
+ const current = await kv();
19
+ const key = unique();
20
+ await current.set({ key, value: 1, ttlMs: 50 });
21
+ await new Promise((resolve) => setTimeout(resolve, 120));
22
+ expect(await current.get({ key })).toBeUndefined();
23
+ });
24
+ it("add only sets when absent", async () => {
25
+ const current = await kv();
26
+ const key = unique();
27
+ expect(await current.add({ key, value: 1 })).toBe(true);
28
+ expect(await current.add({ key, value: 2 })).toBe(false);
29
+ expect(await current.get({ key })).toBe(1);
30
+ });
31
+ it("delete removes", async () => {
32
+ const current = await kv();
33
+ const key = unique();
34
+ await current.set({ key, value: 1 });
35
+ await current.delete({ key });
36
+ expect(await current.get({ key })).toBeUndefined();
37
+ });
38
+ });
39
+ };
40
+ var conformanceLock = (props) => {
41
+ const { lock } = props;
42
+ const unique = () => `conformance:${crypto.randomUUID()}`;
43
+ describe("lock contract v1", async () => {
44
+ it("has a name and acquires a free key", async () => {
45
+ const current = await lock();
46
+ expect(current.name).toBeTruthy();
47
+ const lease = await current.acquire({ key: unique(), leaseMs: 1e3, waitMs: 0 });
48
+ expect(lease?.token).toBeGreaterThan(0);
49
+ await lease?.release();
50
+ });
51
+ it("refuses a held key with waitMs 0, and tokens only go up", async () => {
52
+ const current = await lock();
53
+ const key = unique();
54
+ const first = await current.acquire({ key, leaseMs: 1e3, waitMs: 0 });
55
+ expect(await current.acquire({ key, leaseMs: 1e3, waitMs: 0 })).toBeNull();
56
+ await first?.release();
57
+ const second = await current.acquire({ key, leaseMs: 1e3, waitMs: 0 });
58
+ expect(second?.token).toBeGreaterThan(first?.token);
59
+ await second?.release();
60
+ });
61
+ it("a waiter gets the lock after release", async () => {
62
+ const current = await lock();
63
+ const key = unique();
64
+ const first = await current.acquire({ key, leaseMs: 5e3, waitMs: 0 });
65
+ const waiting = current.acquire({ key, leaseMs: 1e3, waitMs: 2e3 });
66
+ setTimeout(() => void first?.release(), 50);
67
+ const second = await waiting;
68
+ expect(second).not.toBeNull();
69
+ await second?.release();
70
+ });
71
+ it("an expired lease can be taken over, and the old holder can no longer release or extend it", async () => {
72
+ const current = await lock();
73
+ const key = unique();
74
+ const first = await current.acquire({ key, leaseMs: 50, waitMs: 0 });
75
+ await new Promise((resolve) => setTimeout(resolve, 120));
76
+ const second = await current.acquire({ key, leaseMs: 1e3, waitMs: 0 });
77
+ expect(second).not.toBeNull();
78
+ expect(await first?.extend({ ms: 1e3 })).toBe(false);
79
+ await first?.release();
80
+ expect(await current.acquire({ key, leaseMs: 1e3, waitMs: 0 })).toBeNull();
81
+ expect(await second?.extend({ ms: 1e3 })).toBe(true);
82
+ await second?.release();
83
+ });
84
+ it("keys are independent", async () => {
85
+ const current = await lock();
86
+ const [a, b] = await Promise.all([current.acquire({ key: unique(), leaseMs: 1e3, waitMs: 0 }), current.acquire({ key: unique(), leaseMs: 1e3, waitMs: 0 })]);
87
+ expect(a).not.toBeNull();
88
+ expect(b).not.toBeNull();
89
+ await Promise.all([a?.release(), b?.release()]);
90
+ });
91
+ it("generation starts at 0 and bump increments it", async () => {
92
+ const current = await lock();
93
+ const key = unique();
94
+ expect(await current.generation({ key })).toBe(0);
95
+ expect(await current.generation({ key, bump: true })).toBe(1);
96
+ expect(await current.generation({ key, bump: true })).toBe(2);
97
+ expect(await current.generation({ key })).toBe(2);
98
+ });
99
+ });
100
+ };
101
+ var conformancePlugin = (props) => {
102
+ const { plugin, calls } = props;
103
+ describe(`plugin contract: ${plugin.name}`, () => {
104
+ it("has a name and version 1", () => {
105
+ expect(plugin.name).toBeTruthy();
106
+ expect(plugin.version ?? 1).toBe(1);
107
+ });
108
+ it.each(calls)("call %# returns next() or throws an action error", async (call) => {
109
+ const expected = { "~result": true, ok: true, data: "next", input: call.input };
110
+ try {
111
+ const result = await plugin.run({ input: call.input, args: call.args ?? [], ctx: call.ctx ?? {}, meta: call.meta ?? {}, errors: {}, next: (async () => expected) });
112
+ expect(result["~result"]).toBe(true);
113
+ } catch (error) {
114
+ expect(errorGet({ error }), String(error)).toBeDefined();
115
+ }
116
+ });
117
+ });
118
+ };
119
+ var conformanceResponse = (props) => {
120
+ const { response } = props;
121
+ const info = { meta: { name: "conformance" }, correlationId: "00000000-0000-0000-0000-000000000000" };
122
+ const internal = errorCreate({ code: "INTERNAL", message: "Internal error", cause: new Error("SELECT secret FROM users"), correlationId: info.correlationId });
123
+ describe("response contract", () => {
124
+ it("ok() is true for success and false for failure", () => {
125
+ expect(response.ok({ result: response.success({ data: { id: 1 }, info }) })).toBe(true);
126
+ expect(response.ok({ result: response.failure({ error: errorCreate({ code: "NOT_FOUND" }), info }) })).toBe(false);
127
+ });
128
+ it("results survive JSON (what React sends to the client)", () => {
129
+ for (const result of [response.success({ data: { id: 1, at: "2026-01-01" }, info }), response.failure({ error: internal, info })]) expect(JSON.parse(JSON.stringify(result ?? null))).toEqual(result ?? null);
130
+ });
131
+ it("a failure never carries the cause or the stack", () => {
132
+ const text = JSON.stringify(response.failure({ error: internal, info }));
133
+ expect(text).not.toContain("SELECT secret");
134
+ expect(text).not.toContain("at ");
135
+ });
136
+ });
137
+ };
138
+
139
+ export { conformanceKv, conformanceLock, conformancePlugin, conformanceResponse };
package/dist/gate.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { d as TPlugin } from './index-DV3R2g7H.js';
2
+ import { b as TPluginRead, c as TPluginShape, T as TGateCheck } from './index-CZFS0TSh.js';
3
+ import './index-CuAEDv-H.js';
4
+
5
+ declare const gateCreate: <User>(props: Readonly<{
6
+ name?: string;
7
+ user: TPluginRead<User | null | undefined, TPluginShape<object>>;
8
+ check?: TGateCheck<User>;
9
+ message?: {
10
+ unauthorized?: string;
11
+ forbidden?: string;
12
+ };
13
+ }>) => TPlugin<TPluginShape<object>, {
14
+ user: User;
15
+ }, {}, true>;
16
+
17
+ export { gateCreate };
package/dist/gate.js ADDED
@@ -0,0 +1,2 @@
1
+ export { gateCreate } from './chunk-GFGIJNSY.js';
2
+ import './chunk-IFAKJ72B.js';
@@ -0,0 +1,12 @@
1
+ import { e as TError } from '../index-CuAEDv-H.js';
2
+
3
+ declare const i18nNextIntl: (props: Readonly<{
4
+ translations: () => Promise<{
5
+ (key: string, values?: Record<string, unknown>): string;
6
+ has: (key: string) => boolean;
7
+ }>;
8
+ }>) => (messageProps: Readonly<{
9
+ error: TError;
10
+ }>) => Promise<string>;
11
+
12
+ export { i18nNextIntl };
@@ -0,0 +1,11 @@
1
+ // src/i18n/next-intl.ts
2
+ var i18nNextIntl = (props) => {
3
+ const { translations } = props;
4
+ return async (messageProps) => {
5
+ const t = await translations();
6
+ const data = messageProps.error.data;
7
+ return t.has(messageProps.error.code) ? t(messageProps.error.code, typeof data === "object" && data !== null ? data : void 0) : messageProps.error.message;
8
+ };
9
+ };
10
+
11
+ export { i18nNextIntl };
@@ -0,0 +1,12 @@
1
+ import { T as TKv } from './index-BSA9a_EW.js';
2
+ import { d as TPlugin } from './index-DV3R2g7H.js';
3
+ import { b as TPluginRead, c as TPluginShape } from './index-CZFS0TSh.js';
4
+ import './index-CuAEDv-H.js';
5
+
6
+ declare const idempotencyCreate: <Ctx extends object = object>(props: Readonly<{
7
+ kv: TKv;
8
+ key: TPluginRead<string | undefined, TPluginShape<Ctx>>;
9
+ ttlMs?: number;
10
+ }>) => TPlugin<TPluginShape<Ctx>>;
11
+
12
+ export { idempotencyCreate };
@@ -0,0 +1,28 @@
1
+ import { errorCreate } from './chunk-IFAKJ72B.js';
2
+
3
+ // src/idempotency/create.ts
4
+ var idempotencyCreate = (props) => {
5
+ const { kv, key } = props;
6
+ const ttlMs = props.ttlMs ?? 24 * 60 * 60 * 1e3;
7
+ return {
8
+ name: `idempotency:${kv.name}`,
9
+ version: 1,
10
+ run: async (call) => {
11
+ const found = await key({ input: call.input, args: call.args, ctx: call.ctx, meta: call.meta });
12
+ if (!found) return call.next();
13
+ const name = `idempotency:${found}`;
14
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([call.input, call.args])));
15
+ const fingerprint = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
16
+ const conflict = (reason) => errorCreate({ code: "CONFLICT", message: reason === "IN_FLIGHT" ? "This request is still being processed" : "This idempotency key was used with a different request", data: { reason } });
17
+ const stored = await kv.get({ key: name });
18
+ if (stored && stored.fingerprint !== fingerprint) throw conflict("KEY_REUSED");
19
+ if (stored?.state === "done") return { "~result": true, ok: true, data: stored.data, input: call.input };
20
+ if (stored || !await kv.add({ key: name, value: { state: "running", fingerprint }, ttlMs })) throw conflict("IN_FLIGHT");
21
+ const result = await call.next();
22
+ await (result.ok ? kv.set({ key: name, value: { state: "done", fingerprint, data: result.data }, ttlMs }) : kv.delete({ key: name }));
23
+ return result;
24
+ }
25
+ };
26
+ };
27
+
28
+ export { idempotencyCreate };
@@ -0,0 +1,22 @@
1
+ type TKv = {
2
+ readonly name: string;
3
+ readonly version?: 1;
4
+ readonly get: (props: Readonly<{
5
+ key: string;
6
+ }>) => Promise<unknown>;
7
+ readonly set: (props: Readonly<{
8
+ key: string;
9
+ value: unknown;
10
+ ttlMs?: number;
11
+ }>) => Promise<void>;
12
+ readonly add: (props: Readonly<{
13
+ key: string;
14
+ value: unknown;
15
+ ttlMs?: number;
16
+ }>) => Promise<boolean>;
17
+ readonly delete: (props: Readonly<{
18
+ key: string;
19
+ }>) => Promise<void>;
20
+ };
21
+
22
+ export type { TKv as T };