@openfn/language-common 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ast.json CHANGED
@@ -541,7 +541,7 @@
541
541
  "operation"
542
542
  ],
543
543
  "docs": {
544
- "description": "Scopes an array of data based on a JSONPath.\nUseful when the source data has `n` items you would like to map to\nan operation.\nThe operation will receive a slice of the data based of each item\nof the JSONPath provided.\n\nIt also ensures the results of an operation make their way back into\nthe state's references.",
544
+ "description": "Iterates over an array of items and invokes an operation upon each one, where the state\nobject is _scoped_ so that state.data is the item under iteration.\nThe rest of the state object is untouched and can be referenced as usual.\nYou can pass an array directly, or use lazy state or a JSONPath string to\nreference a slice of state.",
545
545
  "tags": [
546
546
  {
547
547
  "title": "public",
@@ -555,7 +555,18 @@
555
555
  },
556
556
  {
557
557
  "title": "example",
558
- "description": "each(\"$.[*]\",\n create(\"SObject\",\n field(\"FirstName\", sourceValue(\"$.firstName\"))\n )\n)"
558
+ "description": "each(\n $.data,\n // Inside the callback operation, `$.data` is scoped to the item under iteration\n insert(\"patient\", {\n patient_name: $.data.properties.case_name,\n patient_id: $.data.case_id,\n })\n);",
559
+ "caption": "Using lazy state ($) to iterate over items in state.data and pass each into an \"insert\" operation"
560
+ },
561
+ {
562
+ "title": "example",
563
+ "description": "each(\n $.data,\n insert(\"patient\", (state) => ({\n patient_id: state.data.case_id,\n ...state.data\n }))\n);",
564
+ "caption": "Iterate over items in state.data and pass each one into an \"insert\" operation"
565
+ },
566
+ {
567
+ "title": "example",
568
+ "description": "each(\n \"$.data[*]\",\n insert(\"patient\", (state) => ({\n patient_name: state.data.properties.case_name,\n patient_id: state.data.case_id,\n }))\n);",
569
+ "caption": "Using JSON path to iterate over items in state.data and pass each one into an \"insert\" operation"
559
570
  },
560
571
  {
561
572
  "title": "param",
package/dist/index.cjs CHANGED
@@ -60,6 +60,7 @@ __export(src_exports, {
60
60
  sourceValue: () => sourceValue,
61
61
  splitKeys: () => splitKeys,
62
62
  toArray: () => toArray,
63
+ util: () => util_exports,
63
64
  validate: () => validate
64
65
  });
65
66
  module.exports = __toCommonJS(src_exports);
@@ -111,6 +112,30 @@ var import_node_stream3 = require("stream");
111
112
  var import_undici2 = require("undici");
112
113
  var import_date_fns2 = __toESM(require("date-fns"), 1);
113
114
 
115
+ // src/util/index.js
116
+ var util_exports = {};
117
+ __export(util_exports, {
118
+ ERROR_ABSOLUTE_URL: () => ERROR_ABSOLUTE_URL,
119
+ ERROR_URL_MISMATCH: () => ERROR_URL_MISMATCH,
120
+ assertRelativeUrl: () => assertRelativeUrl,
121
+ decode: () => decode,
122
+ del: () => del,
123
+ enableMockClient: () => enableMockClient,
124
+ encode: () => encode,
125
+ expandReferences: () => expandReferences,
126
+ get: () => get,
127
+ logResponse: () => logResponse,
128
+ makeBasicAuthHeader: () => makeBasicAuthHeader,
129
+ normalizeOauthConfig: () => normalizeOauthConfig,
130
+ parseDate: () => parse_date_default,
131
+ parseUrl: () => parseUrl,
132
+ post: () => post,
133
+ put: () => put,
134
+ request: () => request,
135
+ throwError: () => throw_error_default,
136
+ uuid: () => uuid
137
+ });
138
+
114
139
  // src/util/http.js
115
140
  var import_undici = require("undici");
116
141
  var import_http_status_codes = require("http-status-codes");
@@ -118,6 +143,25 @@ var import_node_stream = require("stream");
118
143
  var import_node_querystring = __toESM(require("querystring"), 1);
119
144
  var import_node_path = __toESM(require("path"), 1);
120
145
  var clients = /* @__PURE__ */ new Map();
146
+ var makeBasicAuthHeader = (username, password) => {
147
+ const buff = Buffer.from(`${username}:${password}`);
148
+ const credentials = buff.toString("base64");
149
+ return { Authorization: `Basic ${credentials}` };
150
+ };
151
+ var logResponse = (response) => {
152
+ const { method, url, statusCode, duration } = response;
153
+ if (method && url && duration && statusCode) {
154
+ const message = `${method} ${url} - ${statusCode} in ${duration}ms`;
155
+ if (response instanceof Error) {
156
+ console.error(message);
157
+ console.error("response body: ");
158
+ console.error(response.body || "[no body]");
159
+ } else {
160
+ console.log(message);
161
+ }
162
+ }
163
+ return response;
164
+ };
121
165
  var getClient = (baseUrl, options2) => {
122
166
  const { tls } = options2;
123
167
  if (!clients.has(baseUrl)) {
@@ -125,15 +169,24 @@ var getClient = (baseUrl, options2) => {
125
169
  }
126
170
  return clients.get(baseUrl);
127
171
  };
172
+ var enableMockClient = (baseUrl) => {
173
+ const mockAgent = new import_undici.MockAgent({ connections: 1 });
174
+ mockAgent.disableNetConnect();
175
+ const client = mockAgent.get(baseUrl);
176
+ if (!clients.has(baseUrl)) {
177
+ clients.set(baseUrl, client);
178
+ }
179
+ return client;
180
+ };
128
181
  var assertOK = async (response, errorMap, fullUrl, method, startTime) => {
129
182
  const errMapMessage = errorMap[response.statusCode];
130
183
  const isError = typeof errMapMessage === "boolean" ? errMapMessage : errMapMessage || response.statusCode >= 400;
131
184
  if (isError) {
132
185
  const body = await readResponseBody(response);
133
186
  const statusText = (0, import_http_status_codes.getReasonPhrase)(response.statusCode);
134
- const defaultErrorMesssage = `${method} to ${fullUrl} returned ${response.statusCode}: ${statusText}`;
187
+ const defaultErrorMessage = `${method} to ${fullUrl} returned ${response.statusCode}: ${statusText}`;
135
188
  const duration = Date.now() - startTime;
136
- const errMessage = typeof errMapMessage === "function" ? errMapMessage(response) : errMapMessage || defaultErrorMesssage;
189
+ const errMessage = typeof errMapMessage === "function" ? errMapMessage(response) : errMapMessage || defaultErrorMessage;
137
190
  const error = new Error(errMessage);
138
191
  error.statusCode = response.statusCode;
139
192
  error.statusMessage = statusText;
@@ -145,6 +198,17 @@ var assertOK = async (response, errorMap, fullUrl, method, startTime) => {
145
198
  throw error;
146
199
  }
147
200
  };
201
+ var ERROR_ABSOLUTE_URL = "Absolute URLs not suppored";
202
+ var assertRelativeUrl = (path2) => {
203
+ if (/https?:\/\//.test(path2)) {
204
+ const e = new Error("UNEXPECTED_ABSOLUTE_URL");
205
+ e.code = "UNEXPECTED_ABSOLUTE_URL";
206
+ e.description = "An absolute URL was provided (https://...) but only a path (/a/b/c) is supported";
207
+ e.url = path2;
208
+ e.fix = "Remove the protocol, domain and origin from the provided URL. Maybe you need to use the generic HTTP helper functions instead?";
209
+ throw e;
210
+ }
211
+ };
148
212
  var ERROR_URL_MISMATCH = "Target origin does not match baseUrl origin";
149
213
  var parseUrl = (pathOrUrl = "", baseUrl) => {
150
214
  let fullUrl;
@@ -251,9 +315,10 @@ async function readResponseBody(response, parseAs) {
251
315
  return contentType && contentType.includes("application/json") ? response.body.json() : response.body.text();
252
316
  }
253
317
  }
254
-
255
- // src/util/helpers.js
256
- var import_node_crypto = require("crypto");
318
+ var get = (url, options2) => request("GET", url, options2);
319
+ var post = (url, body, options2) => request("POST", url, { body, ...options2 });
320
+ var put = (url, body, options2) => request("PUT", url, { body, ...options2 });
321
+ var del = (url, body, options2) => request("DELETE", url, { body, ...options2 });
257
322
 
258
323
  // src/util/references.js
259
324
  var import_node_stream2 = require("stream");
@@ -288,6 +353,22 @@ function expandReference(state, value) {
288
353
  }
289
354
  return value;
290
355
  }
356
+ function normalizeOauthConfig(configuration) {
357
+ const { access_token, accessToken } = configuration;
358
+ if (access_token && accessToken)
359
+ throw new Error(
360
+ 'Both "accessToken" & "access_token" keys found in configuration; please use only "access_token" for OAuth2 credentials.'
361
+ );
362
+ if (access_token)
363
+ return { ...configuration, accessToken: access_token };
364
+ console.log(
365
+ 'Key "access_token" not found in state.configuration;',
366
+ "is this a standard OAuth 2.0 JSON credential?"
367
+ );
368
+ if (accessToken)
369
+ console.log('Using "accessToken" from state.configuration');
370
+ return configuration;
371
+ }
291
372
 
292
373
  // src/util/parse-date.js
293
374
  var import_date_fns = require("date-fns");
@@ -315,6 +396,31 @@ var parse_date_default = (d, startDate) => {
315
396
  return d;
316
397
  };
317
398
 
399
+ // src/util/throw-error.js
400
+ var throw_error_default = (code, { description, fix, ...extras } = {}) => {
401
+ const message = description ? `${code}: ${description}` : code;
402
+ const e = new Error(message);
403
+ e.code = code;
404
+ if (description) {
405
+ e.description = description;
406
+ }
407
+ if (fix) {
408
+ e.fix = fix;
409
+ }
410
+ for (const key in extras) {
411
+ e[key] = extras[key];
412
+ }
413
+ throw e;
414
+ };
415
+
416
+ // src/util/base64.js
417
+ var encode = (data) => Buffer.from(data, "utf-8").toString("base64");
418
+ var decode = (base64Data) => Buffer.from(base64Data, "base64").toString("utf-8");
419
+
420
+ // src/util/uuid.js
421
+ var import_node_crypto = require("crypto");
422
+ var uuid = () => (0, import_node_crypto.randomUUID)();
423
+
318
424
  // src/Adaptor.js
319
425
  var schemaCache = {};
320
426
  function execute(...operations) {
@@ -732,9 +838,9 @@ function each2(dataSource, operation) {
732
838
  // src/http.js
733
839
  var http_exports = {};
734
840
  __export(http_exports, {
735
- get: () => get2,
841
+ get: () => get3,
736
842
  options: () => options,
737
- post: () => post,
843
+ post: () => post2,
738
844
  request: () => req
739
845
  });
740
846
  var import_set = __toESM(require("lodash/set"), 1);
@@ -787,10 +893,10 @@ var req = function(method, url, options2) {
787
893
  };
788
894
  };
789
895
  };
790
- function get2(url, options2) {
896
+ function get3(url, options2) {
791
897
  return req("GET", url, options2);
792
898
  }
793
- function post(path2, data, options2) {
899
+ function post2(path2, data, options2) {
794
900
  return req("POST", path2, { body: data, ...options2 });
795
901
  }
796
902
 
@@ -840,5 +946,6 @@ var src_default = Adaptor_exports;
840
946
  sourceValue,
841
947
  splitKeys,
842
948
  toArray,
949
+ util,
843
950
  validate
844
951
  });
package/dist/index.js CHANGED
@@ -40,7 +40,7 @@ __export(Adaptor_exports, {
40
40
  toArray: () => toArray,
41
41
  validate: () => validate
42
42
  });
43
- import get from "lodash/get.js";
43
+ import get2 from "lodash/get.js";
44
44
  import omit from "lodash/omit.js";
45
45
  import curry from "lodash/fp/curry.js";
46
46
  import groupBy from "lodash/groupBy.js";
@@ -51,6 +51,30 @@ import { Readable as Readable3 } from "stream";
51
51
  import { request as request2 } from "undici";
52
52
  import dateFns from "date-fns";
53
53
 
54
+ // src/util/index.js
55
+ var util_exports = {};
56
+ __export(util_exports, {
57
+ ERROR_ABSOLUTE_URL: () => ERROR_ABSOLUTE_URL,
58
+ ERROR_URL_MISMATCH: () => ERROR_URL_MISMATCH,
59
+ assertRelativeUrl: () => assertRelativeUrl,
60
+ decode: () => decode,
61
+ del: () => del,
62
+ enableMockClient: () => enableMockClient,
63
+ encode: () => encode,
64
+ expandReferences: () => expandReferences,
65
+ get: () => get,
66
+ logResponse: () => logResponse,
67
+ makeBasicAuthHeader: () => makeBasicAuthHeader,
68
+ normalizeOauthConfig: () => normalizeOauthConfig,
69
+ parseDate: () => parse_date_default,
70
+ parseUrl: () => parseUrl,
71
+ post: () => post,
72
+ put: () => put,
73
+ request: () => request,
74
+ throwError: () => throw_error_default,
75
+ uuid: () => uuid
76
+ });
77
+
54
78
  // src/util/http.js
55
79
  import { Client, MockAgent } from "undici";
56
80
  import { getReasonPhrase } from "http-status-codes";
@@ -58,6 +82,25 @@ import { Readable } from "stream";
58
82
  import querystring from "querystring";
59
83
  import path from "path";
60
84
  var clients = /* @__PURE__ */ new Map();
85
+ var makeBasicAuthHeader = (username, password) => {
86
+ const buff = Buffer.from(`${username}:${password}`);
87
+ const credentials = buff.toString("base64");
88
+ return { Authorization: `Basic ${credentials}` };
89
+ };
90
+ var logResponse = (response) => {
91
+ const { method, url, statusCode, duration } = response;
92
+ if (method && url && duration && statusCode) {
93
+ const message = `${method} ${url} - ${statusCode} in ${duration}ms`;
94
+ if (response instanceof Error) {
95
+ console.error(message);
96
+ console.error("response body: ");
97
+ console.error(response.body || "[no body]");
98
+ } else {
99
+ console.log(message);
100
+ }
101
+ }
102
+ return response;
103
+ };
61
104
  var getClient = (baseUrl, options2) => {
62
105
  const { tls } = options2;
63
106
  if (!clients.has(baseUrl)) {
@@ -65,15 +108,24 @@ var getClient = (baseUrl, options2) => {
65
108
  }
66
109
  return clients.get(baseUrl);
67
110
  };
111
+ var enableMockClient = (baseUrl) => {
112
+ const mockAgent = new MockAgent({ connections: 1 });
113
+ mockAgent.disableNetConnect();
114
+ const client = mockAgent.get(baseUrl);
115
+ if (!clients.has(baseUrl)) {
116
+ clients.set(baseUrl, client);
117
+ }
118
+ return client;
119
+ };
68
120
  var assertOK = async (response, errorMap, fullUrl, method, startTime) => {
69
121
  const errMapMessage = errorMap[response.statusCode];
70
122
  const isError = typeof errMapMessage === "boolean" ? errMapMessage : errMapMessage || response.statusCode >= 400;
71
123
  if (isError) {
72
124
  const body = await readResponseBody(response);
73
125
  const statusText = getReasonPhrase(response.statusCode);
74
- const defaultErrorMesssage = `${method} to ${fullUrl} returned ${response.statusCode}: ${statusText}`;
126
+ const defaultErrorMessage = `${method} to ${fullUrl} returned ${response.statusCode}: ${statusText}`;
75
127
  const duration = Date.now() - startTime;
76
- const errMessage = typeof errMapMessage === "function" ? errMapMessage(response) : errMapMessage || defaultErrorMesssage;
128
+ const errMessage = typeof errMapMessage === "function" ? errMapMessage(response) : errMapMessage || defaultErrorMessage;
77
129
  const error = new Error(errMessage);
78
130
  error.statusCode = response.statusCode;
79
131
  error.statusMessage = statusText;
@@ -85,6 +137,17 @@ var assertOK = async (response, errorMap, fullUrl, method, startTime) => {
85
137
  throw error;
86
138
  }
87
139
  };
140
+ var ERROR_ABSOLUTE_URL = "Absolute URLs not suppored";
141
+ var assertRelativeUrl = (path2) => {
142
+ if (/https?:\/\//.test(path2)) {
143
+ const e = new Error("UNEXPECTED_ABSOLUTE_URL");
144
+ e.code = "UNEXPECTED_ABSOLUTE_URL";
145
+ e.description = "An absolute URL was provided (https://...) but only a path (/a/b/c) is supported";
146
+ e.url = path2;
147
+ e.fix = "Remove the protocol, domain and origin from the provided URL. Maybe you need to use the generic HTTP helper functions instead?";
148
+ throw e;
149
+ }
150
+ };
88
151
  var ERROR_URL_MISMATCH = "Target origin does not match baseUrl origin";
89
152
  var parseUrl = (pathOrUrl = "", baseUrl) => {
90
153
  let fullUrl;
@@ -191,6 +254,10 @@ async function readResponseBody(response, parseAs) {
191
254
  return contentType && contentType.includes("application/json") ? response.body.json() : response.body.text();
192
255
  }
193
256
  }
257
+ var get = (url, options2) => request("GET", url, options2);
258
+ var post = (url, body, options2) => request("POST", url, { body, ...options2 });
259
+ var put = (url, body, options2) => request("PUT", url, { body, ...options2 });
260
+ var del = (url, body, options2) => request("DELETE", url, { body, ...options2 });
194
261
 
195
262
  // src/util/references.js
196
263
  import { Readable as Readable2, Writable } from "stream";
@@ -225,6 +292,22 @@ function expandReference(state, value) {
225
292
  }
226
293
  return value;
227
294
  }
295
+ function normalizeOauthConfig(configuration) {
296
+ const { access_token, accessToken } = configuration;
297
+ if (access_token && accessToken)
298
+ throw new Error(
299
+ 'Both "accessToken" & "access_token" keys found in configuration; please use only "access_token" for OAuth2 credentials.'
300
+ );
301
+ if (access_token)
302
+ return { ...configuration, accessToken: access_token };
303
+ console.log(
304
+ 'Key "access_token" not found in state.configuration;',
305
+ "is this a standard OAuth 2.0 JSON credential?"
306
+ );
307
+ if (accessToken)
308
+ console.log('Using "accessToken" from state.configuration');
309
+ return configuration;
310
+ }
228
311
 
229
312
  // src/util/parse-date.js
230
313
  import { startOfToday, startOfYesterday, subHours, subDays, startOfDay } from "date-fns";
@@ -252,6 +335,31 @@ var parse_date_default = (d, startDate) => {
252
335
  return d;
253
336
  };
254
337
 
338
+ // src/util/throw-error.js
339
+ var throw_error_default = (code, { description, fix, ...extras } = {}) => {
340
+ const message = description ? `${code}: ${description}` : code;
341
+ const e = new Error(message);
342
+ e.code = code;
343
+ if (description) {
344
+ e.description = description;
345
+ }
346
+ if (fix) {
347
+ e.fix = fix;
348
+ }
349
+ for (const key in extras) {
350
+ e[key] = extras[key];
351
+ }
352
+ throw e;
353
+ };
354
+
355
+ // src/util/base64.js
356
+ var encode = (data) => Buffer.from(data, "utf-8").toString("base64");
357
+ var decode = (base64Data) => Buffer.from(base64Data, "base64").toString("utf-8");
358
+
359
+ // src/util/uuid.js
360
+ import { randomUUID } from "crypto";
361
+ var uuid = () => randomUUID();
362
+
255
363
  // src/Adaptor.js
256
364
  var schemaCache = {};
257
365
  function execute(...operations) {
@@ -404,7 +512,7 @@ function group(arrayOfObjects, keyPath, callback = (s) => s) {
404
512
  arrayOfObjects,
405
513
  keyPath
406
514
  );
407
- const results = groupBy(resolvedArray, (item) => get(item, resolvedKeyPath));
515
+ const results = groupBy(resolvedArray, (item) => get2(item, resolvedKeyPath));
408
516
  return callback({ ...state, data: omit(results, [void 0]) });
409
517
  };
410
518
  }
@@ -669,9 +777,9 @@ function each2(dataSource, operation) {
669
777
  // src/http.js
670
778
  var http_exports = {};
671
779
  __export(http_exports, {
672
- get: () => get2,
780
+ get: () => get3,
673
781
  options: () => options,
674
- post: () => post,
782
+ post: () => post2,
675
783
  request: () => req
676
784
  });
677
785
  import set from "lodash/set";
@@ -724,10 +832,10 @@ var req = function(method, url, options2) {
724
832
  };
725
833
  };
726
834
  };
727
- function get2(url, options2) {
835
+ function get3(url, options2) {
728
836
  return req("GET", url, options2);
729
837
  }
730
- function post(path2, data, options2) {
838
+ function post2(path2, data, options2) {
731
839
  return req("POST", path2, { body: data, ...options2 });
732
840
  }
733
841
 
@@ -780,5 +888,6 @@ export {
780
888
  sourceValue,
781
889
  splitKeys,
782
890
  toArray,
891
+ util_exports as util,
783
892
  validate
784
893
  };
package/dist/util.cjs CHANGED
@@ -42,6 +42,7 @@ __export(util_exports, {
42
42
  post: () => post,
43
43
  put: () => put,
44
44
  request: () => request,
45
+ throwError: () => throw_error_default,
45
46
  uuid: () => uuid
46
47
  });
47
48
  module.exports = __toCommonJS(util_exports);
@@ -94,9 +95,9 @@ var assertOK = async (response, errorMap, fullUrl, method, startTime) => {
94
95
  if (isError) {
95
96
  const body = await readResponseBody(response);
96
97
  const statusText = (0, import_http_status_codes.getReasonPhrase)(response.statusCode);
97
- const defaultErrorMesssage = `${method} to ${fullUrl} returned ${response.statusCode}: ${statusText}`;
98
+ const defaultErrorMessage = `${method} to ${fullUrl} returned ${response.statusCode}: ${statusText}`;
98
99
  const duration = Date.now() - startTime;
99
- const errMessage = typeof errMapMessage === "function" ? errMapMessage(response) : errMapMessage || defaultErrorMesssage;
100
+ const errMessage = typeof errMapMessage === "function" ? errMapMessage(response) : errMapMessage || defaultErrorMessage;
100
101
  const error = new Error(errMessage);
101
102
  error.statusCode = response.statusCode;
102
103
  error.statusMessage = statusText;
@@ -230,12 +231,6 @@ var post = (url, body, options) => request("POST", url, { body, ...options });
230
231
  var put = (url, body, options) => request("PUT", url, { body, ...options });
231
232
  var del = (url, body, options) => request("DELETE", url, { body, ...options });
232
233
 
233
- // src/util/helpers.js
234
- var import_node_crypto = require("crypto");
235
- var encode = (data) => Buffer.from(data, "utf-8").toString("base64");
236
- var decode = (base64Data) => Buffer.from(base64Data, "base64").toString("utf-8");
237
- var uuid = () => (0, import_node_crypto.randomUUID)();
238
-
239
234
  // src/util/references.js
240
235
  var import_node_stream2 = require("stream");
241
236
  function expandReferences(state, ...args) {
@@ -311,6 +306,31 @@ var parse_date_default = (d, startDate) => {
311
306
  }
312
307
  return d;
313
308
  };
309
+
310
+ // src/util/throw-error.js
311
+ var throw_error_default = (code, { description, fix, ...extras } = {}) => {
312
+ const message = description ? `${code}: ${description}` : code;
313
+ const e = new Error(message);
314
+ e.code = code;
315
+ if (description) {
316
+ e.description = description;
317
+ }
318
+ if (fix) {
319
+ e.fix = fix;
320
+ }
321
+ for (const key in extras) {
322
+ e[key] = extras[key];
323
+ }
324
+ throw e;
325
+ };
326
+
327
+ // src/util/base64.js
328
+ var encode = (data) => Buffer.from(data, "utf-8").toString("base64");
329
+ var decode = (base64Data) => Buffer.from(base64Data, "base64").toString("utf-8");
330
+
331
+ // src/util/uuid.js
332
+ var import_node_crypto = require("crypto");
333
+ var uuid = () => (0, import_node_crypto.randomUUID)();
314
334
  // Annotate the CommonJS export names for ESM import in node:
315
335
  0 && (module.exports = {
316
336
  ERROR_ABSOLUTE_URL,
@@ -330,5 +350,6 @@ var parse_date_default = (d, startDate) => {
330
350
  post,
331
351
  put,
332
352
  request,
353
+ throwError,
333
354
  uuid
334
355
  });
package/dist/util.js CHANGED
@@ -46,9 +46,9 @@ var assertOK = async (response, errorMap, fullUrl, method, startTime) => {
46
46
  if (isError) {
47
47
  const body = await readResponseBody(response);
48
48
  const statusText = getReasonPhrase(response.statusCode);
49
- const defaultErrorMesssage = `${method} to ${fullUrl} returned ${response.statusCode}: ${statusText}`;
49
+ const defaultErrorMessage = `${method} to ${fullUrl} returned ${response.statusCode}: ${statusText}`;
50
50
  const duration = Date.now() - startTime;
51
- const errMessage = typeof errMapMessage === "function" ? errMapMessage(response) : errMapMessage || defaultErrorMesssage;
51
+ const errMessage = typeof errMapMessage === "function" ? errMapMessage(response) : errMapMessage || defaultErrorMessage;
52
52
  const error = new Error(errMessage);
53
53
  error.statusCode = response.statusCode;
54
54
  error.statusMessage = statusText;
@@ -182,12 +182,6 @@ var post = (url, body, options) => request("POST", url, { body, ...options });
182
182
  var put = (url, body, options) => request("PUT", url, { body, ...options });
183
183
  var del = (url, body, options) => request("DELETE", url, { body, ...options });
184
184
 
185
- // src/util/helpers.js
186
- import { randomUUID } from "crypto";
187
- var encode = (data) => Buffer.from(data, "utf-8").toString("base64");
188
- var decode = (base64Data) => Buffer.from(base64Data, "base64").toString("utf-8");
189
- var uuid = () => randomUUID();
190
-
191
185
  // src/util/references.js
192
186
  import { Readable as Readable2, Writable } from "stream";
193
187
  function expandReferences(state, ...args) {
@@ -263,6 +257,31 @@ var parse_date_default = (d, startDate) => {
263
257
  }
264
258
  return d;
265
259
  };
260
+
261
+ // src/util/throw-error.js
262
+ var throw_error_default = (code, { description, fix, ...extras } = {}) => {
263
+ const message = description ? `${code}: ${description}` : code;
264
+ const e = new Error(message);
265
+ e.code = code;
266
+ if (description) {
267
+ e.description = description;
268
+ }
269
+ if (fix) {
270
+ e.fix = fix;
271
+ }
272
+ for (const key in extras) {
273
+ e[key] = extras[key];
274
+ }
275
+ throw e;
276
+ };
277
+
278
+ // src/util/base64.js
279
+ var encode = (data) => Buffer.from(data, "utf-8").toString("base64");
280
+ var decode = (base64Data) => Buffer.from(base64Data, "base64").toString("utf-8");
281
+
282
+ // src/util/uuid.js
283
+ import { randomUUID } from "crypto";
284
+ var uuid = () => randomUUID();
266
285
  export {
267
286
  ERROR_ABSOLUTE_URL,
268
287
  ERROR_URL_MISMATCH,
@@ -281,5 +300,6 @@ export {
281
300
  post,
282
301
  put,
283
302
  request,
303
+ throw_error_default as throwError,
284
304
  uuid
285
305
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-common",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Common Expressions for OpenFn",
5
5
  "homepage": "https://docs.openfn.org",
6
6
  "repository": {
@@ -39,7 +39,7 @@
39
39
  "csvtojson": "^2.0.10",
40
40
  "date-fns": "^2.25.0",
41
41
  "http-status-codes": "^2.3.0",
42
- "jsonpath-plus": "^10.0.0",
42
+ "jsonpath-plus": "^10.2.0",
43
43
  "lodash": "^4.17.21",
44
44
  "undici": "^5.28.4"
45
45
  },
@@ -138,22 +138,38 @@ export function lastReferenceValue(path: string): Operation;
138
138
  */
139
139
  export function asData(data: string | object | Function, state: object): any[];
140
140
  /**
141
- * Scopes an array of data based on a JSONPath.
142
- * Useful when the source data has `n` items you would like to map to
143
- * an operation.
144
- * The operation will receive a slice of the data based of each item
145
- * of the JSONPath provided.
146
- *
147
- * It also ensures the results of an operation make their way back into
148
- * the state's references.
141
+ * Iterates over an array of items and invokes an operation upon each one, where the state
142
+ * object is _scoped_ so that state.data is the item under iteration.
143
+ * The rest of the state object is untouched and can be referenced as usual.
144
+ * You can pass an array directly, or use lazy state or a JSONPath string to
145
+ * reference a slice of state.
149
146
  * @public
150
147
  * @function
151
- * @example
152
- * each("$.[*]",
153
- * create("SObject",
154
- * field("FirstName", sourceValue("$.firstName"))
155
- * )
156
- * )
148
+ * @example <caption>Using lazy state ($) to iterate over items in state.data and pass each into an "insert" operation</caption>
149
+ * each(
150
+ * $.data,
151
+ * // Inside the callback operation, `$.data` is scoped to the item under iteration
152
+ * insert("patient", {
153
+ * patient_name: $.data.properties.case_name,
154
+ * patient_id: $.data.case_id,
155
+ * })
156
+ * );
157
+ * @example <caption>Iterate over items in state.data and pass each one into an "insert" operation</caption>
158
+ * each(
159
+ * $.data,
160
+ * insert("patient", (state) => ({
161
+ * patient_id: state.data.case_id,
162
+ * ...state.data
163
+ * }))
164
+ * );
165
+ * @example <caption>Using JSON path to iterate over items in state.data and pass each one into an "insert" operation</caption>
166
+ * each(
167
+ * "$.data[*]",
168
+ * insert("patient", (state) => ({
169
+ * patient_name: state.data.properties.case_name,
170
+ * patient_id: state.data.case_id,
171
+ * }))
172
+ * );
157
173
  * @param {DataSource} dataSource - JSONPath referencing a point in `state`.
158
174
  * @param {Operation} operation - The operation needed to be repeated.
159
175
  * @returns {Operation}
package/types/http.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * @function
9
9
  * @public
10
10
  * @example <caption>Get with a query an oath token</caption>
11
- * get($.data.url, http.options({ query: $.query }).oath($.configuration.access_token)
11
+ * get($.data.url, http.options({ query: $.query }).oath($.configuration.access_token))
12
12
  */
13
13
  export function options(opts?: {}): any;
14
14
  /**
package/types/index.d.ts CHANGED
@@ -4,5 +4,6 @@ export * from './Adaptor';
4
4
  export * as beta from './beta';
5
5
  export * as http from './http';
6
6
  export * as dateFns from './dateFns';
7
+ export * as util from './util';
7
8
  import * as metadata from './metadata';
8
9
  export { metadata };
@@ -1,4 +1,4 @@
1
- declare type Entity = {
1
+ export declare type Entity = {
2
2
  name: string;
3
3
  type: string;
4
4
  label?: string;
@@ -8,4 +8,4 @@ declare type Entity = {
8
8
  meta?: Record<string, any>;
9
9
  addChild: (e: Entity, name?: string) => void;
10
10
  };
11
- declare type DataType = 'string' | 'boolean' | 'date';
11
+ export declare type DataType = 'string' | 'boolean' | 'date';
@@ -1,3 +1,2 @@
1
1
  export function encode(data: string): string;
2
2
  export function decode(base64Data: string): string;
3
- export function uuid(): string;
@@ -1,5 +1,6 @@
1
1
  export * from "./http";
2
- export * from "./helpers";
3
2
  export * from "./references";
4
- export { parseDate };
5
- import parseDate from "./parse-date";
3
+ export { default as parseDate } from "./parse-date";
4
+ export { default as throwError } from "./throw-error";
5
+ export { uuid } from "./uuid";
6
+ export { encode, decode } from "./base64";
@@ -0,0 +1,5 @@
1
+ declare function _default(code: any, { description, fix, ...extras }?: {
2
+ description: any;
3
+ fix: any;
4
+ }): never;
5
+ export default _default;
@@ -0,0 +1 @@
1
+ export function uuid(): string;