@openfn/language-dhis2 6.3.4 → 7.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.
package/dist/index.cjs CHANGED
@@ -26,7 +26,6 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
26
26
  var src_exports = {};
27
27
  __export(src_exports, {
28
28
  alterState: () => import_language_common3.alterState,
29
- attr: () => attr,
30
29
  create: () => create,
31
30
  cursor: () => import_language_common3.cursor,
32
31
  dataPath: () => import_language_common3.dataPath,
@@ -34,27 +33,23 @@ __export(src_exports, {
34
33
  dateFns: () => import_language_common3.dateFns,
35
34
  default: () => src_default,
36
35
  destroy: () => destroy,
37
- discover: () => discover,
38
- dv: () => dv,
39
36
  each: () => import_language_common3.each,
40
37
  execute: () => execute,
41
38
  field: () => import_language_common3.field,
42
39
  fields: () => import_language_common3.fields,
43
- findAttributeValue: () => findAttributeValue,
44
- findAttributeValueById: () => findAttributeValueById,
45
40
  fn: () => import_language_common3.fn,
46
41
  fnIf: () => import_language_common3.fnIf,
47
42
  get: () => get,
48
43
  group: () => import_language_common3.group,
49
- http: () => import_language_common3.http,
44
+ http: () => http_exports,
50
45
  lastReferenceValue: () => import_language_common3.lastReferenceValue,
51
46
  merge: () => import_language_common3.merge,
52
47
  metadata: () => metadata_default,
53
- patch: () => patch,
54
- post: () => post,
55
48
  sourceValue: () => import_language_common3.sourceValue,
49
+ tracker: () => tracker_exports,
56
50
  update: () => update,
57
- upsert: () => upsert
51
+ upsert: () => upsert,
52
+ util: () => util_exports
58
53
  });
59
54
  module.exports = __toCommonJS(src_exports);
60
55
 
@@ -64,13 +59,47 @@ var import_metadata = require("@openfn/language-common/metadata");
64
59
  // src/meta/helper.js
65
60
  var import_axios = __toESM(require("axios"), 1);
66
61
 
67
- // src/Utils.js
62
+ // src/util.js
63
+ var util_exports = {};
64
+ __export(util_exports, {
65
+ CONTENT_TYPES: () => CONTENT_TYPES,
66
+ attr: () => attr,
67
+ configureAuth: () => configureAuth,
68
+ dv: () => dv,
69
+ ensureArray: () => ensureArray,
70
+ findAttributeValue: () => findAttributeValue,
71
+ findAttributeValueById: () => findAttributeValueById,
72
+ handleHttpResponse: () => handleHttpResponse,
73
+ handleResponse: () => handleResponse,
74
+ prefixVersionToPath: () => prefixVersionToPath,
75
+ prettyJson: () => prettyJson,
76
+ request: () => request,
77
+ selectId: () => selectId,
78
+ shouldUseNewTracker: () => shouldUseNewTracker
79
+ });
68
80
  var import_language_common = require("@openfn/language-common");
81
+ var import_util = require("@openfn/language-common/util");
69
82
  function shouldUseNewTracker(resourceType) {
70
83
  return /^(enrollments|relationships|events|trackedEntities)$/.test(
71
84
  resourceType
72
85
  );
73
86
  }
87
+ function attr(attribute, value) {
88
+ return { attribute, value };
89
+ }
90
+ function dv(dataElement, value) {
91
+ return { dataElement, value };
92
+ }
93
+ function findAttributeValue(trackedEntity, attributeDisplayName) {
94
+ var _a, _b;
95
+ return (_b = (_a = trackedEntity == null ? void 0 : trackedEntity.attributes) == null ? void 0 : _a.find(
96
+ (a) => (a == null ? void 0 : a.displayName.toLowerCase()) == attributeDisplayName.toLowerCase()
97
+ )) == null ? void 0 : _b.value;
98
+ }
99
+ function findAttributeValueById(trackedEntity, attributeUid) {
100
+ var _a, _b;
101
+ return (_b = (_a = trackedEntity == null ? void 0 : trackedEntity.attributes) == null ? void 0 : _a.find((a) => (a == null ? void 0 : a.attribute) == attributeUid)) == null ? void 0 : _b.value;
102
+ }
74
103
  var CONTENT_TYPES = {
75
104
  xml: "application/xml",
76
105
  json: "application/json",
@@ -78,10 +107,6 @@ var CONTENT_TYPES = {
78
107
  csv: "application/csv",
79
108
  xls: "application/vnd.ms-excel"
80
109
  };
81
- function buildUrl(urlString, hostUrl, apiVersion) {
82
- const pathSuffix = apiVersion ? `/${apiVersion}${urlString}` : `${urlString}`;
83
- return hostUrl + "/api" + pathSuffix;
84
- }
85
110
  function selectId(resourceType) {
86
111
  switch (resourceType) {
87
112
  case "trackedEntityInstances":
@@ -90,11 +115,20 @@ function selectId(resourceType) {
90
115
  return "id";
91
116
  }
92
117
  }
93
- function handleResponse(result, state, callback) {
94
- const { data } = result;
95
- if (callback)
96
- return callback((0, import_language_common.composeNextState)(state, data));
97
- return (0, import_language_common.composeNextState)(state, data);
118
+ function handleHttpResponse(result, state) {
119
+ const { body, ...responseWithoutBody } = result;
120
+ const nextState = {
121
+ ...(0, import_language_common.composeNextState)(state, body),
122
+ response: responseWithoutBody
123
+ };
124
+ return nextState;
125
+ }
126
+ function handleResponse(result, state) {
127
+ const { body } = result;
128
+ const nextState = {
129
+ ...(0, import_language_common.composeNextState)(state, body)
130
+ };
131
+ return nextState;
98
132
  }
99
133
  function prettyJson(data) {
100
134
  return JSON.stringify(data, null, 2);
@@ -102,23 +136,61 @@ function prettyJson(data) {
102
136
  function ensureArray(data, key) {
103
137
  return Array.isArray(data) ? { [key]: data } : { [key]: [data] };
104
138
  }
105
- function generateUrl(configuration, options, resourceType, path = null) {
106
- let { hostUrl, apiVersion } = configuration;
139
+ function prefixVersionToPath(configuration, options, resourceType, path = null) {
140
+ let { apiVersion } = configuration;
107
141
  const urlString = "/" + resourceType;
108
142
  if (options == null ? void 0 : options.apiVersion)
109
143
  apiVersion = options.apiVersion;
110
144
  const apiMessage = apiVersion ? `Using DHIS2 api version ${apiVersion}` : "Using latest available version of the DHIS2 api on this server.";
111
145
  console.log(apiMessage);
112
- const url = buildUrl(urlString, hostUrl, apiVersion);
146
+ const pathSuffix = apiVersion ? `/${apiVersion}${urlString}` : `${urlString}`;
147
+ const urlPath = "/api" + pathSuffix;
113
148
  if (path)
114
- return `${url}/${path}`;
115
- return url;
149
+ return `${urlPath}/${path}`;
150
+ return urlPath;
151
+ }
152
+ var configureAuth = (auth, headers = {}) => {
153
+ if ("pat" in auth) {
154
+ Object.assign(headers, {
155
+ Authorization: `ApiToken ${auth.pat}`
156
+ });
157
+ } else if ("password" in auth) {
158
+ Object.assign(headers, (0, import_util.makeBasicAuthHeader)(auth.username, auth.password));
159
+ } else {
160
+ throw new Error(
161
+ "Invalid authorization credentials. Include an pat, username or password in state.configuration"
162
+ );
163
+ }
164
+ return headers;
165
+ };
166
+ async function request(configuration, requestData) {
167
+ const { hostUrl } = configuration;
168
+ const { method, path, options = {}, data = {} } = requestData;
169
+ const {
170
+ headers = { "content-type": "application/json" },
171
+ query = {},
172
+ parseAs = "json"
173
+ } = options;
174
+ if (options)
175
+ console.log(`with params: `, query);
176
+ const authHeaders = configureAuth(configuration, headers);
177
+ const opts = {
178
+ headers: {
179
+ ...authHeaders,
180
+ ...headers
181
+ },
182
+ query,
183
+ parseAs,
184
+ body: data,
185
+ baseUrl: hostUrl
186
+ };
187
+ return (0, import_util.request)(method, path, opts).then(import_util.logResponse);
116
188
  }
117
189
 
118
190
  // src/meta/helper.js
119
191
  var createHelper = (configuration = {}) => {
120
192
  const { username, password } = configuration;
121
- const get2 = (url) => (0, import_axios.default)({
193
+ const get3 = (url) => (0, import_axios.default)({
122
194
  url,
123
195
  headers: { "Content-Type": "application/json" },
124
196
  responseType: "json",
@@ -143,20 +215,24 @@ var createHelper = (configuration = {}) => {
143
215
  ];
144
216
  };
145
217
  const getOrgUnits = async () => {
146
- const url = generateUrl(configuration, {}, "organisationUnits");
147
- const response = await get2(url);
218
+ const url = prefixVersionToPath(configuration, {}, "organisationUnits");
219
+ const response = await get3(url);
148
220
  return response.data;
149
221
  };
150
222
  const getPrograms = () => {
151
223
  };
152
224
  const getTrackedEntityTypes = async () => {
153
- const url = generateUrl(configuration, {}, "trackedEntityTypes");
154
- const response = await get2(url);
225
+ const url = prefixVersionToPath(configuration, {}, "trackedEntityTypes");
226
+ const response = await get3(url);
155
227
  return response.data;
156
228
  };
157
229
  const getAttributes = async () => {
158
- const url = generateUrl(configuration, {}, "trackedEntityAttributes");
159
- const response = await get2(url);
230
+ const url = prefixVersionToPath(
231
+ configuration,
232
+ {},
233
+ "trackedEntityAttributes"
234
+ );
235
+ const response = await get3(url);
160
236
  return response.data;
161
237
  };
162
238
  return {
@@ -209,21 +285,16 @@ var metadata_default = metadata;
209
285
  var Adaptor_exports = {};
210
286
  __export(Adaptor_exports, {
211
287
  alterState: () => import_language_common3.alterState,
212
- attr: () => attr,
213
288
  create: () => create,
214
289
  cursor: () => import_language_common3.cursor,
215
290
  dataPath: () => import_language_common3.dataPath,
216
291
  dataValue: () => import_language_common3.dataValue,
217
292
  dateFns: () => import_language_common3.dateFns,
218
293
  destroy: () => destroy,
219
- discover: () => discover,
220
- dv: () => dv,
221
294
  each: () => import_language_common3.each,
222
295
  execute: () => execute,
223
296
  field: () => import_language_common3.field,
224
297
  fields: () => import_language_common3.fields,
225
- findAttributeValue: () => findAttributeValue,
226
- findAttributeValueById: () => findAttributeValueById,
227
298
  fn: () => import_language_common3.fn,
228
299
  fnIf: () => import_language_common3.fnIf,
229
300
  get: () => get,
@@ -231,50 +302,13 @@ __export(Adaptor_exports, {
231
302
  http: () => import_language_common3.http,
232
303
  lastReferenceValue: () => import_language_common3.lastReferenceValue,
233
304
  merge: () => import_language_common3.merge,
234
- patch: () => patch,
235
- post: () => post,
236
305
  sourceValue: () => import_language_common3.sourceValue,
237
306
  update: () => update,
238
307
  upsert: () => upsert
239
308
  });
240
- var import_axios3 = __toESM(require("axios"), 1);
241
309
  var import_language_common2 = require("@openfn/language-common");
242
- var import_util = require("@openfn/language-common/util");
243
- var import_lodash = __toESM(require("lodash"), 1);
244
-
245
- // src/Client.js
246
- var import_axios2 = __toESM(require("axios"), 1);
247
- var import_qs = __toESM(require("qs"), 1);
248
- function request({ username, password, pat }, axiosRequest) {
249
- const { method, url, params } = axiosRequest;
250
- console.log(`Sending ${method} request to ${url}`);
251
- if (params)
252
- console.log(`with params: `, params);
253
- const safeRedirect = ["get", "head", "options", "trace"].includes(
254
- method.toLowerCase()
255
- );
256
- const headers = {
257
- "Content-Type": "application/json"
258
- };
259
- let auth;
260
- if (pat) {
261
- headers.Authorization = `ApiToken ${pat}`;
262
- } else {
263
- auth = { username, password };
264
- }
265
- return (0, import_axios2.default)({
266
- headers,
267
- responseType: "json",
268
- auth,
269
- maxRedirects: safeRedirect ? 5 : 0,
270
- paramsSerializer: (params2) => import_qs.default.stringify(params2, { arrayFormat: "repeat" }),
271
- ...axiosRequest
272
- });
273
- }
274
-
275
- // src/Adaptor.js
310
+ var import_util3 = require("@openfn/language-common/util");
276
311
  var import_language_common3 = require("@openfn/language-common");
277
- var { indexOf } = import_lodash.default;
278
312
  function execute(...operations) {
279
313
  const initialState = {
280
314
  references: [],
@@ -305,91 +339,76 @@ function configMigrationHelper(state) {
305
339
  }
306
340
  return state;
307
341
  }
308
- import_axios3.default.interceptors.response.use(
309
- function(response) {
310
- var _a, _b;
311
- const contentType = (_a = response.headers["content-type"]) == null ? void 0 : _a.split(";")[0];
312
- const acceptHeaders = response.config.headers["Accept"].split(";")[0].split(",");
313
- if (response.config.method === "get" && response.config.responseType != "arraybuffer") {
314
- if (indexOf(acceptHeaders, contentType) === -1) {
315
- const newError = {
316
- status: 404,
317
- message: "Unexpected content returned",
318
- responseData: response.data
319
- };
320
- console.error(newError.message);
321
- return Promise.reject(newError);
322
- }
323
- }
324
- if (typeof (response == null ? void 0 : response.data) === "string" && contentType === ((_b = CONTENT_TYPES) == null ? void 0 : _b.json)) {
325
- try {
326
- response = { ...response, data: JSON.parse(response.data) };
327
- } catch (error) {
328
- console.warn("Non-JSON response detected, unable to parse.");
329
- }
342
+ function create(path, data, params = {}) {
343
+ return async (state) => {
344
+ var _a;
345
+ if (path === "tracker") {
346
+ throw new Error("Invalid resourceType. Use `tracker.import()` instead.");
330
347
  }
331
- return response;
332
- },
333
- function(error) {
334
- var _a, _b, _c, _d;
335
- if ((_a = error.config) == null ? void 0 : _a.auth)
336
- error.config.auth = "--REDACTED--";
337
- if ((_b = error.config) == null ? void 0 : _b.data)
338
- error.config.data = "--REDACTED--";
339
- const details = (_c = error.response) == null ? void 0 : _c.data;
340
- console.error(error.message || "That didn't work.");
341
- if (details)
342
- console.log(JSON.stringify(details, null, 2));
343
- return Promise.reject({
344
- request: error.config,
345
- message: error.message,
346
- response: (_d = error.response) == null ? void 0 : _d.data
347
- });
348
- }
349
- );
350
- function create(resourceType, data, options = {}, callback = (s) => s) {
351
- return (state) => {
352
- console.log(`Preparing create operation...`);
353
- const [resolvedResourceType, resolvedData, resolvedOptions] = (0, import_util.expandReferences)(state, resourceType, data, options);
354
- const { params, requestConfig } = resolvedOptions;
348
+ const [resolvedPath, resolvedData, resolvedParams] = (0, import_util3.expandReferences)(
349
+ state,
350
+ path,
351
+ data,
352
+ params
353
+ );
355
354
  const { configuration } = state;
356
- let promise;
357
- if (shouldUseNewTracker(resolvedResourceType)) {
358
- promise = callNewTracker(
355
+ let response;
356
+ if (shouldUseNewTracker(resolvedPath)) {
357
+ response = await callNewTracker(
359
358
  "create",
360
359
  configuration,
361
- resolvedOptions,
362
- resolvedResourceType,
360
+ {
361
+ query: resolvedParams
362
+ },
363
+ resolvedPath,
363
364
  resolvedData
364
365
  );
365
366
  } else {
366
- promise = request(configuration, {
367
- method: "post",
368
- url: generateUrl(configuration, resolvedOptions, resolvedResourceType),
369
- params,
370
- data: resolvedData,
371
- ...requestConfig
367
+ response = await request(configuration, {
368
+ method: "POST",
369
+ path: prefixVersionToPath(configuration, {}, resolvedPath),
370
+ options: {
371
+ query: resolvedParams
372
+ },
373
+ data: resolvedData
372
374
  });
373
375
  }
374
- return promise.then((result) => {
375
- const details = `with response ${JSON.stringify(result.data, null, 2)}`;
376
- console.log(`Created ${resolvedResourceType} ${details}`);
377
- const { location } = result.headers;
378
- if (location)
379
- console.log(`Record available @ ${location}`);
380
- return handleResponse(result, state, callback);
376
+ const details = `with response ${JSON.stringify(
377
+ (_a = response.body) == null ? void 0 : _a.message,
378
+ null,
379
+ 2
380
+ )}`;
381
+ console.log(`Created ${resolvedPath} ${details}`);
382
+ const { location } = response.headers;
383
+ if (location)
384
+ console.log(`Record available @ ${location}`);
385
+ return handleResponse(response, state);
386
+ };
387
+ }
388
+ function get(path, params = {}) {
389
+ return async (state) => {
390
+ const [resolvedPath, resolvedParams] = (0, import_util3.expandReferences)(
391
+ state,
392
+ path,
393
+ params
394
+ );
395
+ const response = await request(state.configuration, {
396
+ method: "GET",
397
+ path: prefixVersionToPath(state.configuration, {}, resolvedPath),
398
+ options: { query: resolvedParams }
381
399
  });
400
+ console.log(`Retrieved ${resolvedPath}`);
401
+ return handleResponse(response, state);
382
402
  };
383
403
  }
384
- function update(resourceType, path, data, options = {}, callback = (s) => s) {
385
- return (state) => {
404
+ function update(resourceType, path, data, options = {}) {
405
+ return async (state) => {
386
406
  console.log(`Preparing update operation...`);
387
- const [resolvedResourceType, resolvedPath, resolvedData, resolvedOptions] = (0, import_util.expandReferences)(state, resourceType, path, data, options);
388
- const { requestConfig } = resolvedOptions;
407
+ const [resolvedResourceType, resolvedPath, resolvedData, resolvedOptions] = (0, import_util3.expandReferences)(state, resourceType, path, data, options);
389
408
  const { configuration } = state;
390
- let promise;
409
+ let response;
391
410
  if (shouldUseNewTracker(resolvedResourceType)) {
392
- promise = callNewTracker(
411
+ response = await callNewTracker(
393
412
  "update",
394
413
  configuration,
395
414
  resolvedOptions,
@@ -397,73 +416,29 @@ function update(resourceType, path, data, options = {}, callback = (s) => s) {
397
416
  resolvedData
398
417
  );
399
418
  } else {
400
- promise = request(configuration, {
401
- method: "put",
402
- url: generateUrl(
419
+ response = await request(configuration, {
420
+ method: "PUT",
421
+ path: prefixVersionToPath(
403
422
  configuration,
404
423
  resolvedOptions,
405
424
  resolvedResourceType,
406
425
  resolvedPath
407
426
  ),
408
- options,
409
- data: resolvedData,
410
- ...requestConfig
427
+ options: resolvedOptions,
428
+ data: resolvedData
411
429
  });
412
430
  }
413
- return promise.then((result) => {
414
- console.log(`Updated ${resolvedResourceType} at ${resolvedPath}`);
415
- return handleResponse(result, state, callback);
416
- });
417
- };
418
- }
419
- function get(resourceType, query, options = {}, callback = (s) => s) {
420
- return (state) => {
421
- console.log("Preparing get operation...");
422
- const [resolvedResourceType, resolvedQuery, resolvedOptions] = (0, import_util.expandReferences)(state, resourceType, query, options);
423
- const { params, requestConfig, asBase64 = false } = resolvedOptions;
424
- const { configuration } = state;
425
- return request(configuration, {
426
- method: "get",
427
- url: generateUrl(configuration, resolvedOptions, resolvedResourceType),
428
- params: {
429
- ...resolvedQuery,
430
- ...params
431
- },
432
- responseType: asBase64 ? "arraybuffer" : "json",
433
- ...requestConfig
434
- }).then((result) => {
435
- console.log(`Retrieved ${resolvedResourceType}`);
436
- const response = asBase64 ? { data: (0, import_util.encode)(result.data) } : result;
437
- return handleResponse(response, state, callback);
438
- });
431
+ console.log(`Updated ${resolvedResourceType} at ${resolvedPath}`);
432
+ return handleResponse(response, state);
439
433
  };
440
434
  }
441
- function post(resourceType, data, query, options = {}, callback = (s) => s) {
442
- return (state) => {
443
- console.log("Preparing post operation...");
444
- const [resolvedResourceType, resolvedQuery, resolvedOptions, resolvedData] = (0, import_util.expandReferences)(state, resourceType, query, options, data);
445
- const { params, requestConfig } = resolvedOptions;
435
+ function upsert(resourceType, query, data, options = {}) {
436
+ return async (state) => {
437
+ const [resolvedResourceType, resolvedOptions, resolvedData, resolvedQuery] = (0, import_util3.expandReferences)(state, resourceType, options, data, query);
438
+ let response;
446
439
  const { configuration } = state;
447
- return request(configuration, {
448
- method: "post",
449
- url: generateUrl(configuration, resolvedOptions, resolvedResourceType),
450
- params: { ...resolvedQuery, ...params },
451
- responseType: "json",
452
- data: resolvedData,
453
- ...requestConfig
454
- }).then((result) => {
455
- console.log(`Created ${resolvedResourceType}`);
456
- return handleResponse(result, state, callback);
457
- });
458
- };
459
- }
460
- function upsert(resourceType, query, data, options = {}, callback = (s) => s) {
461
- return (state) => {
462
- const [resolvedResourceType, resolvedOptions, resolvedData] = (0, import_util.expandReferences)(state, resourceType, options, data);
463
- let promise;
464
440
  if (shouldUseNewTracker(resolvedResourceType)) {
465
- const { configuration } = state;
466
- promise = callNewTracker(
441
+ response = await callNewTracker(
467
442
  "create_and_update",
468
443
  configuration,
469
444
  resolvedOptions,
@@ -472,128 +447,67 @@ function upsert(resourceType, query, data, options = {}, callback = (s) => s) {
472
447
  );
473
448
  } else {
474
449
  console.log(`Preparing upsert via 'get' then 'create' OR 'update'...`);
475
- promise = get(
476
- resourceType,
477
- query,
478
- options
479
- )(state).then((resp) => {
480
- const resources = resp.data[resourceType];
481
- if (resources.length > 1) {
482
- throw new RangeError(
483
- `Cannot upsert on Non-unique attribute. The operation found more than one records for your request.`
484
- );
485
- } else if (resources.length <= 0) {
486
- return create(resourceType, data, options)(state);
487
- } else {
488
- const path = resources[0][selectId(resourceType)];
489
- return update(resourceType, path, data, options)(state);
450
+ response = await request(configuration, {
451
+ method: "GET",
452
+ path: prefixVersionToPath(
453
+ configuration,
454
+ resolvedOptions,
455
+ resolvedResourceType
456
+ ),
457
+ options: {
458
+ ...resolvedOptions,
459
+ query: {
460
+ ...resolvedQuery
461
+ }
490
462
  }
491
463
  });
492
- }
493
- return promise.then((result) => {
494
- console.log(`Performed a "composed upsert" on ${resourceType}`);
495
- return handleResponse(result, state, callback);
496
- });
497
- };
498
- }
499
- function discover(httpMethod, endpoint) {
500
- return (state) => {
501
- console.log(
502
- `Discovering query/import parameters for ${httpMethod} on ${endpoint}`
503
- );
504
- return import_axios3.default.get(
505
- "https://dhis2.github.io/dhis2-api-specification/spec/metadata_openapi.json",
506
- {
507
- transformResponse: [
508
- (data) => {
509
- let tempData = JSON.parse(data);
510
- let filteredData = tempData.paths[endpoint][httpMethod];
511
- return {
512
- ...filteredData,
513
- parameters: filteredData.parameters.reduce(
514
- (acc, currentValue) => {
515
- let index = currentValue["$ref"].lastIndexOf("/") + 1;
516
- let paramRef = currentValue["$ref"].slice(index);
517
- let param = tempData.components.parameters[paramRef];
518
- if (param.schema["$ref"]) {
519
- let schemaRefIndex = param.schema["$ref"].lastIndexOf("/") + 1;
520
- let schemaRef = param.schema["$ref"].slice(schemaRefIndex);
521
- param.schema = tempData.components.schemas[schemaRef];
522
- }
523
- param.schema = JSON.stringify(param.schema);
524
- let descIndex;
525
- if (indexOf(param.description, ",") === -1 && indexOf(param.description, ".") > -1)
526
- descIndex = indexOf(param.description, ".");
527
- else if (indexOf(param.description, ",") > -1 && indexOf(param.description, ".") > -1) {
528
- descIndex = indexOf(param.description, ".") < indexOf(param.description, ",") ? indexOf(param.description, ".") : indexOf(param.description, ",");
529
- } else {
530
- descIndex = param.description.length;
531
- }
532
- param.description = param.description.slice(0, descIndex);
533
- acc[paramRef] = param;
534
- return acc;
535
- },
536
- {}
537
- )
538
- };
539
- }
540
- ]
464
+ const resources = response.body[resourceType];
465
+ if (resources.length > 1) {
466
+ (0, import_util3.throwError)(409, {
467
+ description: "Upsert failed: Multiple records found for a non-unique attribute.",
468
+ fix: "Ensure the attribute is unique or modify the request to target a single record.",
469
+ error: "Conflict"
470
+ });
471
+ } else if (resources.length <= 0) {
472
+ console.log(`Preparing create operation...`);
473
+ response = await request(configuration, {
474
+ method: "POST",
475
+ path: prefixVersionToPath(
476
+ configuration,
477
+ resolvedOptions,
478
+ resolvedResourceType
479
+ ),
480
+ options: resolvedOptions,
481
+ data: resolvedData
482
+ });
483
+ } else {
484
+ const path = resources[0][selectId(resourceType)];
485
+ console.log(`Preparing update operation...`);
486
+ response = await request(configuration, {
487
+ method: "PUT",
488
+ path: prefixVersionToPath(
489
+ configuration,
490
+ resolvedOptions,
491
+ resolvedResourceType,
492
+ path
493
+ ),
494
+ options: resolvedOptions,
495
+ data: resolvedData
496
+ });
541
497
  }
542
- ).then((result) => {
543
- console.log(
544
- ` =======================================================================================
545
- Query Parameters for ${httpMethod} on ${endpoint} [${result.data.description ?? "<description_missing>"}]
546
- =======================================================================================`
547
- );
548
- console.table(result.data.parameters, [
549
- "in",
550
- "required",
551
- "description"
552
- ]);
553
- console.table(result.data.parameters, ["schema"]);
554
- console.log(
555
- `=========================================Responses===============================
556
- ${prettyJson(
557
- result.data.responses
558
- )}
559
- =======================================================================================`
560
- );
561
- return { ...state, data: result.data };
562
- });
563
- };
564
- }
565
- function patch(resourceType, path, data, options = {}, callback = (s) => s) {
566
- return (state) => {
567
- console.log("Preparing patch operation...");
568
- const [resolvedResourceType, resolvedPath, resolvedData, resolvedOptions] = (0, import_util.expandReferences)(state, resourceType, path, data, options);
569
- const { params, requestConfig } = resolvedOptions;
570
- const { configuration } = state;
571
- return request(configuration, {
572
- method: "patch",
573
- url: generateUrl(
574
- configuration,
575
- resolvedOptions,
576
- resolvedResourceType,
577
- resolvedPath
578
- ),
579
- params,
580
- data: resolvedData,
581
- ...requestConfig
582
- }).then((result) => {
583
- console.log(`Patched ${resolvedResourceType} at ${resolvedPath}`);
584
- return handleResponse(result, state, callback);
585
- });
498
+ }
499
+ console.log(`Performed a "composed upsert" on ${resourceType}`);
500
+ return handleResponse(response, state);
586
501
  };
587
502
  }
588
- function destroy(resourceType, path, data = null, options = {}, callback = false) {
589
- return (state) => {
503
+ function destroy(resourceType, path, data = null, options = {}) {
504
+ return async (state) => {
590
505
  console.log("Preparing destroy operation...");
591
- const [resolvedResourceType, resolvedPath, resolvedData, resolvedOptions] = (0, import_util.expandReferences)(state, resourceType, path, data, options);
592
- const { params, requestConfig } = resolvedOptions;
506
+ const [resolvedResourceType, resolvedPath, resolvedData, resolvedOptions] = (0, import_util3.expandReferences)(state, resourceType, path, data, options);
593
507
  const { configuration } = state;
594
- let promise;
508
+ let response;
595
509
  if (shouldUseNewTracker(resolvedResourceType)) {
596
- promise = callNewTracker(
510
+ response = await callNewTracker(
597
511
  "delete",
598
512
  configuration,
599
513
  resolvedOptions,
@@ -601,43 +515,23 @@ function destroy(resourceType, path, data = null, options = {}, callback = false
601
515
  resolvedData
602
516
  );
603
517
  } else {
604
- promise = request({
605
- method: "delete",
606
- url: generateUrl(
518
+ response = await request(configuration, {
519
+ method: "DELETE",
520
+ path: prefixVersionToPath(
607
521
  configuration,
608
522
  resolvedOptions,
609
523
  resolvedResourceType,
610
524
  resolvedPath
611
525
  ),
612
- params,
613
- resolvedData,
614
- ...requestConfig
526
+ options: resolvedOptions,
527
+ data: resolvedData
615
528
  });
616
529
  }
617
- return promise.then((result) => {
618
- console.log(`Deleted ${resolvedResourceType} at ${resolvedPath}`);
619
- return handleResponse(result, state, callback);
620
- });
530
+ console.log(`Deleted ${resolvedResourceType} at ${resolvedPath}`);
531
+ return handleResponse(response, state);
621
532
  };
622
533
  }
623
- function findAttributeValueById(trackedEntity, attributeUid) {
624
- var _a, _b;
625
- return (_b = (_a = trackedEntity == null ? void 0 : trackedEntity.attributes) == null ? void 0 : _a.find((a) => (a == null ? void 0 : a.attribute) == attributeUid)) == null ? void 0 : _b.value;
626
- }
627
- function findAttributeValue(trackedEntity, attributeDisplayName) {
628
- var _a, _b;
629
- return (_b = (_a = trackedEntity == null ? void 0 : trackedEntity.attributes) == null ? void 0 : _a.find(
630
- (a) => (a == null ? void 0 : a.displayName.toLowerCase()) == attributeDisplayName.toLowerCase()
631
- )) == null ? void 0 : _b.value;
632
- }
633
- function attr(attribute, value) {
634
- return { attribute, value };
635
- }
636
- function dv(dataElement, value) {
637
- return { dataElement, value };
638
- }
639
534
  function callNewTracker(type = "update", configuration, options, resourceType, data = {}) {
640
- const { params, requestConfig, ...opts } = options;
641
535
  let importStrategy;
642
536
  switch (type) {
643
537
  case "create":
@@ -653,41 +547,193 @@ function callNewTracker(type = "update", configuration, options, resourceType, d
653
547
  importStrategy = "CREATE_AND_UPDATE";
654
548
  }
655
549
  return request(configuration, {
656
- method: "post",
657
- url: generateUrl(
658
- configuration,
659
- {
660
- ...opts,
550
+ method: "POST",
551
+ path: prefixVersionToPath(configuration, options, "tracker"),
552
+ options: {
553
+ ...options,
554
+ query: {
555
+ ...options.query,
556
+ async: false,
661
557
  importStrategy
662
- },
663
- "tracker"
664
- ),
665
- params: { async: false, ...params },
666
- data: ensureArray(data, resourceType),
667
- ...requestConfig
558
+ }
559
+ },
560
+ data: ensureArray(data, resourceType)
668
561
  });
669
562
  }
670
563
 
564
+ // src/http.js
565
+ var http_exports = {};
566
+ __export(http_exports, {
567
+ get: () => get2,
568
+ patch: () => patch,
569
+ post: () => post,
570
+ request: () => request2
571
+ });
572
+ var import_util5 = require("@openfn/language-common/util");
573
+ function get2(path, options = {}) {
574
+ return async (state) => {
575
+ console.log("Preparing get operation...");
576
+ const [resolvedPath, resolvedOptions] = (0, import_util5.expandReferences)(
577
+ state,
578
+ path,
579
+ options
580
+ );
581
+ const { parseAs } = resolvedOptions;
582
+ const response = await request(state.configuration, {
583
+ method: "GET",
584
+ path: prefixVersionToPath(
585
+ state.configuration,
586
+ resolvedOptions,
587
+ resolvedPath
588
+ ),
589
+ options: resolvedOptions
590
+ });
591
+ return handleHttpResponse(response, state);
592
+ };
593
+ }
594
+ function post(path, data, options = {}) {
595
+ return async (state) => {
596
+ console.log("Preparing post operation...");
597
+ const [resolvedPath, resolvedOptions, resolvedData] = (0, import_util5.expandReferences)(
598
+ state,
599
+ path,
600
+ options,
601
+ data
602
+ );
603
+ const { configuration } = state;
604
+ let response;
605
+ response = await request(configuration, {
606
+ method: "POST",
607
+ path: prefixVersionToPath(
608
+ configuration,
609
+ resolvedOptions,
610
+ resolvedPath
611
+ ),
612
+ options: resolvedOptions,
613
+ data: resolvedData
614
+ });
615
+ return handleHttpResponse(response, state);
616
+ };
617
+ }
618
+ function patch(resourceType, path, data, options = {}) {
619
+ return async (state) => {
620
+ console.log("Preparing patch operation...");
621
+ const [resolvedResourceType, resolvedPath, resolvedData, resolvedOptions] = (0, import_util5.expandReferences)(state, resourceType, path, data, options);
622
+ const { configuration } = state;
623
+ let response;
624
+ response = await request(configuration, {
625
+ method: "PATCH",
626
+ path: prefixVersionToPath(
627
+ configuration,
628
+ resolvedOptions,
629
+ resolvedResourceType,
630
+ resolvedPath
631
+ ),
632
+ options: resolvedOptions,
633
+ data: resolvedData
634
+ });
635
+ return handleHttpResponse(response, state);
636
+ };
637
+ }
638
+ function request2(method, path, options = {}) {
639
+ return async (state) => {
640
+ console.log(`Preparing a ${method.toLowerCase()} operation...`);
641
+ const [resolvedMethod, resolvedPath, resolvedOptions = {}] = (0, import_util5.expandReferences)(state, method, path, options);
642
+ const { data } = resolvedOptions;
643
+ const { configuration } = state;
644
+ let response;
645
+ response = await request(configuration, {
646
+ method: resolvedMethod,
647
+ path: prefixVersionToPath(
648
+ configuration,
649
+ resolvedOptions,
650
+ resolvedPath
651
+ ),
652
+ options: resolvedOptions,
653
+ data
654
+ });
655
+ return handleHttpResponse(response, state);
656
+ };
657
+ }
658
+
659
+ // src/tracker.js
660
+ var tracker_exports = {};
661
+ __export(tracker_exports, {
662
+ export: () => _export,
663
+ import: () => _import
664
+ });
665
+ var import_util6 = require("@openfn/language-common/util");
666
+ function _import(strategy, payload, options = {}) {
667
+ return async (state) => {
668
+ console.log("Preparing tracker import operation...");
669
+ const [resolvedStrategy, resolvedPayload, resolvedOptions] = (0, import_util6.expandReferences)(state, strategy, payload, options);
670
+ const { apiVersion, parseAs, ...query } = resolvedOptions;
671
+ const response = await request(state.configuration, {
672
+ method: "POST",
673
+ path: prefixVersionToPath(
674
+ state.configuration,
675
+ {
676
+ ...resolvedOptions,
677
+ resolvedStrategy
678
+ },
679
+ "tracker"
680
+ ),
681
+ options: {
682
+ apiVersion,
683
+ parseAs,
684
+ query: {
685
+ ...query,
686
+ async: false
687
+ }
688
+ },
689
+ data: resolvedPayload
690
+ });
691
+ return handleHttpResponse(response, state);
692
+ };
693
+ }
694
+ function _export(path, query, options = {}) {
695
+ return async (state) => {
696
+ console.log("Preparing tracker export operation...");
697
+ const [resolvedPath, resolvedQuery, resolvedOptions] = (0, import_util6.expandReferences)(
698
+ state,
699
+ path,
700
+ query,
701
+ options
702
+ );
703
+ const response = await request(state.configuration, {
704
+ method: "GET",
705
+ path: prefixVersionToPath(
706
+ state.configuration,
707
+ resolvedOptions,
708
+ `tracker/${resolvedPath}`
709
+ ),
710
+ options: {
711
+ ...resolvedOptions,
712
+ query: {
713
+ ...resolvedQuery,
714
+ async: false
715
+ }
716
+ }
717
+ });
718
+ return handleHttpResponse(response, state);
719
+ };
720
+ }
721
+
671
722
  // src/index.js
672
723
  var src_default = Adaptor_exports;
673
724
  // Annotate the CommonJS export names for ESM import in node:
674
725
  0 && (module.exports = {
675
726
  alterState,
676
- attr,
677
727
  create,
678
728
  cursor,
679
729
  dataPath,
680
730
  dataValue,
681
731
  dateFns,
682
732
  destroy,
683
- discover,
684
- dv,
685
733
  each,
686
734
  execute,
687
735
  field,
688
736
  fields,
689
- findAttributeValue,
690
- findAttributeValueById,
691
737
  fn,
692
738
  fnIf,
693
739
  get,
@@ -696,9 +742,9 @@ var src_default = Adaptor_exports;
696
742
  lastReferenceValue,
697
743
  merge,
698
744
  metadata,
699
- patch,
700
- post,
701
745
  sourceValue,
746
+ tracker,
702
747
  update,
703
- upsert
748
+ upsert,
749
+ util
704
750
  });