polite-crawler 0.6.2 → 0.6.3

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.
Files changed (35) hide show
  1. package/README.md +52 -0
  2. package/build/api.d.mts +210 -21
  3. package/build/api.mjs +322 -4
  4. package/build/api.mjs.map +1 -1
  5. package/build/{cli-daemon-DBvq5TU3.mjs → cli-daemon-Dh7_akeK.mjs} +2 -2
  6. package/build/{cli-daemon-DBvq5TU3.mjs.map → cli-daemon-Dh7_akeK.mjs.map} +1 -1
  7. package/build/{cli-recipes-C--_YyuP.mjs → cli-recipes-DnmjTnyY.mjs} +2 -2
  8. package/build/{cli-recipes-C--_YyuP.mjs.map → cli-recipes-DnmjTnyY.mjs.map} +1 -1
  9. package/build/cli.mjs +7 -7
  10. package/build/{daemon-BkJp3wXR.mjs → daemon-Skkq_MW8.mjs} +3 -3
  11. package/build/{daemon-BkJp3wXR.mjs.map → daemon-Skkq_MW8.mjs.map} +1 -1
  12. package/build/{diff-DcbpHrxv.mjs → diff-BUGMvIqe.mjs} +2 -2
  13. package/build/{diff-DcbpHrxv.mjs.map → diff-BUGMvIqe.mjs.map} +1 -1
  14. package/build/{extract-DpycIF0M.mjs → extract-Cm_bF25a.mjs} +2 -2
  15. package/build/{extract-DpycIF0M.mjs.map → extract-Cm_bF25a.mjs.map} +1 -1
  16. package/build/index.d.mts +13 -9
  17. package/build/index.mjs +10 -10
  18. package/build/{open-BIvV3pHE.mjs → open-Cw4NVDBE.mjs} +75 -54
  19. package/build/open-Cw4NVDBE.mjs.map +1 -0
  20. package/build/politeness.d.mts +27 -0
  21. package/build/politeness.mjs.map +1 -1
  22. package/build/{recipe-rECpzNa-.mjs → recipe-CRT_I64C.mjs} +3 -3
  23. package/build/{recipe-rECpzNa-.mjs.map → recipe-CRT_I64C.mjs.map} +1 -1
  24. package/build/{recipe-product-tVKjy4xu.mjs → recipe-product-n0fZKTxE.mjs} +4 -4
  25. package/build/{recipe-product-tVKjy4xu.mjs.map → recipe-product-n0fZKTxE.mjs.map} +1 -1
  26. package/build/{runtime-Hyr9qD0-.mjs → runtime-BYb320jE.mjs} +2 -2
  27. package/build/{runtime-Hyr9qD0-.mjs.map → runtime-BYb320jE.mjs.map} +1 -1
  28. package/build/{version-D1VudHdM.mjs → version-bKln1r5i.mjs} +2 -2
  29. package/build/{version-D1VudHdM.mjs.map → version-bKln1r5i.mjs.map} +1 -1
  30. package/build/{wacz-D_Onr46C.mjs → wacz-fsby_Qur.mjs} +3 -3
  31. package/build/{wacz-D_Onr46C.mjs.map → wacz-fsby_Qur.mjs.map} +1 -1
  32. package/build/{warc-l7lECYMZ.mjs → warc-C9VpeTjp.mjs} +2 -2
  33. package/build/{warc-l7lECYMZ.mjs.map → warc-C9VpeTjp.mjs.map} +1 -1
  34. package/package.json +3 -1
  35. package/build/open-BIvV3pHE.mjs.map +0 -1
package/build/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Outcome } from "./classify.mjs";
2
2
  import { AiInput, Signals } from "./signals.mjs";
3
- import { Clock, DEFAULT_POLICY, HostCounts, HostResult, HostStateStore, HostStop, MemoryHostStateStore, PolicyOptions, PolitenessPolicy, VALIDATOR_MEMO, ValidatorAnswer, ValidatorLimits, ValidatorMemo, ValidatorReport, ValidatorVerdict, nextValidatorMemo, realClock } from "./politeness.mjs";
3
+ import { Clock, DEFAULT_POLICY, HostCounts, HostResult, HostStateStore, HostStop, MemoryHostStateStore, PolicyOptions, PolitenessPolicy, QuotaRecord, QuotaStore, VALIDATOR_MEMO, ValidatorAnswer, ValidatorLimits, ValidatorMemo, ValidatorReport, ValidatorVerdict, nextValidatorMemo, realClock } from "./politeness.mjs";
4
4
  import { ALLOW_ALL, Robots, RobotsDecision, RobotsGroup, RobotsRule, RobotsSignal, decide, parseRobots } from "./robots.mjs";
5
5
  import { ScopeOptions, cacheKeyOf, canonicalUrl, siteOf } from "./urls.mjs";
6
6
  import { DAYS, Day, Hours, HoursComparison, Interval, Week, compareHours, describeWeek, disagreements, fromCompact, fromSchemaOrg, fromText, toHoursWeek } from "./hours.mjs";
