@requence/service 1.0.0-alpha.1 → 1.0.0-alpha.2

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/build/index.js CHANGED
@@ -1,19 +1,28 @@
1
1
  import {
2
- clone,
3
- createObjectProxy,
4
- deobfuscate,
5
- obfuscate
6
- } from "./chunk-2exhyr7n.js";
2
+ clone,
3
+ createObjectProxy,
4
+ deobfuscate,
5
+ obfuscate
6
+ } from "./chunk-0x9092n4.js";
7
7
 
8
8
  // src/index.ts
9
- import {readFileSync} from "node:fs";
10
- import {z as z8} from "zod";
9
+ import { readFileSync } from "node:fs";
10
+ import { z as z8 } from "zod";
11
11
 
12
12
  // ../helpers/src/context/context.ts
13
- import {z} from "zod";
13
+ import { z } from "zod";
14
+ var contextSchema = z.object({
15
+ input: z.any(),
16
+ meta: z.any(),
17
+ tenant: z.object({ name: z.string() }),
18
+ data: z.record(z.string(), z.any()),
19
+ errors: z.record(z.string(), z.string()),
20
+ dates: z.record(z.string(), z.string().datetime())
21
+ });
14
22
  function isRecord(data) {
15
23
  return typeof data === "object" && data !== null && !Array.isArray(data);
16
24
  }
25
+ var internalKey = Symbol.for("internal");
17
26
  function getInternalContext(contextHelper) {
18
27
  return contextHelper[internalKey];
19
28
  }
@@ -84,24 +93,16 @@ function createContextHelper(context, nodes) {
84
93
  if (!nodeIds) {
85
94
  return null;
86
95
  }
87
- return nodeIds.map((nodeId) => results.get(nodeId)?.error).filter((str) => typeof str === "string").join("\n");
96
+ return nodeIds.map((nodeId) => results.get(nodeId)?.error).filter((str) => typeof str === "string").join(`
97
+ `);
88
98
  }
89
99
  };
90
100
  }
91
- var contextSchema = z.object({
92
- input: z.any(),
93
- meta: z.any(),
94
- tenant: z.object({ name: z.string() }),
95
- data: z.record(z.string(), z.any()),
96
- errors: z.record(z.string(), z.string()),
97
- dates: z.record(z.string(), z.string().datetime())
98
- });
99
- var internalKey = Symbol.for("internal");
100
101
  // ../helpers/src/protocol/command.ts
101
- import {z as z5} from "zod";
102
+ import { z as z5 } from "zod";
102
103
 
103
104
  // ../helpers/src/protocol/nodes.ts
104
- import {ZodError, z as z4} from "zod";
105
+ import { ZodError, z as z4 } from "zod";
105
106
 
106
107
  // ../helpers/src/protocol/getNodeOutputs.ts
