@usesocial/cli 0.19.5 → 0.19.7

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @usesocial/cli
2
2
 
3
+ ## 0.19.7
4
+
5
+ ### Patch Changes
6
+
7
+ - [#149](https://github.com/usesocial/monorepo/pull/149) [`23797dd`](https://github.com/usesocial/monorepo/commit/23797dd3f65fd1b0012fb3f92bf997696231b148) Thanks [@CyrusNuevoDia](https://github.com/CyrusNuevoDia)! - Add privacy-safe sync failure correlation fields to CLI exception telemetry.
8
+
9
+ ## 0.19.6
10
+
11
+ ### Patch Changes
12
+
13
+ - [#147](https://github.com/usesocial/monorepo/pull/147) [`df61320`](https://github.com/usesocial/monorepo/commit/df61320ec0e5d4eacc9eae02c843710be388d532) Thanks [@CyrusNuevoDia](https://github.com/CyrusNuevoDia)! - Advertise normalized X and LinkedIn result envelopes, simplify LinkedIn mirror views, and keep LinkedIn usage logs at zero cost.
14
+
3
15
  ## 0.19.5
4
16
 
5
17
  ### Patch Changes
package/dist/index.mjs CHANGED
@@ -648,6 +648,12 @@ var CancelledError = class extends Error {
648
648
  };
649
649
  /** True for any of the typed errors above (single-instance instanceof is safe within this package graph). */
650
650
  const isTypedCLIError = (error) => error instanceof UsageError || error instanceof AuthError || error instanceof NotFoundError || error instanceof CancelledError;
651
+ //#endregion
652
+ //#region ../../packages/billing/src/constants.ts
653
+ const partnerUserPlanId = (partnerSlug) => `social_linkedin_${partnerSlug}`;
654
+ const partnerBillingPlanId = (partnerSlug) => `partner_${partnerSlug}`;
655
+ partnerUserPlanId("slashy");
656
+ partnerBillingPlanId("slashy");
651
657
  const MARKUP_BPS = 5e3;
652
658
  //#endregion
653
659
  //#region ../../packages/billing/src/markup.ts
@@ -1246,16 +1252,123 @@ const helpDescriptionFor = (adapter, op, context) => {
1246
1252
  };
1247
1253
  const buildRuntimeContract = (adapter, op, context) => {
1248
1254
  const hazard = adapter.hazardFor(op);
1255
+ const upstreamPagination = op.endpoint.pagination;
1256
+ const listOutput = upstreamPagination.style !== "none";
1257
+ const pagination = upstreamPagination.style === "none" ? upstreamPagination : upstreamPagination.style === "cursor" ? {
1258
+ style: "cursor",
1259
+ ...upstreamPagination.limitParam ? { limitParam: upstreamPagination.limitParam } : {},
1260
+ ...upstreamPagination.cursorParam ? { cursorParam: upstreamPagination.cursorParam } : {},
1261
+ cursorPath: "meta.cursor",
1262
+ itemsPath: "items",
1263
+ ..."totalCountPath" in upstreamPagination && upstreamPagination.totalCountPath ? { totalCountPath: "meta.totalCount" } : {}
1264
+ } : {
1265
+ style: "offset",
1266
+ ...upstreamPagination.limitParam ? { limitParam: upstreamPagination.limitParam } : {},
1267
+ offsetParam: upstreamPagination.offsetParam,
1268
+ itemsPath: "items",
1269
+ ...upstreamPagination.totalCountPath ? { totalCountPath: "meta.totalCount" } : {}
1270
+ };
1271
+ const outputSchema = {
1272
+ $schema: "https://json-schema.org/draft/2020-12/schema",
1273
+ type: "object",
1274
+ properties: {
1275
+ account: {
1276
+ type: "object",
1277
+ properties: {
1278
+ platform: { type: "string" },
1279
+ username: { type: ["string", "null"] }
1280
+ },
1281
+ required: ["platform"],
1282
+ additionalProperties: false
1283
+ },
1284
+ ...listOutput ? { items: {
1285
+ type: "array",
1286
+ items: {}
1287
+ } } : { data: {
1288
+ type: "object",
1289
+ additionalProperties: true
1290
+ } },
1291
+ meta: {
1292
+ type: "object",
1293
+ properties: {
1294
+ resolved: {
1295
+ type: "array",
1296
+ items: {
1297
+ type: "object",
1298
+ properties: {
1299
+ input: { type: "string" },
1300
+ id: { type: "string" },
1301
+ url: { type: "string" },
1302
+ source: { type: "string" }
1303
+ },
1304
+ required: [
1305
+ "input",
1306
+ "id",
1307
+ "source"
1308
+ ],
1309
+ additionalProperties: true
1310
+ }
1311
+ },
1312
+ cost: {
1313
+ type: "number",
1314
+ minimum: 0
1315
+ },
1316
+ cache: {
1317
+ type: "object",
1318
+ properties: {
1319
+ hit: { type: "boolean" },
1320
+ status: { type: "string" },
1321
+ age_s: { type: ["number", "null"] },
1322
+ source: { type: "string" },
1323
+ tables: {
1324
+ type: "array",
1325
+ items: {
1326
+ type: "object",
1327
+ additionalProperties: true
1328
+ }
1329
+ },
1330
+ migration: {
1331
+ type: "object",
1332
+ additionalProperties: true
1333
+ }
1334
+ },
1335
+ required: ["hit"],
1336
+ additionalProperties: true
1337
+ },
1338
+ cursor: { type: "string" },
1339
+ totalCount: { type: "number" },
1340
+ errors: {
1341
+ type: "array",
1342
+ items: {}
1343
+ },
1344
+ includes: {
1345
+ type: "object",
1346
+ additionalProperties: true
1347
+ }
1348
+ },
1349
+ required: ["resolved", "cache"],
1350
+ additionalProperties: true
1351
+ }
1352
+ },
1353
+ required: [
1354
+ "account",
1355
+ listOutput ? "items" : "data",
1356
+ "meta"
1357
+ ],
1358
+ additionalProperties: false
1359
+ };
1249
1360
  return {
1250
1361
  inputSchema: adapter.schema(adapter.contractInputSchemaName(op)),
1251
- outputSchema: adapter.schema(`${op.schemaBaseName}Output`),
1362
+ outputSchema,
1363
+ upstreamOutputSchema: adapter.schema(`${op.schemaBaseName}Output`),
1252
1364
  auth: adapter.authFor(op),
1253
1365
  capability: op.endpoint.capability,
1254
1366
  mutates: op.endpoint.mutates,
1255
1367
  method: op.endpoint.method,
1256
1368
  idempotency: adapter.idempotencyFor(op),
1257
1369
  ...hazard ? { hazard } : {},
1258
- pagination: op.endpoint.pagination,
1370
+ pagination,
1371
+ upstreamPagination,
1259
1372
  responseShaping: adapter.responseShapingFor(op),
1260
1373
  ...adapter.includeIdField === true && op.config.idField ? { idField: op.config.idField } : {},
1261
1374
  ...op.config.itemUrlTemplate ? { itemUrlTemplate: op.config.itemUrlTemplate } : {},
@@ -1793,7 +1906,7 @@ const userTypeValues = ["individual", "organization"];
1793
1906
  const LINKEDIN_CACHE_METADATA = {
1794
1907
  joins: [
1795
1908
  "li_*.user_id = li_profiles.provider_id",
1796
- "li_messages.conversation_id = li_conversations.id",
1909
+ "li_messages.chat_id = li_conversations.chat_id",
1797
1910
  "li_messages.sender_id = li_profiles.provider_id",
1798
1911
  "li_posts.author_id = li_profiles.provider_id"
1799
1912
  ],
@@ -1803,8 +1916,7 @@ const LINKEDIN_CACHE_METADATA = {
1803
1916
  "li_conversations.user_type": userTypeValues,
1804
1917
  "li_messages.sender_type": userTypeValues,
1805
1918
  "li_posts.author_type": userTypeValues,
1806
- "li_requests.type": ["received", "sent"],
1807
- "li_requests.user_type": userTypeValues
1919
+ "li_requests.type": ["received", "sent"]
1808
1920
  },
1809
1921
  indexed: {
1810
1922
  li_connections: [
@@ -1823,7 +1935,7 @@ const LINKEDIN_CACHE_METADATA = {
1823
1935
  ],
1824
1936
  li_messages: [
1825
1937
  "created_at",
1826
- "conversation_id",
1938
+ "chat_id",
1827
1939
  "sender_id"
1828
1940
  ],
1829
1941
  li_posts: [
@@ -2430,6 +2542,10 @@ const MIGRATIONS = [
2430
2542
  {
2431
2543
  "tag": "0010_x_timeline",
2432
2544
  "sql": "CREATE TABLE \"x_timeline_raw\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"created_at\" integer,\n \"author_id\" text,\n \"conversation_id\" text,\n \"in_reply_to_user_id\" text,\n \"lang\" text,\n \"reply_settings\" text,\n \"text\" text,\n \"url\" text,\n \"paid_partnership\" integer,\n \"possibly_sensitive\" integer,\n \"like_count\" integer,\n \"retweet_count\" integer,\n \"reply_count\" integer,\n \"quote_count\" integer,\n \"bookmark_count\" integer,\n \"impression_count\" integer,\n \"raw\" text NOT NULL,\n \"synced_at\" integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX \"x_timeline_created_at_idx\" ON \"x_timeline_raw\" (\"created_at\");--> statement-breakpoint\nCREATE INDEX \"x_timeline_author_id_created_at_idx\" ON \"x_timeline_raw\" (\"author_id\",\"created_at\");--> statement-breakpoint\nCREATE INDEX \"x_timeline_conversation_id_created_at_idx\" ON \"x_timeline_raw\" (\"conversation_id\",\"created_at\");--> statement-breakpoint\nCREATE VIEW \"x_timeline\" AS\nSELECT \"id\", \"created_at\", \"author_id\", \"conversation_id\", \"in_reply_to_user_id\", \"lang\",\n \"reply_settings\", \"text\", \"url\", \"paid_partnership\", \"possibly_sensitive\",\n \"like_count\", \"retweet_count\", \"reply_count\", \"quote_count\", \"bookmark_count\",\n \"impression_count\"\nFROM \"x_timeline_raw\";\n"
2545
+ },
2546
+ {
2547
+ "tag": "0011_linkedin_public_views",
2548
+ "sql": "DROP VIEW IF EXISTS \"li_requests\";\nDROP VIEW IF EXISTS \"li_conversations\";\nDROP VIEW IF EXISTS \"li_messages\";\nCREATE VIEW \"li_requests\" AS\nSELECT \"id\", \"created_at\", \"type\", json_extract(\"raw\", '$.message') AS \"message\",\n \"user_id\", \"user_public_identifier\" AS \"user_username\",\n \"user_display_name\" AS \"user_name\",\n COALESCE(\"user_headline\", \"user_description\") AS \"user_headline\",\n \"user_profile_url\", \"user_public_picture_url\" AS \"user_avatar_url\"\nFROM \"li_requests_raw\";\nCREATE VIEW \"li_conversations\" AS\nSELECT \"id\" AS \"chat_id\", \"created_at\", \"last_message_timestamp\" AS \"last_message_at\", \"name\",\n CASE\n WHEN \"is_1to1\" = 1 THEN '1to1'\n WHEN \"is_group\" = 1 THEN 'group'\n ELSE \"type\"\n END AS \"type\",\n \"unread_count\", \"is_archived\", \"is_pinned\", \"is_readonly\", \"is_channel\",\n \"muted_until\", \"image_url\", \"creator_id\", \"user_id\",\n \"user_public_identifier\" AS \"user_username\", \"user_display_name\" AS \"user_name\",\n COALESCE(\"user_headline\", \"user_description\") AS \"user_headline\", \"user_description\",\n \"user_profile_url\", \"user_public_picture_url\" AS \"user_avatar_url\", \"user_type\",\n \"user_specifics_network_distance\" AS \"user_distance\"\nFROM \"li_conversations_raw\";\nCREATE VIEW \"li_messages\" AS\nSELECT \"id\", \"timestamp\" AS \"created_at\", \"chat_id\", \"text\",\n \"sender_id\", \"is_deleted\", \"is_delivered\", \"is_edited\", \"is_event\", \"is_hidden\",\n \"is_mentionned\" AS \"is_mentioned\", \"is_pinned\", \"is_seen\", \"is_sender\",\n \"sender_public_identifier\" AS \"sender_username\",\n \"sender_display_name\" AS \"sender_name\", \"sender_description\" AS \"sender_headline\",\n \"sender_public_picture_url\" AS \"sender_avatar_url\", \"sender_profile_url\",\n \"sender_type\", \"sender_specifics_network_distance\" AS \"sender_distance\"\nFROM \"li_messages_raw\";\n"
2433
2549
  }
2434
2550
  ];
2435
2551
  //#endregion
@@ -11056,14 +11172,6 @@ const CONNECTED_ACCOUNT_STATUSES = [
11056
11172
  "failed",
11057
11173
  "expired"
11058
11174
  ];
11059
- const ACCOUNT_CONNECT_ATTEMPT_LANES = ["provider", "legacy"];
11060
- const ACCOUNT_CONNECT_ATTEMPT_STATUSES = [
11061
- "pending_billing",
11062
- "pending_approval",
11063
- "connected",
11064
- "expired",
11065
- "failed"
11066
- ];
11067
11175
  const PROXY_SURFACES = [
11068
11176
  "cli",
11069
11177
  "mcp",
@@ -11086,9 +11194,11 @@ const CLI_CAPABILITIES = [
11086
11194
  "social:read",
11087
11195
  "x:read",
11088
11196
  "linkedin:read",
11197
+ "partner:read",
11089
11198
  "social:write",
11090
11199
  "x:write",
11091
- "linkedin:write"
11200
+ "linkedin:write",
11201
+ "partner:write"
11092
11202
  ];
11093
11203
  const FEEDBACK_TYPES = ["bug", "feature"];
11094
11204
  const WRAPPED_STATUSES = [
@@ -11126,8 +11236,6 @@ const WEBHOOK_OPERATION_STATES = [
11126
11236
  _enum(PLATFORMS);
11127
11237
  _enum(CONNECTED_ACCOUNT_STATUSES);
11128
11238
  _enum(MATERIALIZED_CONNECTED_ACCOUNT_STATUSES);
11129
- _enum(ACCOUNT_CONNECT_ATTEMPT_LANES);
11130
- _enum(ACCOUNT_CONNECT_ATTEMPT_STATUSES);
11131
11239
  _enum(PROXY_SURFACES);
11132
11240
  _enum(PROXY_CACHE_STATUSES);
11133
11241
  _enum(PROXY_CAPABILITIES);
@@ -11298,9 +11406,53 @@ const timestamptz = (name) => timestamp(name, {
11298
11406
  withTimezone: true,
11299
11407
  mode: "date"
11300
11408
  });
11409
+ const partners = pgTable("partners", {
11410
+ id: text$1("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
11411
+ slug: text$1("slug").notNull(),
11412
+ displayName: text$1("display_name").notNull(),
11413
+ callbackURL: text$1("callback_url").notNull(),
11414
+ authDomain: text$1("auth_domain").notNull(),
11415
+ apiKeyPrefix: text$1("api_key_prefix").notNull(),
11416
+ apiKeyHash: text$1("api_key_hash").notNull(),
11417
+ disabledAt: timestamptz("disabled_at"),
11418
+ createdAt: timestamptz("created_at").notNull().defaultNow(),
11419
+ updatedAt: timestamptz("updated_at").notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
11420
+ }, (table) => [
11421
+ uniqueIndex("partners_slug_key").on(table.slug),
11422
+ uniqueIndex("partners_api_key_prefix_key").on(table.apiKeyPrefix),
11423
+ check("partners_slug_check", sql`${table.slug} ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$'`),
11424
+ check("partners_display_name_nonempty_check", sql`length(${table.displayName}) > 0`),
11425
+ check("partners_callback_url_https_check", sql`${table.callbackURL} ~ '^https://[^[:space:]]+$'`),
11426
+ check("partners_auth_domain_hostname_check", sql`${table.authDomain} ~ '^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$'`),
11427
+ check("partners_api_key_prefix_nonempty_check", sql`length(${table.apiKeyPrefix}) > 0`),
11428
+ check("partners_api_key_hash_check", sql`${table.apiKeyHash} ~ '^[0-9a-f]{64}$'`)
11429
+ ]);
11430
+ const partnerUsers = pgTable("partner_users", {
11431
+ partnerId: text$1("partner_id").notNull().references(() => partners.id),
11432
+ externalUserId: text$1("external_user_id").notNull(),
11433
+ userId: text$1("user_id").notNull().references(() => user.id),
11434
+ activeSessionId: text$1("active_session_id").references(() => session.id, { onDelete: "set null" }),
11435
+ canceledAt: timestamptz("canceled_at"),
11436
+ upstreamDeletedAt: timestamptz("upstream_deleted_at"),
11437
+ entitlementCanceledAt: timestamptz("entitlement_canceled_at"),
11438
+ createdAt: timestamptz("created_at").notNull().defaultNow(),
11439
+ updatedAt: timestamptz("updated_at").notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
11440
+ }, (table) => [
11441
+ primaryKey({
11442
+ name: "partner_users_pkey",
11443
+ columns: [table.partnerId, table.externalUserId]
11444
+ }),
11445
+ uniqueIndex("partner_users_user_id_key").on(table.userId),
11446
+ uniqueIndex("partner_users_partner_user_id_key").on(table.partnerId, table.userId),
11447
+ uniqueIndex("partner_users_active_session_id_key").on(table.activeSessionId).where(sql`${table.activeSessionId} is not null`),
11448
+ check("partner_users_external_user_id_nonempty_check", sql`length(${table.externalUserId}) > 0`),
11449
+ check("partner_users_cleanup_requires_cancellation_check", sql`(${table.upstreamDeletedAt} is null and ${table.entitlementCanceledAt} is null) or ${table.canceledAt} is not null`),
11450
+ check("partner_users_canceled_session_check", sql`${table.canceledAt} is null or ${table.activeSessionId} is null`)
11451
+ ]);
11301
11452
  const connectedAccounts = pgTable("connected_accounts", {
11302
11453
  id: text$1("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
11303
11454
  userId: text$1("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
11455
+ partnerId: text$1("partner_id"),
11304
11456
  platform: text$1("platform", { enum: PLATFORMS }).notNull(),
11305
11457
  platformAccountId: text$1("platform_account_id"),
11306
11458
  platformProfileId: text$1("platform_profile_id"),
@@ -11320,47 +11472,44 @@ const connectedAccounts = pgTable("connected_accounts", {
11320
11472
  createdAt: timestamptz("created_at").notNull().defaultNow(),
11321
11473
  updatedAt: timestamptz("updated_at").notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
11322
11474
  }, (table) => [
11323
- uniqueIndex("connected_accounts_platform_account_pkey").on(table.platform, table.platformAccountId),
11324
- uniqueIndex("connected_accounts_platform_profile_pkey").on(table.platform, table.platformProfileId).where(sql`${table.platformProfileId} is not null`),
11475
+ uniqueIndex("connected_accounts_direct_platform_account_key").on(table.platform, table.platformAccountId).where(sql`${table.partnerId} is null`),
11476
+ uniqueIndex("connected_accounts_partner_platform_account_key").on(table.partnerId, table.platform, table.platformAccountId).where(sql`${table.partnerId} is not null`),
11477
+ uniqueIndex("connected_accounts_direct_platform_profile_key").on(table.platform, table.platformProfileId).where(sql`${table.partnerId} is null and ${table.platformProfileId} is not null`),
11478
+ uniqueIndex("connected_accounts_partner_platform_profile_key").on(table.partnerId, table.platform, table.platformProfileId).where(sql`${table.partnerId} is not null and ${table.platformProfileId} is not null`),
11325
11479
  uniqueIndex("connected_accounts_user_platform_pkey").on(table.userId, table.platform, table.platformAccountId),
11326
11480
  uniqueIndex("connected_accounts_user_platform_id_key").on(table.userId, table.platform, table.id),
11327
11481
  index("connected_accounts_user_platform_idx").on(table.userId, table.platform).where(sql`${table.status} = 'connected'`),
11328
11482
  index("connected_accounts_user_username_idx").on(table.userId, table.platform, table.username),
11329
- uniqueIndex("connected_accounts_active_partial_user_platform_key").on(table.userId, table.platform).where(sql`${table.status} in ('pending_billing', 'pending_approval')`),
11483
+ uniqueIndex("connected_accounts_direct_active_partial_user_platform_key").on(table.userId, table.platform).where(sql`${table.partnerId} is null and ${table.status} in ('pending_billing', 'pending_approval')`),
11484
+ uniqueIndex("connected_accounts_partner_user_platform_key").on(table.userId, table.platform).where(sql`${table.partnerId} is not null`),
11330
11485
  index("connected_accounts_partial_expiry_idx").on(table.connectExpiresAt).where(sql`${table.status} in ('pending_billing', 'pending_approval')`),
11331
11486
  index("connected_accounts_terminal_updated_idx").on(table.updatedAt).where(sql`${table.status} in ('failed', 'expired')`),
11332
11487
  check("connected_accounts_platform_check", sqlCheckIn(table.platform, PLATFORMS)),
11333
11488
  check("connected_accounts_status_check", sqlCheckIn(table.status, CONNECTED_ACCOUNT_STATUSES)),
11334
- check("connected_accounts_materialized_fields_check", sql`${table.status} in ('pending_billing', 'pending_approval', 'failed', 'expired') or (${table.platformAccountId} is not null and ${table.platformProfileId} is not null and ${table.username} is not null and ${table.displayName} is not null and ${table.connectedAt} is not null and ${table.lastSeenAt} is not null)`)
11489
+ check("connected_accounts_partner_platform_check", sql`${table.partnerId} is null or ${table.platform} = 'linkedin'`),
11490
+ check("connected_accounts_materialized_fields_check", sql`${table.status} in ('pending_billing', 'pending_approval', 'failed', 'expired') or (${table.platformAccountId} is not null and ${table.platformProfileId} is not null and ${table.username} is not null and ${table.displayName} is not null and ${table.connectedAt} is not null and ${table.lastSeenAt} is not null)`),
11491
+ foreignKey({
11492
+ name: "connected_accounts_partner_user_fk",
11493
+ columns: [table.partnerId, table.userId],
11494
+ foreignColumns: [partnerUsers.partnerId, partnerUsers.userId]
11495
+ })
11335
11496
  ]);
11336
- pgTable("account_connect_attempts", {
11497
+ pgTable("partner_billable_account_periods", {
11337
11498
  id: text$1("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
11338
- userId: text$1("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
11339
- platform: text$1("platform", { enum: PLATFORMS }).notNull(),
11340
- lane: text$1("lane", { enum: ACCOUNT_CONNECT_ATTEMPT_LANES }).notNull(),
11341
- targetPaidSeats: integer("target_paid_seats").notNull(),
11342
- status: text$1("status", { enum: ACCOUNT_CONNECT_ATTEMPT_STATUSES }).notNull().default("pending_billing"),
11343
- connectedAccountId: text$1("connected_account_id").references(() => connectedAccounts.id, { onDelete: "set null" }),
11344
- operationKey: text$1("operation_key").notNull(),
11345
- billingPaymentURL: text$1("billing_payment_url"),
11346
- billingRequiredAction: jsonb("billing_required_action").$type(),
11347
- failureCode: text$1("failure_code"),
11348
- failureStage: text$1("failure_stage"),
11349
- hostedAuthBindingId: text$1("hosted_auth_binding_id"),
11350
- hostedAuthAccountId: text$1("hosted_auth_account_id"),
11351
- hostedAuthBoundAt: timestamptz("hosted_auth_bound_at"),
11352
- expiresAt: timestamptz("expires_at").notNull(),
11353
- createdAt: timestamptz("created_at").notNull().defaultNow(),
11354
- updatedAt: timestamptz("updated_at").notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
11499
+ partnerId: text$1("partner_id").notNull(),
11500
+ userId: text$1("user_id").notNull(),
11501
+ platformAccountId: text$1("platform_account_id").notNull(),
11502
+ periodStart: timestamptz("period_start").notNull(),
11503
+ firstObservedAt: timestamptz("first_observed_at").notNull(),
11504
+ autumnTrackedAt: timestamptz("autumn_tracked_at")
11355
11505
  }, (table) => [
11356
- uniqueIndex("account_connect_attempts_operation_key_key").on(table.operationKey),
11357
- uniqueIndex("account_connect_attempts_hosted_auth_binding_id_key").on(table.hostedAuthBindingId),
11358
- uniqueIndex("account_connect_attempts_active_user_platform_key").on(table.userId, table.platform).where(sql`${table.status} in ('pending_billing', 'pending_approval')`),
11359
- index("account_connect_attempts_expiry_idx").on(table.expiresAt).where(sql`${table.status} in ('pending_billing', 'pending_approval')`),
11360
- check("account_connect_attempts_platform_check", sqlCheckIn(table.platform, PLATFORMS)),
11361
- check("account_connect_attempts_lane_check", sqlCheckIn(table.lane, ACCOUNT_CONNECT_ATTEMPT_LANES)),
11362
- check("account_connect_attempts_status_check", sqlCheckIn(table.status, ACCOUNT_CONNECT_ATTEMPT_STATUSES)),
11363
- check("account_connect_attempts_target_paid_seats_check", sql`${table.targetPaidSeats} >= 0`)
11506
+ uniqueIndex("partner_billable_account_periods_account_period_key").on(table.partnerId, table.platformAccountId, table.periodStart),
11507
+ index("partner_billable_account_periods_untracked_idx").on(table.firstObservedAt, table.id).where(sql`${table.autumnTrackedAt} is null`),
11508
+ foreignKey({
11509
+ name: "partner_billable_account_periods_partner_user_fk",
11510
+ columns: [table.partnerId, table.userId],
11511
+ foreignColumns: [partnerUsers.partnerId, partnerUsers.userId]
11512
+ })
11364
11513
  ]);
11365
11514
  pgTable("account_defaults", {
11366
11515
  userId: text$1("user_id").notNull(),
@@ -14917,6 +15066,50 @@ const schemas$1 = {
14917
15066
  var UnexpectedLinkedinResponseError = class extends Error {
14918
15067
  name = "UnexpectedLinkedinResponseError";
14919
15068
  };
15069
+ const linkedinInboxRecordsFrom = (data) => {
15070
+ if (Array.isArray(data)) return data.filter((item) => typeof item === "object" && item !== null && !Array.isArray(item));
15071
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return [];
15072
+ const record = data;
15073
+ for (const key of [
15074
+ "data",
15075
+ "items",
15076
+ "inboxes"
15077
+ ]) {
15078
+ const value = record[key];
15079
+ if (Array.isArray(value)) return value.filter((item) => typeof item === "object" && item !== null && !Array.isArray(item));
15080
+ }
15081
+ return [];
15082
+ };
15083
+ const linkedinInboxString = (inbox, keys) => {
15084
+ for (const key of keys) {
15085
+ const value = inbox[key];
15086
+ if (typeof value === "string" && value.length > 0) return value;
15087
+ }
15088
+ };
15089
+ const linkedinInboxText = (inbox) => [linkedinInboxString(inbox, ["id", "inbox_id"]), linkedinInboxString(inbox, [
15090
+ "provider",
15091
+ "provider_id",
15092
+ "type",
15093
+ "inbox_type",
15094
+ "name",
15095
+ "label"
15096
+ ])].filter(Boolean).join(" ").toLowerCase();
15097
+ const classicLinkedinInboxIdFrom = (data) => {
15098
+ const withIds = linkedinInboxRecordsFrom(data).map((inbox) => ({
15099
+ id: linkedinInboxString(inbox, ["id", "inbox_id"]),
15100
+ inbox
15101
+ })).filter((item) => Boolean(item.id));
15102
+ const exact = withIds.find(({ id }) => id === "CLASSIC_PRIMARY");
15103
+ if (exact) return exact.id;
15104
+ const classic = withIds.find(({ inbox }) => {
15105
+ const text = linkedinInboxText(inbox);
15106
+ return text.includes("linkedin_classic") || text.includes("classic");
15107
+ });
15108
+ if (classic) return classic.id;
15109
+ const primary = withIds.find(({ inbox }) => linkedinInboxText(inbox).includes("primary"));
15110
+ if (primary) return primary.id;
15111
+ return withIds.length === 1 ? withIds[0]?.id : void 0;
15112
+ };
14920
15113
  const commandMeta$2 = (meta) => commandMeta$3(meta);
14921
15114
  const schema$1 = (name) => {
14922
15115
  const resolved = schemas$1[name];
@@ -15439,57 +15632,12 @@ const requireAccountSelector$1 = (selector) => {
15439
15632
  return selector;
15440
15633
  };
15441
15634
  const linkedinClassicInboxIdCache = /* @__PURE__ */ new WeakMap();
15442
- const inboxRecordsFrom = (data) => {
15443
- if (Array.isArray(data)) return data.filter((item) => Boolean(item && typeof item === "object" && !Array.isArray(item)));
15444
- const record = dataRecordFrom$1(data);
15445
- if (!record) return [];
15446
- for (const key of [
15447
- "data",
15448
- "items",
15449
- "inboxes"
15450
- ]) {
15451
- const value = record[key];
15452
- if (Array.isArray(value)) return value.filter((item) => Boolean(item && typeof item === "object" && !Array.isArray(item)));
15453
- }
15454
- return [];
15455
- };
15456
- const inboxString = (inbox, keys) => {
15457
- for (const key of keys) {
15458
- const value = inbox[key];
15459
- if (typeof value === "string" && value.length > 0) return value;
15460
- }
15461
- };
15462
- const inboxText = (inbox) => [inboxString(inbox, ["id", "inbox_id"]), inboxString(inbox, [
15463
- "provider",
15464
- "provider_id",
15465
- "type",
15466
- "inbox_type",
15467
- "name",
15468
- "label"
15469
- ])].filter(Boolean).join(" ").toLowerCase();
15470
- const classicInboxIdFrom = (data) => {
15471
- const withIds = inboxRecordsFrom(data).map((inbox) => ({
15472
- id: inboxString(inbox, ["id", "inbox_id"]),
15473
- inbox
15474
- })).filter((item) => Boolean(item.id));
15475
- const exact = withIds.find(({ id }) => id === "CLASSIC_PRIMARY");
15476
- if (exact) return exact.id;
15477
- const classic = withIds.find(({ inbox }) => {
15478
- const text = inboxText(inbox);
15479
- return text.includes("linkedin_classic") || text.includes("classic");
15480
- });
15481
- if (classic) return classic.id;
15482
- const primary = withIds.find(({ inbox }) => inboxText(inbox).includes("primary"));
15483
- if (primary) return primary.id;
15484
- return withIds.length === 1 ? withIds[0]?.id : void 0;
15485
- };
15486
15635
  const linkedinClassicInboxId = async (args) => {
15487
15636
  const cache = linkedinClassicInboxIdCache.get(args.api) ?? /* @__PURE__ */ new Map();
15488
15637
  linkedinClassicInboxIdCache.set(args.api, cache);
15489
15638
  const cached = cache.get(args.cacheKey);
15490
15639
  if (cached) return cached;
15491
- const response = await args.api.get("linkedin/inboxes", { headers: args.headers });
15492
- const inboxId = classicInboxIdFrom(await response.json());
15640
+ const inboxId = classicLinkedinInboxIdFrom(await (await args.api.get("linkedin/inboxes", { headers: args.headers })).json());
15493
15641
  if (!inboxId) throw new UsageError("Could not find a LinkedIn classic inbox for this account.");
15494
15642
  cache.set(args.cacheKey, inboxId);
15495
15643
  return inboxId;
@@ -24510,7 +24658,7 @@ function createEnv(opts) {
24510
24658
  }
24511
24659
  //#endregion
24512
24660
  //#region package.json
24513
- var version$1 = "0.19.5";
24661
+ var version$1 = "0.19.7";
24514
24662
  //#endregion
24515
24663
  //#region src/lib/env.ts
24516
24664
  const URLWithTrailingSlash = url().transform(ensureTrailingSlash);
@@ -25179,14 +25327,14 @@ const cacheFromLocal = (local, now) => ({
25179
25327
  });
25180
25328
  const nextCursorFrom = (contract, data) => {
25181
25329
  if (!isRecord$7(contract)) return;
25182
- const pagination = contract.pagination;
25330
+ const pagination = contract.upstreamPagination ?? contract.pagination;
25183
25331
  if (!isRecord$7(pagination)) return;
25184
25332
  const response = pagination.response;
25185
25333
  return stringAtPath(data, isRecord$7(response) ? response.nextCursorPath : null) ?? stringAtPath(data, pagination.cursorPath);
25186
25334
  };
25187
25335
  const totalCountFrom = (contract, data) => {
25188
25336
  if (!isRecord$7(contract)) return;
25189
- const pagination = contract.pagination;
25337
+ const pagination = contract.upstreamPagination ?? contract.pagination;
25190
25338
  if (!isRecord$7(pagination)) return;
25191
25339
  return numberAtPath(data, pagination.totalCountPath);
25192
25340
  };
@@ -31204,6 +31352,45 @@ const recordValue = (value) => value && typeof value === "object" ? value : void
31204
31352
  const stringProperty = (value) => typeof value === "string" ? value : void 0;
31205
31353
  const numberProperty = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
31206
31354
  const causeOf = (value) => recordValue(value)?.cause;
31355
+ const SYNC_REQUEST_PATHS = {
31356
+ li_connections: /* @__PURE__ */ new Set(["/users/connections"]),
31357
+ li_conversations: /* @__PURE__ */ new Set(["/chats"]),
31358
+ li_messages: /* @__PURE__ */ new Set(["/chats/:chat_id/messages"]),
31359
+ li_posts: /* @__PURE__ */ new Set(["/users/:identifier/posts"]),
31360
+ li_requests: /* @__PURE__ */ new Set(["/users/me/relation-requests/received", "/users/me/relation-requests/sent"]),
31361
+ x_bookmarks: /* @__PURE__ */ new Set(["/users/:id/bookmarks"]),
31362
+ x_followers: /* @__PURE__ */ new Set(["/users/:id/followers"]),
31363
+ x_following: /* @__PURE__ */ new Set(["/users/:id/following"]),
31364
+ x_liked: /* @__PURE__ */ new Set(["/users/:id/liked_tweets"]),
31365
+ x_mentions: /* @__PURE__ */ new Set(["/users/:id/mentions"]),
31366
+ x_messages: /* @__PURE__ */ new Set(["/dm_events"]),
31367
+ x_timeline: /* @__PURE__ */ new Set(["/users/:id/timelines/reverse_chronological"]),
31368
+ x_tweets: /* @__PURE__ */ new Set(["/users/:id/tweets"])
31369
+ };
31370
+ const syncPlatformForCommand = (command) => {
31371
+ if (command === "linkedin" || command?.startsWith("linkedin ")) return "linkedin";
31372
+ if (command === "x" || command?.startsWith("x ")) return "x";
31373
+ };
31374
+ const syncCollection = (value, platform) => {
31375
+ if (!(platform && typeof value === "string" && value in SYNC_REQUEST_PATHS)) return;
31376
+ if (platform === "linkedin" ? value.startsWith("li_") : value.startsWith("x_")) return value;
31377
+ };
31378
+ const syncFailureProperties = (error, command) => {
31379
+ const errorRecord = recordValue(error);
31380
+ if (!(errorRecord?.name === "SyncPageError" && errorRecord._tag === "SyncPageError")) return {};
31381
+ const platform = syncPlatformForCommand(command);
31382
+ const collection = syncCollection(errorRecord.collectionKey, platform);
31383
+ const requestPath = collection && typeof errorRecord.requestPath === "string" && errorRecord.requestPath.startsWith("/") && !errorRecord.requestPath.includes("?") && !errorRecord.requestPath.includes("#") && SYNC_REQUEST_PATHS[collection].has(errorRecord.requestPath) ? errorRecord.requestPath : void 0;
31384
+ const pagesCompleted = Number.isSafeInteger(errorRecord.pagesCompleted) && errorRecord.pagesCompleted >= 0 ? errorRecord.pagesCompleted : void 0;
31385
+ const cursorPersisted = typeof errorRecord.cursorPersisted === "boolean" ? errorRecord.cursorPersisted : void 0;
31386
+ return withoutUndefined({
31387
+ sync_platform: platform,
31388
+ sync_collection: collection,
31389
+ sync_request_path: requestPath,
31390
+ sync_pages_completed: pagesCompleted,
31391
+ sync_cursor_persisted: cursorPersisted
31392
+ });
31393
+ };
31207
31394
  const causeProperties = (error) => {
31208
31395
  const causeNames = [];
31209
31396
  const causeCodes = [];
@@ -31246,6 +31433,7 @@ const buildFailureProperties = (error, ctx) => {
31246
31433
  retry_after_seconds: error instanceof CLIAPIError ? error.retryAfterSeconds : void 0,
31247
31434
  retry_count: error instanceof CLIAPIError ? error.retryCount : void 0,
31248
31435
  retry_budget_exhausted: error instanceof CLIAPIError ? error.retryBudgetExhausted : void 0,
31436
+ ...syncFailureProperties(error, ctx.command),
31249
31437
  ...causeProperties(error),
31250
31438
  top_frame: topFrame
31251
31439
  });
@@ -33504,22 +33692,26 @@ const USAGE_LOG_PAGE_LIMIT = 100;
33504
33692
  const USAGE_LOG_MAX_AUTO_PAGES = 50;
33505
33693
  const cursorFrom = (usage) => usage.nextCursor ?? null;
33506
33694
  const normalizeUsageLogForOutput = (item) => {
33695
+ const withLinkedinSeatPricing = (log) => log.platform === "linkedin" ? {
33696
+ ...log,
33697
+ usageUSD: 0
33698
+ } : log;
33507
33699
  if (typeof item === "object" && item !== null && "createdAt" in item && item.createdAt instanceof Date) {
33508
33700
  const { credits, ...rest } = item;
33509
- return {
33701
+ return withLinkedinSeatPricing({
33510
33702
  ...rest,
33511
33703
  createdAt: item.createdAt.toISOString(),
33512
33704
  ...typeof credits === "number" ? { usageUSD: creditsToUsageUSD(credits) } : {}
33513
- };
33705
+ });
33514
33706
  }
33515
33707
  if (typeof item === "object" && item !== null && "credits" in item) {
33516
33708
  const { credits, ...rest } = item;
33517
- return {
33709
+ return withLinkedinSeatPricing({
33518
33710
  ...rest,
33519
33711
  ...typeof credits === "number" ? { usageUSD: creditsToUsageUSD(credits) } : {}
33520
- };
33712
+ });
33521
33713
  }
33522
- return item;
33714
+ return typeof item === "object" && item !== null ? withLinkedinSeatPricing(item) : item;
33523
33715
  };
33524
33716
  const sumByFrom = (value) => {
33525
33717
  if (value === void 0) return;
@@ -39561,7 +39753,9 @@ const CLIContractMetadata = object({
39561
39753
  outputSchema: unknown().optional(),
39562
39754
  pagination: JSONMetadata.optional(),
39563
39755
  params: record(string(), JSONMetadata).optional(),
39564
- responseShaping: JSONMetadata.optional()
39756
+ responseShaping: JSONMetadata.optional(),
39757
+ upstreamOutputSchema: unknown().optional(),
39758
+ upstreamPagination: JSONMetadata.optional()
39565
39759
  }).strict();
39566
39760
  const issueSummary = (error) => error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
39567
39761
  const invalidMetadataError = (label, error) => /* @__PURE__ */ new Error(`Invalid CLI contract metadata for ${label}: ${issueSummary(error)}`);