sim 2.2.31 → 2.2.32-preview.312.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8137,6 +8137,40 @@ function resolveProfile(overrides = {}) {
8137
8137
  }
8138
8138
  };
8139
8139
  }
8140
+ // ../utils/src/retry.ts
8141
+ var DEFAULT_BACKOFF_BASE_MS = 500;
8142
+ var DEFAULT_BACKOFF_MAX_MS = 30000;
8143
+ function backoffWithJitter(attempt, retryAfterMs, options = {}) {
8144
+ const baseMs = options.baseMs ?? DEFAULT_BACKOFF_BASE_MS;
8145
+ const maxMs = options.maxMs ?? DEFAULT_BACKOFF_MAX_MS;
8146
+ if (retryAfterMs !== null) {
8147
+ return Math.min(Math.max(retryAfterMs, baseMs), maxMs);
8148
+ }
8149
+ const exponential = Math.min(baseMs * 2 ** (attempt - 1), maxMs);
8150
+ const jitter = crypto.getRandomValues(new Uint32Array(1))[0] / 4294967296;
8151
+ return exponential * (0.8 + jitter * 0.4);
8152
+ }
8153
+ var RETRY_AFTER_MAX_MS = 30000;
8154
+ function parseRetryAfter(header, maxMs = RETRY_AFTER_MAX_MS) {
8155
+ if (!header)
8156
+ return null;
8157
+ const trimmed = header.trim();
8158
+ if (trimmed.length === 0)
8159
+ return null;
8160
+ const seconds = Number(trimmed);
8161
+ if (Number.isFinite(seconds) && seconds >= 0) {
8162
+ return Math.min(Math.floor(seconds * 1000), maxMs);
8163
+ }
8164
+ const dateMs = Date.parse(trimmed);
8165
+ if (!Number.isNaN(dateMs)) {
8166
+ const delta = dateMs - Date.now();
8167
+ if (delta <= 0)
8168
+ return 0;
8169
+ return Math.min(delta, maxMs);
8170
+ }
8171
+ return null;
8172
+ }
8173
+
8140
8174
  // src/output/io.ts
8141
8175
  import { format } from "node:util";
