@haneinfo/import-export
v0.9.10
Published
Two-step draft imports and bounded snapshot exports using background jobs.
Readme
Import and export
CSV/xlsx transfers on the existing background-jobs worker, Form validator and list-view query port.
Install the import-export plugin alongside those mechanisms and StateMachine/definition-registry;
include prisma/import-export.prisma in the App schema and migrate it normally. No second queue or
transition engine is introduced. The duplicate-key update is staged with a minor changeset.
Imports are two separate jobs. POST /import-export/imports/preflight accepts machineCode,
format (csv or xlsx), contentBase64, and mapping (file header to subject Form field key).
Values are converted to Form field ids, then validated and normalized by Form. CSV requires UTF-8,
with or without BOM. Xlsx reads the first worksheet using ExcelJS. Headers must be unique text;
subform values can be JSON arrays of rows keyed by Form column ids. Formula cells and unsupported
active cell objects are refused. System state and all declared numbering columns are preflight
errors even when unmapped. Formula fields are calculated by Form and cannot be mapped.
Preflight creates no instances and reports global column errors and per-row diagnostics. Default
duplicate detection rejects subsequent identical normalized rows within the same upload; it
makes no universal business-key claim and does not compare unrelated existing instances.
A person confirms through POST /import-export/imports/:preflightJobId/confirm with
{ "confirmed": true }, using interactive authentication. The job creates one initial-state draft
for every valid row, reports invalid/failed rows separately, and never submits it. The authenticated
creator needs state-machine:instance:write at enqueue and execution. Changed definition versions
require another preflight. Results remain creator-only through background jobs.
Import holds a transaction-scoped lock for the preflight. Each row uses a savepoint; its draft and
unique (preflightId, rowNumber) receipt commit atomically with the job result. A failed/interrupted
attempt rolls back; replay or multiple confirmations reuse committed receipts. An operator may
manually reset an eligible failed/interrupted job to PENDING after ensuring no original worker is
still active. No automatic takeover of RUNNING jobs is provided. Corrected data uses a new preflight.
POST /import-export/exports accepts { format, source }, where source is { viewId } or
{ machineCode, query }. It exports all filtered readable rows (ignoring saved pagination), with
the saved/current sort and displayed columns. The handler uses one PostgreSQL RepeatableRead
snapshot, batches through ListViewPort.batchesFor, and streams rows into a file writer. It holds
bounded query batches plus capped output file bytes, not the complete instance result. A read-all
permission change between batches aborts the export. Snapshot data may be older than live data at
download time; it represents the handler's first database read, rather than enqueue time.
Only the creator downloads GET /import-export/exports/:jobId/file. Job results contain base64
file bytes, metadata, expiry and an authenticated relative downloadPath; no bearer link is issued.
An expired file cannot be downloaded even before cleanup. A periodic enqueuer schedules an expiry
background job; it removes expired file content, retaining metadata. It does not remove inbox/history
or existing JSON diagnostics. CSV has a UTF-8 BOM. Both formats neutralize formula-like text beginning with
=, +, -, @ (also after whitespace/control characters) with a leading apostrophe.
Configuration under runtime.importExport:
| Option | Default | Meaning |
| --- | ---: | --- |
| maxImportRows | 10000 | Maximum data rows per upload |
| maxExportRows | 10000 | Maximum complete result; over cap fails with 請縮小篩選 and no file |
| maxInputBytes | 10485760 | Input file bytes |
| maxXlsxUncompressedBytes | 104857600 | Total actual uncompressed ZIP bytes, including all entries |
| maxXlsxCompressionRatio | 200 | Maximum uncompressed-to-compressed byte ratio per ZIP entry |
| maxXlsxEntries | 1000 | Maximum ZIP entries, including directories |
| maxOutputBytes | 26214400 | Output file bytes before base64 |
| retentionHours | 24 | File lifetime from completion |
| batchSize | 200 | Query batch rows, maximum 500 |
| cleanupPollIntervalMs | 60000 | Expiry-job enqueue interval; maximum 2147483647 ms |
| cleanupWorkerEnabled | true | Enable periodic expiry-job enqueueing |
Xlsx imports inspect ZIP metadata and stream each entry to count actual expanded bytes before
ExcelJS loads the workbook. Over-limit archives fail with FILE_TOO_LARGE; malformed ZIPs fail
with INVALID_FILE. These ZIP limits do not bound the memory required to build a workbook model.
Register ImportExportMcpTools.commands({ scopeNamespace }) and BackgroundJobsMcpTools.commands({ scopeNamespace })
into the App's @haneinfo/commands registry. MCP exposes only start_import_preflight (<namespace>:instance:write),
start_instance_export (<namespace>:list-view:read) and the existing get_job_status
(<namespace>:jobs:read). It never exposes confirmation. Status wraps report/file/error data in
$userContent. Export has no new business permission: list-view enforces existing instance reads.
Libraries: ExcelJS 4.4.0, csv-parse 7.0.3 and csv-stringify 6.9.0, all MIT licensed. See the validation
report for package sizes, test evidence and outstanding maintainer policy choices.
Mutating tools additionally declare mutates: true. Both the generated catalog and MCP wire
annotations then report readOnlyHint: false, even for writes authorized by existing read scopes.
This conservative declaration cannot turn a write scope into a read-only operation.
Optional duplicate keys
HTTP preflight and MCP start_import_preflight accept optional duplicateKey, an array of 1 to 5 distinct top-level subject Form field keys, all present in mapping. Use keys rather than stable ids. See schemas/preflight.json for the input structure. INVALID_DUPLICATE_KEY rejects invalid keys (structural errors at enqueue, subject/mapping errors in the global preflight report).
With duplicateKey, compare Form-normalized values: later matching file rows get DUPLICATE_KEY_IN_FILE; keys present in any state of the same machine get DUPLICATE_KEY_EXISTING. Diagnostics contain the row number (path), key names (details.duplicateKey) and reason, never existing instance ids or contents. Empty components (including whitespace-only strings and empty arrays) skip key comparison while required validation still applies. Without duplicateKey, whole-row DUPLICATE_ROW behavior stays unchanged.
Existing-key detection uses parameterized PostgreSQL JSONB equality and EXISTS, bypassing read rules to prevent duplicates hidden by permissions. Reports remain creator-only. Confirmation uses the preflight result without rechecking keys: a concurrent insertion after preflight can therefore create a duplicate. This is advisory duplicate detection, not a database uniqueness constraint. MCP still provides no confirmation tool. Custom ImportExportStore implementations must implement duplicateExists(tx, machineCode, key), returning only a boolean for stable-id JSON values.
Import field discovery and error CSV files
GET /import-export/machines/:code/fields requires state-machine:instance:write and returns an array of { key, label, type, required }. It uses the published subject Form without definition-management permission. Only writable top-level fields are listed: formulas, numbered/system fields, layout containers and dividers are excluded. Root subforms remain importable as JSON, like preflight. Required reflects the definition flag, not conditional visibility. Labels are returned verbatim. Missing published metadata produces MACHINE_NOT_FOUND (404); absent subjects produce SUBJECT_REQUIRED (409).
Successful preflight and import job results additionally contain format: csv, rowCount (failed source rows), filename, mimeType, expiresAt, downloadPath and file (base64, until cleanup). GET /import-export/imports/:jobId/file downloads the error CSV for either job type. Use downloadPath from the result. The job creator alone can download; even ADMIN receives JOB_NOT_FOUND for somebody else's job. An unfinished, missing-file, wrong-kind or expired report receives IMPORT_REPORT_NOT_AVAILABLE (404). Empty error reports contain the header only.
CSV columns are $rowNumber, source., $errorCodes and $reasons. Source columns retain parsed input values, including unmapped cells; row numbers are the original parser row numbers. Multiple diagnostics share a source row, separated by semicolons. Global preflight column errors apply to every source row. Existing-key diagnostics say only 已存在; no existing instance id/content or arbitrary runtime diagnostic detail is copied into the CSV. Runtime row failures use a generic reason and retain the error code. Both headers and cells use the export writer with UTF-8 BOM and formula neutralization (including leading whitespace/control characters).
The same maxOutputBytes cap (default 26214400 bytes) applies to each error CSV. Exceeding it fails the entire job with EXPORT_FILE_TOO_LARGE: no partial file, and an import transaction rolls back all newly created drafts/receipts. Error files expire after retentionHours (default 24), are immediately unavailable at expiry, and cleanup removes file from export/preflight/import job results. Existing JSON diagnostics, parsed source rows, upload params and metadata retain the existing job retention behavior; this change expires the downloadable file only. A retained preflight can still be confirmed under existing version/authorization checks. Old preflights without source values can still be confirmed, but cannot reconstruct original columns for a new error report.
MCP still exposes only start_import_preflight and start_instance_export, plus get_job_status from background-jobs. The preflight description references the field-discovery endpoint. No confirm-import MCP tool exists.
Submitter name export
When the selected columns include $submitterId, CSV and xlsx insert $submitterName immediately after it. Other column selections remain unchanged; result columns lists the actual file headers in the same order. Names come only from authorized list-view batchesFor rows, through one identity-store lookup per batch in the export snapshot. Null names become empty cells. The existing BOM, string-only xlsx writing and formula-injection neutralization apply equally to names. Names are display metadata and cannot be filtered or sorted.
Instance access lists (implementation)
Implemented against approved decision 202610-c8e3.
Exports inherit personal and role instance access from ListView sourceFor/batchesFor, before counts and pagination. READ and WRITE both permit exporting readable instances, including permanent assigned/delegated readers. CSV/xlsx keep existing name and formula-injection handling. Snapshot exports also fail on role-name changes. Import global write checks, duplicate detection and human-only import confirmation remain unchanged; instance WRITE does not grant bulk import.
Upgrade the affected mechanisms together after applying the App migration. The maintained model, HTTP routes, read-only list_instance_access MCP tool, errors and permission contract are documented in @haneinfo/state-machine/agent-guide.md. Its prisma/instance-access.sql migrates the existing reader table to USER/ROLE, READ/WRITE and ASSIGNED/DELEGATED/GRANTED rows while retaining timestamps. The maintainer selected (instanceId, principalType, principalId, source) uniqueness. Manual grants are limited to 100 by default; permanent READ entries survive manual removal. See the package repository validation/equipment-loan/instance-access/report.md for SQL, tests and App restoration evidence.
Instance lifecycle (approved decision 202610-f1a8)
Implemented from approved decision 202610-f1a8. Upgrade state-machine, list-view, collaboration, attachments, import-export, assignment and timer together. No frontend, automatic archive or bulk lifecycle operations are included. Permanently purged data cannot be restored by this API: database and private file backups must cover the entire deletion retention period and be restored consistently.
Export resolves the existing list-view query, including archived EXCLUDE/INCLUDE/ONLY, for every batch and saved view. Deleted rows are always excluded. A filtered empty export has zero rows; it does not change the existing collection/export API into a single-instance endpoint. Existing completed export snapshots and their job-owned download retention are unchanged. Duplicate-key preflight adds deleted_at IS NULL independently of read access; archived rows still participate because the application exists. No archive predicate is applied to duplicate detection. Existing ImportRowReceipt rows have no instance foreign key and remain as idempotency/audit evidence after purge, preventing an old confirmed job retry from recreating a deliberately removed draft. Results are still job-owner-only. No new file storage or purge listener is needed for stored job results.
Data change log source (approved decision 202610-d9a5)
Confirmed imports create drafts with runtime.start({ ..., source: 'IMPORT' }) (plugin API
1.21.0), so @haneinfo/state-machine records their initial values as IMPORT rows attributed to the
confirming user, in the same row transaction as the draft and its receipt. Runtimes without the
change log ignore the field. Nothing else in import or export changes.
Localized field labels (approved decision 202610-a8d3)
Implemented under the approved decision. GET /import-export/machines/:code/fields resolves
Form labels in ?locale= (zh-TW or en, else INVALID_LOCALE/400) or Accept-Language, zh-TW by
default (fieldsFor(userId, code, { locale })). Mapping keys and export columns are unchanged.
Requires plugin API 1.26.0.
