// NIHO ホストスクリプトの試験器(host-script-sdk-v0.4)。 // このファイルは NIHO が生成します。直接編集せず、SDK を入れ直して更新してください。 // // - 外部通信・ファイル書き込みはしません(読むのは runFixture({ file }) で指定したスクリプトだけ)。 // - 本番と同じ上限・同じ呼び方で、storage / bookings / devices / fetch / drive / GCAL_FORMAT をメモリ上で再現します。 // - 隔離(サンドボックス)ではありません。自分で書いた、またはレビューしたコードだけを動かしてください。 import { readFile } from "node:fs/promises"; export const SDK_VERSION = "host-script-sdk-v0.4"; export const LIMITS = { "sourceMaxBytes": 131072, "configMaxBytes": 8192, "configStringMaxLength": 1024, "configMaxProperties": 30, "outputMaxBytes": 8192, "outputStringMaxLength": 512, "outputMaxProperties": 20, "logMaxBytes": 16384, "invocationMaxBytes": 65536, "invokeTimeoutMs": 15000, "minIntervalMinutes": 5, "maxIntervalMinutes": 43200, "driveTriggerInputMaxBytes": 49152, "storage": { "maxKeys": 500, "valueMaxBytes": 8192, "keyMaxLength": 200, "listMaxLimit": 100 }, "bookings": { "listMaxLimit": 100, "maxRangeDays": 93, "bookingIdMaxLength": 64 }, "devices": { "actionKeyMaxLength": 80, "domains": [ "MUSIC", "FACILITY", "LIGHT", "PLUG", "SCENE", "ACCESS" ] }, "fetch": { "bodyMaxCharacters": 32768, "bodyMaxBytes": 32768 }, "drive": { "rangeMaxLength": 200, "readMaxRows": 200, "readMaxColumns": 50, "writeMaxRows": 100, "writeMaxColumns": 50, "cellMaxCharacters": 2000, "responseMaxBytes": 49152, "documentResponseMaxBytes": 40960, "documentWriteMaxCharacters": 12000, "documentSearchMaxCharacters": 500, "documentDeleteMaxCharacters": 50000, "documentReplaceMaxOccurrences": 1000, "documentMaxResultCharacters": 200000 }, "gcal": { "outputLimits": { "summaryChars": 1024, "descriptionChars": 8192, "locationChars": 1024 }, "colorIds": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" ], "inputMaxBytes": 49152, "responseMaxBytes": 32768, "timeoutMs": 10000 } }; export const PERMISSIONS = ["devices.execute","fetch","storage","drive","bookings.read","gcal.format"]; const FORBIDDEN_SOURCE_PATTERN = new RegExp("(?:\\b(?:return|await)\\s+|=>\\s*|=\\s*)(?:fetch|WebSocket|XMLHttpRequest|eval|Function|importScripts)\\s*\\("); const EXPORT_DEFAULT_PATTERN = new RegExp("export\\s+default\\s+"); // 試験器だけの検査。本番の Worker は他のファイルを読めないため、import は配備の時点で失敗する。 // 手元では Node のモジュール(fs など)を読めてしまうので、先に止める。 const IMPORT_PATTERN = /(?:^|\n)[ \t]*import[ \t]+[\w*{"']|\bimport[ \t]*\(/; const DEFAULT_NOW = "2026-01-01T00:00:00.000Z"; const SAMPLE_GCAL_FORMAT_INPUT = { "version": 1, "spot": { "id": "sample-spot", "name": "NIHO鎌倉(見本)", "slug": "sample", "timeZone": "Asia/Tokyo" }, "booking": { "id": "sample-booking", "revision": 1, "bookingType": "PERSONAL", "spaceScope": "DESIGNATED_AREA", "zones": [ { "key": "meeting-room", "label": "会議室" } ], "placeLabel": "会議室", "startAt": "2026-12-01T01:00:00.000Z", "endAt": "2026-12-01T03:00:00.000Z", "start": { "date": "2026-12-01", "time": "10:00", "weekday": "火" }, "end": { "date": "2026-12-01", "time": "12:00", "weekday": "火" }, "headCount": 2, "title": "見本の利用", "memo": "窓側を希望", "staffMemo": null, "reservationStatus": "CONFIRMED", "isProvisional": false, "awaitingReply": false, "provisionalExpiresAt": null, "organizer": { "type": "SPOT", "name": "NIHO鎌倉(見本)" }, "creatorName": "見本 太郎", "options": [], "payment": { "status": "PAID", "billingLabel": "見本の決済", "totalAmount": 0, "manualPaymentMethod": null }, "createdAt": "2026-11-18T00:00:00.000Z", "updatedAt": "2026-11-18T00:00:00.000Z", "hostUrl": null }, "applicant": { "kind": "MEMBER", "fullName": "見本 太郎", "fullNameKana": "みほん たろう", "organization": null, "email": "taro@example.invalid", "phone": "090-0000-0000" }, "request": null, "member": { "userId": "sample-user", "displayName": "見本 太郎", "fullName": "見本 太郎", "email": "taro@example.invalid", "phone": "090-0000-0000", "spotContact": { "fullName": "見本 太郎", "email": "taro@example.invalid", "phone": "090-0000-0000" } }, "participants": [], "defaults": { "summary": "会議室:見本 太郎さん(2名)", "description": "場所:会議室\n利用者:見本 太郎さん\n人数:2名", "colorId": null }, "truncated": [] }; // ===== 本番の入口と共有するソース(host-script-runtime-shared.ts) ===== function createHostScriptEnv(input, call) { return Object.freeze({ config: Object.freeze(input.config && typeof input.config === "object" ? input.config : {}), devices: Object.freeze({ execute: (deviceInput) => call("devices.execute", deviceInput) }), drive: Object.freeze({ read: (range) => call("drive.execute", { operation: "read", fileHandle: "driveFile", range }), append: (operationKey, range, values) => call("drive.execute", { operation: "append", fileHandle: "driveFile", operationKey, range, values }), update: (operationKey, range, values) => call("drive.execute", { operation: "update", fileHandle: "driveFile", operationKey, range, values }), clear: (operationKey, range) => call("drive.execute", { operation: "clear", fileHandle: "driveFile", operationKey, range }), readDocument: () => call("drive.execute", { operation: "readDocument", fileHandle: "driveFile" }), appendText: (operationKey, text, requiredRevisionId) => call("drive.execute", { operation: "appendText", fileHandle: "driveFile", operationKey, text, requiredRevisionId }), insertText: (operationKey, index, text, requiredRevisionId) => call("drive.execute", { operation: "insertText", fileHandle: "driveFile", operationKey, index, text, requiredRevisionId }), replaceAllText: (operationKey, searchText, replaceText, matchCase = false, requiredRevisionId) => call("drive.execute", { operation: "replaceAllText", fileHandle: "driveFile", operationKey, searchText, replaceText, matchCase, requiredRevisionId }), deleteText: (operationKey, startIndex, endIndex, requiredRevisionId) => call("drive.execute", { operation: "deleteText", fileHandle: "driveFile", operationKey, startIndex, endIndex, requiredRevisionId }), }), bookings: Object.freeze({ list: (options) => call("bookings.execute", { operation: "list", ...(options && typeof options === "object" ? options : {}) }), get: async (bookingId) => (await call("bookings.execute", { operation: "get", bookingId })).booking, }), storage: Object.freeze({ get: async (key) => (await call("storage.execute", { operation: "get", key })).value, set: (key, value) => call("storage.execute", { operation: "set", key, value }), delete: (key) => call("storage.execute", { operation: "delete", key }), list: (options) => call("storage.execute", { operation: "list", ...(options && typeof options === "object" ? options : {}) }), }), fetch: (url, init) => call("fetch", { url: String(url), body: init && typeof init.body === "string" ? init.body : "", }), }); } async function callHostScriptUserFunction(userScript, input, env) { return typeof userScript === "function" ? input.invocationKind === "STUDIO_DRIVE_SCRIPT" ? await userScript(Object.freeze(input.triggerInput ?? null), env) : await userScript(env) : userScript && typeof userScript.fetch === "function" ? await userScript.fetch(undefined, env) : (() => { throw new Error("INVALID_USER_SCRIPT_EXPORT"); })(); } async function callHostScriptGcalFormat(userScript, input) { if (typeof userScript !== "function") throw new Error("INVALID_USER_SCRIPT_EXPORT"); return await userScript(Object.freeze(input.formatInput ?? null)); } // ===== ここから試験器 ===== const encoder = new TextEncoder(); const byteLength = (value) => encoder.encode(value).length; const cpLength = (value) => Array.from(value).length; const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value); const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key); const clone = (value) => (value === undefined ? undefined : JSON.parse(JSON.stringify(value))); const issue = (path, message) => ({ path, message }); const issuesText = (issues) => issues.map((item) => item.path + ": " + item.message).join(" / "); /** 本番の HostScriptError に相当。入力の検査・上限の失敗に使う。 */ export class HostScriptFailure extends Error { constructor(code, message, status = 400) { super(message); this.name = "HostScriptFailure"; this.code = code; this.status = status; } } /** * 試験器の capability の失敗。権限不足は "PERMISSION_REQUIRED"、その他は従来の * "CAPABILITY_FAILED_" としてユーザー関数へ返す。詳細は calls と error.hint へ出す。 */ export class CapabilityFailure extends Error { constructor(code, httpStatus, detail, issues) { super(code); this.name = "CapabilityFailure"; this.code = code; this.httpStatus = httpStatus; this.detail = detail; this.issues = issues ?? null; } } // 本番の runtimeErrorResponse: 404/401/403/503 以外の HostScriptError は 400 になる。 const hostHttpStatus = (status) => (status === 404 || status === 401 || status === 403 || status === 503 ? status : 400); const hostFailure = (code, detail, status = 400) => new CapabilityFailure(code, hostHttpStatus(status), detail); const validationFailure = (issues) => new CapabilityFailure("VALIDATION_ERROR", 400, issuesText(issues), issues); // ===== ソース・設定・出力の検査(host-script-service.ts と同じ規則) ===== export function checkSource(source) { if (typeof source !== "string" || source.length === 0) { return { ok: false, code: "INVALID_SOURCE", message: "スクリプトが空です" }; } if (byteLength(source) > LIMITS.sourceMaxBytes) { return { ok: false, code: "SOURCE_TOO_LARGE", message: "スクリプトは128KiB以下にしてください" }; } if (FORBIDDEN_SOURCE_PATTERN.test(source)) { return { ok: false, code: "UNSAFE_SOURCE", message: "外部通信はenv.fetchを使用してください" }; } if (!EXPORT_DEFAULT_PATTERN.test(source)) { return { ok: false, code: "INVALID_SOURCE", message: "export defaultの実行関数が必要です" }; } // コメントの中の「import」は数えない(本番の検査は生のソースを見るが、これは試験器だけの検査)。 const code = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"); if (IMPORT_PATTERN.test(code)) { return { ok: false, code: "EMULATOR_IMPORT_BLOCKED", message: "import は使えません(本番の Worker も他のファイルを読めません)。1 ファイルにまとめてください" }; } return { ok: true }; } const CONFIG_KEY_PATTERN = /^[a-z][a-zA-Z0-9_]{0,63}$/; const SCALAR_TYPES = ["string", "number", "integer", "boolean"]; function checkTrimmedString(value, path, issues, { min = 0, max }) { if (typeof value !== "string") { issues.push(issue(path, "文字列が必要です")); return null; } const trimmed = value.trim(); const length = cpLength(trimmed); if (length < min) issues.push(issue(path, min <= 1 ? "空にできません" : min + "文字以上にしてください")); if (length > max) issues.push(issue(path, max + "文字以下にしてください")); return trimmed; } function rejectUnknownKeys(object, allowed, path, issues) { for (const key of Object.keys(object)) { if (!allowed.includes(key)) issues.push(issue(path ? path + "." + key : key, "未知の項目です")); } } function isScalar(value) { return typeof value === "string" || typeof value === "number" || typeof value === "boolean"; } function checkRequiredList(required, properties, path, issues, max) { if (required === undefined) return; if (!Array.isArray(required) || required.some((key) => typeof key !== "string") || required.length > max) { issues.push(issue(path, "文字列の配列(" + max + "件以下)にしてください")); return; } if (new Set(required).size !== required.length) issues.push(issue(path, "requiredが重複しています")); for (const key of required) { if (!hasOwn(properties, key)) issues.push(issue(path, "requiredは宣言済みの項目のみ指定できます: " + key)); } } function checkSchemaShell(schema, path, issues, maxProperties, propertyChecker) { if (!isPlainObject(schema)) { issues.push(issue(path, "オブジェクトが必要です")); return; } rejectUnknownKeys(schema, ["type", "properties", "required"], path, issues); if (schema.type !== "object") issues.push(issue(path + ".type", "object を指定してください")); if (!isPlainObject(schema.properties)) { issues.push(issue(path + ".properties", "オブジェクトが必要です")); return; } const keys = Object.keys(schema.properties); if (keys.length > maxProperties) issues.push(issue(path + ".properties", "項目は" + maxProperties + "件以下です")); for (const key of keys) { const propertyPath = path + ".properties." + key; if (!CONFIG_KEY_PATTERN.test(key)) issues.push(issue(propertyPath, "キーは小文字で始まる英数字と_の64文字以下にしてください")); propertyChecker(schema.properties[key], propertyPath, issues); } checkRequiredList(schema.required, schema.properties, path + ".required", issues, maxProperties); } function checkEditableProperty(property, path, issues) { if (!isPlainObject(property)) { issues.push(issue(path, "オブジェクトが必要です")); return; } rejectUnknownKeys(property, ["type", "title", "description", "default", "enum", "minimum", "maximum"], path, issues); if (!SCALAR_TYPES.includes(property.type)) issues.push(issue(path + ".type", "string / number / integer / boolean のいずれかです")); checkTrimmedString(property.title, path + ".title", issues, { min: 1, max: 80 }); if (property.description !== undefined) checkTrimmedString(property.description, path + ".description", issues, { max: 240 }); if (property.default !== undefined && !isScalar(property.default)) issues.push(issue(path + ".default", "文字列・数値・真偽値のいずれかです")); if (property.enum !== undefined) { if (!Array.isArray(property.enum) || property.enum.length < 1 || property.enum.length > 50 || !property.enum.every(isScalar)) { issues.push(issue(path + ".enum", "文字列・数値・真偽値の配列(1〜50件)にしてください")); } } for (const bound of ["minimum", "maximum"]) { if (property[bound] !== undefined && (typeof property[bound] !== "number" || !Number.isFinite(property[bound]))) { issues.push(issue(path + "." + bound, "数値が必要です")); } } if (typeof property.minimum === "number" && typeof property.maximum === "number" && property.minimum > property.maximum) { issues.push(issue(path, "minimumはmaximum以下にしてください")); } } function isOutputEnumLabel(value) { if (typeof value !== "string") return false; const trimmed = value.trim(); const length = cpLength(trimmed); return length >= 1 && length <= 64 && !/[\u0000-\u001f\u007f@]/u.test(trimmed) && !trimmed.includes("://"); } function checkOutputProperty(property, path, issues) { if (!isPlainObject(property)) { issues.push(issue(path, "オブジェクトが必要です")); return; } rejectUnknownKeys(property, ["type", "title", "description", "enum"], path, issues); if (!SCALAR_TYPES.includes(property.type)) issues.push(issue(path + ".type", "string / number / integer / boolean のいずれかです")); checkTrimmedString(property.title, path + ".title", issues, { min: 1, max: 80 }); if (property.description !== undefined) checkTrimmedString(property.description, path + ".description", issues, { max: 240 }); if (property.enum !== undefined) { if (!Array.isArray(property.enum) || property.enum.length < 1 || property.enum.length > 50) { issues.push(issue(path + ".enum", "1〜50件の配列にしてください")); } else { for (const candidate of property.enum) { const matches = property.type === "integer" ? typeof candidate === "number" && Number.isInteger(candidate) : property.type === "number" ? typeof candidate === "number" && Number.isFinite(candidate) : typeof candidate === property.type; if (!matches) issues.push(issue(path + ".enum", "enumの型が出力型と一致しません")); if (typeof candidate === "string" && !isOutputEnumLabel(candidate)) { issues.push(issue(path + ".enum", "制御文字・メールアドレス・URLは使えません(1〜64文字): " + candidate)); } } } } else if (property.type !== "boolean") { issues.push(issue(path + ".enum", "分類出力にはenumが必要です")); } } /** script.json を本番の HostScriptUpsertInputSchema と同じ規則で検査する。問題が無ければ空配列。 */ export function checkManifest(manifest) { const issues = []; if (!isPlainObject(manifest)) return [issue("(script.json)", "オブジェクトが必要です")]; rejectUnknownKeys(manifest, ["$schema", "name", "description", "trigger", "permissions", "configSchema", "configValues", "outputSchema"], "", issues); checkTrimmedString(manifest.name, "name", issues, { min: 1, max: 80 }); checkTrimmedString(manifest.description, "description", issues, { min: 1, max: 500 }); const trigger = manifest.trigger; if (!isPlainObject(trigger)) { issues.push(issue("trigger", "SCHEDULE / STUDIO_EVENT / GCAL_FORMAT のいずれかを { kind } で指定してください")); } else if (trigger.kind === "SCHEDULE") { rejectUnknownKeys(trigger, ["kind", "intervalMinutes"], "trigger", issues); const minutes = trigger.intervalMinutes; if (!Number.isInteger(minutes) || minutes < LIMITS.minIntervalMinutes || minutes > LIMITS.maxIntervalMinutes) { issues.push(issue("trigger.intervalMinutes", LIMITS.minIntervalMinutes + "〜" + LIMITS.maxIntervalMinutes + "の整数(分)にしてください")); } } else if (trigger.kind === "STUDIO_EVENT" || trigger.kind === "GCAL_FORMAT") { rejectUnknownKeys(trigger, ["kind"], "trigger", issues); } else { issues.push(issue("trigger.kind", "SCHEDULE / STUDIO_EVENT / GCAL_FORMAT のいずれかです")); } if (manifest.permissions !== undefined) { const permissions = manifest.permissions; if (!Array.isArray(permissions) || permissions.length > PERMISSIONS.length || !permissions.every((item) => PERMISSIONS.includes(item))) { issues.push(issue("permissions", "使える権限: " + PERMISSIONS.join(", "))); } else if (new Set(permissions).size !== permissions.length) { issues.push(issue("permissions", "permissionsが重複しています")); } } // 候補版の送信(HostScriptManifestSchema・Issue #21588)と同じ規則: Google 予定の出力は gcal.format の宣言が必要。 // 権限が無いときの失敗(PERMISSION_MISSING)を試すときは、fixture の permissions で差し替える。 if (isPlainObject(trigger) && trigger.kind === "GCAL_FORMAT" && !(Array.isArray(manifest.permissions) && manifest.permissions.includes("gcal.format"))) { issues.push(issue("permissions", "GCAL_FORMATにはpermissionsのgcal.formatが必要です")); } if (manifest.configSchema !== undefined) { checkSchemaShell(manifest.configSchema, "configSchema", issues, LIMITS.configMaxProperties, checkEditableProperty); } if (manifest.outputSchema !== undefined && manifest.outputSchema !== null) { checkSchemaShell(manifest.outputSchema, "outputSchema", issues, LIMITS.outputMaxProperties, checkOutputProperty); if (byteLength(JSON.stringify(manifest.outputSchema)) > LIMITS.outputMaxBytes) issues.push(issue("outputSchema", "出力契約は8KiB以下にしてください")); } if (manifest.configValues !== undefined && !isPlainObject(manifest.configValues)) { issues.push(issue("configValues", "オブジェクトが必要です")); } if (issues.length === 0) { // 本番は保存のときに、設定の値(省略は空)が configSchema に合っているかも確かめる。 try { assertConfigValues(manifest.configSchema ?? { type: "object", properties: {} }, manifest.configValues ?? {}); } catch (error) { if (!(error instanceof HostScriptFailure)) throw error; issues.push(issue("configValues", error.message)); } } return issues; } /** 本番の assertConfigValues と同じ検査。違反があれば HostScriptFailure を投げる。 */ export function assertConfigValues(schema, values) { if (byteLength(JSON.stringify(values)) > LIMITS.configMaxBytes) throw new HostScriptFailure("CONFIG_TOO_LARGE", "設定値は8KiB以下にしてください"); const declared = isPlainObject(schema) && isPlainObject(schema.properties) ? schema.properties : {}; for (const key of Object.keys(values)) { const property = hasOwn(declared, key) ? declared[key] : undefined; if (!property) throw new HostScriptFailure("INVALID_CONFIG", "未宣言の設定です: " + key); const expected = property.type; const value = values[key]; const actual = typeof value; if ((expected === "number" || expected === "integer") ? actual !== "number" : actual !== expected) { throw new HostScriptFailure("INVALID_CONFIG", "設定値の型が違います: " + key); } if (expected === "integer" && !Number.isInteger(value)) throw new HostScriptFailure("INVALID_CONFIG", "整数が必要です: " + key); if (typeof value === "number" && !Number.isFinite(value)) throw new HostScriptFailure("INVALID_CONFIG", "有限の数値が必要です: " + key); if (typeof value === "string" && value.length > LIMITS.configStringMaxLength) throw new HostScriptFailure("INVALID_CONFIG", "設定値が長すぎます: " + key); if (property.enum && !property.enum.some((candidate) => candidate === value)) throw new HostScriptFailure("INVALID_CONFIG", "選択肢にない値です: " + key); if (typeof value === "number") { if (property.minimum !== undefined && value < property.minimum) throw new HostScriptFailure("INVALID_CONFIG", key + "は" + property.minimum + "以上にしてください"); if (property.maximum !== undefined && value > property.maximum) throw new HostScriptFailure("INVALID_CONFIG", key + "は" + property.maximum + "以下にしてください"); } } for (const key of schema && Array.isArray(schema.required) ? schema.required : []) { if (!hasOwn(values, key)) throw new HostScriptFailure("INVALID_CONFIG", "必須設定がありません: " + key); } } /** 本番の validateHostScriptOutput と同じ検査(出力契約 outputSchema を宣言した STUDIO_EVENT の戻り値)。 */ export function validateOutput(schema, output) { if (!output || typeof output !== "object" || Array.isArray(output)) { throw new HostScriptFailure("OUTPUT_SCHEMA_MISMATCH", "スクリプト出力が宣言と一致しません"); } if (byteLength(JSON.stringify(output)) > LIMITS.outputMaxBytes) throw new HostScriptFailure("OUTPUT_TOO_LARGE", "スクリプト出力は8KiB以下にしてください"); const properties = isPlainObject(schema) && isPlainObject(schema.properties) ? schema.properties : {}; const validated = {}; for (const [key, value] of Object.entries(output)) { const property = hasOwn(properties, key) ? properties[key] : undefined; if (!property) throw new HostScriptFailure("OUTPUT_SCHEMA_MISMATCH", "スクリプト出力に未宣言項目があります"); const actual = typeof value; const matchesType = property.type === "integer" ? actual === "number" && Number.isInteger(value) : property.type === "number" ? actual === "number" && Number.isFinite(value) : actual === property.type; if (!matchesType) throw new HostScriptFailure("OUTPUT_SCHEMA_MISMATCH", "スクリプト出力の型が宣言と一致しません"); if (typeof value === "string" && value.length > LIMITS.outputStringMaxLength) throw new HostScriptFailure("OUTPUT_TOO_LARGE", "スクリプト出力の文字列が長すぎます"); if (property.enum && !property.enum.some((allowed) => allowed === value)) throw new HostScriptFailure("OUTPUT_SCHEMA_MISMATCH", "スクリプト出力が宣言した選択肢にありません"); validated[key] = value; } for (const key of schema && Array.isArray(schema.required) ? schema.required : []) { if (!hasOwn(validated, key)) throw new HostScriptFailure("OUTPUT_SCHEMA_MISMATCH", "スクリプト出力に必須項目がありません"); } return validated; } /** Google 予定の出力(GCAL_FORMAT)の戻り値の検査。本番の parseGcalFormatOutput と同じ規則。 */ export function parseGcalFormatOutput(value) { const limits = LIMITS.gcal.outputLimits; if (!isPlainObject(value)) return { ok: false, reason: "(戻り値): オブジェクトで返してください" }; for (const key of Object.keys(value)) { if (!["summary", "description", "location", "colorId"].includes(key)) return { ok: false, reason: key + ": 未知の項目です" }; } const textProblem = (key, max, required) => { const text = value[key]; if (text === undefined && !required) return null; if (typeof text !== "string") return key + ": 文字列にしてください"; if (cpLength(text) > max) return key + ": " + max + "文字以下にしてください"; if (required && text.trim().length === 0) return key + " は空にできません"; return null; }; const problem = textProblem("summary", limits.summaryChars, true) ?? textProblem("description", limits.descriptionChars, false) ?? textProblem("location", limits.locationChars, false) ?? (value.colorId !== undefined && !LIMITS.gcal.colorIds.includes(value.colorId) ? "colorId: \"1\" から \"11\" の文字列にしてください" : null); if (problem) return { ok: false, reason: problem }; return { ok: true, output: { summary: value.summary, description: value.description ?? "", location: value.location ?? "", colorId: value.colorId ?? null, }, }; } // ===== capability の入力検査(本番の zod スキーマと同じ規則) ===== const STORAGE_KEY_CONTROL = /[\u0000-\u001f\u007f]/u; const ISO_DATETIME_WITH_OFFSET = /^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$/; function checkString(value, path, issues, { min = 0, max, trim = false }) { if (typeof value !== "string") { issues.push(issue(path, "文字列が必要です")); return null; } const text = trim ? value.trim() : value; const length = cpLength(text); if (length < min) issues.push(issue(path, "空にできません")); if (length > max) issues.push(issue(path, max + "文字以下にしてください")); return text; } function checkInteger(value, path, issues, min, max) { if (!Number.isInteger(value) || value < min || value > max) { issues.push(issue(path, min + "〜" + max + "の整数にしてください")); return false; } return true; } function checkStorageKey(value, path, issues) { const text = checkString(value, path, issues, { min: 1, max: LIMITS.storage.keyMaxLength }); if (text !== null && STORAGE_KEY_CONTROL.test(text)) issues.push(issue(path, "keyに制御文字は使えません")); } function checkDiscriminated(input, shapes, issues) { if (!isPlainObject(input)) { issues.push(issue("(入力)", "オブジェクトが必要です")); return null; } const operation = input.operation; if (typeof operation !== "string" || !hasOwn(shapes, operation)) { issues.push(issue("operation", "操作は " + Object.keys(shapes).join(" / ") + " のいずれかです")); return null; } const shape = shapes[operation]; rejectUnknownKeys(input, shape.keys, "", issues); for (const key of shape.required) { if (!hasOwn(input, key)) issues.push(issue(key, "必須です")); } return operation; } function parseStorageInput(input) { const issues = []; const operation = checkDiscriminated(input, { get: { keys: ["operation", "key"], required: ["key"] }, set: { keys: ["operation", "key", "value"], required: ["key", "value"] }, delete: { keys: ["operation", "key"], required: ["key"] }, list: { keys: ["operation", "prefix", "cursor", "limit"], required: [] }, }, issues); if (operation === null) return { ok: false, issues }; if (hasOwn(input, "key")) checkStorageKey(input.key, "key", issues); if (operation === "list") { if (hasOwn(input, "prefix")) checkString(input.prefix, "prefix", issues, { max: LIMITS.storage.keyMaxLength }); if (hasOwn(input, "cursor")) checkStorageKey(input.cursor, "cursor", issues); if (hasOwn(input, "limit")) checkInteger(input.limit, "limit", issues, 1, LIMITS.storage.listMaxLimit); } return issues.length ? { ok: false, issues } : { ok: true, input }; } function parseBookingsInput(input) { const issues = []; const operation = checkDiscriminated(input, { list: { keys: ["operation", "from", "to", "source", "includeDeleted", "updatedSince", "cursor", "limit"], required: ["from", "to"] }, get: { keys: ["operation", "bookingId"], required: ["bookingId"] }, }, issues); if (operation === null) return { ok: false, issues }; if (operation === "get") { checkString(input.bookingId, "bookingId", issues, { min: 1, max: LIMITS.bookings.bookingIdMaxLength }); } else { for (const key of ["from", "to", "updatedSince"]) { if (hasOwn(input, key) && !(typeof input[key] === "string" && ISO_DATETIME_WITH_OFFSET.test(input[key]))) { issues.push(issue(key, "タイムゾーン付きのISO 8601日時にしてください(例: 2026-11-15T00:00:00+09:00)")); } } if (hasOwn(input, "source") && input.source !== "NIHOAPP" && input.source !== "EXTERNAL_GCAL") issues.push(issue("source", "NIHOAPP / EXTERNAL_GCAL のいずれかです")); if (hasOwn(input, "includeDeleted") && typeof input.includeDeleted !== "boolean") issues.push(issue("includeDeleted", "真偽値にしてください")); if (hasOwn(input, "cursor")) checkString(input.cursor, "cursor", issues, { min: 1, max: 200 }); if (hasOwn(input, "limit")) checkInteger(input.limit, "limit", issues, 1, LIMITS.bookings.listMaxLimit); } return issues.length ? { ok: false, issues } : { ok: true, input }; } const DEVICE_DOMAINS = LIMITS.devices.domains; const AC_MODES = ["auto", "cool", "dry", "fan", "heat"]; const AC_FAN_SPEEDS = ["auto", "low", "medium", "high"]; function parseDeviceInput(input) { const issues = []; if (!isPlainObject(input)) return { ok: false, issues: [issue("(入力)", "オブジェクトが必要です")] }; rejectUnknownKeys(input, ["domain", "actionKey", "acControl", "actionParams"], "", issues); if (!DEVICE_DOMAINS.includes(input.domain)) issues.push(issue("domain", DEVICE_DOMAINS.join(" / ") + " のいずれかです")); const actionKey = checkString(input.actionKey, "actionKey", issues, { min: 1, max: LIMITS.devices.actionKeyMaxLength, trim: true }); if (input.acControl !== undefined) { const control = input.acControl; if (!isPlainObject(control)) { issues.push(issue("acControl", "オブジェクトが必要です")); } else { rejectUnknownKeys(control, ["temperature", "mode", "fanSpeed"], "acControl", issues); if (typeof control.temperature !== "number" || !(control.temperature >= 16 && control.temperature <= 30)) issues.push(issue("acControl.temperature", "16〜30の数値にしてください")); if (!AC_MODES.includes(control.mode)) issues.push(issue("acControl.mode", AC_MODES.join(" / ") + " のいずれかです")); if (!AC_FAN_SPEEDS.includes(control.fanSpeed)) issues.push(issue("acControl.fanSpeed", AC_FAN_SPEEDS.join(" / ") + " のいずれかです")); } } if (input.actionParams !== undefined) { if (!isPlainObject(input.actionParams)) { issues.push(issue("actionParams", "オブジェクトが必要です")); } else { for (const [key, value] of Object.entries(input.actionParams)) { if (!(value === null || isScalar(value))) issues.push(issue("actionParams." + key, "文字列・数値・真偽値・nullのいずれかです")); } } } return issues.length ? { ok: false, issues } : { ok: true, input: { ...input, actionKey } }; } function parseFetchInput(input) { const issues = []; if (!isPlainObject(input)) return { ok: false, issues: [issue("(入力)", "オブジェクトが必要です")] }; rejectUnknownKeys(input, ["url", "body"], "", issues); if (typeof input.url !== "string") { issues.push(issue("url", "文字列が必要です")); } else { try { new URL(input.url); } catch { issues.push(issue("url", "URLとして解釈できません")); } } if (input.body !== undefined) checkString(input.body, "body", issues, { max: LIMITS.fetch.bodyMaxCharacters }); return issues.length ? { ok: false, issues } : { ok: true, input }; } function driveColumnNumber(column) { return Array.from(column.toUpperCase()).reduce((value, character) => value * 26 + character.charCodeAt(0) - 64, 0); } function columnLetters(number) { let value = Math.max(1, number); let name = ""; while (value > 0) { const remainder = (value - 1) % 26; name = String.fromCharCode(65 + remainder) + name; value = Math.floor((value - 1) / 26); } return name; } /** 本番の validateBoundedDriveRange と同じ。問題があれば理由、無ければ null。 */ function validateBoundedDriveRange(range, operation) { const separator = range.lastIndexOf("!"); if (separator === 0 || separator === range.length - 1) return "rangeのシート名またはA1範囲が不正です"; const a1 = separator >= 0 ? range.slice(separator + 1) : range; const limits = LIMITS.drive; if (operation === "append") { const columnRange = /^([A-Za-z]{1,3}):([A-Za-z]{1,3})$/.exec(a1); if (columnRange) { const firstColumn = driveColumnNumber(columnRange[1]); const lastColumn = driveColumnNumber(columnRange[2]); if (lastColumn < firstColumn || lastColumn - firstColumn + 1 > limits.writeMaxColumns) { return "appendのrangeは" + limits.writeMaxColumns + "列以内にしてください"; } return null; } } const cellRange = /^([A-Za-z]{1,3})([1-9][0-9]{0,6})(?::([A-Za-z]{1,3})([1-9][0-9]{0,6}))?$/.exec(a1); if (!cellRange) { return operation === "append" ? "appendのrangeはA:CまたはA1:C100形式で指定してください" : "rangeはA1:C100のような有限のセル範囲で指定してください"; } const firstColumn = driveColumnNumber(cellRange[1]); const lastColumn = driveColumnNumber(cellRange[3] ?? cellRange[1]); const firstRow = Number(cellRange[2]); const lastRow = Number(cellRange[4] ?? cellRange[2]); const maxRows = operation === "read" ? limits.readMaxRows : limits.writeMaxRows; const maxColumns = operation === "read" ? limits.readMaxColumns : limits.writeMaxColumns; if (lastColumn < firstColumn || lastRow < firstRow || lastColumn - firstColumn + 1 > maxColumns || lastRow - firstRow + 1 > maxRows) { return operation + "のrangeは" + maxRows + "行×" + maxColumns + "列以内にしてください"; } return null; } function checkDriveCell(value, path, issues) { if (typeof value === "string") { if (cpLength(value) > LIMITS.drive.cellMaxCharacters) issues.push(issue(path, LIMITS.drive.cellMaxCharacters + "文字以下にしてください")); } else if (!(value === null || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))) { issues.push(issue(path, "文字列・数値・真偽値・nullのいずれかです")); } } function checkDriveValues(values, issues) { if (!Array.isArray(values) || values.length < 1 || values.length > LIMITS.drive.writeMaxRows) { issues.push(issue("values", "1〜" + LIMITS.drive.writeMaxRows + "行の配列にしてください")); return; } values.forEach((row, rowIndex) => { if (!Array.isArray(row) || row.length > LIMITS.drive.writeMaxColumns) { issues.push(issue("values[" + rowIndex + "]", LIMITS.drive.writeMaxColumns + "列以下の配列にしてください")); return; } row.forEach((cell, columnIndex) => checkDriveCell(cell, "values[" + rowIndex + "][" + columnIndex + "]", issues)); }); } function parseDriveInput(input) { const issues = []; const base = ["operation", "fileHandle"]; const keyed = [...base, "operationKey"]; const operation = checkDiscriminated(input, { read: { keys: [...base, "range"], required: ["fileHandle", "range"] }, append: { keys: [...keyed, "range", "values"], required: ["fileHandle", "operationKey", "range", "values"] }, update: { keys: [...keyed, "range", "values"], required: ["fileHandle", "operationKey", "range", "values"] }, clear: { keys: [...keyed, "range"], required: ["fileHandle", "operationKey", "range"] }, readDocument: { keys: base, required: ["fileHandle"] }, appendText: { keys: [...keyed, "text", "requiredRevisionId"], required: ["fileHandle", "operationKey", "text"] }, insertText: { keys: [...keyed, "index", "text", "requiredRevisionId"], required: ["fileHandle", "operationKey", "index", "text", "requiredRevisionId"] }, replaceAllText: { keys: [...keyed, "searchText", "replaceText", "matchCase", "requiredRevisionId"], required: ["fileHandle", "operationKey", "searchText", "replaceText"] }, deleteText: { keys: [...keyed, "startIndex", "endIndex", "requiredRevisionId"], required: ["fileHandle", "operationKey", "startIndex", "endIndex", "requiredRevisionId"] }, }, issues); if (operation === null) return { ok: false, issues }; const limits = LIMITS.drive; const parsed = { ...input }; if (hasOwn(input, "fileHandle") && input.fileHandle !== "driveFile") issues.push(issue("fileHandle", "driveFile を指定してください")); if (hasOwn(input, "operationKey")) parsed.operationKey = checkString(input.operationKey, "operationKey", issues, { min: 1, max: 120, trim: true }); if (hasOwn(input, "range")) { parsed.range = checkString(input.range, "range", issues, { min: 1, max: limits.rangeMaxLength, trim: true }); if (typeof parsed.range === "string" && parsed.range.length > 0 && cpLength(parsed.range) <= limits.rangeMaxLength) { const message = validateBoundedDriveRange(parsed.range, operation); if (message) issues.push(issue("range", message)); } } if (hasOwn(input, "values")) checkDriveValues(input.values, issues); if (hasOwn(input, "requiredRevisionId")) parsed.requiredRevisionId = checkString(input.requiredRevisionId, "requiredRevisionId", issues, { min: 1, max: 256, trim: true }); if (operation === "appendText" || operation === "insertText") { checkString(input.text, "text", issues, { min: 1, max: limits.documentWriteMaxCharacters }); } if (operation === "insertText") checkInteger(input.index, "index", issues, 1, 1000000); if (operation === "replaceAllText") { checkString(input.searchText, "searchText", issues, { min: 1, max: limits.documentSearchMaxCharacters }); checkString(input.replaceText, "replaceText", issues, { max: limits.documentWriteMaxCharacters }); if (hasOwn(input, "matchCase") && typeof input.matchCase !== "boolean") issues.push(issue("matchCase", "真偽値にしてください")); parsed.matchCase = input.matchCase ?? false; } if (operation === "deleteText") { const startOk = checkInteger(input.startIndex, "startIndex", issues, 1, 1000000); const endOk = checkInteger(input.endIndex, "endIndex", issues, 1, 1000000); if (startOk && endOk && (input.endIndex <= input.startIndex || input.endIndex - input.startIndex > limits.documentDeleteMaxCharacters)) { issues.push(issue("endIndex", "削除範囲は1文字以上" + limits.documentDeleteMaxCharacters + "文字以内にしてください")); } } return issues.length ? { ok: false, issues } : { ok: true, input: parsed }; } // ===== セッション(fixture の state をメモリに持つ) ===== const BOOKING_SOURCES = ["NIHOAPP", "EXTERNAL_GCAL"]; function fixtureError(message) { return new HostScriptFailure("FIXTURE_INVALID", message); } function toIso(value, label) { const date = new Date(value); if (typeof value !== "string" || Number.isNaN(date.getTime())) throw fixtureError(label + " は ISO 8601 の日時にしてください"); return date.toISOString(); } function normalizeBooking(raw, index, nowIso) { const label = "state.bookings[" + index + "]"; if (!isPlainObject(raw)) throw fixtureError(label + " はオブジェクトにしてください"); if (typeof raw.id !== "string" || raw.id.length === 0) throw fixtureError(label + ".id が必要です"); const startAt = toIso(raw.startAt, label + ".startAt"); const endAt = toIso(raw.endAt, label + ".endAt"); const source = raw.source ?? "NIHOAPP"; if (!BOOKING_SOURCES.includes(source)) throw fixtureError(label + ".source は NIHOAPP / EXTERNAL_GCAL のいずれかです"); const updatedAt = raw.updatedAt === undefined ? nowIso : toIso(raw.updatedAt, label + ".updatedAt"); const deletedAt = raw.deletedAt !== undefined && raw.deletedAt !== null ? toIso(raw.deletedAt, label + ".deletedAt") : raw.deleted === true ? updatedAt : null; return { id: raw.id, revision: raw.revision ?? 1, source, externalProvider: raw.externalProvider ?? null, externalCalendarId: raw.externalCalendarId ?? null, externalEventId: raw.externalEventId ?? null, bookingType: raw.bookingType ?? "PERSONAL", spaceScope: raw.spaceScope ?? "DESIGNATED_AREA", reservationStatus: raw.reservationStatus ?? "CONFIRMED", title: raw.title ?? null, description: raw.description ?? null, startAt, endAt, useZone: raw.useZone ?? [], headCount: raw.headCount ?? 1, externalHeadCount: raw.externalHeadCount ?? null, seriesId: raw.seriesId ?? null, createdAt: raw.createdAt === undefined ? nowIso : toIso(raw.createdAt, label + ".createdAt"), updatedAt, deletedAt, }; } function projectBooking(row) { return { id: row.id, revision: row.revision, source: row.source, externalProvider: row.externalProvider, externalCalendarId: row.externalCalendarId, externalEventId: row.externalEventId, bookingType: row.bookingType, spaceScope: row.spaceScope, reservationStatus: row.reservationStatus, title: row.title, description: row.description, startAt: row.startAt, endAt: row.endAt, useZone: clone(row.useZone), headCount: row.headCount, externalHeadCount: row.externalHeadCount, seriesId: row.seriesId, createdAt: row.createdAt, updatedAt: row.updatedAt, deleted: row.deletedAt !== null, deletedAt: row.deletedAt, }; } function normalizeDrive(raw, nowIso) { if (raw === undefined || raw === null) return null; if (!isPlainObject(raw)) throw fixtureError("state.drive はオブジェクトにしてください"); const kind = raw.kind ?? (raw.document ? "DOCUMENT" : "SPREADSHEET"); if (kind !== "SPREADSHEET" && kind !== "DOCUMENT") throw fixtureError("state.drive.kind は SPREADSHEET / DOCUMENT のいずれかです"); const sheets = {}; if (kind === "SPREADSHEET") { const given = isPlainObject(raw.sheets) ? raw.sheets : { Sheet1: [] }; for (const [name, rows] of Object.entries(given)) { if (!Array.isArray(rows) || rows.some((row) => !Array.isArray(row))) throw fixtureError("state.drive.sheets." + name + " は行の配列(配列の配列)にしてください"); sheets[name] = clone(rows); } if (Object.keys(sheets).length === 0) sheets.Sheet1 = []; } let document = null; if (kind === "DOCUMENT") { const given = isPlainObject(raw.document) ? raw.document : {}; const text = typeof given.text === "string" ? given.text : ""; document = { text: text.endsWith("\n") ? text : text + "\n", revisionId: typeof given.revisionId === "string" ? given.revisionId : "emulator-rev-1", revisionCount: 1 }; } return { kind, sheets, document, nowIso }; } /** fixture の state からセッションを作る。lower-level API(通常は runFixture を使う)。 */ export function createSession({ now = DEFAULT_NOW, permissions = [], invocationKind = "SCHEDULE", state = {} } = {}) { const nowDate = new Date(now); if (Number.isNaN(nowDate.getTime())) throw fixtureError("now は ISO 8601 の日時にしてください"); const nowIso = nowDate.toISOString(); if (!isPlainObject(state)) throw fixtureError("state はオブジェクトにしてください"); const bookings = (state.bookings === undefined ? [] : state.bookings); if (!Array.isArray(bookings)) throw fixtureError("state.bookings は配列にしてください"); const storage = new Map(); if (state.storage !== undefined) { if (!isPlainObject(state.storage)) throw fixtureError("state.storage はオブジェクトにしてください"); for (const [key, value] of Object.entries(state.storage)) storage.set(key, { value: clone(value), updatedAt: nowIso }); } for (const key of ["devices", "fetch"]) { if (state[key] !== undefined && !isPlainObject(state[key])) throw fixtureError("state." + key + " はオブジェクトにしてください"); } return { now: nowDate, nowIso, permissions: [...permissions], invocationKind, bookings: bookings.map((row, index) => normalizeBooking(row, index, nowIso)), storage, drive: normalizeDrive(state.drive, nowIso), driveOperations: new Map(), devices: state.devices ?? {}, fetchResponses: state.fetch ?? {}, calls: [], }; } function requirePermission(session, permission) { if (!session.permissions.includes(permission)) { throw hostFailure("PERMISSION_REQUIRED", "このスクリプトの公開版は" + permission + "を宣言していません。permissionsに追加して公開し直してください", 403); } } // ===== storage ===== function sortedStorageKeys(session) { return Array.from(session.storage.keys()).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); } function executeStorage(session, input) { if (input.operation === "get") { const entry = session.storage.get(input.key); return entry ? { key: input.key, found: true, value: clone(entry.value), updatedAt: entry.updatedAt } : { key: input.key, found: false, value: null, updatedAt: null }; } if (input.operation === "delete") return { key: input.key, deleted: session.storage.delete(input.key) }; if (input.operation === "list") { const limit = input.limit ?? LIMITS.storage.listMaxLimit; const matched = sortedStorageKeys(session).filter((key) => (!input.prefix || key.startsWith(input.prefix)) && (!input.cursor || key > input.cursor)); const page = matched.slice(0, limit); return { keys: page.map((key) => ({ key, updatedAt: session.storage.get(key).updatedAt })), nextCursor: matched.length > limit ? page[page.length - 1] ?? null : null, }; } if (input.value === undefined) throw hostFailure("STORAGE_VALUE_INVALID", "保存する値がありません。削除はstorage.deleteを使ってください"); let encoded; try { encoded = JSON.stringify(input.value); } catch { throw hostFailure("STORAGE_VALUE_INVALID", "JSONとして保存できる値にしてください"); } if (byteLength(encoded) > LIMITS.storage.valueMaxBytes) throw hostFailure("STORAGE_VALUE_TOO_LARGE", "保存する値は8KiB以下にしてください", 413); if (!session.storage.has(input.key) && session.storage.size >= LIMITS.storage.maxKeys) { throw hostFailure("STORAGE_KEY_LIMIT_EXCEEDED", "保存できるkeyは" + LIMITS.storage.maxKeys + "件までです。不要なkeyをstorage.deleteで消してください", 409); } session.storage.set(input.key, { value: JSON.parse(encoded), updatedAt: session.nowIso }); return { key: input.key, saved: true, updatedAt: session.nowIso }; } // ===== bookings ===== function encodeBookingCursor(row) { return Buffer.from(JSON.stringify([row.startAt, row.id]), "utf8").toString("base64url"); } function decodeBookingCursor(cursor) { try { const decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")); if (Array.isArray(decoded) && decoded.length === 2 && typeof decoded[0] === "string" && typeof decoded[1] === "string") { const startAt = new Date(decoded[0]); if (!Number.isNaN(startAt.getTime()) && decoded[1].length > 0) return { startAt: startAt.getTime(), id: decoded[1] }; } } catch { // 下で同じエラーにする } throw hostFailure("BOOKINGS_CURSOR_INVALID", "cursorは前回のnextCursorをそのまま渡してください"); } function executeBookings(session, input) { requirePermission(session, "bookings.read"); if (input.operation === "get") { const row = session.bookings.find((booking) => booking.id === input.bookingId); return { booking: row ? projectBooking(row) : null }; } const from = new Date(input.from).getTime(); const to = new Date(input.to).getTime(); if (to <= from) throw hostFailure("BOOKINGS_RANGE_INVALID", "toはfromより後の時刻にしてください"); if (to - from > LIMITS.bookings.maxRangeDays * 24 * 60 * 60 * 1000) { throw hostFailure("BOOKINGS_RANGE_TOO_LONG", "期間は" + LIMITS.bookings.maxRangeDays + "日以内にしてください"); } const limit = input.limit ?? LIMITS.bookings.listMaxLimit; const cursor = input.cursor ? decodeBookingCursor(input.cursor) : null; const updatedSince = input.updatedSince ? new Date(input.updatedSince).getTime() : null; const startOf = (row) => new Date(row.startAt).getTime(); const rows = session.bookings .filter((row) => startOf(row) < to && new Date(row.endAt).getTime() > from && (input.includeDeleted || row.deletedAt === null) && (!input.source || row.source === input.source) && (updatedSince === null || new Date(row.updatedAt).getTime() > updatedSince) && (!cursor || startOf(row) > cursor.startAt || (startOf(row) === cursor.startAt && row.id > cursor.id))) .sort((a, b) => startOf(a) - startOf(b) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); const page = rows.slice(0, limit); const last = page[page.length - 1]; return { bookings: page.map(projectBooking), nextCursor: rows.length > limit && last ? encodeBookingCursor(last) : null, }; } // ===== devices / fetch(実際には何も送らない) ===== function executeDevice(session, input) { const actionKey = input.actionKey.trim().toUpperCase(); if (input.domain === "ACCESS") { throw new CapabilityFailure("FORBIDDEN", 403, "鍵の操作は施錠からのみ実行できます"); } const isAcControl = actionKey === "AC_CONTROL"; if (isAcControl && input.domain !== "FACILITY") throw new CapabilityFailure("VALIDATION_ERROR", 400, "AC_CONTROL は FACILITY でのみ指定できます"); if (isAcControl && !input.acControl) throw new CapabilityFailure("VALIDATION_ERROR", 400, "acControl が必要です"); if (!isAcControl && input.acControl) throw new CapabilityFailure("VALIDATION_ERROR", 400, "acControl は AC_CONTROL でのみ指定できます"); const entry = session.devices[input.domain + ":" + actionKey]; if (isPlainObject(entry) && isPlainObject(entry.error)) { throw new CapabilityFailure(String(entry.error.code ?? "DEVICE_ERROR"), Number(entry.error.status ?? 502), entry.error.message ?? "fixture が指定した失敗です"); } return { ok: true, domain: input.domain, actionKey, provider: "EMULATOR", targetDeviceId: "emulated-device", targetDeviceName: "試験器の機器", remoteType: null, hubDeviceId: null, command: null, commandType: null, commandId: null, ...(isPlainObject(entry) && isPlainObject(entry.response) ? clone(entry.response) : {}), }; } function ipv4Octets(hostname) { const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname); return match ? match.slice(1).map(Number) : null; } function isGlobalIpv4(octets) { const [a, b, c] = octets; return !(a === 0 || a === 10 || a === 127 || a >= 224 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 0 && (c === 0 || c === 2)) || (a === 192 && b === 88 && c === 99) || (a === 192 && b === 168) || (a === 198 && (b === 18 || b === 19)) || (a === 198 && b === 51 && c === 100) || (a === 203 && b === 0 && c === 113)); } function isGlobalIpv6(hostname) { const groups = hostname.split(":"); const first = parseInt(groups[0] || "0", 16); const second = parseInt(groups[1] || "0", 16); if ((first & 0xe000) !== 0x2000) return false; return !(first === 0x2002 || (first === 0x2001 && (second === 0 || second === 0xdb8))); } /** 本番の SSRF 遮断のうち、DNS を引かずに判定できる部分だけ(DNS の解決先の検査はしない)。 */ function outboundUrlProblem(rawUrl) { let url; try { url = new URL(rawUrl); } catch { return "INVALID_URL"; } if (url.protocol !== "https:" || !url.hostname || url.username.length > 0 || url.password.length > 0 || url.hash.length > 0) return "INVALID_URL"; const hostname = url.hostname.startsWith("[") && url.hostname.endsWith("]") ? url.hostname.slice(1, -1) : url.hostname; const octets = ipv4Octets(hostname); if (octets) return isGlobalIpv4(octets) ? null : "SSRF_BLOCKED"; if (hostname.includes(":")) return isGlobalIpv6(hostname) ? null : "SSRF_BLOCKED"; return null; } function executeFetch(session, input) { const problem = outboundUrlProblem(input.url); if (problem) throw new CapabilityFailure(problem, 500, "外部通信の宛先として使えない URL です"); if (byteLength(input.body ?? "") > LIMITS.fetch.bodyMaxBytes) throw hostFailure("PAYLOAD_TOO_LARGE", "env.fetch bodyは32KiB以下です", 413); const entry = session.fetchResponses[input.url]; if (isPlainObject(entry) && entry.error) throw new CapabilityFailure("OUTBOUND_FAILED", 500, "fixture が指定した通信の失敗です"); const status = isPlainObject(entry) && Number.isInteger(entry.status) ? entry.status : 200; return { ok: status >= 200 && status < 300, status }; } // ===== drive ===== function parseA1Range(range, drive) { const separator = range.lastIndexOf("!"); let sheet = Object.keys(drive.sheets)[0]; let a1 = range; if (separator >= 0) { sheet = range.slice(0, separator); a1 = range.slice(separator + 1); if (sheet.length >= 2 && sheet.startsWith("'") && sheet.endsWith("'")) sheet = sheet.slice(1, -1).replace(/''/g, "'"); } const columns = /^([A-Za-z]{1,3}):([A-Za-z]{1,3})$/.exec(a1); if (columns) return { sheet, firstColumn: driveColumnNumber(columns[1]), lastColumn: driveColumnNumber(columns[2]), firstRow: null, lastRow: null, single: false }; const cells = /^([A-Za-z]{1,3})([1-9][0-9]*)(?::([A-Za-z]{1,3})([1-9][0-9]*))?$/.exec(a1); return { sheet, firstColumn: driveColumnNumber(cells[1]), lastColumn: driveColumnNumber(cells[3] ?? cells[1]), firstRow: Number(cells[2]), lastRow: Number(cells[4] ?? cells[2]), single: cells[3] === undefined, }; } function a1Text(sheet, range) { const quoted = /^[\p{L}\p{N}_]+$/u.test(sheet) ? sheet : "'" + sheet.replace(/'/g, "''") + "'"; const start = columnLetters(range.firstColumn) + (range.firstRow ?? ""); const end = columnLetters(range.lastColumn) + (range.lastRow ?? ""); return quoted + "!" + start + ":" + end; } const cellText = (cell) => (cell === null || cell === undefined ? "" : typeof cell === "boolean" ? (cell ? "TRUE" : "FALSE") : String(cell)); function boundedDriveResult(result) { if (byteLength(JSON.stringify(result)) <= LIMITS.drive.responseMaxBytes) return result; return { ...result, ...(hasOwn(result, "values") ? { values: [] } : {}), ...(hasOwn(result, "text") ? { text: "" } : {}), truncated: true }; } function normalizeDocumentText(text) { return text.split("\n") .map((line) => line.replace(/\r\n?/g, "\n").replace(/ {2,}/g, " ").trim()) .filter((line) => line.length > 0) .join("\n"); } function bytesPrefix(text, maxBytes) { if (byteLength(text) <= maxBytes) return { text, truncated: false }; let low = 0; let high = text.length; while (low < high) { const midpoint = Math.ceil((low + high) / 2); if (byteLength(text.slice(0, midpoint)) <= maxBytes) low = midpoint; else high = midpoint - 1; } return { text: text.slice(0, low), truncated: true }; } function countOccurrences(text, searchText, matchCase) { const haystack = matchCase ? text : text.toLocaleLowerCase(); const needle = matchCase ? searchText : searchText.toLocaleLowerCase(); let count = 0; let offset = 0; while (count <= LIMITS.drive.documentReplaceMaxOccurrences) { const found = haystack.indexOf(needle, offset); if (found < 0) break; count += 1; offset = found + Math.max(1, needle.length); } return count; } function replaceAllOccurrences(text, searchText, replaceText, matchCase) { const haystack = matchCase ? text : text.toLocaleLowerCase(); const needle = matchCase ? searchText : searchText.toLocaleLowerCase(); let out = ""; let offset = 0; for (;;) { const found = haystack.indexOf(needle, offset); if (found < 0) break; out += text.slice(offset, found) + replaceText; offset = found + Math.max(1, needle.length); } return out + text.slice(offset); } function readSheet(drive, sheetName) { if (!hasOwn(drive.sheets, sheetName)) return null; return drive.sheets[sheetName]; } function sheetDataRows(rows) { let last = 0; rows.forEach((row, index) => { if (row.some((cell) => cellText(cell) !== "")) last = index + 1; }); return last; } function executeDriveRead(drive, input) { const range = parseA1Range(input.range, drive); const rows = readSheet(drive, range.sheet); if (!rows) throw hostFailure("DRIVE_SCRIPT_READ_FAILED", "スプレッドシートを読み取れませんでした", 502); const grid = []; for (let row = range.firstRow; row <= range.lastRow; row += 1) { const cells = []; for (let column = range.firstColumn; column <= range.lastColumn; column += 1) cells.push(cellText((rows[row - 1] ?? [])[column - 1])); while (cells.length > 0 && cells[cells.length - 1] === "") cells.pop(); grid.push(cells); } while (grid.length > 0 && grid[grid.length - 1].length === 0) grid.pop(); let truncated = false; const limits = LIMITS.drive; const bounded = grid.slice(0, limits.readMaxRows).map((row) => row.slice(0, limits.readMaxColumns).map((cell) => { if (cell.length > limits.cellMaxCharacters) truncated = true; return cell.slice(0, limits.cellMaxCharacters); })); if (grid.length > limits.readMaxRows || grid.some((row) => row.length > limits.readMaxColumns)) truncated = true; return boundedDriveResult({ operation: "read", range: a1Text(range.sheet, range), values: bounded, truncated }); } function reserveDriveWrite(session, input) { const hash = JSON.stringify(input); const existing = session.driveOperations.get(input.operationKey); if (!existing) { session.driveOperations.set(input.operationKey, { operation: input.operation, hash, status: "PENDING", result: null }); return null; } if (existing.operation === input.operation && existing.hash === hash && existing.status === "SUCCEEDED" && existing.result) { return { ...existing.result, replayed: true }; } throw hostFailure("DRIVE_SCRIPT_OPERATION_AMBIGUOUS", "同じoperationKeyのDrive書き込みは再実行できません", 409); } function nextRevisionId(document) { document.revisionCount += 1; document.revisionId = "emulator-rev-" + document.revisionCount; } function executeDriveSheetWrite(drive, input) { const range = parseA1Range(input.range, drive); const rows = readSheet(drive, range.sheet); if (!rows) throw hostFailure("DRIVE_SCRIPT_WRITE_FAILED", "Driveファイルへ書き込めませんでした", 502); if (input.operation === "clear") { const lastRow = range.lastRow ?? rows.length; for (let row = range.firstRow ?? 1; row <= Math.min(lastRow, rows.length); row += 1) { for (let column = range.firstColumn; column <= range.lastColumn; column += 1) { if (rows[row - 1] && column - 1 < rows[row - 1].length) rows[row - 1][column - 1] = null; } } return { operation: "clear", clearedRange: a1Text(range.sheet, range) }; } const width = Math.max(...input.values.map((row) => row.length)); const cells = input.values.reduce((sum, row) => sum + row.length, 0); let firstRow; if (input.operation === "append") { firstRow = sheetDataRows(rows) + 1; } else { firstRow = range.firstRow; const bounded = !range.single; if (bounded && (input.values.length > range.lastRow - range.firstRow + 1 || width > range.lastColumn - range.firstColumn + 1)) { throw hostFailure("DRIVE_SCRIPT_WRITE_FAILED", "Driveファイルへ書き込めませんでした", 502); } } while (rows.length < firstRow - 1 + input.values.length) rows.push([]); input.values.forEach((row, rowOffset) => { const target = rows[firstRow - 1 + rowOffset]; row.forEach((cell, columnOffset) => { const index = range.firstColumn - 1 + columnOffset; while (target.length < index) target.push(null); target[index] = cell; }); }); const written = { sheet: range.sheet, firstColumn: range.firstColumn, lastColumn: range.firstColumn + width - 1, firstRow, lastRow: firstRow + input.values.length - 1 }; return { operation: input.operation, updatedRange: a1Text(range.sheet, written), updatedRows: input.values.length, updatedCells: cells }; } function documentBounds(document) { const endOfContent = 1 + document.text.length; return { startIndex: 1, endIndex: Math.max(1, endOfContent - 1) }; } function executeDriveDocumentWrite(drive, input) { const document = drive.document; if (input.requiredRevisionId && input.requiredRevisionId !== document.revisionId) { throw hostFailure("DRIVE_SCRIPT_REVISION_CONFLICT", "Googleドキュメントが読み取り後に変更されています。再読み取りしてから再実行してください", 409); } const bounds = documentBounds(document); let occurrencesChanged = null; if (input.operation === "appendText") { const at = bounds.endIndex - 1; document.text = document.text.slice(0, at) + input.text + document.text.slice(at); } else if (input.operation === "insertText") { if (input.index < bounds.startIndex || input.index > bounds.endIndex) throw hostFailure("DRIVE_SCRIPT_RANGE_INVALID", "挿入位置がドキュメント本文の範囲外です", 400); const at = input.index - 1; document.text = document.text.slice(0, at) + input.text + document.text.slice(at); } else if (input.operation === "deleteText") { if (input.startIndex < bounds.startIndex || input.endIndex > bounds.endIndex) throw hostFailure("DRIVE_SCRIPT_RANGE_INVALID", "削除範囲がドキュメント本文の範囲外です", 400); document.text = document.text.slice(0, input.startIndex - 1) + document.text.slice(input.endIndex - 1); } else { const occurrences = countOccurrences(document.text, input.searchText, input.matchCase); const resulting = document.text.length + occurrences * (input.replaceText.length - input.searchText.length); if (occurrences > LIMITS.drive.documentReplaceMaxOccurrences || resulting > LIMITS.drive.documentMaxResultCharacters) { throw hostFailure("DRIVE_SCRIPT_WRITE_LIMIT_EXCEEDED", "置換件数または置換後のドキュメントサイズが上限を超えます", 413); } document.text = replaceAllOccurrences(document.text, input.searchText, input.replaceText, input.matchCase); occurrencesChanged = occurrences; } // 何も置き換えなかった置換では、版は変わらない。 if (occurrencesChanged !== 0) nextRevisionId(document); return { operation: input.operation, occurrencesChanged }; } const SPREADSHEET_OPERATIONS = ["read", "append", "update", "clear"]; const DOCUMENT_OPERATIONS = ["readDocument", "appendText", "insertText", "replaceAllText", "deleteText"]; function executeDrive(session, input) { if (session.invocationKind !== "STUDIO_DRIVE_SCRIPT") throw hostFailure("DRIVE_SCRIPT_SCOPE_INVALID", "Drive操作の対象を確認できません", 403); const drive = session.drive; if (!drive) throw hostFailure("DRIVE_SCRIPT_FILE_UNAVAILABLE", "連携済みDriveファイルを利用できません", 409); const supported = drive.kind === "SPREADSHEET" ? SPREADSHEET_OPERATIONS : DOCUMENT_OPERATIONS; if (!supported.includes(input.operation)) throw hostFailure("DRIVE_SCRIPT_OPERATION_NOT_SUPPORTED", "選択したDriveファイルではこの操作を利用できません", 409); if (input.operation === "read") return executeDriveRead(drive, input); if (input.operation === "readDocument") { const bounded = bytesPrefix(normalizeDocumentText(drive.document.text), LIMITS.drive.documentResponseMaxBytes); return boundedDriveResult({ operation: "readDocument", revisionId: drive.document.revisionId, text: bounded.text, truncated: bounded.truncated }); } const replay = reserveDriveWrite(session, input); if (replay) return replay; const reservation = session.driveOperations.get(input.operationKey); try { const result = drive.kind === "SPREADSHEET" ? executeDriveSheetWrite(drive, input) : executeDriveDocumentWrite(drive, input); const stored = boundedDriveResult({ ...result, replayed: false }); reservation.status = "SUCCEEDED"; reservation.result = stored; return stored; } catch (error) { reservation.status = "FAILED"; throw error; } } // ===== capability の入口 ===== const CAPABILITIES = { "storage.execute": { parse: parseStorageInput, run: executeStorage }, "bookings.execute": { parse: parseBookingsInput, run: executeBookings }, "devices.execute": { parse: parseDeviceInput, run: executeDevice }, "fetch": { parse: parseFetchInput, run: executeFetch }, "drive.execute": { parse: parseDriveInput, run: executeDrive }, }; /** * capability を 1 回呼ぶ(本番の POST /playground-host-script-capabilities/:runId/ に相当)。 * 入力は本番と同じく JSON を往復させてから検査する。失敗は CapabilityFailure を投げる。 */ export function executeCapability(session, name, payload) { const wire = JSON.parse(JSON.stringify(payload ?? {})); if (!hasOwn(CAPABILITIES, name)) throw new CapabilityFailure("NOT_FOUND", 404, "未知の capability です: " + name); const capability = CAPABILITIES[name]; const parsed = capability.parse(wire); if (!parsed.ok) throw validationFailure(parsed.issues); return clone(capability.run(session, parsed.input)); } function createCall(session) { return async (name, payload) => { const record = { name, input: undefined, ok: false }; session.calls.push(record); try { record.input = clone(payload ?? {}); const result = executeCapability(session, name, payload); record.ok = true; record.result = clone(result); return result; } catch (error) { if (error instanceof CapabilityFailure) { record.error = { code: error.code, status: error.httpStatus, detail: error.detail }; throw new Error(error.code === "PERMISSION_REQUIRED" ? error.code : "CAPABILITY_FAILED_" + error.httpStatus); } record.error = { code: "REQUEST_FAILED", detail: error instanceof Error ? error.message : String(error) }; throw error; } }; } // ===== 実行 ===== const KINDS = { SCHEDULE: "SCHEDULE", STUDIO_EVENT: "STUDIO_DRIVE_SCRIPT", GCAL_FORMAT: "GCAL_FORMAT" }; function mergeInput(base, patch) { if (patch === undefined) return clone(base); if (!isPlainObject(base) || !isPlainObject(patch)) return clone(patch); const merged = clone(base); for (const key of Object.keys(patch)) { merged[key] = isPlainObject(patch[key]) && isPlainObject(merged[key]) ? mergeInput(merged[key], patch[key]) : clone(patch[key]); } return merged; } function defaultStudioEventInput(nowIso, driveKind) { return { version: 1, event: { type: "membership.member.created", occurredAt: nowIso, subjectType: "SPOT_MEMBER", data: { spotMemberId: "sample-spot-member", userId: "sample-user", member: { spotMemberId: "sample-spot-member", userId: "sample-user", email: "member@example.invalid", fullName: "見本 花子", displayName: "はな" }, }, }, drive: { fileHandle: "driveFile", kind: driveKind }, }; } let sandboxDepth = 0; let restoreSandbox = null; /** 実行の間だけ、時計を固定し、直接の外部通信を塞ぎ、console を捕まえる。 */ function installSandbox(nowMs, logs) { sandboxDepth += 1; if (sandboxDepth > 1) return () => { sandboxDepth -= 1; }; const RealDate = globalThis.Date; class EmulatedDate extends RealDate { constructor(...args) { if (args.length === 0) super(nowMs); else super(...args); } static now() { return nowMs; } } const saved = { Date: globalThis.Date, fetch: globalThis.fetch, WebSocket: globalThis.WebSocket, exit: process.exit, console: {} }; const blocked = function blockedNetwork() { throw new Error("EMULATOR_NETWORK_BLOCKED: 外部通信は env.fetch を使ってください"); }; globalThis.Date = EmulatedDate; globalThis.fetch = blocked; process.exit = function blockedExit() { throw new Error("EMULATOR_PROCESS_EXIT_BLOCKED: process.exit は使えません"); }; if (saved.WebSocket !== undefined) globalThis.WebSocket = blocked; for (const method of ["log", "info", "warn", "error", "debug"]) { saved.console[method] = console[method]; console[method] = (...args) => { if (logs.length < 100) logs.push(method + ": " + args.map((item) => (typeof item === "string" ? item : safeStringify(item))).join(" ").slice(0, 500)); }; } restoreSandbox = () => { globalThis.Date = saved.Date; globalThis.fetch = saved.fetch; process.exit = saved.exit; if (saved.WebSocket !== undefined) globalThis.WebSocket = saved.WebSocket; for (const method of Object.keys(saved.console)) console[method] = saved.console[method]; restoreSandbox = null; }; return () => { sandboxDepth -= 1; if (sandboxDepth === 0 && restoreSandbox) restoreSandbox(); }; } function safeStringify(value) { try { return JSON.stringify(value) ?? String(value); } catch { return String(value); } } let importCounter = 0; async function loadUserModule(source) { importCounter += 1; // 実行ごとに新しいモジュールとして読む(前の fixture のモジュール変数を持ち越さない)。 const text = source + "\n//# niho-emulator-run-" + importCounter + "\n"; return import("data:text/javascript;base64," + Buffer.from(text, "utf8").toString("base64")); } function withTimeout(promise, ms) { let timer; const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new HostScriptFailure("TIMEOUT", "実行が" + ms + "ミリ秒を超えました")), ms); }); return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); } let queue = Promise.resolve(); function enqueue(task) { const run = queue.then(task, task); queue = run.catch(() => undefined); return run; } function failureResult(base, stage, code, detail, extra) { return { ...base, ok: false, output: null, error: { stage, code, ...(detail ? { detail } : {}), ...(extra ?? {}) } }; } /** * fixture 1 件を実行する。 * @param {{ source?: string, file?: string, manifest: object, fixture?: object }} params * @returns {Promise<{ ok: boolean, kind: string, output: unknown, error: null | { stage: string, code: string, detail?: string, hint?: string }, calls: object[], storage: object, drive: null | object, logs: string[], warnings: string[] }>} */ export function runFixture(params) { return enqueue(() => runFixtureNow(params ?? {})); } async function runFixtureNow({ source, file, manifest, fixture }) { const fixtureValue = fixture ?? {}; const base = { ok: true, kind: manifest?.trigger?.kind ?? null, output: null, error: null, calls: [], storage: {}, drive: null, logs: [], warnings: [] }; const problems = checkManifest(manifest); if (problems.length > 0) return failureResult(base, "manifest", "INVALID_MANIFEST", issuesText(problems)); let text = source; if (text === undefined) { try { text = await readFile(file, "utf8"); } catch (error) { return failureResult(base, "source", "SOURCE_NOT_FOUND", error instanceof Error ? error.message : String(error)); } } const sourceCheck = checkSource(text); if (!sourceCheck.ok) return failureResult(base, "source", sourceCheck.code, sourceCheck.message); const invocationKind = KINDS[manifest.trigger.kind]; let session; let config; let permissions; let input; try { permissions = fixtureValue.permissions ?? manifest.permissions ?? []; if (!Array.isArray(permissions) || !permissions.every((item) => PERMISSIONS.includes(item))) throw fixtureError("permissions は " + PERMISSIONS.join(" / ") + " の配列にしてください"); session = createSession({ now: fixtureValue.now ?? DEFAULT_NOW, permissions, invocationKind, state: fixtureValue.state ?? {} }); config = { ...(manifest.configValues ?? {}), ...(fixtureValue.config ?? {}) }; if (fixtureValue.config !== undefined && !isPlainObject(fixtureValue.config)) throw fixtureError("config はオブジェクトにしてください"); assertConfigValues(manifest.configSchema ?? { type: "object", properties: {} }, config); if (fixtureValue.input !== undefined && !isPlainObject(fixtureValue.input)) throw fixtureError("input はオブジェクトにしてください"); if (invocationKind === "GCAL_FORMAT") input = mergeInput(SAMPLE_GCAL_FORMAT_INPUT, fixtureValue.input); else if (invocationKind === "STUDIO_DRIVE_SCRIPT") input = mergeInput(defaultStudioEventInput(session.nowIso, session.drive ? session.drive.kind : "SPREADSHEET"), fixtureValue.input); } catch (error) { if (error instanceof HostScriptFailure) return failureResult(base, error.code === "FIXTURE_INVALID" ? "fixture" : "config", error.code, error.message); throw error; } // 本番の invokeHostScript / invokeHostScriptGcalFormat と同じ入力の大きさの検査。 const payload = JSON.stringify({ runId: "run", scriptId: "script", spotId: "spot", sourceDigest: "sha256:digest", issuedAt: 0, config, capabilityToken: "token", invocationKind, ...(invocationKind === "STUDIO_DRIVE_SCRIPT" ? { triggerInput: input } : {}), ...(invocationKind === "GCAL_FORMAT" ? { formatInput: input } : {}), }); if (invocationKind === "GCAL_FORMAT") { if (!permissions.includes("gcal.format")) return failureResult(base, "permission", "PERMISSION_MISSING", "公開版が gcal.format を宣言していません。script.json の permissions に追加してください"); if (byteLength(JSON.stringify(input)) > LIMITS.gcal.inputMaxBytes || byteLength(payload) > LIMITS.invocationMaxBytes) return failureResult(base, "input", "INPUT_TOO_LARGE", "入力が大きすぎます"); } else { if (byteLength(payload) > LIMITS.invocationMaxBytes) return failureResult(base, "input", "PAYLOAD_TOO_LARGE", "管理JSへの実行入力は64KiB以下です"); if (invocationKind === "STUDIO_DRIVE_SCRIPT" && byteLength(JSON.stringify(input)) > LIMITS.driveTriggerInputMaxBytes) return failureResult(base, "input", "DRIVE_SCRIPT_TRIGGER_INPUT_TOO_LARGE", "起動入力は48KiB以下です"); } const logs = []; const result = { ...base, logs, calls: session.calls }; const restore = installSandbox(session.now.getTime(), logs); try { let module; try { module = await loadUserModule(text); } catch (error) { return finish(failureResult(result, "load", "SOURCE_LOAD_FAILED", error instanceof Error ? error.message : String(error)), session); } const userScript = module.default; const timeoutMs = invocationKind === "GCAL_FORMAT" ? LIMITS.gcal.timeoutMs : LIMITS.invokeTimeoutMs; const runInput = { invocationKind, config, triggerInput: input, formatInput: input }; let output; try { output = await withTimeout( invocationKind === "GCAL_FORMAT" ? callHostScriptGcalFormat(userScript, runInput) : callHostScriptUserFunction(userScript, runInput, createHostScriptEnv(runInput, createCall(session))), timeoutMs, ); // 本番の Worker は Response.json で返すため、JSON にできない値はここで失敗する。 output = JSON.parse(JSON.stringify({ output: output ?? null })).output; } catch (error) { return finish(scriptFailure(result, invocationKind, error, session), session); } return finish(finishOutput(result, invocationKind, manifest, output, permissions), session); } finally { restore(); } } function lastFailedCall(session) { for (let index = session.calls.length - 1; index >= 0; index -= 1) { if (session.calls[index].error) return session.calls[index]; } return null; } function scriptFailure(result, invocationKind, error, session) { if (error instanceof HostScriptFailure && error.code === "TIMEOUT") return failureResult(result, "script", "TIMEOUT", error.message); const message = error instanceof Error ? String(error.message) : String(error); if (invocationKind === "GCAL_FORMAT") return failureResult(result, "script", "SCRIPT_THREW", message.slice(0, 500)); const code = error instanceof Error ? message.slice(0, 120) : "USER_SCRIPT_FAILED"; const failed = code === "PERMISSION_REQUIRED" || /^CAPABILITY_FAILED_/.test(code) ? lastFailedCall(session) : null; const hint = failed ? failed.name + " の " + failed.error.code + "(" + failed.error.detail + ")" : undefined; return failureResult(result, "script", code, undefined, hint ? { hint } : undefined); } function finishOutput(result, invocationKind, manifest, output, permissions) { if (invocationKind === "GCAL_FORMAT") { if (byteLength(JSON.stringify({ ok: true, elapsedMs: 0, output })) > LIMITS.gcal.responseMaxBytes) return failureResult(result, "output", "OUTPUT_TOO_LARGE", "出力は32KiB以下にしてください"); const parsed = parseGcalFormatOutput(output); if (!parsed.ok) return failureResult(result, "output", "INVALID_OUTPUT", parsed.reason); return { ...result, output: parsed.output }; } if (invocationKind === "STUDIO_DRIVE_SCRIPT") { if (manifest.outputSchema) { try { return { ...result, output: validateOutput(manifest.outputSchema, output) }; } catch (error) { if (error instanceof HostScriptFailure) return failureResult(result, "output", error.code, error.message); throw error; } } return { ...result, output }; } const warnings = [...result.warnings]; if (manifest.outputSchema) warnings.push("outputSchema は STUDIO_EVENT の戻り値にだけ使われます(SCHEDULE の戻り値は検証されず、実行ログへ残ります)"); if (byteLength(JSON.stringify({ statusCode: 200, result: { ok: true, elapsedMs: 0, output } })) > LIMITS.logMaxBytes) { warnings.push("戻り値が大きいため、本番の実行ログには保存されません(16KiBを超えると truncated だけが残ります)"); } return { ...result, output, warnings }; } function finish(result, session) { const storage = {}; for (const key of sortedStorageKeys(session)) storage[key] = clone(session.storage.get(key).value); const drive = session.drive ? session.drive.kind === "SPREADSHEET" ? { kind: "SPREADSHEET", sheets: clone(session.drive.sheets) } : { kind: "DOCUMENT", document: { text: session.drive.document.text, revisionId: session.drive.document.revisionId } } : null; return { ...result, storage, drive, calls: clone(session.calls) }; } // ===== 期待値の照合 ===== /** expected が actual の部分集合か。オブジェクトは expected のキーだけ、配列は同じ長さで要素ごとに照合する。 */ function subsetMismatch(actual, expected, path) { if (Array.isArray(expected)) { if (!Array.isArray(actual)) return path + ": 配列が必要です(実際: " + safeStringify(actual) + ")"; if (actual.length !== expected.length) return path + ": 要素数が違います(期待 " + expected.length + " / 実際 " + actual.length + ")"; for (let index = 0; index < expected.length; index += 1) { const mismatch = subsetMismatch(actual[index], expected[index], path + "[" + index + "]"); if (mismatch) return mismatch; } return null; } if (isPlainObject(expected)) { if (!isPlainObject(actual)) return path + ": オブジェクトが必要です(実際: " + safeStringify(actual) + ")"; for (const key of Object.keys(expected)) { if (!hasOwn(actual, key)) return path + "." + key + ": 存在しません"; const mismatch = subsetMismatch(actual[key], expected[key], path + "." + key); if (mismatch) return mismatch; } return null; } return Object.is(actual, expected) || actual === expected ? null : path + ": 期待 " + safeStringify(expected) + " / 実際 " + safeStringify(actual); } /** * 実行結果を fixture の expect と照合する。 * - output / storage / drive: expect に書いた項目だけを部分一致で確かめる(配列は同じ長さ)。 * - calls: expect の呼び出しが、実際の呼び出しの中に順番どおりに(間に別の呼び出しがあってもよい)含まれる。 * - callCounts: capability 名ごとの呼び出し回数(例: { "devices.execute": 0 })。 * - error: 省略か null は「失敗しないこと」。文字列は error.code、オブジェクトは部分一致。 */ export function matchExpect(result, expectation) { const expected = expectation ?? {}; const failures = []; if (expected.error === undefined || expected.error === null) { if (result.error) failures.push("想定外の失敗: " + result.error.code + (result.error.detail ? "(" + result.error.detail + ")" : "") + (result.error.hint ? " " + result.error.hint : "")); } else if (!result.error) { failures.push("失敗するはずでしたが成功しました"); } else { const mismatch = subsetMismatch(result.error, typeof expected.error === "string" ? { code: expected.error } : expected.error, "error"); if (mismatch) failures.push(mismatch); } for (const key of ["output", "storage", "drive"]) { if (expected[key] !== undefined) { const mismatch = subsetMismatch(result[key], expected[key], key); if (mismatch) failures.push(mismatch); } } if (expected.calls !== undefined) { if (!Array.isArray(expected.calls)) { failures.push("calls: 配列にしてください"); } else { let position = 0; expected.calls.forEach((call, index) => { let found = -1; for (let candidate = position; candidate < result.calls.length; candidate += 1) { if (subsetMismatch(result.calls[candidate], call, "calls") === null) { found = candidate; break; } } if (found < 0) failures.push("calls[" + index + "]: 一致する呼び出しがありません " + safeStringify(call)); else position = found + 1; }); } } if (expected.callCounts !== undefined) { for (const [name, count] of Object.entries(expected.callCounts)) { const actual = result.calls.filter((call) => call.name === name).length; if (actual !== count) failures.push("callCounts." + name + ": 期待 " + count + " / 実際 " + actual); } } return { pass: failures.length === 0, failures }; }