@@ -3572,7 +3572,7 @@ export declare class WatchStore {
3572
3572
  */
3573
3573
  export declare const runWatch: (runtime: CrawlRuntime, source: WatchStore | (() => Promise<WatchStore>), options?: WatchRunnerOptions) => WatchRun;
3574
3574
  /** This is the version of the package. A test makes sure that it agrees with `package.json`. */
3575
- export declare const VERSION = "0.6.2";
3575
+ export declare const VERSION = "0.6.3";
3576
3576
  /** This is the product token that robots.txt rules match when an application gives no token. */
3577
3577
  export declare const DEFAULT_TOKEN = "PoliteCrawler";
3578
3578
  /** This page tells a site owner what the crawler is and how to control it. */
@@ -4340,12 +4340,15 @@ interface SqliteHostStateOptions {
4340
4340
  * The table `validators` keeps the validator memo of each host (`ValidatorMemo`), so the processes
4341
4341
  * share it and it stays after a restart. A file of version 0.1.0 gets the table when it opens.
4342
4342
  *
4343
+ * The table `quotas` keeps the record of each quota and key of `polite-crawler/api` (`QuotaStore`). Give
4344
+ * the store to `quotaGate`, so the count of a key stays after a restart and the processes share it.
4345
+ *
4343
4346
  * The state is not a projection of the capture log. A deletion of the file loses only the pace,
4344
4347
  * the counts, the stops and the memos, and the crawler starts them again.
4345
4348
  *
4346
4349
  * @beta
4347
4350
  */
4348
- export declare class SqliteHostStateStore implements HostStateStore {
4351
+ export declare class SqliteHostStateStore implements HostStateStore, QuotaStore {
4349
4352
  readonly path: string;
4350
4353
  private readonly db;
4351
4354
  private readonly statements;
@@ -4355,11 +4358,6 @@ export declare class SqliteHostStateStore implements HostStateStore {
4355
4358
  private closed;
4356
4359
  private readonly pollMs;
4357
4360
  constructor(path: string, options?: SqliteHostStateOptions);
4358
- /**
4359
- * This method makes the tables, or adds the tables of a later version to an older file. It is one
4360
- * transaction, so two processes that open one old file at the same time do not collide.
4361
- */
4362
- private migrate;
4363
4361
  private stmt;
4364
4362
  /** This method does one step in one transaction. */
4365
4363
  private step;
@@ -4375,6 +4373,12 @@ export declare class SqliteHostStateStore implements HostStateStore {
4375
4373
  reset(host?: string): void;
4376
4374
  validators(host: string): ValidatorMemo | undefined;
4377
4375
  noteValidators(host: string, report: ValidatorReport, now: number): ValidatorMemo;
4376
+ /**
4377
+ * This method changes the record of a quota and a key in one transaction. So two processes cannot
4378
+ * count one call twice or lose a call. A row that is not JSON goes to `step` as no record. The gate
4379
+ * of `quotaGate` examines each record that it gets.
4380
+ */
4381
+ changeQuota(quota: string, key: string, step: (record: QuotaRecord | undefined) => QuotaRecord): QuotaRecord;
4378
4382
  /** This value is the number of hosts that the store holds. */
4379
4383
  get size(): number;
4380
4384
  /** This method closes the file. A second close does nothing. */
@@ -4894,4 +4898,4 @@ interface WaczResult extends ArchiveCounts {
4894
4898
  * The export writes temporary files beside `out` and removes them at the end.
4895
4899
  */
4896
4900
  export declare const exportWacz: (source: ArchiveSource, options: ArchiveOptions) => Promise<WaczResult>;
4897
- export { ALLOW_ALL, type AiInput, type ArchiveCounts, type ArchiveFilter, type ArchiveOptions, type ArchiveSource, type Archived, type BlobStore, type CacheEntry, type CacheIndex, type CaptureFilter, type CaptureLogOptions, type CapturePayload, type CaptureReader, type CaptureRecord, type CaptureWriter, type CatchUpResult, type ChangeCommandOptions, type Changefreq, type ChunkOptions, type Clock, type CrawlEvent, type CrawlOptions, type CrawlPage, type CrawlRun, type CrawlRunOptions, type CrawlRuntime, type CrawlStop, type CrawlSummary, type CrawlerOptions, DAYS, DEFAULT_POLICY, type Daemon, type DaemonDue, type DaemonMcpHooks, type DaemonMcpHost, type DaemonMcpOptions, type DaemonMcpService, type DaemonOptions, type DaemonState, type DaemonStatus, type DaemonTask, type DaemonTick, type DamagedLine, type Day, type DiffHunk, type DiffInput, type DiffLimits, type DiffLine, type DiffOptions, type DiffResult, type DiffSide, type DiffSummary, type DigestOptions, type DirectoryKey, type DiscoverOptions, type DiscoverResult, type DiscoverRunOptions, type DiscoverSource, type DiscoverStop, type DiscoveredUrl, type Doc, type DocDigest, type DocIndexOptions, type DocInput, type DocVersion, type Duration, type EgressOptions, type EgressResolve, type EmbedCallOptions, type EmbedOptions, type EmbedResult, type EmbedStop, type Embedder, type EmbeddingModel, type ExtractOptions, type ExtractResult, type ExtractSource, type ExtractSummary, type ExtractedDoc, type Extractor, type FeatureExtractor, type FetchOptions, type FetchOutcome, type FetchRequest, type Fetched, type FieldCandidate, type FieldCheck, type FieldClaim, type FieldKind, type FieldResult, type FieldSpan, type FieldStatus, type FieldsChecked, type FileBlobStoreOptions, type FindIndexOptions, type FindOptions, type Found, type FusedRank, type HostCounts, type HostResult, type HostStateStore, type HostStop, type Hours, type HoursComparison, type HybridCrawler, type HybridFindOptions, type HybridOptions, type HybridSearch, type HybridSearchOptions, type IndexBuild, type IndexCounts, type Indexed, type Interval, type JsonRecord, type JwkInput, type KeyDirectory, type KeyInput, type Latest, MemoryHostStateStore, type MetaChange, type Money, type OllamaEmbedderOptions, type OpenOptions, type OpenedCrawler, type Outcome, type PageExtract, type PageLink, type PageOptions, type PageResult, type Passage, type PdfOptions, type PdfText, type PlaywrightRenderer, type PolicyOptions, type PoliteCrawler, type PolitenessPolicy, type Pooling, type ProductOptions, type ProductRead, type ProductResult, type ProductVariant, type RankMode, type RankOptions, type Ranked, type ReadOptions, type ReadResult, type ReadingIndex, type Recipe, type RecipeCapture, type RecipeDefinition, type RecipeDoc, type RecipeExtract, type RecipeRequest, type RecipeRequestOptions, type RecipeResult, type RecipeRunOptions, type RecipeTarget, type RecordInput, type RefusedReason, type ReindexResult, type RenderOptions, type RenderRequest, type Rendered, type Renderer, type RequestSigner, type Robots, type RobotsDecision, type RobotsGroup, type RobotsRule, type RobotsSignal, type RuntimeOptions, type ScanOptions, type ScheduleOptions, type ScheduleResult, type ScopeOptions, type SearchOptions, type SearchRank, type Signals, type SignatureAgentType, type SignatureCheck, type SignedRequest, type SitemapEntry, type SitemapKind, type SitemapLimits, type SitemapRead, type SqliteHostStateOptions, type StoreRuntime, type StoredChunk, type TextChunk, type TextDiff, type TransformersEmbedderOptions, type TransformersModule, type UrlPattern, VALIDATOR_MEMO, type ValidatorAnswer, type ValidatorLimits, type ValidatorMemo, type ValidatorReport, type ValidatorVerdict, type Variant, type VectorCounts, type VectorHit, type VectorStoreOptions, type VectorWrite, type VenueLink, type VenueLocation, type VenueOptions, type VenueOsm, type VenuePage, type VenueRead, type VenueReading, type VenueResult, type VenueSource, type Verified, type VerifyOptions, type VerifyResult, type VersionAt, type VersionChoice, type VersionText, type WaczResult, type WarcResult, type WatchEntry, type WatchEvent, type WatchKind, type WatchList, type WatchOptions, type WatchPending, type WatchRescheduleOptions, type WatchRow, type WatchRun, type WatchRunOptions, type WatchRunnerOptions, type WatchSchedule, type WatchState, type WatchStop, type WatchStoreOptions, type WatchSummary, type WatchUpdate, type WebArchive, type WebBotAuthOptions, type WebBotAuthSigner, type Week, type WordPart, bodyEncoding, cacheKeyOf, canonicalUrl, compareHours, decide, decodeBody, describeWeek, disagreements, extractPage, fromCompact, fromSchemaOrg, fromText, nextValidatorMemo, parseRobots, realClock, siteOf, toHoursWeek, typesOf };
4901
+ export { ALLOW_ALL, type AiInput, type ArchiveCounts, type ArchiveFilter, type ArchiveOptions, type ArchiveSource, type Archived, type BlobStore, type CacheEntry, type CacheIndex, type CaptureFilter, type CaptureLogOptions, type CapturePayload, type CaptureReader, type CaptureRecord, type CaptureWriter, type CatchUpResult, type ChangeCommandOptions, type Changefreq, type ChunkOptions, type Clock, type CrawlEvent, type CrawlOptions, type CrawlPage, type CrawlRun, type CrawlRunOptions, type CrawlRuntime, type CrawlStop, type CrawlSummary, type CrawlerOptions, DAYS, DEFAULT_POLICY, type Daemon, type DaemonDue, type DaemonMcpHooks, type DaemonMcpHost, type DaemonMcpOptions, type DaemonMcpService, type DaemonOptions, type DaemonState, type DaemonStatus, type DaemonTask, type DaemonTick, type DamagedLine, type Day, type DiffHunk, type DiffInput, type DiffLimits, type DiffLine, type DiffOptions, type DiffResult, type DiffSide, type DiffSummary, type DigestOptions, type DirectoryKey, type DiscoverOptions, type DiscoverResult, type DiscoverRunOptions, type DiscoverSource, type DiscoverStop, type DiscoveredUrl, type Doc, type DocDigest, type DocIndexOptions, type DocInput, type DocVersion, type Duration, type EgressOptions, type EgressResolve, type EmbedCallOptions, type EmbedOptions, type EmbedResult, type EmbedStop, type Embedder, type EmbeddingModel, type ExtractOptions, type ExtractResult, type ExtractSource, type ExtractSummary, type ExtractedDoc, type Extractor, type FeatureExtractor, type FetchOptions, type FetchOutcome, type FetchRequest, type Fetched, type FieldCandidate, type FieldCheck, type FieldClaim, type FieldKind, type FieldResult, type FieldSpan, type FieldStatus, type FieldsChecked, type FileBlobStoreOptions, type FindIndexOptions, type FindOptions, type Found, type FusedRank, type HostCounts, type HostResult, type HostStateStore, type HostStop, type Hours, type HoursComparison, type HybridCrawler, type HybridFindOptions, type HybridOptions, type HybridSearch, type HybridSearchOptions, type IndexBuild, type IndexCounts, type Indexed, type Interval, type JsonRecord, type JwkInput, type KeyDirectory, type KeyInput, type Latest, MemoryHostStateStore, type MetaChange, type Money, type OllamaEmbedderOptions, type OpenOptions, type OpenedCrawler, type Outcome, type PageExtract, type PageLink, type PageOptions, type PageResult, type Passage, type PdfOptions, type PdfText, type PlaywrightRenderer, type PolicyOptions, type PoliteCrawler, type PolitenessPolicy, type Pooling, type ProductOptions, type ProductRead, type ProductResult, type ProductVariant, type QuotaRecord, type QuotaStore, type RankMode, type RankOptions, type Ranked, type ReadOptions, type ReadResult, type ReadingIndex, type Recipe, type RecipeCapture, type RecipeDefinition, type RecipeDoc, type RecipeExtract, type RecipeRequest, type RecipeRequestOptions, type RecipeResult, type RecipeRunOptions, type RecipeTarget, type RecordInput, type RefusedReason, type ReindexResult, type RenderOptions, type RenderRequest, type Rendered, type Renderer, type RequestSigner, type Robots, type RobotsDecision, type RobotsGroup, type RobotsRule, type RobotsSignal, type RuntimeOptions, type ScanOptions, type ScheduleOptions, type ScheduleResult, type ScopeOptions, type SearchOptions, type SearchRank, type Signals, type SignatureAgentType, type SignatureCheck, type SignedRequest, type SitemapEntry, type SitemapKind, type SitemapLimits, type SitemapRead, type SqliteHostStateOptions, type StoreRuntime, type StoredChunk, type TextChunk, type TextDiff, type TransformersEmbedderOptions, type TransformersModule, type UrlPattern, VALIDATOR_MEMO, type ValidatorAnswer, type ValidatorLimits, type ValidatorMemo, type ValidatorReport, type ValidatorVerdict, type Variant, type VectorCounts, type VectorHit, type VectorStoreOptions, type VectorWrite, type VenueLink, type VenueLocation, type VenueOptions, type VenueOsm, type VenuePage, type VenueRead, type VenueReading, type VenueResult, type VenueSource, type Verified, type VerifyOptions, type VerifyResult, type VersionAt, type VersionChoice, type VersionText, type WaczResult, type WarcResult, type WatchEntry, type WatchEvent, type WatchKind, type WatchList, type WatchOptions, type WatchPending, type WatchRescheduleOptions, type WatchRow, type WatchRun, type WatchRunOptions, type WatchRunnerOptions, type WatchSchedule, type WatchState, type WatchStop, type WatchStoreOptions, type WatchSummary, type WatchUpdate, type WebArchive, type WebBotAuthOptions, type WebBotAuthSigner, type Week, type WordPart, bodyEncoding, cacheKeyOf, canonicalUrl, compareHours, decide, decodeBody, describeWeek, disagreements, extractPage, fromCompact, fromSchemaOrg, fromText, nextValidatorMemo, parseRobots, realClock, siteOf, toHoursWeek, typesOf };
package/build/index.mjs CHANGED
@@ -1,22 +1,22 @@
1
1
  import { n as FileBlobStore, t as CaptureLog } from "./log-CB5bADmd.mjs";
2
2
  import { t as browserMissing } from "./browser-C_dFMvO3.mjs";
3
- import { c as startDaemon, i as daemonStateFile, n as DAEMON_STATE_SCHEMA, o as readDaemonState, r as changeCommand, s as scheduleWatches, t as DAEMON_DEFAULTS } from "./daemon-BkJp3wXR.mjs";
4
- import { A as DEADLINE_NOTE, F as EgressRefused, I as egressLookup, M as makeRecord, O as CAPTURE_SCHEMA, S as readPdf, T as locate, _ as archivedDocId, a as fetchPage, c as isHeldBack, d as recordOverride, f as reindex, h as archiveExtractor, i as fetchAndIndex, j as DEFAULT_SECRET_PARAMS, k as Crawler, l as isoTime, m as versionAtTime, n as HELD_BACK, o as findDocuments, p as verifyQuote, r as catchUpIndex, s as heldBackMeta, t as Extractors, u as readDocument, x as isPdf } from "./runtime-Hyr9qD0-.mjs";
5
- import { a as formatDiff, n as diffDocument, r as diffTexts, t as DIFF_LIMITS } from "./diff-DcbpHrxv.mjs";
6
- import { A as NO_EMBEDDER, C as DISCOVER_LIMITS, D as readSitemap, E as feedDate, O as DocIndex, S as crawlSite, T as SITEMAP_LIMITS, _ as estimateTokens, b as SqliteHostStateStore, c as WatchStore, d as VectorStore, f as createHybridSearch, g as chunkTokensOf, h as chunkText, i as openCrawler, k as FAST_RANK_SHARE, l as runWatch, m as HYBRID_DEFAULTS, n as defaultUserAgent, o as WATCH_LIMITS, p as CHUNK_LIMITS, r as isMailbox, s as WATCH_SCHEMA, t as createRuntime, u as VECTORS_SCHEMA, v as fuseRanks, w as discoverSite, x as CRAWL_LIMITS, y as unitVector } from "./open-BIvV3pHE.mjs";
3
+ import { c as startDaemon, i as daemonStateFile, n as DAEMON_STATE_SCHEMA, o as readDaemonState, r as changeCommand, s as scheduleWatches, t as DAEMON_DEFAULTS } from "./daemon-Skkq_MW8.mjs";
4
+ import { A as DEADLINE_NOTE, F as EgressRefused, I as egressLookup, M as makeRecord, O as CAPTURE_SCHEMA, S as readPdf, T as locate, _ as archivedDocId, a as fetchPage, c as isHeldBack, d as recordOverride, f as reindex, h as archiveExtractor, i as fetchAndIndex, j as DEFAULT_SECRET_PARAMS, k as Crawler, l as isoTime, m as versionAtTime, n as HELD_BACK, o as findDocuments, p as verifyQuote, r as catchUpIndex, s as heldBackMeta, t as Extractors, u as readDocument, x as isPdf } from "./runtime-BYb320jE.mjs";
5
+ import { a as formatDiff, n as diffDocument, r as diffTexts, t as DIFF_LIMITS } from "./diff-BUGMvIqe.mjs";
6
+ import { A as NO_EMBEDDER, C as DISCOVER_LIMITS, D as readSitemap, E as feedDate, O as DocIndex, S as crawlSite, T as SITEMAP_LIMITS, _ as estimateTokens, b as SqliteHostStateStore, c as WatchStore, d as VectorStore, f as createHybridSearch, g as chunkTokensOf, h as chunkText, i as openCrawler, k as FAST_RANK_SHARE, l as runWatch, m as HYBRID_DEFAULTS, n as defaultUserAgent, o as WATCH_LIMITS, p as CHUNK_LIMITS, r as isMailbox, s as WATCH_SCHEMA, t as createRuntime, u as VECTORS_SCHEMA, v as fuseRanks, w as discoverSite, x as CRAWL_LIMITS, y as unitVector } from "./open-Cw4NVDBE.mjs";
7
7
  import { i as ollamaEmbedder, n as OLLAMA_MODELS, r as isLoopback, t as NO_OLLAMA } from "./ollama-B7eNmGhl.mjs";
8
8
  import { n as TRANSFORMERS_MODELS, r as transformersEmbedder, t as NO_TRANSFORMERS } from "./transformers-Cb-KaPge.mjs";
9
- import { n as checkFields, r as extractDocument, t as FIELD_KINDS } from "./extract-DpycIF0M.mjs";
9
+ import { n as checkFields, r as extractDocument, t as FIELD_KINDS } from "./extract-Cm_bF25a.mjs";
10
10
  import { DAYS, compareHours, describeWeek, disagreements, fromCompact, fromSchemaOrg, fromText, toHoursWeek } from "./hours.mjs";
11
11
  import { a as bodyEncoding, o as decodeBody, r as typesOf, t as extractPage } from "./html-CawWTgMQ.mjs";
12
12
  import { DEFAULT_POLICY, MemoryHostStateStore, VALIDATOR_MEMO, nextValidatorMemo, realClock } from "./politeness.mjs";
13
- import { a as readJson, i as defineRecipe, n as RESERVED_RECIPES, o as registerRecipe, s as runRecipe, t as RECIPE_LIMITS } from "./recipe-rECpzNa-.mjs";
14
- import { a as readAmount, c as locationMatches, d as readVenue, f as venueReadingsOf, i as productOf, l as namesVenue, n as pickProduct, o as readProduct, r as pickVariant, s as VENUE_LIMITS, t as PRODUCT_LIMITS, u as rankHoursLinks } from "./recipe-product-tVKjy4xu.mjs";
13
+ import { a as readJson, i as defineRecipe, n as RESERVED_RECIPES, o as registerRecipe, s as runRecipe, t as RECIPE_LIMITS } from "./recipe-CRT_I64C.mjs";
14
+ import { a as readAmount, c as locationMatches, d as readVenue, f as venueReadingsOf, i as productOf, l as namesVenue, n as pickProduct, o as readProduct, r as pickVariant, s as VENUE_LIMITS, t as PRODUCT_LIMITS, u as rankHoursLinks } from "./recipe-product-n0fZKTxE.mjs";
15
15
  import { n as RenderRefused, r as playwrightRenderer, t as NO_PLAYWRIGHT } from "./render-B0NrFDkJ.mjs";
16
16
  import { ALLOW_ALL, decide, parseRobots } from "./robots.mjs";
17
17
  import { cacheKeyOf, canonicalUrl, siteOf } from "./urls.mjs";
18
- import { i as durationMs, n as DEFAULT_TOKEN, r as VERSION, t as BOT_PAGE } from "./version-D1VudHdM.mjs";
18
+ import { i as durationMs, n as DEFAULT_TOKEN, r as VERSION, t as BOT_PAGE } from "./version-bKln1r5i.mjs";
19
19
  import { i as keyDirectory, n as KEY_DIRECTORY_TYPE, o as verifySignature, r as createWebBotAuthSigner, t as KEY_DIRECTORY_PATH } from "./webbotauth-DbiWmibz.mjs";
20
- import { t as exportWacz } from "./wacz-D_Onr46C.mjs";
21
- import { n as exportWarc } from "./warc-l7lECYMZ.mjs";
20
+ import { t as exportWacz } from "./wacz-fsby_Qur.mjs";
21
+ import { n as exportWarc } from "./warc-C9VpeTjp.mjs";
22
22
  export { ALLOW_ALL, BOT_PAGE, CAPTURE_SCHEMA, CHUNK_LIMITS, CRAWL_LIMITS, CaptureLog, Crawler, DAEMON_DEFAULTS, DAEMON_STATE_SCHEMA, DAYS, DEADLINE_NOTE, DEFAULT_POLICY, DEFAULT_SECRET_PARAMS, DEFAULT_TOKEN, DIFF_LIMITS, DISCOVER_LIMITS, DocIndex, EgressRefused, Extractors, FAST_RANK_SHARE, FIELD_KINDS, FileBlobStore, HELD_BACK, HYBRID_DEFAULTS, KEY_DIRECTORY_PATH, KEY_DIRECTORY_TYPE, MemoryHostStateStore, NO_EMBEDDER, NO_OLLAMA, NO_PLAYWRIGHT, NO_TRANSFORMERS, OLLAMA_MODELS, PRODUCT_LIMITS, RECIPE_LIMITS, RESERVED_RECIPES, RenderRefused, SITEMAP_LIMITS, SqliteHostStateStore, TRANSFORMERS_MODELS, VALIDATOR_MEMO, VECTORS_SCHEMA, VENUE_LIMITS, VERSION, VectorStore, WATCH_LIMITS, WATCH_SCHEMA, WatchStore, archiveExtractor, archivedDocId, bodyEncoding, browserMissing, cacheKeyOf, canonicalUrl, catchUpIndex, changeCommand, checkFields, chunkText, chunkTokensOf, compareHours, crawlSite, createHybridSearch, createRuntime, createWebBotAuthSigner, daemonStateFile, decide, decodeBody, defaultUserAgent, defineRecipe, describeWeek, diffDocument, diffTexts, disagreements, discoverSite, durationMs, egressLookup, estimateTokens, exportWacz, exportWarc, extractDocument, extractPage, feedDate, fetchAndIndex, fetchPage, findDocuments, formatDiff, fromCompact, fromSchemaOrg, fromText, fuseRanks, heldBackMeta, isHeldBack, isLoopback, isMailbox, isPdf, isoTime, keyDirectory, locate, locationMatches, makeRecord, namesVenue, nextValidatorMemo, ollamaEmbedder, openCrawler, parseRobots, pickProduct, pickVariant, playwrightRenderer, productOf, rankHoursLinks, readAmount, readDaemonState, readDocument, readJson, readPdf, readProduct, readSitemap, readVenue, realClock, recordOverride, registerRecipe, reindex, runRecipe, runWatch, scheduleWatches, siteOf, startDaemon, toHoursWeek, transformersEmbedder, typesOf, unitVector, venueReadingsOf, verifyQuote, verifySignature, versionAtTime };
@@ -1,21 +1,22 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
2
2
  import { r as checkedRenderer } from "./browser-C_dFMvO3.mjs";
3
- import { i as durationMs, n as DEFAULT_TOKEN, r as VERSION, t as BOT_PAGE } from "./version-D1VudHdM.mjs";
3
+ import { i as durationMs, n as DEFAULT_TOKEN, r as VERSION, t as BOT_PAGE } from "./version-bKln1r5i.mjs";
4
4
  import { n as FileBlobStore, t as CaptureLog } from "./log-CB5bADmd.mjs";
5
- import { A as DEADLINE_NOTE, C as fold, D as snippetOf, E as parseQuery, N as sha256$1, P as stableStringify, a as fetchPage, c as isHeldBack, f as reindex, i as fetchAndIndex, k as Crawler, l as isoTime, o as findDocuments, p as verifyQuote, r as catchUpIndex, t as Extractors, u as readDocument, y as archivedOf } from "./runtime-Hyr9qD0-.mjs";
6
- import { n as diffDocument, r as diffTexts } from "./diff-DcbpHrxv.mjs";
5
+ import { A as DEADLINE_NOTE, C as fold, D as snippetOf, E as parseQuery, N as sha256$1, P as stableStringify, a as fetchPage, c as isHeldBack, f as reindex, i as fetchAndIndex, k as Crawler, l as isoTime, o as findDocuments, p as verifyQuote, r as catchUpIndex, t as Extractors, u as readDocument, y as archivedOf } from "./runtime-BYb320jE.mjs";
6
+ import { n as diffDocument, r as diffTexts } from "./diff-BUGMvIqe.mjs";
7
7
  import { o as decodeBody, t as extractPage } from "./html-CawWTgMQ.mjs";
8
8
  import { cacheKeyOf, canonicalUrl, scopeTest } from "./urls.mjs";
9
- import { r as extractDocument } from "./extract-DpycIF0M.mjs";
9
+ import { r as extractDocument } from "./extract-Cm_bF25a.mjs";
10
10
  import { matchesPattern } from "./robots.mjs";
11
11
  import { MemoryHostStateStore, nextValidatorMemo, realClock } from "./politeness.mjs";
12
12
  import { r as playwrightRenderer } from "./render-B0NrFDkJ.mjs";
13
- import { o as registerRecipe } from "./recipe-rECpzNa-.mjs";
13
+ import { o as registerRecipe } from "./recipe-CRT_I64C.mjs";
14
14
  import { createHash, randomUUID } from "node:crypto";
15
15
  import { dirname, join } from "node:path";
16
16
  import { existsSync, lstatSync, mkdirSync, realpathSync, statSync } from "node:fs";
17
17
  import { createGunzip } from "node:zlib";
18
18
  import { DatabaseSync } from "node:sqlite";
19
+ import { migrate, openDatabase, transaction } from "@mark1russell7/sqlite";
19
20
  /** The search index reads this many characters of each text, at most. */
20
21
  const MAX_INDEX_CHARS = 2e5;
21
22
  /**
@@ -2166,6 +2167,36 @@ const NO_END = 9e15;
2166
2167
  const SHARED_WAIT_MS = 1e3;
2167
2168
  /** The store removes the rows of idle hosts after this many reservations. */
2168
2169
  const SWEEP_EVERY = 1e3;
2170
+ /**
2171
+ * These are the steps of the schema of the file, for `migrate` of `@mark1russell7/sqlite`. The
2172
+ * version of a file (`PRAGMA user_version`) is the count of its steps. Do not change a step: add a step.
2173
+ */
2174
+ const MIGRATIONS = [`CREATE TABLE IF NOT EXISTS hosts (
2175
+ host TEXT PRIMARY KEY,
2176
+ next_at REAL NOT NULL DEFAULT 0,
2177
+ leased_until REAL NOT NULL DEFAULT 0,
2178
+ owner TEXT,
2179
+ failures INTEGER NOT NULL DEFAULT 0,
2180
+ waits INTEGER NOT NULL DEFAULT 0,
2181
+ stop_until REAL,
2182
+ stop_reason TEXT
2183
+ );
2184
+ CREATE TABLE IF NOT EXISTS validators (
2185
+ host TEXT PRIMARY KEY,
2186
+ skip_etag INTEGER NOT NULL DEFAULT 0,
2187
+ etag TEXT NOT NULL DEFAULT 'unknown',
2188
+ last_modified TEXT NOT NULL DEFAULT 'unknown',
2189
+ etag_misses INTEGER NOT NULL DEFAULT 0,
2190
+ date_misses INTEGER NOT NULL DEFAULT 0,
2191
+ since_probe INTEGER NOT NULL DEFAULT 0,
2192
+ changed_at REAL NOT NULL DEFAULT 0
2193
+ )`, `CREATE TABLE IF NOT EXISTS quotas (
2194
+ quota TEXT NOT NULL,
2195
+ key TEXT NOT NULL,
2196
+ record TEXT NOT NULL,
2197
+ PRIMARY KEY (quota, key)
2198
+ )`];
2199
+ MIGRATIONS.length;
2169
2200
  const verdictOf = (value) => value === "works" || value === "fails" ? value : "unknown";
2170
2201
  const memoOf = (row) => ({
2171
2202
  skipEtag: row.skip_etag === 1,
@@ -2189,6 +2220,9 @@ const memoOf = (row) => ({
2189
2220
  * The table `validators` keeps the validator memo of each host (`ValidatorMemo`), so the processes
2190
2221
  * share it and it stays after a restart. A file of version 0.1.0 gets the table when it opens.
2191
2222
  *
2223
+ * The table `quotas` keeps the record of each quota and key of `polite-crawler/api` (`QuotaStore`). Give
2224
+ * the store to `quotaGate`, so the count of a key stays after a restart and the processes share it.
2225
+ *
2192
2226
  * The state is not a projection of the capture log. A deletion of the file loses only the pace,
2193
2227
  * the counts, the stops and the memos, and the crawler starts them again.
2194
2228
  *
@@ -2205,47 +2239,23 @@ var SqliteHostStateStore = class {
2205
2239
  pollMs;
2206
2240
  constructor(path, options = {}) {
2207
2241
  this.path = path;
2208
- if (path !== ":memory:") mkdirSync(dirname(path), {
2209
- recursive: true,
2210
- mode: 448
2211
- });
2212
2242
  this.pollMs = Math.max(1, Math.min(SHARED_WAIT_MS, options.pollMs ?? SHARED_WAIT_MS));
2213
- this.db = new DatabaseSync(path);
2214
- const wait = Math.max(0, Math.floor(options.busyTimeoutMs ?? 1e4));
2215
- this.db.exec(`PRAGMA busy_timeout = ${String(wait)};`);
2216
- if (path !== ":memory:") this.db.exec("PRAGMA journal_mode = WAL;");
2217
- this.db.exec("PRAGMA synchronous = NORMAL;");
2218
- this.migrate();
2219
- }
2220
- /**
2221
- * This method makes the tables, or adds the tables of a later version to an older file. It is one
2222
- * transaction, so two processes that open one old file at the same time do not collide.
2223
- */
2224
- migrate() {
2225
- this.step(() => {
2226
- this.db.exec(`CREATE TABLE IF NOT EXISTS hosts (
2227
- host TEXT PRIMARY KEY,
2228
- next_at REAL NOT NULL DEFAULT 0,
2229
- leased_until REAL NOT NULL DEFAULT 0,
2230
- owner TEXT,
2231
- failures INTEGER NOT NULL DEFAULT 0,
2232
- waits INTEGER NOT NULL DEFAULT 0,
2233
- stop_until REAL,
2234
- stop_reason TEXT
2235
- )`);
2236
- this.db.exec(`CREATE TABLE IF NOT EXISTS validators (
2237
- host TEXT PRIMARY KEY,
2238
- skip_etag INTEGER NOT NULL DEFAULT 0,
2239
- etag TEXT NOT NULL DEFAULT 'unknown',
2240
- last_modified TEXT NOT NULL DEFAULT 'unknown',
2241
- etag_misses INTEGER NOT NULL DEFAULT 0,
2242
- date_misses INTEGER NOT NULL DEFAULT 0,
2243
- since_probe INTEGER NOT NULL DEFAULT 0,
2244
- changed_at REAL NOT NULL DEFAULT 0
2245
- )`);
2246
- const { user_version: version } = this.db.prepare("PRAGMA user_version").get();
2247
- if (version < 1) this.db.exec(`PRAGMA user_version = ${String(1)}`);
2243
+ this.db = openDatabase(path, {
2244
+ wal: path !== ":memory:",
2245
+ synchronous: "NORMAL",
2246
+ busyTimeoutMs: Math.max(0, Math.floor(options.busyTimeoutMs ?? 1e4)),
2247
+ makeFolder: true,
2248
+ folderMode: 448
2248
2249
  });
2250
+ try {
2251
+ migrate(this.db, MIGRATIONS, {
2252
+ name: "host state store",
2253
+ newer: "keep"
2254
+ });
2255
+ } catch (error) {
2256
+ this.db.close();
2257
+ throw error;
2258
+ }
2249
2259
  }
2250
2260
  stmt(sql) {
2251
2261
  let statement = this.statements.get(sql);
@@ -2258,15 +2268,7 @@ var SqliteHostStateStore = class {
2258
2268
  /** This method does one step in one transaction. */
2259
2269
  step(work) {
2260
2270
  if (this.closed) throw new Error("the host state store is closed");
2261
- this.db.exec("BEGIN IMMEDIATE");
2262
- try {
2263
- const result = work();
2264
- this.db.exec("COMMIT");
2265
- return result;
2266
- } catch (error) {
2267
- if (this.db.isTransaction) this.db.exec("ROLLBACK");
2268
- throw error;
2269
- }
2271
+ return transaction(this.db, work);
2270
2272
  }
2271
2273
  row(host) {
2272
2274
  this.stmt("INSERT OR IGNORE INTO hosts (host) VALUES (?)").run(host);
@@ -2360,6 +2362,25 @@ var SqliteHostStateStore = class {
2360
2362
  return memo;
2361
2363
  });
2362
2364
  }
2365
+ /**
2366
+ * This method changes the record of a quota and a key in one transaction. So two processes cannot
2367
+ * count one call twice or lose a call. A row that is not JSON goes to `step` as no record. The gate
2368
+ * of `quotaGate` examines each record that it gets.
2369
+ */
2370
+ changeQuota(quota, key, step) {
2371
+ return this.step(() => {
2372
+ const row = this.stmt("SELECT record FROM quotas WHERE quota = ? AND key = ?").get(quota, key);
2373
+ let stored;
2374
+ try {
2375
+ stored = row === void 0 ? void 0 : JSON.parse(row.record);
2376
+ } catch {
2377
+ stored = void 0;
2378
+ }
2379
+ const next = step(stored);
2380
+ this.stmt("INSERT INTO quotas (quota, key, record) VALUES (?, ?, ?) ON CONFLICT(quota, key) DO UPDATE SET record = excluded.record").run(quota, key, JSON.stringify(next));
2381
+ return next;
2382
+ });
2383
+ }
2363
2384
  /** This value is the number of hosts that the store holds. */
2364
2385
  get size() {
2365
2386
  return this.stmt("SELECT count(*) AS n FROM hosts").get().n;
@@ -4339,4 +4360,4 @@ const openCrawler = (options) => {
4339
4360
  };
4340
4361
  export { NO_EMBEDDER as A, DISCOVER_LIMITS as C, readSitemap as D, feedDate as E, DocIndex as O, crawlSite as S, SITEMAP_LIMITS as T, estimateTokens as _, open_exports as a, SqliteHostStateStore as b, WatchStore as c, VectorStore as d, createHybridSearch as f, chunkTokensOf as g, chunkText as h, openCrawler as i, FAST_RANK_SHARE as k, runWatch as l, HYBRID_DEFAULTS as m, defaultUserAgent as n, WATCH_LIMITS as o, CHUNK_LIMITS as p, isMailbox as r, WATCH_SCHEMA as s, createRuntime as t, VECTORS_SCHEMA as u, fuseRanks as v, discoverSite as w, CRAWL_LIMITS as x, unitVector as y };
4341
4362
 
4342
- //# sourceMappingURL=open-BIvV3pHE.mjs.map
4363
+ //# sourceMappingURL=open-Cw4NVDBE.mjs.map