8142
8176
  function printLine(...args) {
@@ -8412,6 +8446,7 @@ class SimApiError extends Error {
8412
8446
  details;
8413
8447
  exitCode;
8414
8448
  requestId;
8449
+ retryAfterMs = null;
8415
8450
  constructor(message, status, code = null, details, exitCode = 1, requestId = null) {
8416
8451
  super(message);
8417
8452
  this.status = status;
@@ -8496,7 +8531,9 @@ async function readResponseText(response) {
8496
8531
  try {
8497
8532
  return await response.text();
8498
8533
  } catch (error) {
8499
- throw new SimApiError(`Unable to read the response: ${transportErrorMessage(error)}`, response.status, "RESPONSE_READ_FAILED", undefined, 1, responseRequestId(response));
8534
+ const failure = new SimApiError(`Unable to read the response: ${transportErrorMessage(error)}`, response.status, "RESPONSE_READ_FAILED", undefined, 1, responseRequestId(response));
8535
+ failure.retryAfterMs = parseRetryAfter(response.headers.get("retry-after"), 300000);
8536
+ throw failure;
8500
8537
  }
8501
8538
  }
8502
8539
  function refusalCode(error) {
@@ -8743,6 +8780,7 @@ class SimClient {
8743
8780
  if (!response.ok) {
8744
8781
  const raw = await readResponseText(response);
8745
8782
  const error = toApiError(url, response, raw);
8783
+ error.retryAfterMs = parseRetryAfter(response.headers.get("retry-after"), 300000);
8746
8784
  if (response.status === 401) {
8747
8785
  error.message = `${error.message} — run: sim login --profile ${this.profile.authProfile}`;
8748
8786
  }
@@ -10938,6 +10976,40 @@ var V2_OPERATIONS = {
10938
10976
  }
10939
10977
  }
10940
10978
  },
10979
+ createSearchSource: {
10980
+ method: "POST",
10981
+ path: "/api/v2/organizations/[organizationId]/search/sources",
10982
+ pathParams: ["organizationId"],
10983
+ pathParamDocs: { organizationId: "Organization identifier." },
10984
+ responseMode: "json",
10985
+ summary: "Create Search source",
10986
+ body: {
10987
+ connectorType: { kind: "string", required: true, describe: "Registered connector type." },
10988
+ credentialId: {
10989
+ kind: "string",
10990
+ describe: "OAuth credential identifier for connector types whose `auth.mode` is `oauth` (see connector types), or a saved credential for an `apiKey` connector type that declares `auth.savedCredential` (such as Amazon S3 with a saved AWS credential); otherwise omit it for `apiKey` connectors."
10991
+ },
10992
+ apiKey: {
10993
+ kind: "string",
10994
+ describe: "Write-only API key for connector types whose `auth.mode` is `apiKey` (see connector types), or a personal access token for an OAuth connector that also accepts one, such as GitHub. Send it instead of `credentialId`. Pass a raw key, or a secret reference written as the whole value `{{SECRET_NAME}}`, which the server resolves; `$SECRET_NAME` is not a reference."
10995
+ },
10996
+ sourceConfig: {
10997
+ kind: "object",
10998
+ required: true,
10999
+ describe: "Connector-specific source selection and filtering configuration."
11000
+ },
11001
+ accessMode: {
11002
+ kind: "enum",
11003
+ values: ["admin", "members"],
11004
+ default: "admin",
11005
+ describe: "Source-managed permissions (admin), or individually connected member accounts (members)."
11006
+ },
11007
+ permissionConfig: {
11008
+ kind: "object",
11009
+ describe: "Provider-specific permissions for initial setup. Large CSV snapshots use permission imports after creation."
11010
+ }
11011
+ }
11012
+ },
10941
11013
  createServiceAccountCredential: {
10942
11014
  method: "POST",
10943
11015
  path: "/api/v2/credentials",
@@ -11576,6 +11648,17 @@ var V2_OPERATIONS = {
11576
11648
  workspaceId: { kind: "string", required: true, describe: "Workspace that owns the sandbox." }
11577
11649
  }
11578
11650
  },
11651
+ deleteSearchSource: {
11652
+ method: "DELETE",
11653
+ path: "/api/v2/organizations/[organizationId]/search/sources/[sourceId]",
11654
+ pathParams: ["organizationId", "sourceId"],
11655
+ pathParamDocs: {
11656
+ organizationId: "Organization identifier.",
11657
+ sourceId: "Search source identifier, also used by permission uploads."
11658
+ },
11659
+ responseMode: "json",
11660
+ summary: "Delete Search source"
11661
+ },
11579
11662
  deleteSecret: {
11580
11663
  method: "DELETE",
11581
11664
  path: "/api/v2/secrets/[name]",
@@ -12800,6 +12883,17 @@ var V2_OPERATIONS = {
12800
12883
  workspaceId: { kind: "string", required: true, describe: "Workspace that owns the sandbox." }
12801
12884
  }
12802
12885
  },
12886
+ getSearchSource: {
12887
+ method: "GET",
12888
+ path: "/api/v2/organizations/[organizationId]/search/sources/[sourceId]",
12889
+ pathParams: ["organizationId", "sourceId"],
12890
+ pathParamDocs: {
12891
+ organizationId: "Organization identifier.",
12892
+ sourceId: "Search source identifier, also used by permission uploads."
12893
+ },
12894
+ responseMode: "json",
12895
+ summary: "Get Search source"
12896
+ },
12803
12897
  getSearchSourcePermissions: {
12804
12898
  method: "GET",
12805
12899
  path: "/api/v2/organizations/[organizationId]/search/sources/[sourceId]/permissions",
@@ -15049,6 +15143,38 @@ var V2_OPERATIONS = {
15049
15143
  }
15050
15144
  }
15051
15145
  },
15146
+ listSearchSources: {
15147
+ method: "GET",
15148
+ path: "/api/v2/organizations/[organizationId]/search/sources",
15149
+ pathParams: ["organizationId"],
15150
+ pathParamDocs: { organizationId: "Organization identifier." },
15151
+ responseMode: "json",
15152
+ summary: "List Search sources",
15153
+ query: {
15154
+ sortBy: {
15155
+ kind: "enum",
15156
+ values: ["connectorType", "createdAt", "updatedAt"],
15157
+ default: "createdAt",
15158
+ describe: "Field used to sort the result."
15159
+ },
15160
+ sortOrder: {
15161
+ kind: "enum",
15162
+ values: ["asc", "desc"],
15163
+ default: "desc",
15164
+ describe: "Sort direction."
15165
+ },
15166
+ limit: {
15167
+ kind: "integer",
15168
+ default: 50,
15169
+ maximum: 100,
15170
+ describe: "Maximum connectors to return per page. Must be a whole number from 1 to 100. Defaults to 50."
15171
+ },
15172
+ cursor: {
15173
+ kind: "string",
15174
+ describe: "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor."
15175
+ }
15176
+ }
15177
+ },
15052
15178
  listSecrets: {
15053
15179
  method: "GET",
15054
15180
  path: "/api/v2/secrets",
@@ -16031,6 +16157,23 @@ var V2_OPERATIONS = {
16031
16157
  }
16032
16158
  }
16033
16159
  },
16160
+ prepareSearchSources: {
16161
+ method: "POST",
16162
+ path: "/api/v2/organizations/[organizationId]/search/sources/prepare",
16163
+ pathParams: ["organizationId"],
16164
+ pathParamDocs: { organizationId: "Organization identifier." },
16165
+ responseMode: "json",
16166
+ summary: "Prepare Search sources",
16167
+ body: {
16168
+ connectorType: { kind: "string", required: true, describe: "Registered connector type." },
16169
+ accessMode: {
16170
+ kind: "enum",
16171
+ values: ["admin", "members"],
16172
+ default: "admin",
16173
+ describe: "Source-managed permissions (admin), or individually connected member accounts (members)."
16174
+ }
16175
+ }
16176
+ },
16034
16177
  previewOrganizationAccessRequest: {
16035
16178
  method: "GET",
16036
16179
  path: "/api/v2/organizations/[organizationId]/access-requests/[requestId]/preview",
@@ -18169,6 +18312,36 @@ var V2_OPERATIONS = {
18169
18312
  }
18170
18313
  }
18171
18314
  },
18315
+ updateSearchSource: {
18316
+ method: "PATCH",
18317
+ path: "/api/v2/organizations/[organizationId]/search/sources/[sourceId]",
18318
+ pathParams: ["organizationId", "sourceId"],
18319
+ pathParamDocs: {
18320
+ organizationId: "Organization identifier.",
18321
+ sourceId: "Search source identifier, also used by permission uploads."
18322
+ },
18323
+ responseMode: "json",
18324
+ summary: "Update Search source",
18325
+ body: {
18326
+ apiKey: {
18327
+ kind: "string",
18328
+ describe: "Replacement token for providers supporting credential updates (currently GitLab). For GitLab, supply permissionConfig with the current expectedRevision; omitted CSVs retain grants. Omit to keep the saved token."
18329
+ },
18330
+ sourceConfig: {
18331
+ kind: "object",
18332
+ describe: "Complete replacement source configuration. Read the existing configuration before editing it."
18333
+ },
18334
+ permissionConfig: {
18335
+ kind: "object",
18336
+ describe: "Provider-specific permission update, using the current expectedRevision. Omit to retain permissions."
18337
+ },
18338
+ status: {
18339
+ kind: "enum",
18340
+ values: ["active", "paused"],
18341
+ describe: "Pause or resume this source without changing its ID or stored permissions."
18342
+ }
18343
+ }
18344
+ },
18172
18345
  updateSkill: {
18173
18346
  method: "PATCH",
18174
18347
  path: "/api/v2/skills/[skillId]",
@@ -20514,6 +20687,37 @@ var CLI_CONTRACT = {
20514
20687
  columns: [{ header: "id" }, { header: "name" }, { header: "role" }]
20515
20688
  },
20516
20689
  getOrganization: { command: "organizations get" },
20690
+ prepareSearchSources: {
20691
+ command: "organizations search sources prepare",
20692
+ pathFlags: ORGANIZATION_FLAG
20693
+ },
20694
+ listSearchSources: {
20695
+ command: "organizations search sources list",
20696
+ pathFlags: ORGANIZATION_FLAG,
20697
+ columns: [
20698
+ { header: "id" },
20699
+ { header: "provider", path: "connectorType" },
20700
+ { header: "status" },
20701
+ { header: "approved", format: "bool" }
20702
+ ]
20703
+ },
20704
+ getSearchSource: { command: "organizations search sources get", pathFlags: ORGANIZATION_FLAG },
20705
+ createSearchSource: {
20706
+ command: "organizations search sources create",
20707
+ pathFlags: ORGANIZATION_FLAG,
20708
+ flags: { apiKey: { textSource: true } }
20709
+ },
20710
+ updateSearchSource: {
20711
+ command: "organizations search sources update",
20712
+ pathFlags: ORGANIZATION_FLAG,
20713
+ flags: { apiKey: { textSource: true } },
20714
+ confirm: "This updates source settings and may replace its permission grants."
20715
+ },
20716
+ deleteSearchSource: {
20717
+ command: "organizations search sources delete",
20718
+ pathFlags: ORGANIZATION_FLAG,
20719
+ confirm: "This removes the source and its permission grants."
20720
+ },
20517
20721
  getSearchSourcePermissions: {
20518
20722
  command: "organizations search sources permissions get",
20519
20723
  pathFlags: ORGANIZATION_FLAG
@@ -26856,6 +27060,1743 @@ function attachSecretCommands(program) {
26856
27060
  set.argument("<name>", "Secret name, as referenced in workflows").description(describeOperation(V2_OPERATIONS.setSecret, "Create or replace a named secret, such as an API key or environment variable")).addOption(new Option("--scope <scope>", "Secret ownership scope (required)").choices([...SECRET_SCOPES]).makeOptionMandatory()).option("--value <value|@file>", "Secret value. Passing it inline exposes it to shell history and process listings; @path reads it from a file and @- from stdin, verbatim — a trailing newline is part of the value, so write the file with printf rather than echo. Prefix a literal leading @ with a second one").option("--description <description>", "What the secret is for, shown to teammates; workspace scope only. Omit to leave an existing description unchanged").option("--unredacted", `${V2_OPERATIONS.setSecret.body.unredacted.describe} Pass --no-unredacted to restore redaction`).option("--no-unredacted", "Send --unredacted as false").addHelpText("after", "Omit --value to enter it privately in a terminal. For an existing workspace secret, passing only --description or a redaction flag keeps the stored value and does not prompt. Personal secrets always require a value; they accept no writable metadata. In scripts, pass --value @path or --value @-.").on("option:unredacted", () => redactionSpellings.add("--unredacted")).on("option:no-unredacted", () => redactionSpellings.add("--no-unredacted")).action((name, options) => setSecret(name, options, connectSet, redactionSpellings));
26857
27061
  }
26858
27062
 
27063
+ // src/commands/source-permissions.ts
27064
+ import { readFile } from "node:fs/promises";
27065
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
27066
+
27067
+ // src/transfer/permission-csv.ts
27068
+ import { constants as constants3 } from "node:fs";
27069
+ import { mkdtemp as mkdtemp2, open, rm as rm2, writeFile } from "node:fs/promises";
27070
+ import { tmpdir } from "node:os";
27071
+ import { basename as basename3, join as join4 } from "node:path";
27072
+ import { addAbortSignal, Readable as Readable2 } from "node:stream";
27073
+
27074
+ // ../../node_modules/csv-parse/lib/index.js
27075
+ import { Transform } from "stream";
27076
+
27077
+ // ../../node_modules/csv-parse/lib/utils/is_object.js
27078
+ var is_object = function(obj) {
27079
+ return typeof obj === "object" && obj !== null && !Array.isArray(obj);
27080
+ };
27081
+
27082
+ // ../../node_modules/csv-parse/lib/api/CsvError.js
27083
+ class CsvError extends Error {
27084
+ constructor(code, message, options, ...contexts) {
27085
+ if (Array.isArray(message))
27086
+ message = message.join(" ").trim();
27087
+ super(message);
27088
+ if (Error.captureStackTrace !== undefined) {
27089
+ Error.captureStackTrace(this, CsvError);
27090
+ }
27091
+ this.code = code;
27092
+ for (const context of contexts) {
27093
+ for (const key in context) {
27094
+ const value = context[key];
27095
+ this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value));
27096
+ }
27097
+ }
27098
+ }
27099
+ }
27100
+
27101
+ // ../../node_modules/csv-parse/lib/api/normalize_columns_array.js
27102
+ var normalize_columns_array = function(columns) {
27103
+ const normalizedColumns = [];
27104
+ for (let i = 0, l = columns.length;i < l; i++) {
27105
+ const column = columns[i];
27106
+ if (column === undefined || column === null || column === false) {
27107
+ normalizedColumns[i] = { disabled: true };
27108
+ } else if (typeof column === "string" || typeof column === "number") {
27109
+ normalizedColumns[i] = { name: `${column}` };
27110
+ } else if (is_object(column)) {
27111
+ if (typeof column.name !== "string") {
27112
+ throw new CsvError("CSV_OPTION_COLUMNS_MISSING_NAME", [
27113
+ "Option columns missing name:",
27114
+ `property "name" is required at position ${i}`,
27115
+ "when column is an object literal"
27116
+ ]);
27117
+ }
27118
+ normalizedColumns[i] = column;
27119
+ } else {
27120
+ throw new CsvError("CSV_INVALID_COLUMN_DEFINITION", [
27121
+ "Invalid column definition:",
27122
+ "expect a string or a literal object,",
27123
+ `got ${JSON.stringify(column)} at position ${i}`
27124
+ ]);
27125
+ }
27126
+ }
27127
+ return normalizedColumns;
27128
+ };
27129
+
27130
+ // ../../node_modules/csv-parse/lib/utils/ResizeableBuffer.js
27131
+ class ResizeableBuffer {
27132
+ constructor(size = 100) {
27133
+ this.size = size;
27134
+ this.length = 0;
27135
+ this.buf = Buffer.allocUnsafe(size);
27136
+ }
27137
+ prepend(val) {
27138
+ if (Buffer.isBuffer(val)) {
27139
+ const length = this.length + val.length;
27140
+ if (length >= this.size) {
27141
+ this.resize();
27142
+ if (length >= this.size) {
27143
+ throw Error("INVALID_BUFFER_STATE");
27144
+ }
27145
+ }
27146
+ const buf = this.buf;
27147
+ this.buf = Buffer.allocUnsafe(this.size);
27148
+ val.copy(this.buf, 0);
27149
+ buf.copy(this.buf, val.length);
27150
+ this.length += val.length;
27151
+ } else {
27152
+ const length = this.length++;
27153
+ if (length === this.size) {
27154
+ this.resize();
27155
+ }
27156
+ const buf = this.clone();
27157
+ this.buf[0] = val;
27158
+ buf.copy(this.buf, 1, 0, length);
27159
+ }
27160
+ }
27161
+ append(val) {
27162
+ const length = this.length++;
27163
+ if (length === this.size) {
27164
+ this.resize();
27165
+ }
27166
+ this.buf[length] = val;
27167
+ }
27168
+ clone() {
27169
+ return Buffer.from(this.buf.slice(0, this.length));
27170
+ }
27171
+ resize() {
27172
+ const length = this.length;
27173
+ this.size = this.size * 2;
27174
+ const buf = Buffer.allocUnsafe(this.size);
27175
+ this.buf.copy(buf, 0, 0, length);
27176
+ this.buf = buf;
27177
+ }
27178
+ toString(encoding) {
27179
+ if (encoding) {
27180
+ return this.buf.toString(encoding, 0, this.length);
27181
+ } else {
27182
+ return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length));
27183
+ }
27184
+ }
27185
+ toJSON() {
27186
+ return this.toString("utf8");
27187
+ }
27188
+ reset() {
27189
+ this.length = 0;
27190
+ }
27191
+ }
27192
+ var ResizeableBuffer_default = ResizeableBuffer;
27193
+
27194
+ // ../../node_modules/csv-parse/lib/api/init_state.js
27195
+ var init_state = function(options) {
27196
+ const timchars = [
27197
+ 32,
27198
+ 9,
27199
+ 10,
27200
+ 13,
27201
+ 12,
27202
+ 11,
27203
+ 160,
27204
+ 5760,
27205
+ 8192,
27206
+ 8193,
27207
+ 8194,
27208
+ 8195,
27209
+ 8196,
27210
+ 8197,
27211
+ 8198,
27212
+ 8199,
27213
+ 8200,
27214
+ 8201,
27215
+ 8202,
27216
+ 8232,
27217
+ 8233,
27218
+ 8239,
27219
+ 8287,
27220
+ 12288,
27221
+ 65279
27222
+ ].reduce((acc, codepoint) => {
27223
+ const encoded = Buffer.from(String.fromCharCode(codepoint), options.encoding);
27224
+ if (codepoint !== 63 && encoded.length === 1 && encoded[0] === 63) {
27225
+ return acc;
27226
+ }
27227
+ acc.push(encoded);
27228
+ return acc;
27229
+ }, []);
27230
+ const timcharFirstBytes = new Uint8Array(256);
27231
+ for (const t of timchars)
27232
+ timcharFirstBytes[t[0]] = 1;
27233
+ return {
27234
+ bomSkipped: false,
27235
+ bufBytesStart: 0,
27236
+ castField: options.cast_function,
27237
+ commenting: false,
27238
+ delimiterBufPrevious: undefined,
27239
+ delimiterDiscovered: false,
27240
+ error: undefined,
27241
+ enabled: options.from_line === 1,
27242
+ escaping: false,
27243
+ escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0,
27244
+ expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined,
27245
+ field: new ResizeableBuffer_default(20),
27246
+ firstLineToHeaders: options.cast_first_line_to_header,
27247
+ needMoreDataSize: Math.max(options.comment !== null ? options.comment.length : 0, ...options.delimiter ? options.delimiter.map((delimiter) => delimiter.length) : [], options.delimiter_auto ? 1 : 0, options.quote !== null ? options.quote.length : 0, ...timchars.map((t) => t.length)),
27248
+ previousBuf: undefined,
27249
+ quoting: false,
27250
+ stop: false,
27251
+ rawBuffer: new ResizeableBuffer_default(100),
27252
+ record: [],
27253
+ recordHasError: false,
27254
+ record_length: 0,
27255
+ recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)),
27256
+ trimChars: [
27257
+ Buffer.from(" ", options.encoding)[0],
27258
+ Buffer.from("\t", options.encoding)[0]
27259
+ ],
27260
+ wasQuoting: false,
27261
+ wasRowDelimiter: false,
27262
+ timchars,
27263
+ timcharFirstBytes
27264
+ };
27265
+ };
27266
+
27267
+ // ../../node_modules/csv-parse/lib/utils/underscore.js
27268
+ var underscore = function(str) {
27269
+ return str.replace(/([A-Z])/g, function(_, match) {
27270
+ return "_" + match.toLowerCase();
27271
+ });
27272
+ };
27273
+
27274
+ // ../../node_modules/csv-parse/lib/api/normalize_options.js
27275
+ var normalize_options = function(opts) {
27276
+ const options = {};
27277
+ for (const opt in opts) {
27278
+ options[underscore(opt)] = opts[opt];
27279
+ }
27280
+ if (options.encoding === undefined || options.encoding === true) {
27281
+ options.encoding = "utf8";
27282
+ } else if (options.encoding === null || options.encoding === false) {
27283
+ options.encoding = null;
27284
+ } else if (typeof options.encoding !== "string" && options.encoding !== null) {
27285
+ throw new CsvError("CSV_INVALID_OPTION_ENCODING", [
27286
+ "Invalid option encoding:",
27287
+ "encoding must be a string or null to return a buffer,",
27288
+ `got ${JSON.stringify(options.encoding)}`
27289
+ ], options);
27290
+ }
27291
+ if (options.bom === undefined || options.bom === null || options.bom === false) {
27292
+ options.bom = false;
27293
+ } else if (options.bom !== true) {
27294
+ throw new CsvError("CSV_INVALID_OPTION_BOM", [
27295
+ "Invalid option bom:",
27296
+ "bom must be true,",
27297
+ `got ${JSON.stringify(options.bom)}`
27298
+ ], options);
27299
+ }
27300
+ options.cast_function = null;
27301
+ if (options.cast === undefined || options.cast === null || options.cast === false || options.cast === "") {
27302
+ options.cast = undefined;
27303
+ } else if (typeof options.cast === "function") {
27304
+ options.cast_function = options.cast;
27305
+ options.cast = true;
27306
+ } else if (options.cast !== true) {
27307
+ throw new CsvError("CSV_INVALID_OPTION_CAST", [
27308
+ "Invalid option cast:",
27309
+ "cast must be true or a function,",
27310
+ `got ${JSON.stringify(options.cast)}`
27311
+ ], options);
27312
+ }
27313
+ if (options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === "") {
27314
+ options.cast_date = false;
27315
+ } else if (options.cast_date === true) {
27316
+ options.cast_date = function(value) {
27317
+ const date = Date.parse(value);
27318
+ return !isNaN(date) ? new Date(date) : value;
27319
+ };
27320
+ } else if (typeof options.cast_date !== "function") {
27321
+ throw new CsvError("CSV_INVALID_OPTION_CAST_DATE", [
27322
+ "Invalid option cast_date:",
27323
+ "cast_date must be true or a function,",
27324
+ `got ${JSON.stringify(options.cast_date)}`
27325
+ ], options);
27326
+ }
27327
+ options.cast_first_line_to_header = undefined;
27328
+ if (options.columns === true) {
27329
+ options.cast_first_line_to_header = undefined;
27330
+ } else if (typeof options.columns === "function") {
27331
+ options.cast_first_line_to_header = options.columns;
27332
+ options.columns = true;
27333
+ } else if (Array.isArray(options.columns)) {
27334
+ options.columns = normalize_columns_array(options.columns);
27335
+ } else if (options.columns === undefined || options.columns === null || options.columns === false) {
27336
+ options.columns = false;
27337
+ } else {
27338
+ throw new CsvError("CSV_INVALID_OPTION_COLUMNS", [
27339
+ "Invalid option columns:",
27340
+ "expect an array, a function or true,",
27341
+ `got ${JSON.stringify(options.columns)}`
27342
+ ], options);
27343
+ }
27344
+ if (options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false) {
27345
+ options.group_columns_by_name = false;
27346
+ } else if (options.group_columns_by_name !== true) {
27347
+ throw new CsvError("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME", [
27348
+ "Invalid option group_columns_by_name:",
27349
+ "expect an boolean,",
27350
+ `got ${JSON.stringify(options.group_columns_by_name)}`
27351
+ ], options);
27352
+ } else if (options.columns === false) {
27353
+ throw new CsvError("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME", [
27354
+ "Invalid option group_columns_by_name:",
27355
+ "the `columns` mode must be activated."
27356
+ ], options);
27357
+ }
27358
+ if (options.comment === undefined || options.comment === null || options.comment === false || options.comment === "") {
27359
+ options.comment = null;
27360
+ } else {
27361
+ if (typeof options.comment === "string") {
27362
+ options.comment = Buffer.from(options.comment, options.encoding);
27363
+ }
27364
+ if (!Buffer.isBuffer(options.comment)) {
27365
+ throw new CsvError("CSV_INVALID_OPTION_COMMENT", [
27366
+ "Invalid option comment:",
27367
+ "comment must be a buffer or a string,",
27368
+ `got ${JSON.stringify(options.comment)}`
27369
+ ], options);
27370
+ }
27371
+ }
27372
+ if (options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false) {
27373
+ options.comment_no_infix = false;
27374
+ } else if (options.comment_no_infix !== true) {
27375
+ throw new CsvError("CSV_INVALID_OPTION_COMMENT", [
27376
+ "Invalid option comment_no_infix:",
27377
+ "value must be a boolean,",
27378
+ `got ${JSON.stringify(options.comment_no_infix)}`
27379
+ ], options);
27380
+ }
27381
+ if (options.delimiter_auto === undefined || options.delimiter_auto === null || options.delimiter_auto === false) {
27382
+ options.delimiter_auto = false;
27383
+ } else if (options.delimiter_auto === true) {
27384
+ options.delimiter_auto = {};
27385
+ } else if (!is_object(options.delimiter_auto)) {
27386
+ throw new CsvError("CSV_INVALID_OPTION_DELIMITER_AUTO", [
27387
+ "Invalid option delimiter_auto:",
27388
+ "delimiter_auto must be a boolean or a configuration object,",
27389
+ `got ${JSON.stringify(options.delimiter_auto)}`
27390
+ ], options);
27391
+ }
27392
+ if (options.delimiter_auto) {
27393
+ if (options.delimiter_auto.preferred === undefined)
27394
+ options.delimiter_auto.preferred = {
27395
+ [44]: 1.8,
27396
+ [9]: 1.8,
27397
+ [59]: 1.6,
27398
+ [32]: 1.6,
27399
+ [58]: 1.5,
27400
+ [46]: 1.4,
27401
+ [47]: 1.4
27402
+ };
27403
+ else if (!is_object(options.delimiter_auto.preferred)) {
27404
+ throw new CsvError("CSV_INVALID_OPTION_DELIMITER_AUTO", [
27405
+ "Invalid option delimiter_auto:",
27406
+ "preferred must be an object,",
27407
+ `got ${JSON.stringify(options.delimiter_auto.preferred)}`
27408
+ ], options);
27409
+ }
27410
+ if (options.delimiter_auto.score === undefined)
27411
+ options.delimiter_auto.score = (info, options) => {
27412
+ return (info.total - info.std) * (options.preferred[info.char_code] || 1);
27413
+ };
27414
+ else if (typeof options.delimiter_auto.score !== "function") {
27415
+ throw new CsvError("CSV_INVALID_OPTION_DELIMITER_AUTO", [
27416
+ "Invalid option delimiter_auto:",
27417
+ "score must be a function,",
27418
+ `got ${JSON.stringify(options.delimiter_auto.score)}`
27419
+ ], options);
27420
+ }
27421
+ if (options.delimiter_auto.size === undefined)
27422
+ options.delimiter_auto.size = 2048;
27423
+ else if (typeof options.delimiter_auto.size !== "number") {
27424
+ throw new CsvError("CSV_INVALID_OPTION_DELIMITER_AUTO", [
27425
+ "Invalid option delimiter_auto:",
27426
+ "size must be a number,",
27427
+ `got ${JSON.stringify(options.delimiter_auto.size)}`
27428
+ ], options);
27429
+ }
27430
+ }
27431
+ const delimiter_json = JSON.stringify(options.delimiter);
27432
+ if (options.delimiter_auto !== false) {
27433
+ options.delimiter = [];
27434
+ }
27435
+ if (!Array.isArray(options.delimiter)) {
27436
+ if (options.delimiter === undefined || options.delimiter === null || options.delimiter === false) {
27437
+ options.delimiter = Buffer.from(",", options.encoding);
27438
+ }
27439
+ options.delimiter = [options.delimiter];
27440
+ }
27441
+ options.delimiter = options.delimiter.map(function(delimiter) {
27442
+ if (typeof delimiter === "string") {
27443
+ delimiter = Buffer.from(delimiter, options.encoding);
27444
+ }
27445
+ if (!Buffer.isBuffer(delimiter) || delimiter.length === 0) {
27446
+ throw new CsvError("CSV_INVALID_OPTION_DELIMITER", [
27447
+ "Invalid option delimiter:",
27448
+ "delimiter must be a non empty string or buffer or array of string|buffer,",
27449
+ `got ${delimiter_json}`
27450
+ ], options);
27451
+ }
27452
+ return delimiter;
27453
+ });
27454
+ if (options.escape === undefined || options.escape === true) {
27455
+ options.escape = Buffer.from('"', options.encoding);
27456
+ } else if (typeof options.escape === "string") {
27457
+ options.escape = Buffer.from(options.escape, options.encoding);
27458
+ } else if (options.escape === null || options.escape === false) {
27459
+ options.escape = null;
27460
+ }
27461
+ if (options.escape !== null) {
27462
+ if (!Buffer.isBuffer(options.escape)) {
27463
+ throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`);
27464
+ }
27465
+ }
27466
+ if (options.from === undefined || options.from === null) {
27467
+ options.from = 1;
27468
+ } else {
27469
+ if (typeof options.from === "string" && /\d+/.test(options.from)) {
27470
+ options.from = parseInt(options.from);
27471
+ }
27472
+ if (Number.isInteger(options.from)) {
27473
+ if (options.from < 0) {
27474
+ throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`);
27475
+ }
27476
+ } else {
27477
+ throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`);
27478
+ }
27479
+ }
27480
+ if (options.from_line === undefined || options.from_line === null) {
27481
+ options.from_line = 1;
27482
+ } else {
27483
+ if (typeof options.from_line === "string" && /\d+/.test(options.from_line)) {
27484
+ options.from_line = parseInt(options.from_line);
27485
+ }
27486
+ if (Number.isInteger(options.from_line)) {
27487
+ if (options.from_line <= 0) {
27488
+ throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`);
27489
+ }
27490
+ } else {
27491
+ throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`);
27492
+ }
27493
+ }
27494
+ if (options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null) {
27495
+ options.ignore_last_delimiters = false;
27496
+ } else if (typeof options.ignore_last_delimiters === "number") {
27497
+ options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters);
27498
+ if (options.ignore_last_delimiters === 0) {
27499
+ options.ignore_last_delimiters = false;
27500
+ }
27501
+ } else if (typeof options.ignore_last_delimiters !== "boolean") {
27502
+ throw new CsvError("CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS", [
27503
+ "Invalid option `ignore_last_delimiters`:",
27504
+ "the value must be a boolean value or an integer,",
27505
+ `got ${JSON.stringify(options.ignore_last_delimiters)}`
27506
+ ], options);
27507
+ }
27508
+ if (options.ignore_last_delimiters === true && options.columns === false) {
27509
+ throw new CsvError("CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS", [
27510
+ "The option `ignore_last_delimiters`",
27511
+ "requires the activation of the `columns` option"
27512
+ ], options);
27513
+ }
27514
+ if (options.info === undefined || options.info === null || options.info === false) {
27515
+ options.info = false;
27516
+ } else if (options.info !== true) {
27517
+ throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`);
27518
+ }
27519
+ if (options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false) {
27520
+ options.max_record_size = 0;
27521
+ } else if (Number.isInteger(options.max_record_size) && options.max_record_size >= 0) {} else if (typeof options.max_record_size === "string" && /\d+/.test(options.max_record_size)) {
27522
+ options.max_record_size = parseInt(options.max_record_size);
27523
+ } else {
27524
+ throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`);
27525
+ }
27526
+ if (options.objname === undefined || options.objname === null || options.objname === false) {
27527
+ options.objname = undefined;
27528
+ } else if (Buffer.isBuffer(options.objname)) {
27529
+ if (options.objname.length === 0) {
27530
+ throw new Error(`Invalid Option: objname must be a non empty buffer`);
27531
+ }
27532
+ if (options.encoding === null) {} else {
27533
+ options.objname = options.objname.toString(options.encoding);
27534
+ }
27535
+ } else if (typeof options.objname === "string") {
27536
+ if (options.objname.length === 0) {
27537
+ throw new Error(`Invalid Option: objname must be a non empty string`);
27538
+ }
27539
+ } else if (typeof options.objname === "number") {} else {
27540
+ throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`);
27541
+ }
27542
+ if (options.objname !== undefined) {
27543
+ if (typeof options.objname === "number") {
27544
+ if (options.columns !== false) {
27545
+ throw Error("Invalid Option: objname index cannot be combined with columns or be defined as a field");
27546
+ }
27547
+ } else {
27548
+ if (options.columns === false) {
27549
+ throw Error("Invalid Option: objname field must be combined with columns or be defined as an index");
27550
+ }
27551
+ }
27552
+ }
27553
+ if (options.on_record === undefined || options.on_record === null) {
27554
+ options.on_record = undefined;
27555
+ } else if (typeof options.on_record !== "function") {
27556
+ throw new CsvError("CSV_INVALID_OPTION_ON_RECORD", [
27557
+ "Invalid option `on_record`:",
27558
+ "expect a function,",
27559
+ `got ${JSON.stringify(options.on_record)}`
27560
+ ], options);
27561
+ }
27562
+ if (options.on_skip !== undefined && options.on_skip !== null && typeof options.on_skip !== "function") {
27563
+ throw new Error(`Invalid Option: on_skip must be a function, got ${JSON.stringify(options.on_skip)}`);
27564
+ }
27565
+ if (options.quote === null || options.quote === false || options.quote === "") {
27566
+ options.quote = null;
27567
+ } else {
27568
+ if (options.quote === undefined || options.quote === true) {
27569
+ options.quote = Buffer.from('"', options.encoding);
27570
+ } else if (typeof options.quote === "string") {
27571
+ options.quote = Buffer.from(options.quote, options.encoding);
27572
+ }
27573
+ if (!Buffer.isBuffer(options.quote)) {
27574
+ throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`);
27575
+ }
27576
+ }
27577
+ if (options.raw === undefined || options.raw === null || options.raw === false) {
27578
+ options.raw = false;
27579
+ } else if (options.raw !== true) {
27580
+ throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`);
27581
+ }
27582
+ if (options.record_delimiter === undefined) {
27583
+ options.record_delimiter = [];
27584
+ } else if (typeof options.record_delimiter === "string" || Buffer.isBuffer(options.record_delimiter)) {
27585
+ if (options.record_delimiter.length === 0) {
27586
+ throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
27587
+ "Invalid option `record_delimiter`:",
27588
+ "value must be a non empty string or buffer,",
27589
+ `got ${JSON.stringify(options.record_delimiter)}`
27590
+ ], options);
27591
+ }
27592
+ options.record_delimiter = [options.record_delimiter];
27593
+ } else if (!Array.isArray(options.record_delimiter)) {
27594
+ throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
27595
+ "Invalid option `record_delimiter`:",
27596
+ "value must be a string, a buffer or array of string|buffer,",
27597
+ `got ${JSON.stringify(options.record_delimiter)}`
27598
+ ], options);
27599
+ }
27600
+ options.record_delimiter = options.record_delimiter.map(function(rd, i) {
27601
+ if (typeof rd !== "string" && !Buffer.isBuffer(rd)) {
27602
+ throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
27603
+ "Invalid option `record_delimiter`:",
27604
+ "value must be a string, a buffer or array of string|buffer",
27605
+ `at index ${i},`,
27606
+ `got ${JSON.stringify(rd)}`
27607
+ ], options);
27608
+ } else if (rd.length === 0) {
27609
+ throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
27610
+ "Invalid option `record_delimiter`:",
27611
+ "value must be a non empty string or buffer",
27612
+ `at index ${i},`,
27613
+ `got ${JSON.stringify(rd)}`
27614
+ ], options);
27615
+ }
27616
+ if (typeof rd === "string") {
27617
+ rd = Buffer.from(rd, options.encoding);
27618
+ }
27619
+ return rd;
27620
+ });
27621
+ if (typeof options.relax_column_count === "boolean") {} else if (options.relax_column_count === undefined || options.relax_column_count === null) {
27622
+ options.relax_column_count = false;
27623
+ } else {
27624
+ throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`);
27625
+ }
27626
+ if (typeof options.relax_column_count_less === "boolean") {} else if (options.relax_column_count_less === undefined || options.relax_column_count_less === null) {
27627
+ options.relax_column_count_less = false;
27628
+ } else {
27629
+ throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`);
27630
+ }
27631
+ if (typeof options.relax_column_count_more === "boolean") {} else if (options.relax_column_count_more === undefined || options.relax_column_count_more === null) {
27632
+ options.relax_column_count_more = false;
27633
+ } else {
27634
+ throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`);
27635
+ }
27636
+ if (typeof options.relax_quotes === "boolean") {} else if (options.relax_quotes === undefined || options.relax_quotes === null) {
27637
+ options.relax_quotes = false;
27638
+ } else {
27639
+ throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`);
27640
+ }
27641
+ if (typeof options.skip_empty_lines === "boolean") {} else if (options.skip_empty_lines === undefined || options.skip_empty_lines === null) {
27642
+ options.skip_empty_lines = false;
27643
+ } else {
27644
+ throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`);
27645
+ }
27646
+ if (typeof options.skip_records_with_empty_values === "boolean") {} else if (options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null) {
27647
+ options.skip_records_with_empty_values = false;
27648
+ } else {
27649
+ throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`);
27650
+ }
27651
+ if (typeof options.skip_records_with_error === "boolean") {} else if (options.skip_records_with_error === undefined || options.skip_records_with_error === null) {
27652
+ options.skip_records_with_error = false;
27653
+ } else {
27654
+ throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`);
27655
+ }
27656
+ if (options.rtrim === undefined || options.rtrim === null || options.rtrim === false) {
27657
+ options.rtrim = false;
27658
+ } else if (options.rtrim !== true) {
27659
+ throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`);
27660
+ }
27661
+ if (options.ltrim === undefined || options.ltrim === null || options.ltrim === false) {
27662
+ options.ltrim = false;
27663
+ } else if (options.ltrim !== true) {
27664
+ throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`);
27665
+ }
27666
+ if (options.trim === undefined || options.trim === null || options.trim === false) {
27667
+ options.trim = false;
27668
+ } else if (options.trim !== true) {
27669
+ throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`);
27670
+ }
27671
+ if (options.trim === true && opts.ltrim !== false) {
27672
+ options.ltrim = true;
27673
+ } else if (options.ltrim !== true) {
27674
+ options.ltrim = false;
27675
+ }
27676
+ if (options.trim === true && opts.rtrim !== false) {
27677
+ options.rtrim = true;
27678
+ } else if (options.rtrim !== true) {
27679
+ options.rtrim = false;
27680
+ }
27681
+ if (options.to === undefined || options.to === null) {
27682
+ options.to = -1;
27683
+ } else if (options.to !== -1) {
27684
+ if (typeof options.to === "string" && /\d+/.test(options.to)) {
27685
+ options.to = parseInt(options.to);
27686
+ }
27687
+ if (Number.isInteger(options.to)) {
27688
+ if (options.to <= 0) {
27689
+ throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`);
27690
+ }
27691
+ } else {
27692
+ throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`);
27693
+ }
27694
+ }
27695
+ if (options.to_line === undefined || options.to_line === null) {
27696
+ options.to_line = -1;
27697
+ } else if (options.to_line !== -1) {
27698
+ if (typeof options.to_line === "string" && /\d+/.test(options.to_line)) {
27699
+ options.to_line = parseInt(options.to_line);
27700
+ }
27701
+ if (Number.isInteger(options.to_line)) {
27702
+ if (options.to_line <= 0) {
27703
+ throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`);
27704
+ }
27705
+ } else {
27706
+ throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`);
27707
+ }
27708
+ }
27709
+ return options;
27710
+ };
27711
+
27712
+ // ../../node_modules/csv-parse/lib/utils/delimiter_discover.js
27713
+ var delimiter_discover = function(records, options) {
27714
+ if (!options) {
27715
+ ({ delimiter_auto: options } = normalize_options({ delimiter_auto: true }));
27716
+ }
27717
+ if (typeof records === "string") {
27718
+ records = Buffer.from(records);
27719
+ }
27720
+ if (Buffer.isBuffer(records)) {
27721
+ records = ((data) => {
27722
+ const records = [];
27723
+ const parser = transform({ delimiter: [] });
27724
+ const push = (record) => records.push(record);
27725
+ const close = () => {};
27726
+ const error = parser.parse(data, true, push, close);
27727
+ if (error !== undefined)
27728
+ throw error;
27729
+ return records;
27730
+ })(records);
27731
+ }
27732
+ const info = Array(127).fill().map(() => ({ lines: [] }));
27733
+ records.map(([record], line) => {
27734
+ for (let i = 0, l = record.length;i < l; i++) {
27735
+ const code = record.charCodeAt(i);
27736
+ if (info[code].lines[line] === undefined)
27737
+ info[code].lines[line] = 0;
27738
+ info[code].lines[line]++;
27739
+ }
27740
+ });
27741
+ info.map((info, i) => {
27742
+ info.char_code = i;
27743
+ info.std = std(info.lines);
27744
+ info.total = info.lines.reduce((acc, val) => acc + val, 0);
27745
+ info.preferred = !!options.preferred[i];
27746
+ info.score = options.score(info, options);
27747
+ });
27748
+ const result = info.reduce((acc, info) => acc.score > info.score ? acc : info, {});
27749
+ return String.fromCharCode(result.char_code);
27750
+ };
27751
+ var std = function(array) {
27752
+ const n = array.length;
27753
+ if (n === 0)
27754
+ return 0;
27755
+ const mean = array.reduce((a, b) => a + b) / n;
27756
+ return Math.sqrt(array.map((x) => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / n);
27757
+ };
27758
+
27759
+ // ../../node_modules/csv-parse/lib/api/index.js
27760
+ var isRecordEmpty = function(record) {
27761
+ return record.every((field) => field == null || field.toString && field.toString().trim() === "");
27762
+ };
27763
+ var cr = 13;
27764
+ var nl = 10;
27765
+ var boms = {
27766
+ utf8: Buffer.from([239, 187, 191]),
27767
+ utf16le: Buffer.from([255, 254])
27768
+ };
27769
+ var transform = function(original_options = {}) {
27770
+ const info = {
27771
+ bytes: 0,
27772
+ bytes_records: 0,
27773
+ comment_lines: 0,
27774
+ empty_lines: 0,
27775
+ invalid_field_length: 0,
27776
+ lines: 1,
27777
+ records: 0
27778
+ };
27779
+ const options = normalize_options(original_options);
27780
+ return {
27781
+ info,
27782
+ original_options,
27783
+ options,
27784
+ state: init_state(options),
27785
+ __needMoreData: function(i, bufLen, end) {
27786
+ if (end)
27787
+ return false;
27788
+ const { encoding, escape, quote } = this.options;
27789
+ const { quoting, needMoreDataSize, recordDelimiterMaxLength } = this.state;
27790
+ const numOfCharLeft = bufLen - i - 1;
27791
+ const requiredLength = Math.max(needMoreDataSize, recordDelimiterMaxLength === 0 ? Buffer.from(`\r
27792
+ `, encoding).length : recordDelimiterMaxLength, quoting ? (escape === null ? 0 : escape.length) + quote.length : 0, quoting ? quote.length + recordDelimiterMaxLength : 0);
27793
+ return numOfCharLeft < requiredLength;
27794
+ },
27795
+ parse: function(nextBuf, end, push, close) {
27796
+ const {
27797
+ bom,
27798
+ comment_no_infix,
27799
+ delimiter_auto,
27800
+ encoding,
27801
+ from_line,
27802
+ ltrim,
27803
+ max_record_size,
27804
+ raw,
27805
+ relax_quotes,
27806
+ rtrim,
27807
+ skip_empty_lines,
27808
+ to,
27809
+ to_line
27810
+ } = this.options;
27811
+ let { comment, escape, quote, record_delimiter } = this.options;
27812
+ const {
27813
+ bomSkipped,
27814
+ delimiterDiscovered,
27815
+ delimiterBufPrevious,
27816
+ rawBuffer,
27817
+ escapeIsQuote
27818
+ } = this.state;
27819
+ if (!delimiterDiscovered && delimiter_auto) {
27820
+ let delimiterBuf;
27821
+ if (delimiterBufPrevious === undefined) {
27822
+ delimiterBuf = nextBuf;
27823
+ } else if (delimiterBufPrevious !== undefined && nextBuf === undefined) {
27824
+ delimiterBuf = delimiterBufPrevious;
27825
+ } else {
27826
+ delimiterBuf = Buffer.concat([delimiterBufPrevious, nextBuf]);
27827
+ }
27828
+ nextBuf = undefined;
27829
+ if (end || delimiterBuf.length > delimiter_auto.size) {
27830
+ this.options.delimiter = [
27831
+ Buffer.from(delimiter_discover(delimiterBuf, this.options.delimiter_auto))
27832
+ ];
27833
+ this.state.previousBuf = delimiterBuf;
27834
+ this.state.delimiterBufPrevious = undefined;
27835
+ this.state.delimiterDiscovered = true;
27836
+ } else {
27837
+ this.state.delimiterBufPrevious = delimiterBuf;
27838
+ return;
27839
+ }
27840
+ }
27841
+ const { previousBuf } = this.state;
27842
+ let buf;
27843
+ if (previousBuf === undefined) {
27844
+ if (nextBuf === undefined) {
27845
+ close();
27846
+ return;
27847
+ } else {
27848
+ buf = nextBuf;
27849
+ }
27850
+ } else if (previousBuf !== undefined && nextBuf === undefined) {
27851
+ buf = previousBuf;
27852
+ } else {
27853
+ buf = Buffer.concat([previousBuf, nextBuf]);
27854
+ }
27855
+ if (bomSkipped === false) {
27856
+ if (bom === false) {
27857
+ this.state.bomSkipped = true;
27858
+ } else if (buf.length < 3) {
27859
+ if (end === false) {
27860
+ this.state.previousBuf = buf;
27861
+ return;
27862
+ }
27863
+ } else {
27864
+ for (const encoding in boms) {
27865
+ if (boms[encoding].compare(buf, 0, boms[encoding].length) === 0) {
27866
+ const bomLength = boms[encoding].length;
27867
+ this.state.bufBytesStart += bomLength;
27868
+ buf = buf.slice(bomLength);
27869
+ const options = normalize_options({
27870
+ ...this.original_options,
27871
+ encoding
27872
+ });
27873
+ for (const key in options) {
27874
+ this.options[key] = options[key];
27875
+ }
27876
+ ({ comment, escape, quote } = this.options);
27877
+ break;
27878
+ }
27879
+ }
27880
+ this.state.bomSkipped = true;
27881
+ }
27882
+ }
27883
+ const bufLen = buf.length;
27884
+ let pos;
27885
+ for (pos = 0;pos < bufLen; pos++) {
27886
+ if (this.__needMoreData(pos, bufLen, end)) {
27887
+ break;
27888
+ }
27889
+ if (this.state.wasRowDelimiter === true) {
27890
+ this.info.lines++;
27891
+ this.state.wasRowDelimiter = false;
27892
+ }
27893
+ if (to_line !== -1 && this.info.lines > to_line) {
27894
+ this.state.stop = true;
27895
+ close();
27896
+ return;
27897
+ }
27898
+ if (this.state.quoting === false && record_delimiter.length === 0) {
27899
+ const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos);
27900
+ if (record_delimiterCount) {
27901
+ record_delimiter = this.options.record_delimiter;
27902
+ }
27903
+ }
27904
+ const chr = buf[pos];
27905
+ if (raw === true) {
27906
+ rawBuffer.append(chr);
27907
+ }
27908
+ if ((chr === cr || chr === nl) && this.state.wasRowDelimiter === false) {
27909
+ this.state.wasRowDelimiter = true;
27910
+ }
27911
+ if (this.state.escaping === true) {
27912
+ this.state.escaping = false;
27913
+ } else {
27914
+ if (escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen) {
27915
+ if (escapeIsQuote) {
27916
+ if (this.__isQuote(buf, pos + escape.length)) {
27917
+ this.state.escaping = true;
27918
+ pos += escape.length - 1;
27919
+ continue;
27920
+ }
27921
+ } else {
27922
+ this.state.escaping = true;
27923
+ pos += escape.length - 1;
27924
+ continue;
27925
+ }
27926
+ }
27927
+ if (this.state.commenting === false && this.__isQuote(buf, pos)) {
27928
+ if (this.state.quoting === true) {
27929
+ const nextChr = buf[pos + quote.length];
27930
+ const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos + quote.length);
27931
+ const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos + quote.length, nextChr);
27932
+ const isNextChrDelimiter = this.__isDelimiter(buf, pos + quote.length, nextChr);
27933
+ const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos + quote.length) : this.__isRecordDelimiter(nextChr, buf, pos + quote.length);
27934
+ if (escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)) {
27935
+ pos += escape.length - 1;
27936
+ } else if (!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable) {
27937
+ this.state.quoting = false;
27938
+ this.state.wasQuoting = true;
27939
+ pos += quote.length - 1;
27940
+ continue;
27941
+ } else if (relax_quotes === false) {
27942
+ const err = this.__error(new CsvError("CSV_INVALID_CLOSING_QUOTE", [
27943
+ "Invalid Closing Quote:",
27944
+ `got "${String.fromCharCode(nextChr)}"`,
27945
+ `at line ${this.info.lines}`,
27946
+ "instead of delimiter, record delimiter, trimable character",
27947
+ "(if activated) or comment"
27948
+ ], this.options, this.__infoField()));
27949
+ if (err !== undefined)
27950
+ return err;
27951
+ } else {
27952
+ this.state.quoting = false;
27953
+ this.state.wasQuoting = true;
27954
+ this.state.field.prepend(quote);
27955
+ pos += quote.length - 1;
27956
+ }
27957
+ } else {
27958
+ if (this.state.field.length !== 0) {
27959
+ if (relax_quotes === false) {
27960
+ const info = this.__infoField();
27961
+ const bom = Object.keys(boms).map((b) => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0];
27962
+ const err = this.__error(new CsvError("INVALID_OPENING_QUOTE", [
27963
+ "Invalid Opening Quote:",
27964
+ `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`,
27965
+ bom ? `(${bom} bom)` : undefined
27966
+ ], this.options, info, {
27967
+ field: this.state.field
27968
+ }));
27969
+ if (err !== undefined)
27970
+ return err;
27971
+ }
27972
+ } else {
27973
+ this.state.quoting = true;
27974
+ pos += quote.length - 1;
27975
+ continue;
27976
+ }
27977
+ }
27978
+ }
27979
+ if (this.state.quoting === false) {
27980
+ const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos);
27981
+ if (recordDelimiterLength !== 0) {
27982
+ const skipCommentLine = this.state.commenting && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0;
27983
+ if (skipCommentLine) {
27984
+ this.info.comment_lines++;
27985
+ } else {
27986
+ if (this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1 : 0) >= from_line) {
27987
+ this.state.enabled = true;
27988
+ this.__resetField();
27989
+ this.__resetRecord();
27990
+ pos += recordDelimiterLength - 1;
27991
+ continue;
27992
+ }
27993
+ if (skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) {
27994
+ this.info.empty_lines++;
27995
+ pos += recordDelimiterLength - 1;
27996
+ continue;
27997
+ }
27998
+ this.info.bytes = this.state.bufBytesStart + pos;
27999
+ const errField = this.__onField();
28000
+ if (errField !== undefined)
28001
+ return errField;
28002
+ this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength;
28003
+ const errRecord = this.__onRecord(push);
28004
+ if (errRecord !== undefined)
28005
+ return errRecord;
28006
+ if (to !== -1 && this.info.records >= to) {
28007
+ this.state.stop = true;
28008
+ close();
28009
+ return;
28010
+ }
28011
+ }
28012
+ this.state.commenting = false;
28013
+ pos += recordDelimiterLength - 1;
28014
+ continue;
28015
+ }
28016
+ if (this.state.commenting) {
28017
+ continue;
28018
+ }
28019
+ if (comment !== null && (comment_no_infix === false || this.state.record.length === 0 && this.state.field.length === 0)) {
28020
+ const commentCount = this.__compareBytes(comment, buf, pos, chr);
28021
+ if (commentCount !== 0) {
28022
+ this.state.commenting = true;
28023
+ continue;
28024
+ }
28025
+ }
28026
+ const delimiterLength = this.__isDelimiter(buf, pos, chr);
28027
+ if (delimiterLength !== 0) {
28028
+ this.info.bytes = this.state.bufBytesStart + pos;
28029
+ const errField = this.__onField();
28030
+ if (errField !== undefined)
28031
+ return errField;
28032
+ pos += delimiterLength - 1;
28033
+ continue;
28034
+ }
28035
+ }
28036
+ }
28037
+ if (this.state.commenting === false) {
28038
+ if (max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size) {
28039
+ return this.__error(new CsvError("CSV_MAX_RECORD_SIZE", [
28040
+ "Max Record Size:",
28041
+ "record exceed the maximum number of tolerated bytes",
28042
+ `of ${max_record_size}`,
28043
+ `at line ${this.info.lines}`
28044
+ ], this.options, this.__infoField()));
28045
+ }
28046
+ }
28047
+ const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos);
28048
+ const rappend = rtrim === false || this.state.wasQuoting === false;
28049
+ if (lappend === true && rappend === true) {
28050
+ this.state.field.append(chr);
28051
+ } else if (rtrim === true && !this.__isCharTrimable(buf, pos)) {
28052
+ return this.__error(new CsvError("CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE", [
28053
+ "Invalid Closing Quote:",
28054
+ "found non trimable byte after quote",
28055
+ `at line ${this.info.lines}`
28056
+ ], this.options, this.__infoField()));
28057
+ } else {
28058
+ if (lappend === false) {
28059
+ pos += this.__isCharTrimable(buf, pos) - 1;
28060
+ }
28061
+ continue;
28062
+ }
28063
+ }
28064
+ if (end === true) {
28065
+ if (this.state.quoting === true) {
28066
+ const err = this.__error(new CsvError("CSV_QUOTE_NOT_CLOSED", [
28067
+ "Quote Not Closed:",
28068
+ `the parsing is finished with an opening quote at line ${this.info.lines}`
28069
+ ], this.options, this.__infoField()));
28070
+ if (err !== undefined)
28071
+ return err;
28072
+ } else {
28073
+ if (this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0) {
28074
+ this.info.bytes = this.state.bufBytesStart + pos;
28075
+ const errField = this.__onField();
28076
+ if (errField !== undefined)
28077
+ return errField;
28078
+ const errRecord = this.__onRecord(push);
28079
+ if (errRecord !== undefined)
28080
+ return errRecord;
28081
+ } else if (this.state.wasRowDelimiter === true) {
28082
+ this.info.empty_lines++;
28083
+ } else if (this.state.commenting === true) {
28084
+ this.info.comment_lines++;
28085
+ }
28086
+ }
28087
+ } else {
28088
+ this.state.bufBytesStart += pos;
28089
+ this.state.previousBuf = buf.slice(pos);
28090
+ }
28091
+ if (this.state.wasRowDelimiter === true) {
28092
+ this.info.lines++;
28093
+ this.state.wasRowDelimiter = false;
28094
+ }
28095
+ },
28096
+ __onRecord: function(push) {
28097
+ const {
28098
+ columns,
28099
+ group_columns_by_name,
28100
+ encoding,
28101
+ info,
28102
+ from,
28103
+ relax_column_count,
28104
+ relax_column_count_less,
28105
+ relax_column_count_more,
28106
+ raw,
28107
+ skip_records_with_empty_values
28108
+ } = this.options;
28109
+ const { enabled, record } = this.state;
28110
+ if (enabled === false) {
28111
+ return this.__resetRecord();
28112
+ }
28113
+ const recordLength = record.length;
28114
+ if (columns === true) {
28115
+ if (skip_records_with_empty_values === true && isRecordEmpty(record)) {
28116
+ this.__resetRecord();
28117
+ return;
28118
+ }
28119
+ return this.__firstLineToColumns(record);
28120
+ }
28121
+ if (columns === false && this.info.records === 0) {
28122
+ this.state.expectedRecordLength = recordLength;
28123
+ }
28124
+ if (recordLength !== this.state.expectedRecordLength) {
28125
+ const err = columns === false ? new CsvError("CSV_RECORD_INCONSISTENT_FIELDS_LENGTH", [
28126
+ "Invalid Record Length:",
28127
+ `expect ${this.state.expectedRecordLength},`,
28128
+ `got ${recordLength} on line ${this.info.lines}`
28129
+ ], this.options, this.__infoField(), {
28130
+ record
28131
+ }) : new CsvError("CSV_RECORD_INCONSISTENT_COLUMNS", [
28132
+ "Invalid Record Length:",
28133
+ `columns length is ${columns.length},`,
28134
+ `got ${recordLength} on line ${this.info.lines}`
28135
+ ], this.options, this.__infoField(), {
28136
+ record
28137
+ });
28138
+ if (relax_column_count === true || relax_column_count_less === true && recordLength < this.state.expectedRecordLength || relax_column_count_more === true && recordLength > this.state.expectedRecordLength) {
28139
+ this.info.invalid_field_length++;
28140
+ this.state.error = err;
28141
+ } else {
28142
+ const finalErr = this.__error(err);
28143
+ if (finalErr)
28144
+ return finalErr;
28145
+ }
28146
+ }
28147
+ if (skip_records_with_empty_values === true && isRecordEmpty(record)) {
28148
+ this.__resetRecord();
28149
+ return;
28150
+ }
28151
+ if (this.state.recordHasError === true) {
28152
+ this.__resetRecord();
28153
+ this.state.recordHasError = false;
28154
+ return;
28155
+ }
28156
+ this.info.records++;
28157
+ if (from === 1 || this.info.records >= from) {
28158
+ const { objname } = this.options;
28159
+ if (columns !== false) {
28160
+ const obj = {};
28161
+ for (let i = 0, l = record.length;i < l; i++) {
28162
+ if (columns[i] === undefined || columns[i].disabled)
28163
+ continue;
28164
+ if (group_columns_by_name === true && Object.hasOwn(obj, columns[i].name)) {
28165
+ if (Array.isArray(obj[columns[i].name])) {
28166
+ obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
28167
+ } else {
28168
+ obj[columns[i].name] = [obj[columns[i].name], record[i]];
28169
+ }
28170
+ } else {
28171
+ Object.defineProperty(obj, columns[i].name, {
28172
+ value: record[i],
28173
+ enumerable: true,
28174
+ writable: true,
28175
+ configurable: true
28176
+ });
28177
+ }
28178
+ }
28179
+ if (raw === true || info === true) {
28180
+ const extRecord = Object.assign({ record: obj }, raw === true ? { raw: this.state.rawBuffer.toString(encoding) } : {}, info === true ? { info: this.__infoRecord() } : {});
28181
+ const err = this.__push(objname === undefined ? extRecord : [obj[objname], extRecord], push);
28182
+ if (err) {
28183
+ return err;
28184
+ }
28185
+ } else {
28186
+ const err = this.__push(objname === undefined ? obj : [obj[objname], obj], push);
28187
+ if (err) {
28188
+ return err;
28189
+ }
28190
+ }
28191
+ } else {
28192
+ if (raw === true || info === true) {
28193
+ const extRecord = Object.assign({ record }, raw === true ? { raw: this.state.rawBuffer.toString(encoding) } : {}, info === true ? { info: this.__infoRecord() } : {});
28194
+ const err = this.__push(objname === undefined ? extRecord : [record[objname], extRecord], push);
28195
+ if (err) {
28196
+ return err;
28197
+ }
28198
+ } else {
28199
+ const err = this.__push(objname === undefined ? record : [record[objname], record], push);
28200
+ if (err) {
28201
+ return err;
28202
+ }
28203
+ }
28204
+ }
28205
+ }
28206
+ this.__resetRecord();
28207
+ },
28208
+ __firstLineToColumns: function(record) {
28209
+ const { firstLineToHeaders } = this.state;
28210
+ try {
28211
+ const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record);
28212
+ if (!Array.isArray(headers)) {
28213
+ return this.__error(new CsvError("CSV_INVALID_COLUMN_MAPPING", [
28214
+ "Invalid Column Mapping:",
28215
+ "expect an array from column function,",
28216
+ `got ${JSON.stringify(headers)}`
28217
+ ], this.options, this.__infoField(), {
28218
+ headers
28219
+ }));
28220
+ }
28221
+ const normalizedHeaders = normalize_columns_array(headers);
28222
+ this.state.expectedRecordLength = normalizedHeaders.length;
28223
+ this.options.columns = normalizedHeaders;
28224
+ this.__resetRecord();
28225
+ return;
28226
+ } catch (err) {
28227
+ return err;
28228
+ }
28229
+ },
28230
+ __resetRecord: function() {
28231
+ if (this.options.raw === true) {
28232
+ this.state.rawBuffer.reset();
28233
+ }
28234
+ this.state.error = undefined;
28235
+ this.state.record = [];
28236
+ this.state.record_length = 0;
28237
+ },
28238
+ __onField: function() {
28239
+ const { cast, encoding, rtrim, max_record_size } = this.options;
28240
+ const { enabled, wasQuoting } = this.state;
28241
+ if (enabled === false) {
28242
+ return this.__resetField();
28243
+ }
28244
+ let field = this.state.field.toString(encoding);
28245
+ if (rtrim === true && wasQuoting === false) {
28246
+ field = field.trimRight();
28247
+ }
28248
+ if (cast === true) {
28249
+ const [err, f] = this.__cast(field);
28250
+ if (err !== undefined)
28251
+ return err;
28252
+ field = f;
28253
+ }
28254
+ this.state.record.push(field);
28255
+ if (max_record_size !== 0 && typeof field === "string") {
28256
+ this.state.record_length += field.length;
28257
+ }
28258
+ this.__resetField();
28259
+ },
28260
+ __resetField: function() {
28261
+ this.state.field.reset();
28262
+ this.state.wasQuoting = false;
28263
+ },
28264
+ __push: function(record, push) {
28265
+ const { on_record } = this.options;
28266
+ if (on_record !== undefined) {
28267
+ const info = this.__infoRecord();
28268
+ try {
28269
+ record = on_record.call(null, record, info);
28270
+ } catch (err) {
28271
+ return err;
28272
+ }
28273
+ if (record === undefined || record === null) {
28274
+ return;
28275
+ }
28276
+ }
28277
+ this.info.bytes_records += this.info.bytes;
28278
+ push(record);
28279
+ },
28280
+ __cast: function(field) {
28281
+ const { columns, relax_column_count } = this.options;
28282
+ const isColumns = Array.isArray(columns);
28283
+ if (isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length) {
28284
+ return [undefined, undefined];
28285
+ }
28286
+ if (this.state.castField !== null) {
28287
+ try {
28288
+ const info = this.__infoField();
28289
+ return [undefined, this.state.castField.call(null, field, info)];
28290
+ } catch (err) {
28291
+ return [err];
28292
+ }
28293
+ }
28294
+ if (this.__isFloat(field)) {
28295
+ return [undefined, parseFloat(field)];
28296
+ } else if (this.options.cast_date !== false) {
28297
+ const info = this.__infoField();
28298
+ return [undefined, this.options.cast_date.call(null, field, info)];
28299
+ }
28300
+ return [undefined, field];
28301
+ },
28302
+ __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte) {
28303
+ if (sourceBuf[0] !== firstByte)
28304
+ return 0;
28305
+ const sourceLength = sourceBuf.length;
28306
+ for (let i = 1;i < sourceLength; i++) {
28307
+ if (sourceBuf[i] !== targetBuf[targetPos + i])
28308
+ return 0;
28309
+ }
28310
+ return sourceLength;
28311
+ },
28312
+ __isCharTrimable: function(buf, pos) {
28313
+ const { timchars, timcharFirstBytes } = this.state;
28314
+ const first = buf[pos];
28315
+ if (first === undefined || timcharFirstBytes[first] === 0)
28316
+ return 0;
28317
+ loop1:
28318
+ for (let i = 0;i < timchars.length; i++) {
28319
+ const timchar = timchars[i];
28320
+ for (let j = 0;j < timchar.length; j++) {
28321
+ if (timchar[j] !== buf[pos + j])
28322
+ continue loop1;
28323
+ }
28324
+ return timchar.length;
28325
+ }
28326
+ return 0;
28327
+ },
28328
+ __isDelimiter: function(buf, pos, chr) {
28329
+ const { delimiter, ignore_last_delimiters } = this.options;
28330
+ if (ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1) {
28331
+ return 0;
28332
+ } else if (ignore_last_delimiters !== false && typeof ignore_last_delimiters === "number" && this.state.record.length === ignore_last_delimiters - 1) {
28333
+ return 0;
28334
+ }
28335
+ loop1:
28336
+ for (let i = 0;i < delimiter.length; i++) {
28337
+ const del = delimiter[i];
28338
+ if (del[0] === chr) {
28339
+ for (let j = 1;j < del.length; j++) {
28340
+ if (del[j] !== buf[pos + j])
28341
+ continue loop1;
28342
+ }
28343
+ return del.length;
28344
+ }
28345
+ }
28346
+ return 0;
28347
+ },
28348
+ __isEscape: function(buf, pos, chr) {
28349
+ const { escape } = this.options;
28350
+ if (escape === null)
28351
+ return false;
28352
+ const l = escape.length;
28353
+ if (escape[0] === chr) {
28354
+ for (let i = 0;i < l; i++) {
28355
+ if (escape[i] !== buf[pos + i]) {
28356
+ return false;
28357
+ }
28358
+ }
28359
+ return true;
28360
+ }
28361
+ return false;
28362
+ },
28363
+ __isFloat: function(value) {
28364
+ return value - parseFloat(value) + 1 >= 0;
28365
+ },
28366
+ __isQuote: function(buf, pos) {
28367
+ const { quote } = this.options;
28368
+ if (quote === null)
28369
+ return false;
28370
+ const l = quote.length;
28371
+ for (let i = 0;i < l; i++) {
28372
+ if (quote[i] !== buf[pos + i]) {
28373
+ return false;
28374
+ }
28375
+ }
28376
+ return true;
28377
+ },
28378
+ __isRecordDelimiter: function(chr, buf, pos) {
28379
+ const { record_delimiter } = this.options;
28380
+ const recordDelimiterLength = record_delimiter.length;
28381
+ loop1:
28382
+ for (let i = 0;i < recordDelimiterLength; i++) {
28383
+ const rd = record_delimiter[i];
28384
+ const rdLength = rd.length;
28385
+ if (rd[0] !== chr) {
28386
+ continue;
28387
+ }
28388
+ for (let j = 1;j < rdLength; j++) {
28389
+ if (rd[j] !== buf[pos + j]) {
28390
+ continue loop1;
28391
+ }
28392
+ }
28393
+ return rd.length;
28394
+ }
28395
+ return 0;
28396
+ },
28397
+ __autoDiscoverRecordDelimiter: function(buf, pos) {
28398
+ const { encoding } = this.options;
28399
+ const rds = [
28400
+ Buffer.from(`\r
28401
+ `, encoding),
28402
+ Buffer.from(`
28403
+ `, encoding),
28404
+ Buffer.from("\r", encoding)
28405
+ ];
28406
+ loop:
28407
+ for (let i = 0;i < rds.length; i++) {
28408
+ const l = rds[i].length;
28409
+ for (let j = 0;j < l; j++) {
28410
+ if (rds[i][j] !== buf[pos + j]) {
28411
+ continue loop;
28412
+ }
28413
+ }
28414
+ this.options.record_delimiter.push(rds[i]);
28415
+ this.state.recordDelimiterMaxLength = rds[i].length;
28416
+ return rds[i].length;
28417
+ }
28418
+ return 0;
28419
+ },
28420
+ __error: function(msg) {
28421
+ const { encoding, raw, skip_records_with_error } = this.options;
28422
+ const err = typeof msg === "string" ? new Error(msg) : msg;
28423
+ if (skip_records_with_error) {
28424
+ this.state.recordHasError = true;
28425
+ if (this.options.on_skip !== undefined) {
28426
+ try {
28427
+ this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
28428
+ } catch (err) {
28429
+ return err;
28430
+ }
28431
+ }
28432
+ return;
28433
+ } else {
28434
+ return err;
28435
+ }
28436
+ },
28437
+ __infoDataSet: function() {
28438
+ return {
28439
+ ...this.info,
28440
+ columns: this.options.columns
28441
+ };
28442
+ },
28443
+ __infoRecord: function() {
28444
+ const { columns, raw, encoding } = this.options;
28445
+ return {
28446
+ ...this.__infoDataSet(),
28447
+ bytes_records: this.info.bytes,
28448
+ error: this.state.error,
28449
+ header: columns === true,
28450
+ index: this.state.record.length,
28451
+ raw: raw ? this.state.rawBuffer.toString(encoding) : undefined
28452
+ };
28453
+ },
28454
+ __infoField: function() {
28455
+ const { columns } = this.options;
28456
+ const isColumns = Array.isArray(columns);
28457
+ const bytes_records = this.info.bytes_records;
28458
+ return {
28459
+ ...this.__infoRecord(),
28460
+ bytes_records,
28461
+ column: isColumns === true ? columns.length > this.state.record.length ? columns[this.state.record.length].name : null : this.state.record.length,
28462
+ quoting: this.state.wasQuoting
28463
+ };
28464
+ }
28465
+ };
28466
+ };
28467
+
28468
+ // ../../node_modules/csv-parse/lib/index.js
28469
+ class Parser extends Transform {
28470
+ constructor(opts = {}) {
28471
+ super({ ...{ readableObjectMode: true }, ...opts, encoding: null });
28472
+ this.api = transform({
28473
+ on_skip: (err, chunk) => {
28474
+ this.emit("skip", err, chunk);
28475
+ },
28476
+ ...opts
28477
+ });
28478
+ this.state = this.api.state;
28479
+ this.options = this.api.options;
28480
+ this.info = this.api.info;
28481
+ }
28482
+ _transform(buf, _, callback) {
28483
+ if (this.state.stop === true) {
28484
+ return;
28485
+ }
28486
+ const err = this.api.parse(buf, false, (record) => {
28487
+ this.push(record);
28488
+ }, () => {
28489
+ this.push(null);
28490
+ this.end();
28491
+ this.on("end", this.destroy);
28492
+ });
28493
+ if (err !== undefined) {
28494
+ this.state.stop = true;
28495
+ }
28496
+ callback(err);
28497
+ }
28498
+ _flush(callback) {
28499
+ if (this.state.stop === true) {
28500
+ return;
28501
+ }
28502
+ const err = this.api.parse(undefined, true, (record) => {
28503
+ this.push(record);
28504
+ }, () => {
28505
+ this.push(null);
28506
+ this.on("end", this.destroy);
28507
+ });
28508
+ callback(err);
28509
+ }
28510
+ }
28511
+ var parse = function() {
28512
+ let data, options, callback;
28513
+ for (const i in arguments) {
28514
+ const argument = arguments[i];
28515
+ const type = typeof argument;
28516
+ if (data === undefined && (typeof argument === "string" || Buffer.isBuffer(argument))) {
28517
+ data = argument;
28518
+ } else if (options === undefined && is_object(argument)) {
28519
+ options = argument;
28520
+ } else if (callback === undefined && type === "function") {
28521
+ callback = argument;
28522
+ } else {
28523
+ throw new CsvError("CSV_INVALID_ARGUMENT", ["Invalid argument:", `got ${JSON.stringify(argument)} at index ${i}`], options || {});
28524
+ }
28525
+ }
28526
+ const parser = new Parser(options);
28527
+ if (callback) {
28528
+ const records = options === undefined || options.objname === undefined ? [] : Object.create(null);
28529
+ parser.on("readable", function() {
28530
+ let record;
28531
+ while ((record = this.read()) !== null) {
28532
+ if (options === undefined || options.objname === undefined) {
28533
+ records.push(record);
28534
+ } else {
28535
+ Object.assign(records, {
28536
+ [record[0]]: record[1]
28537
+ });
28538
+ }
28539
+ }
28540
+ });
28541
+ parser.on("error", function(err) {
28542
+ callback(err, undefined, parser.api.__infoDataSet());
28543
+ });
28544
+ parser.on("end", function() {
28545
+ callback(undefined, records, parser.api.__infoDataSet());
28546
+ });
28547
+ }
28548
+ if (data !== undefined) {
28549
+ const writer = function() {
28550
+ parser.write(data);
28551
+ parser.end();
28552
+ };
28553
+ if (typeof setImmediate === "function") {
28554
+ setImmediate(writer);
28555
+ } else {
28556
+ setTimeout(writer, 0);
28557
+ }
28558
+ }
28559
+ return parser;
28560
+ };
28561
+
28562
+ // src/transfer/permission-csv.ts
28563
+ var PART_BYTES = 1024 * 1024;
28564
+ var PART_ROWS = 5000;
28565
+ var MAX_BYTES = 1024 * 1024 * 1024;
28566
+ var MAX_PARTS = 4096;
28567
+ var CSV_PROVIDERS = {
28568
+ gitlab: {
28569
+ userMapping: { header: ["user_id", "email"], maxRows: 500000 },
28570
+ projectPermissions: { header: ["project_path", "user_id"], maxRows: 5000000 }
28571
+ }
28572
+ };
28573
+ async function* snapshotChunks(stream, signal) {
28574
+ const reader = stream.getReader();
28575
+ const cancel = () => {
28576
+ reader.cancel(signal?.reason).catch(() => {});
28577
+ };
28578
+ signal?.addEventListener("abort", cancel, { once: true });
28579
+ try {
28580
+ while (true) {
28581
+ signal?.throwIfAborted();
28582
+ const chunk = await reader.read();
28583
+ signal?.throwIfAborted();
28584
+ if (chunk.done)
28585
+ return;
28586
+ yield chunk.value;
28587
+ }
28588
+ } finally {
28589
+ signal?.removeEventListener("abort", cancel);
28590
+ await reader.cancel();
28591
+ reader.releaseLock();
28592
+ }
28593
+ }
28594
+ async function stagePermissionCsvs(provider, paths, signal) {
28595
+ const directory = await mkdtemp2(join4(tmpdir(), "sim-permissions-")).catch((error) => {
28596
+ throw new SimApiError(`Cannot stage permission CSVs: ${getErrorMessage(error)}`, 0);
28597
+ });
28598
+ const parts = [];
28599
+ const manifest = {};
28600
+ let totalBytes = 0;
28601
+ let inputBytes = 0;
28602
+ const dispose = () => rm2(directory, { recursive: true, force: true });
28603
+ try {
28604
+ for (const field of ["userMapping", "projectPermissions"]) {
28605
+ signal?.throwIfAborted();
28606
+ const path = paths[field];
28607
+ const filename = basename3(embeddedFileKey(path));
28608
+ if (!filename.trim() || filename.length > 255 || /[\p{Cc}/\\]/u.test(filename))
28609
+ throw new SimApiError("Use CSV filenames of 1–255 characters without control characters.", 0);
28610
+ const embedded = embedStore.getStore();
28611
+ if (embedded && !embedded.openFile)
28612
+ throw new SimApiError("This invocation has no machine to read from", 0);
28613
+ const snapshot = await embedded?.openFile?.(embeddedFileKey(path));
28614
+ const handle = embedded ? undefined : await open(path, constants3.O_RDONLY | constants3.O_NONBLOCK);
28615
+ let stream;
28616
+ let snapshotStream;
28617
+ try {
28618
+ const before = await handle?.stat();
28619
+ if (before && !before.isFile())
28620
+ throw new SimApiError(`${field}: use a regular CSV file.`, 0);
28621
+ const size = snapshot?.size ?? before?.size;
28622
+ if (size === undefined || !Number.isSafeInteger(size) || size <= 0 || size > MAX_BYTES - inputBytes)
28623
+ throw new SimApiError("CSV files must be nonempty and total at most 1 GiB.", 0);
28624
+ inputBytes += size;
28625
+ const readSignal = combineSignals(snapshot?.signal, signal);
28626
+ snapshotStream = await snapshot?.stream();
28627
+ stream = snapshotStream ? Readable2.from(snapshotChunks(snapshotStream, readSignal)) : handle?.createReadStream({ autoClose: false });
28628
+ if (!stream)
28629
+ throw new SimApiError(`Cannot read ${field}.`, 0);
28630
+ if (readSignal)
28631
+ addAbortSignal(readSignal, stream);
28632
+ const source = stream;
28633
+ const decode = async function* () {
28634
+ const decoder = new TextDecoder("utf-8", { fatal: true });
28635
+ const decodeText = (chunk) => {
28636
+ try {
28637
+ return decoder.decode(chunk, { stream: chunk !== undefined });
28638
+ } catch {
28639
+ throw new SimApiError(`${field}: CSV must contain valid UTF-8.`, 0);
28640
+ }
28641
+ };
28642
+ let bytes = 0;
28643
+ for await (const chunk of source) {
28644
+ signal?.throwIfAborted();
28645
+ snapshot?.signal?.throwIfAborted();
28646
+ bytes += chunk.length;
28647
+ if (bytes > size)
28648
+ throw new SimApiError(`${field}: input changed during staging.`, 0);
28649
+ for (let offset = 0;offset < chunk.length; offset += 65536) {
28650
+ readSignal?.throwIfAborted();
28651
+ yield decodeText(chunk.subarray(offset, offset + 65536));
28652
+ }
28653
+ }
28654
+ if (bytes !== size)
28655
+ throw new SimApiError(`${field}: input changed during staging.`, 0);
28656
+ yield decodeText();
28657
+ };
28658
+ const definition = CSV_PROVIDERS[provider][field];
28659
+ const header = `${definition.header.join(",")}
28660
+ `;
28661
+ let content = header;
28662
+ let partBytes = Buffer.byteLength(header);
28663
+ let partRows = 0;
28664
+ let rowCount = 0;
28665
+ const startPart = parts.length;
28666
+ const save = async () => {
28667
+ if (parts.length >= MAX_PARTS || totalBytes + partBytes > MAX_BYTES)
28668
+ throw new SimApiError("Permission import exceeds 4,096 parts or 1 GiB.", 0);
28669
+ const partPath = join4(directory, String(parts.length));
28670
+ await writeFile(partPath, content, { mode: 384, flag: "wx" });
28671
+ parts.push({ field, path: partPath });
28672
+ totalBytes += partBytes;
28673
+ };
28674
+ const parser = parse({ bom: true, skip_empty_lines: true, max_record_size: 8192 });
28675
+ const decoded = Readable2.from(decode());
28676
+ decoded.on("error", (error) => parser.destroy(error));
28677
+ decoded.pipe(parser);
28678
+ let first = true;
28679
+ try {
28680
+ const records = parser;
28681
+ for await (const row of records) {
28682
+ if (row.length !== 2 || row.some((cell) => cell.length > 4096))
28683
+ throw new SimApiError(`${field}: expected two CSV columns of at most 4,096 characters.`, 0);
28684
+ if (first && row.every((cell, index) => cell.trim() === definition.header[index])) {
28685
+ first = false;
28686
+ continue;
28687
+ }
28688
+ first = false;
28689
+ rowCount++;
28690
+ if (rowCount > definition.maxRows)
28691
+ throw new SimApiError(`${field}: exceeds ${definition.maxRows} data records.`, 0);
28692
+ const record = `${row.map((cell) => /[",\r\n]/.test(cell) ? `"${cell.replaceAll('"', '""')}"` : cell).join(",")}
28693
+ `;
28694
+ const bytes = Buffer.byteLength(record);
28695
+ if (partRows === PART_ROWS || partBytes + bytes > PART_BYTES) {
28696
+ await save();
28697
+ content = header;
28698
+ partBytes = Buffer.byteLength(header);
28699
+ partRows = 0;
28700
+ }
28701
+ content += record;
28702
+ partBytes += bytes;
28703
+ partRows++;
28704
+ }
28705
+ } finally {
28706
+ decoded.destroy();
28707
+ parser.destroy();
28708
+ }
28709
+ const after = await handle?.stat();
28710
+ if (before && after && (before.size !== after.size || before.mtimeMs !== after.mtimeMs))
28711
+ throw new SimApiError(`${field}: input changed during staging. Rerun the export.`, 0);
28712
+ if (!rowCount)
28713
+ throw new SimApiError(`${field}: at least one data record is required.`, 0);
28714
+ await save();
28715
+ manifest[field] = { filename, rowCount, parts: parts.length - startPart };
28716
+ } catch (error) {
28717
+ if (signal?.aborted || snapshot?.signal?.aborted)
28718
+ throw new SimApiError("Permission CSV upload cancelled.", 0);
28719
+ if (error instanceof CsvError)
28720
+ throw new SimApiError(`${field}: invalid CSV quoting or record length.`, 0);
28721
+ throw error;
28722
+ } finally {
28723
+ stream?.destroy();
28724
+ if (snapshotStream && !snapshotStream.locked)
28725
+ await snapshotStream.cancel();
28726
+ await handle?.close();
28727
+ await snapshot?.dispose();
28728
+ }
28729
+ }
28730
+ return { manifest, parts, dispose };
28731
+ } catch (error) {
28732
+ await dispose();
28733
+ if (error instanceof SimApiError)
28734
+ throw error;
28735
+ if (error instanceof Error && "code" in error && typeof error.code === "string")
28736
+ throw new SimApiError(`Cannot stage permission CSVs: ${error.message}`, 0);
28737
+ throw error;
28738
+ }
28739
+ }
28740
+
28741
+ // src/commands/source-permissions.ts
28742
+ function attachSourcePermissionCommands(program) {
28743
+ let parent = program;
28744
+ for (const name of ["organizations", "search", "sources", "permissions"]) {
28745
+ const child = parent.commands.find((command) => command.name() === name);
28746
+ if (!child)
28747
+ throw new Error(`Missing generated command group: ${name}`);
28748
+ parent = child;
28749
+ }
28750
+ const [command, connect] = apiCommand(parent, "upload", [
28751
+ "createSourcePermissionImport",
28752
+ "putSourcePermissionImportPart",
28753
+ "completeSourcePermissionImport"
28754
+ ]);
28755
+ command.argument("<sourceId>", "Search source identifier").description("Replace source permissions from two CSV files, uploaded in bounded parts").allowExcessArguments(false).requiredOption("--organization <id>", "Organization identifier").addOption(new Option("--provider <provider>", "Permission provider").choices(["gitlab"]).makeOptionMandatory()).requiredOption("--expected-revision <number>", "Revision read before exporting the CSVs").requiredOption("--user-mapping <path>", "Complete user mapping CSV").requiredOption("--project-permissions <path>", "Complete project permissions CSV").option("-y, --yes", "Confirm replacement of all source permissions (required)").action(async (sourceId, options) => {
28756
+ if (!options.yes)
28757
+ throw new SimApiError("This replaces all source permissions. Re-run with --yes to confirm.", 0);
28758
+ const expectedRevision = Number(options.expectedRevision);
28759
+ if (!Number.isInteger(expectedRevision) || expectedRevision <= 0 || expectedRevision >= 2147483647)
28760
+ throw new SimApiError("--expected-revision must be an integer from 1 to 2147483646.", 0);
28761
+ const { client, profile } = connect();
28762
+ const signal = profile.signal;
28763
+ const staged = await stagePermissionCsvs(options.provider, options, signal);
28764
+ const params = { organizationId: options.organization, sourceId };
28765
+ const retry = async (request) => {
28766
+ for (let attempt = 1;; attempt++) {
28767
+ signal?.throwIfAborted();
28768
+ try {
28769
+ return await request();
28770
+ } catch (error) {
28771
+ if (!(error instanceof SimApiError) || attempt >= 5 || error.code !== "RESPONSE_READ_FAILED" && error.status !== 0 && error.status !== 429 && error.status < 500)
28772
+ throw error;
28773
+ await setTimeout2(backoffWithJitter(attempt, error.retryAfterMs, { maxMs: 300000 }), undefined, { signal });
28774
+ }
28775
+ }
28776
+ };
28777
+ try {
28778
+ const started = await client.request("createSourcePermissionImport", {
28779
+ params,
28780
+ body: { provider: options.provider, expectedRevision, ...staged.manifest }
28781
+ });
28782
+ const importParams = { ...params, importId: started.data.id };
28783
+ for (const [partNumber, part] of staged.parts.entries()) {
28784
+ const content = await readFile(part.path, "utf8");
28785
+ const result = await retry(() => client.request("putSourcePermissionImportPart", {
28786
+ params: { ...importParams, partNumber: String(partNumber) },
28787
+ body: { field: part.field, content }
28788
+ }));
28789
+ if (result.data.nextPart !== partNumber + 1)
28790
+ throw new SimApiError("The server returned an unexpected upload position. Permissions were not activated.", 0);
28791
+ }
28792
+ const result = await retry(() => client.request("completeSourcePermissionImport", { params: importParams, body: {} }));
28793
+ printProtocolResult(profile.output, { sourceId, revision: result.data.revision });
28794
+ } finally {
28795
+ await staged.dispose();
28796
+ }
28797
+ });
28798
+ }
28799
+
26859
28800
  // src/telemetry/transport.ts
26860
28801
  import { spawn as spawn4 } from "node:child_process";
26861
28802
  var CAPTURE_PATH = "/i/v0/e/";
@@ -27184,6 +29125,7 @@ function buildProgram(options = {}) {
27184
29125
  attachCredentialCommands(program);
27185
29126
  attachProtocolCommands(program);
27186
29127
  attachSecretCommands(program);
29128
+ attachSourcePermissionCommands(program);
27187
29129
  program.addHelpText("after", options.helpText ?? HELP_EPILOGUE);
27188
29130
  program.addHelpText("beforeAll", ({ command }) => detectCodingAgent(env) !== undefined && command.commands.length > 0 ? AGENT_DISCOVERY_NOTE : "");
27189
29131
  refuseHelpAfterUnknownCommand(program);