107
108
  function getNodeOutputs(node, outputName) {
@@ -237,10 +238,10 @@ function identifyNode(nodeId, getNode) {
237
238
  }
238
239
 
239
240
  // ../helpers/src/protocol/node.ts
240
- import {z as z3} from "zod";
241
+ import { z as z3 } from "zod";
241
242
 
242
243
  // ../helpers/src/protocol/jsonSchema.ts
243
- import {z as z2} from "zod";
244
+ import { z as z2 } from "zod";
244
245
  var jsonSchema7Schema = z2.lazy(() => z2.object({
245
246
  $id: z2.string().optional(),
246
247
  $schema: z2.string().optional(),
@@ -303,37 +304,6 @@ var jsonSchema7ObjectSchema = z2.object({
303
304
  });
304
305
 
305
306
  // ../helpers/src/protocol/node.ts
306
- function validateOutputs(outputs, ctx) {
307
- const exitOutputs = new Set(outputs.filter((output) => output.exit).map((output) => output.default ? "__default__" : output.name));
308
- outputs.filter((output) => !output.exit).forEach((output) => {
309
- const name = output.default ? "__default__" : output.name;
310
- if (exitOutputs.has(name)) {
311
- ctx.addIssue({
312
- code: "custom",
313
- message: output.default ? `default exit output cannot be mixed with target output "${output.target}"` : `named exit output "${name}" cannot be mixed with target output "${output.target}"`
314
- });
315
- }
316
- });
317
- const targets = new Map;
318
- outputs.forEach((output) => {
319
- const name = output.default ? "__default__" : output.name;
320
- const target = output.exit ? "__exit__" : output.target;
321
- if (!targets.has(name)) {
322
- targets.set(name, new Set);
323
- }
324
- const knownTargets = targets.get(name);
325
- if (knownTargets.has(target)) {
326
- ctx.addIssue({
327
- code: "custom",
328
- message: [
329
- output.default ? "duplicate default output" : `duplicate named output "${name}"`,
330
- output.exit ? "for exit" : `for target "${target}"`
331
- ].join(" ")
332
- });
333
- }
334
- knownTargets.add(target);
335
- });
336
- }
337
307
  var outputDefinitionSchema = z3.object({
338
308
  schema: jsonSchema7Schema.nullable().optional()
339
309
  }).and(z3.union([
@@ -379,6 +349,37 @@ var outputSchema = z3.union([z3.string().min(1), outputDefinitionSchema]).transf
379
349
  }
380
350
  return output;
381
351
  });
352
+ function validateOutputs(outputs, ctx) {
353
+ const exitOutputs = new Set(outputs.filter((output) => output.exit).map((output) => output.default ? "__default__" : output.name));
354
+ outputs.filter((output) => !output.exit).forEach((output) => {
355
+ const name = output.default ? "__default__" : output.name;
356
+ if (exitOutputs.has(name)) {
357
+ ctx.addIssue({
358
+ code: "custom",
359
+ message: output.default ? `default exit output cannot be mixed with target output "${output.target}"` : `named exit output "${name}" cannot be mixed with target output "${output.target}"`
360
+ });
361
+ }
362
+ });
363
+ const targets = new Map;
364
+ outputs.forEach((output) => {
365
+ const name = output.default ? "__default__" : output.name;
366
+ const target = output.exit ? "__exit__" : output.target;
367
+ if (!targets.has(name)) {
368
+ targets.set(name, new Set);
369
+ }
370
+ const knownTargets = targets.get(name);
371
+ if (knownTargets.has(target)) {
372
+ ctx.addIssue({
373
+ code: "custom",
374
+ message: [
375
+ output.default ? "duplicate default output" : `duplicate named output "${name}"`,
376
+ output.exit ? "for exit" : `for target "${target}"`
377
+ ].join(" ")
378
+ });
379
+ }
380
+ knownTargets.add(target);
381
+ });
382
+ }
382
383
  var defaultOutputsSchema = z3.array(defaultOutputSchema).default([]).superRefine(validateOutputs);
383
384
  var outputsSchema = z3.array(outputSchema).default([]).superRefine(validateOutputs);
384
385
  var idSchema = z3.string().uuid().default(() => crypto.randomUUID());
@@ -397,8 +398,9 @@ var serviceNodeSchema = z3.object({
397
398
  inputSchema: jsonSchema7ObjectSchema.nullable().optional(),
398
399
  id: idSchema,
399
400
  name: z3.string(),
400
- version: z3.string().default("*"),
401
+ version: z3.string(),
401
402
  configuration: z3.any().optional(),
403
+ configurationSchema: jsonSchema7Schema.nullable().optional(),
402
404
  alias: z3.string().optional(),
403
405
  ttl: z3.number().int().min(1).optional(),
404
406
  retry: z3.number().int().min(1).optional(),
@@ -457,24 +459,24 @@ var nodesSchema = z4.array(nodeSchema).transform((nodes) => {
457
459
  const names = new Map;
458
460
  let entryNode = null;
459
461
  let firstNodeId = null;
460
- for (const node2 of nodes) {
461
- if (node2.type === "entry") {
462
- entryNode = node2;
462
+ for (const node of nodes) {
463
+ if (node.type === "entry") {
464
+ entryNode = node;
463
465
  }
464
- if ((node2.type === "service" || node2.type === "logic") && !firstNodeId) {
465
- firstNodeId = node2.id;
466
+ if ((node.type === "service" || node.type === "logic") && !firstNodeId) {
467
+ firstNodeId = node.id;
466
468
  }
467
- if ("alias" in node2 && node2.alias) {
468
- if (!aliases.has(node2.alias)) {
469
- aliases.set(node2.alias, []);
469
+ if ("alias" in node && node.alias) {
470
+ if (!aliases.has(node.alias)) {
471
+ aliases.set(node.alias, []);
470
472
  }
471
- aliases.get(node2.alias).push(node2.id);
473
+ aliases.get(node.alias).push(node.id);
472
474
  }
473
- if ("name" in node2 && node2.name) {
474
- if (!names.has(node2.name)) {
475
- names.set(node2.name, []);
475
+ if ("name" in node && node.name) {
476
+ if (!names.has(node.name)) {
477
+ names.set(node.name, []);
476
478
  }
477
- names.get(node2.name).push(node2.id);
479
+ names.get(node.name).push(node.id);
478
480
  }
479
481
  }
480
482
  if (!entryNode && firstNodeId) {
@@ -493,15 +495,15 @@ var nodesSchema = z4.array(nodeSchema).transform((nodes) => {
493
495
  }
494
496
  return identifier;
495
497
  };
496
- return nodes.map((node2) => {
497
- node2.output = node2.output.map((output) => ("target" in output) ? {
498
+ return nodes.map((node) => {
499
+ node.output = node.output.map((output) => ("target" in output) ? {
498
500
  ...output,
499
501
  target: resolveOutput(output.target)
500
502
  } : output);
501
- if ("subject" in node2) {
502
- node2.subject = resolveOutput(node2.subject);
503
+ if ("subject" in node) {
504
+ node.subject = resolveOutput(node.subject);
503
505
  }
504
- return node2;
506
+ return node;
505
507
  });
506
508
  }).transform((nodes) => {
507
509
  const { getInputs, getNode } = createNodeMaps(nodes);
@@ -509,28 +511,28 @@ var nodesSchema = z4.array(nodeSchema).transform((nodes) => {
509
511
  const nodeIds = new Set;
510
512
  const catchSubjects = new Map;
511
513
  const identify = (nodeId) => identifyNode(nodeId, getNode);
512
- for (const node2 of nodes) {
513
- if (nodeIds.has(node2.id)) {
514
+ for (const node of nodes) {
515
+ if (nodeIds.has(node.id)) {
514
516
  throw new NodesError("id is not unique", {
515
- id: node2.id
517
+ id: node.id
516
518
  });
517
519
  }
518
- nodeIds.add(node2.id);
519
- if ("alias" in node2 && node2.alias) {
520
- if (nodeAliases.has(node2.alias)) {
520
+ nodeIds.add(node.id);
521
+ if ("alias" in node && node.alias) {
522
+ if (nodeAliases.has(node.alias)) {
521
523
  throw new NodesError("alias is not unique", {
522
- alias: node2.alias
524
+ alias: node.alias
523
525
  });
524
526
  }
525
- nodeAliases.add(node2.alias);
527
+ nodeAliases.add(node.alias);
526
528
  }
527
- if (node2.type === "catch") {
528
- if (catchSubjects.has(node2.subject)) {
529
+ if (node.type === "catch") {
530
+ if (catchSubjects.has(node.subject)) {
529
531
  throw new NodesError("only one catch node per service allowed", {
530
- id: node2.subject
532
+ id: node.subject
531
533
  });
532
534
  }
533
- catchSubjects.set(node2.subject, node2);
535
+ catchSubjects.set(node.subject, node);
534
536
  }
535
537
  }
536
538
  if (!getNode("__entry__")) {
@@ -539,21 +541,21 @@ var nodesSchema = z4.array(nodeSchema).transform((nodes) => {
539
541
  if (getInputs("__exit__").length === 0) {
540
542
  throw new NodesError("no path leads to exit");
541
543
  }
542
- for (const catchNode of nodes.filter((node2) => node2.type === "catch")) {
544
+ for (const catchNode of nodes.filter((node) => node.type === "catch")) {
543
545
  if (!getNode(catchNode.subject)) {
544
546
  throw new NodesError("catch node has invalid subject", {
545
547
  id: catchNode.subject
546
548
  });
547
549
  }
548
550
  }
549
- for (const node2 of nodes) {
550
- if (node2.type === "or") {
551
- const inputs = getInputs(node2);
551
+ for (const node of nodes) {
552
+ if (node.type === "or") {
553
+ const inputs = getInputs(node);
552
554
  if (!inputs || inputs.length < 2) {
553
555
  throw new NodesError("or nodes need at least 2 inputs");
554
556
  }
555
557
  }
556
- for (const targetNodeId of getNodeOutputs(node2)) {
558
+ for (const targetNodeId of getNodeOutputs(node)) {
557
559
  if (targetNodeId !== "__exit__" && !getNode(targetNodeId)) {
558
560
  throw new NodesError("missing node", {
559
561
  id: targetNodeId
@@ -575,8 +577,8 @@ var nodesSchema = z4.array(nodeSchema).transform((nodes) => {
575
577
  }
576
578
  for (const possiblePath of possiblePaths) {
577
579
  for (const pathSegment of possiblePath) {
578
- const node2 = pathSegment === "__exit__" ? null : getNode(pathSegment);
579
- if (node2?.type === "catch" && possiblePath.includes(node2.subject)) {
580
+ const node = pathSegment === "__exit__" ? null : getNode(pathSegment);
581
+ if (node?.type === "catch" && possiblePath.includes(node.subject)) {
580
582
  throw new NodesError("Unresolvable, inputs needs both catch and subject", {
581
583
  path: possiblePath.map(identify)
582
584
  });
@@ -603,7 +605,7 @@ var createNodesSchema = z5.object({
603
605
  });
604
606
  var commandSchema = z5.union([abortSchema, createNodesSchema]);
605
607
  // ../helpers/src/protocol/update.ts
606
- import {z as z6} from "zod";
608
+ import { z as z6 } from "zod";
607
609
  var baseUpdateSchema = z6.object({
608
610
  timestamp: z6.number().int().transform((int) => new Date(int))
609
611
  });
@@ -665,22 +667,11 @@ var updateSchema = z6.discriminatedUnion("type", [
665
667
  taskErrorUpdateSchema,
666
668
  taskFinishedUpdateSchema
667
669
  ]);
668
- // src/connections/createAmqpConnection.ts
669
- import {connect} from "amqp-connection-manager";
670
- import semver from "semver";
671
- import {z as z7} from "zod";
670
+ // src/createAmqpConnection.ts
671
+ import { connect } from "amqp-connection-manager";
672
+ import { z as z7 } from "zod";
672
673
 
673
674
  // src/helpers.ts
674
- function isOutputValue(value) {
675
- return value !== null && typeof value === "object" && OUTPUT_VALUE in value;
676
- }
677
- function unwrapResult(result) {
678
- if (isOutputValue(result)) {
679
- return { value: result.value, outputName: result[OUTPUT_VALUE] };
680
- }
681
- return { value: result, outputName: null };
682
- }
683
-
684
675
  class RetryError extends Error {
685
676
  delay;
686
677
  constructor(delay) {
@@ -692,6 +683,15 @@ class RetryError extends Error {
692
683
  class AbortError extends Error {
693
684
  }
694
685
  var OUTPUT_VALUE = Symbol("output_value");
686
+ function isOutputValue(value) {
687
+ return value !== null && typeof value === "object" && OUTPUT_VALUE in value;
688
+ }
689
+ function unwrapResult(result) {
690
+ if (isOutputValue(result)) {
691
+ return { value: result.value, outputName: result[OUTPUT_VALUE] };
692
+ }
693
+ return { value: result, outputName: null };
694
+ }
695
695
  function createExtendedContextHelper(options) {
696
696
  const contextHelper = createContextHelper(options.context, options.nodes);
697
697
  const internalContext = getInternalContext(contextHelper);
@@ -738,10 +738,7 @@ function createExtendedContextHelper(options) {
738
738
  });
739
739
  }
740
740
 
741
- // src/connections/createAmqpConnection.ts
742
- function isMessageHandlerGenerator(handler) {
743
- return handler.constructor.name === "GeneratorFunction" || handler.constructor.name === "AsyncGeneratorFunction";
744
- }
741
+ // src/createAmqpConnection.ts
745
742
  var messageKeySchema = z7.string().transform((str) => deobfuscate(str)).pipe(z7.array(z7.string().uuid()).length(3)).transform((arr) => ({
746
743
  taskId: arr[0],
747
744
  serviceId: arr[1],
@@ -769,6 +766,9 @@ var payloadSchema = z7.object({ content: z7.instanceof(Buffer) }).transform((msg
769
766
  state: z7.record(z7.any())
770
767
  })
771
768
  }));
769
+ function isMessageHandlerGenerator(handler) {
770
+ return handler.constructor.name === "GeneratorFunction" || handler.constructor.name === "AsyncGeneratorFunction";
771
+ }
772
772
  var activeMessages = new Set;
773
773
  function createConnection({
774
774
  url,
@@ -777,7 +777,7 @@ function createConnection({
777
777
  silent = false,
778
778
  connectionTimeout
779
779
  }, messageHandler) {
780
- const queue = url.username;
780
+ const queue = `${url.username}@${version}`;
781
781
  const exchange = url.username;
782
782
  const connection = connect(url.toString());
783
783
  const connectedPromise = new Promise((resolve, reject) => {
@@ -833,36 +833,9 @@ function createConnection({
833
833
  try {
834
834
  let deferred = false;
835
835
  let deferredReason = null;
836
- const {
837
- messageId,
838
- serviceId,
839
- taskId,
840
- version: expectedVersion
841
- } = headerSchema.parse(message);
836
+ const { messageId, serviceId, taskId } = headerSchema.parse(message);
842
837
  activeMessages.add(messageId);
843
838
  removeActiveMessage = () => activeMessages.delete(messageId);
844
- if (!semver.satisfies(version, expectedVersion)) {
845
- let expirationDate = message.properties.headers?.["original-expiration-date"] ?? null;
846
- if (!expirationDate && message.properties.expiration) {
847
- expirationDate = String(Date.now() + parseInt(message.properties.expiration));
848
- }
849
- if (expirationDate && Date.now() > parseInt(expirationDate)) {
850
- channel.nack(message, false, false);
851
- return;
852
- }
853
- const properties = {
854
- ...message.properties,
855
- headers: {
856
- ...message.properties.headers,
857
- "version-mismatch": version,
858
- "original-expiration-date": expirationDate
859
- },
860
- expiration: 0
861
- };
862
- channel.publish(`${exchange}-retry`, "retry", message.content, properties);
863
- channel.ack(message);
864
- return;
865
- }
866
839
  const payload = payloadSchema.parse(message);
867
840
  let acked = false;
868
841
  const ack = () => {
@@ -917,13 +890,15 @@ function createConnection({
917
890
  console.warn("returning a value in a deferred message resets the deferred status");
918
891
  }
919
892
  const { value, outputName } = unwrapResult(result);
920
- publish({
921
- messageId,
922
- taskId,
923
- serviceId,
924
- data: value,
925
- outputName
926
- });
893
+ if (!done || typeof value !== "undefined") {
894
+ publish({
895
+ messageId,
896
+ taskId,
897
+ serviceId,
898
+ data: value,
899
+ outputName
900
+ });
901
+ }
927
902
  if (done) {
928
903
  break;
929
904
  }
@@ -946,14 +921,14 @@ function createConnection({
946
921
  });
947
922
  }
948
923
  }
949
- publish({
924
+ setImmediate(() => publish({
950
925
  messageId,
951
926
  taskId,
952
927
  serviceId,
953
928
  data: deferredReason,
954
929
  deferred,
955
930
  done: !deferred
956
- });
931
+ }));
957
932
  } catch (error) {
958
933
  if (error instanceof RetryError) {
959
934
  const properties = {
@@ -1002,61 +977,63 @@ function createConnection({
1002
977
  }
1003
978
  });
1004
979
  const api = {
1005
- close: () => channel.close(),
1006
- open: () => connectedPromise.then(() => api),
1007
- sendToOutput(messageKey, outputName, data) {
1008
- const { taskId, serviceId, messageId } = messageKeySchema.parse(messageKey);
1009
- if (activeMessages.has(messageId)) {
1010
- throw new Error("Cannot send deferred message while callback handler is still running");
1011
- }
1012
- publish({
1013
- messageId,
1014
- taskId,
1015
- serviceId,
1016
- data,
1017
- outputName
1018
- });
980
+ close: async () => {
981
+ await channel.close();
982
+ await connection.close();
1019
983
  },
1020
- send(messageKey, data) {
1021
- const { taskId, serviceId, messageId } = messageKeySchema.parse(messageKey);
1022
- if (activeMessages.has(messageId)) {
1023
- throw new Error("Cannot send deferred message while callback handler is still running");
1024
- }
1025
- publish({
1026
- messageId,
1027
- taskId,
1028
- serviceId,
1029
- data
984
+ open: () => connectedPromise.then(() => api),
985
+ async act(messageKey, actor) {
986
+ await actor({
987
+ sendToOutput(outputName, data) {
988
+ const { taskId: taskId2, serviceId: serviceId2, messageId: messageId2 } = messageKeySchema.parse(messageKey);
989
+ if (activeMessages.has(messageId2)) {
990
+ throw new Error("Cannot send deferred message while callback handler is still running");
991
+ }
992
+ publish({
993
+ messageId: messageId2,
994
+ taskId: taskId2,
995
+ serviceId: serviceId2,
996
+ data,
997
+ outputName
998
+ });
999
+ },
1000
+ send(data) {
1001
+ const { taskId: taskId2, serviceId: serviceId2, messageId: messageId2 } = messageKeySchema.parse(messageKey);
1002
+ if (activeMessages.has(messageId2)) {
1003
+ throw new Error("Cannot send deferred message while callback handler is still running");
1004
+ }
1005
+ publish({
1006
+ messageId: messageId2,
1007
+ taskId: taskId2,
1008
+ serviceId: serviceId2,
1009
+ data
1010
+ });
1011
+ },
1012
+ abort(error) {
1013
+ const { taskId: taskId2, serviceId: serviceId2, messageId: messageId2 } = messageKeySchema.parse(messageKey);
1014
+ if (activeMessages.has(messageId2)) {
1015
+ throw new Error("Cannot send deferred message while callback handler is still running");
1016
+ }
1017
+ channel.publish(`${exchange}-retry`, "requeue", error instanceof Error ? error.message : error, {
1018
+ correlationId: messageId2,
1019
+ expiration: 0,
1020
+ priority: 0,
1021
+ contentType: "text/plain",
1022
+ headers: {
1023
+ taskId: taskId2,
1024
+ serviceId: serviceId2,
1025
+ abort: true
1026
+ }
1027
+ });
1028
+ }
1030
1029
  });
1031
- },
1032
- end(messageKey) {
1033
1030
  const { taskId, serviceId, messageId } = messageKeySchema.parse(messageKey);
1034
- if (activeMessages.has(messageId)) {
1035
- throw new Error("Cannot send deferred message while callback handler is still running");
1036
- }
1037
- publish({
1031
+ setImmediate(() => publish({
1038
1032
  messageId,
1039
1033
  taskId,
1040
1034
  serviceId,
1041
1035
  done: true
1042
- });
1043
- },
1044
- abort(messageKey, error) {
1045
- const { taskId, serviceId, messageId } = messageKeySchema.parse(messageKey);
1046
- if (activeMessages.has(messageId)) {
1047
- throw new Error("Cannot send deferred message while callback handler is still running");
1048
- }
1049
- channel.publish(`${exchange}-retry`, "requeue", error instanceof Error ? error.message : error, {
1050
- correlationId: messageId,
1051
- expiration: 0,
1052
- priority: 0,
1053
- contentType: "text/plain",
1054
- headers: {
1055
- taskId,
1056
- serviceId,
1057
- abort: true
1058
- }
1059
- });
1036
+ }));
1060
1037
  }
1061
1038
  };
1062
1039
  return api;
@@ -1104,5 +1081,5 @@ export {
1104
1081
  createService as default
1105
1082
  };
1106
1083
 
1107
- //# debugId=B9746B0F55303A5264756E2164756E21
1084
+ //# debugId=8A6F0759E8DF605064756E2164756E21
1108
1085
  //# sourceMappingURL=index.js.map